18 Commits

Author SHA1 Message Date
Mika Kuns
d37d2419d6 feat(cli): pre-install port check in install-autostart
All checks were successful
CI (Node) / build-test (push) Successful in 9s
Release / release (push) Successful in 8s
Release (Node) / release (push) Successful in 12s
Before registering the Scheduled Task / Run-key / launchd / systemd unit,
probe /health on the resolved port. If a non-claude-mailbox service
answers, refuse with a helpful hint (`--port <n>` or mailbox.json) so
users don't end up with autostart firing against an occupied port.
Pass --skip-port-check to bypass.

The doctor already had this logic in Step 2; now standalone
install-autostart invocations are protected too.
2026-05-19 14:09:21 +02:00
Mika Kuns
ee0b72f43b feat: change default port from 47822 to 37849 (v1.2.0)
All checks were successful
CI (Node) / build-test (push) Successful in 10s
CI (.NET) / build (push) Successful in 11s
47822 collided with ClaudeDo.Worker.exe on at least one user's machine.
37849 is high, registered to nobody, and avoids the prior conflict.
Both the Node port and the .NET port move together (still
wire-compatible). Defaults change only — if a user has a custom port
in mailbox.json, that stays.
2026-05-19 14:07:56 +02:00
Mika Kuns
d3abc762fd fix(ci): allow same-version npm version call (idempotent when source already bumped)
Some checks failed
Release / release (push) Failing after 6s
Release (Node) / release (push) Successful in 11s
2026-05-19 13:55:11 +02:00
Mika Kuns
d0eb2af183 chore(node): release v1.1.0
Some checks failed
CI (Node) / build-test (push) Successful in 9s
Release / release (push) Successful in 6s
Release (Node) / release (push) Failing after 4s
2026-05-19 13:53:34 +02:00
Mika Kuns
42237149a1 feat: stdio MCP wrapper + Windows Run-key autostart fallback (v1.0.1)
Some checks failed
CI (Node) / build-test (push) Successful in 9s
Release (Node) / release (push) Failing after 1s
Release / release (push) Successful in 7s
Two production-readiness fixes so colleagues can install cleanly:

1. Plugin's MCP server now spawns `claude-mailbox mcp-stdio`, a small
   stdio MCP wrapper that proxies tool calls to the daemon's REST API.
   Claude Code does not support env-var substitution in HTTP MCP `url`
   fields (issue #46889), so the wrapper is the only way to make the
   daemon URL configurable per machine via CLAUDE_MAILBOX_URL.

2. Windows `install-autostart` now falls back from `schtasks /Create`
   to an HKCU\Software\Microsoft\Windows\CurrentVersion\Run entry
   when Group Policy blocks the Scheduled Task path. Both modes are
   per-user, no admin, persist across logoffs. The chosen mode is
   recorded in ~/.claude-mailbox/autostart-mode so status/start/stop/
   uninstall-autostart pick the right cleanup path.

Also bumps the npm version to 1.0.1 to align with the published 1.0.0
plus this patch.
2026-05-19 13:43:55 +02:00
Mika Kuns
ac626f678b fix(cli,plugin): CLAUDE_MAILBOX_URL env override + port-conflict-aware doctor
All checks were successful
CI (Node) / build-test (push) Successful in 9s
The plugin's UserPromptSubmit and SessionStart hooks call `claude-mailbox`
with no --url flag, so they previously always hit the hardcoded
http://127.0.0.1:47822/mcp default. If port 47822 was held by another
local service (e.g. ClaudeDo), the daemon couldn't bind there and every
hook was talking to the wrong process.

CLI default for --url now resolves to $CLAUDE_MAILBOX_URL when set,
falling back to http://127.0.0.1:47822. Doctor gained a Step 2 that
probes /health on 47822, identifies foreign occupants, picks a free
port, writes both ~/.claude-mailbox/mailbox.json and the
CLAUDE_MAILBOX_URL entry in .claude/settings.json env so the hooks
follow along automatically.

Also adds a fallback hint when Windows schtasks /Create fails with
Access is denied (Group Policy restricts non-admin task creation): run
install-autostart from an elevated shell, or accept an ephemeral serve
for the current session.
2026-05-19 13:30:51 +02:00
Mika Kuns
73a49e405f docs(readme): use .git suffix on marketplace clone URL 2026-05-19 13:18:52 +02:00
Mika Kuns
43e8d0d4ca fix(ci): add pretest hook so vitest sees built dist/cli.js
All checks were successful
CI (Node) / build-test (push) Successful in 8s
Release / release (push) Successful in 8s
Release (Node) / release (push) Successful in 13s
2026-05-19 13:12:59 +02:00
Mika Kuns
50f2b5a7cb docs(readme): restructure for getting-started flow
Some checks failed
CI (Node) / build-test (push) Failing after 5s
Release (Node) / release (push) Failing after 5s
Release / release (push) Successful in 7s
2026-05-19 12:56:27 +02:00
Mika Kuns
19d7a591df chore(node): release v0.1.0 2026-05-19 12:01:41 +02:00
Mika Kuns
48b6ba6452 feat(plugin): SessionStart hook discovers and announces active peers
session-announce now calls /v1/list with the session's X-Mailbox header,
which both registers the session with the daemon and returns all known
mailboxes in one round-trip. The output appends an "Active peers" block
listing mailboxes seen within the last hour (configurable via
--peer-window-minutes), capped at 10 entries by default. Self is
filtered out; the list is sorted most-recent-first.

So when the user says "I started a second session, coordinate with it",
Claude already has the peer's mailbox name in context — no manual
list_mailboxes call needed.

The peer-formatting logic is extracted into formatActivePeerList for
unit testing; CLI tests now pin --url to an unreachable port to keep
assertions stable on machines that have a real daemon running.
2026-05-19 11:59:31 +02:00
Mika Kuns
9fd321043f feat(mcp): identity-via-arg + plugin ships .mcp.json
MCP tools (send/check_inbox/peek_inbox/list_mailboxes) now accept the
caller's mailbox name as an explicit argument (from/name), falling back
to the X-Mailbox header for legacy single-session HTTP setups. This
unblocks multi-session coordination through a shared .mcp.json — each
Claude session passes its own session-derived name on every call,
instead of relying on a single transport header that all sessions
would share.

The plugin now ships .mcp.json (no header), and the SessionStart
announcement spells out the exact args to pass to each mcp__mailbox__*
tool so Claude wires it up automatically.
2026-05-19 11:50:58 +02:00
Mika Kuns
462d6561e1 feat(plugin): per-session mailbox identity + mailbox-update command
The hook now derives a unique mailbox name from the session_id supplied
on hook stdin, so two parallel Claude Code sessions in the same project
get distinct mailboxes (e.g. `claude-a8b3c1d2`, `claude-d4e5f6a7`)
instead of colliding on a shared env value. An optional
CLAUDE_MAILBOX_NAME base prefix flavors the names as `<base>-<sid>`.

Adds:
- `claude-mailbox session-announce` subcommand for the new SessionStart
  hook, which prints the current session's mailbox name to context
- `/claude-mailbox:mailbox-update` slash command for `npm update` +
  daemon restart
- stdin parsing helpers (parseHookStdin, deriveSessionName) with unit
  tests; the doctor no longer needs a mandatory name prompt
2026-05-19 11:39:14 +02:00
Mika Kuns
c231f8c18c feat(plugin): add /claude-mailbox:mailbox-doctor for one-command setup
The doctor command runs entirely inside Claude Code and walks through:
binary install via npm, daemon autostart, mailbox-name prompt with write
to per-project `.claude/settings.json` env, and a self → self smoke test.
Also adds `/claude-mailbox:mailbox-status` as a read-only health check.

Reduces the colleague onboarding to: add marketplace, install plugin,
run the doctor — no terminal context-switch required.
2026-05-19 10:55:05 +02:00
Mika Kuns
5c5843e62d feat(plugin): ship Claude Code plugin + marketplace manifest
Adds a /plugin marketplace at the repo root and a `claude-mailbox` plugin under
plugin/ that wires the UserPromptSubmit hook without needing the per-user
`install-hook` step. The hook command (`claude-mailbox check --hook`) now reads
the mailbox name from $CLAUDE_MAILBOX_NAME when --name is omitted and emits a
one-line setup hint when the daemon is unreachable, so a missing daemon is loud
instead of invisible.

The plugin only contains the Claude Code glue — the daemon binary is still a
separate prerequisite (`npm i -g @kuns/claude-mailbox` + install-autostart),
and the plugin/README plus main README spell out the three-step setup.
2026-05-19 10:49:36 +02:00
Mika Kuns
66967167bc feat(node): add Claude Code UserPromptSubmit hook for auto inbox-check
Adds `install-hook` / `uninstall-hook` subcommands that idempotently patch
~/.claude/settings.json (or .claude/settings.json with --project), plus a
`--hook` flag on `check` that emits human-readable output and stays silent
on empty inbox or unreachable daemon.
2026-05-19 10:09:30 +02:00
a5a2895725 fix(ci): use NPM_PUBLISH_TOKEN for Gitea npm registry auth
All checks were successful
Release / release (push) Successful in 7s
Release (Node) / release (push) Successful in 10s
The auto-generated secrets.GITEA_TOKEN lacks write:package scope,
causing npm publish to fail with E401. Use a dedicated repo secret
NPM_PUBLISH_TOKEN with a personal access token that has write:package.
2026-04-30 12:20:51 +00:00
mika kuns
05d87d2aa7 feat(node): add TypeScript sibling project for npm-based install
Some checks failed
CI (Node) / build-test (push) Successful in 6s
CI (.NET) / build (push) Successful in 10s
Release / release (push) Successful in 8s
Release (Node) / release (push) Failing after 10s
Introduces @kuns/claude-mailbox under node/, a wire-compatible TypeScript
port of the .NET daemon that distributes via the public Gitea npm registry.
The .NET project stays in src/ClaudeMailbox/ untouched; users pick whichever
flavor they prefer.

- node/ project: fastify + @modelcontextprotocol/sdk StreamableHTTPServerTransport
  + better-sqlite3, schema and wire surface match the C# version (port 47822,
  X-Mailbox header, MCP tool names, snake_case SQLite columns)
- Cross-platform autostart: Scheduled Task (Win, no admin) / Windows Service
  (Win, --service) / launchd (mac) / systemd --user (linux)
- 9/9 vitest tests pass; end-to-end /health + send/check round-trip verified
- CI split: existing ci.yml/release.yml renamed to *-dotnet.yml with path
  filters, new ci-node.yml and release-node.yml publish to Gitea npm registry
- install.ps1 / install.sh bootstrap one-liners at repo root; homebrew/
  contains a tap formula template
- README install section reordered: npm path primary, dotnet publish secondary

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 14:06:46 +02:00
42 changed files with 7452 additions and 102 deletions

View File

@@ -0,0 +1,14 @@
{
"name": "claude-mailbox",
"owner": {
"name": "Mika Kuns"
},
"description": "Plugins for the Claude-Mailbox project.",
"plugins": [
{
"name": "claude-mailbox",
"source": "./plugin",
"description": "Auto-checks the local Claude-Mailbox daemon before every prompt and injects pending messages."
}
]
}

View File

@@ -1,12 +1,24 @@
name: CI name: CI (.NET)
on: on:
push: push:
branches: branches:
- main - main
paths:
- "src/**"
- "tests/**"
- "ClaudeMailbox.slnx"
- "global.json"
- ".gitea/workflows/ci-dotnet.yml"
pull_request: pull_request:
branches: branches:
- main - main
paths:
- "src/**"
- "tests/**"
- "ClaudeMailbox.slnx"
- "global.json"
- ".gitea/workflows/ci-dotnet.yml"
jobs: jobs:
build: build:

View File

@@ -0,0 +1,34 @@
name: CI (Node)
on:
push:
branches: [main]
paths:
- "node/**"
- ".gitea/workflows/ci-node.yml"
pull_request:
paths:
- "node/**"
- ".gitea/workflows/ci-node.yml"
jobs:
build-test:
runs-on: ubuntu-latest
defaults:
run:
working-directory: node
steps:
- name: Checkout
uses: https://github.com/actions/checkout@v4
- name: Node version
run: node --version && npm --version
- name: Install
run: npm ci
- name: Test
run: npm test
- name: Build
run: npm run build

View File

@@ -0,0 +1,117 @@
name: Release (Node)
on:
push:
tags:
- 'v*'
jobs:
release:
runs-on: ubuntu-latest
env:
GITEA_API: https://git.kuns.dev/api/v1
REPO: releases/ClaudeMailbox
NPM_REGISTRY_HOST: git.kuns.dev/api/packages/releases/npm/
defaults:
run:
working-directory: node
steps:
- name: Checkout tag
uses: https://github.com/actions/checkout@v4
with:
fetch-depth: 0
- name: Node version
run: node --version && npm --version
- name: Resolve version
id: ver
run: |
set -euo pipefail
TAG="${{ github.ref_name }}"
VERSION="${TAG#v}"
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
- name: Set package version
env:
VERSION: ${{ steps.ver.outputs.version }}
run: npm version --no-git-tag-version --allow-same-version "$VERSION"
- name: Install
run: npm ci
- name: Test
run: npm test
- name: Pack
env:
VERSION: ${{ steps.ver.outputs.version }}
run: |
set -euo pipefail
npm pack
mv "kuns-claude-mailbox-${VERSION}.tgz" "claude-mailbox-${VERSION}.tgz"
( sha256sum "claude-mailbox-${VERSION}.tgz" > checksums.txt )
- name: Configure npm auth for Gitea
env:
NPM_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }}
run: |
set -euo pipefail
if [ -z "${NPM_TOKEN:-}" ]; then
echo "::error::NPM_PUBLISH_TOKEN secret is not set (needs Gitea token with write:package scope)" >&2
exit 1
fi
echo "@kuns:registry=https://${NPM_REGISTRY_HOST}" > .npmrc
echo "//${NPM_REGISTRY_HOST}:_authToken=${NPM_TOKEN}" >> .npmrc
- name: Publish to Gitea npm registry
run: npm publish --access public
- name: Find or create Gitea release
id: release
env:
TAG: ${{ steps.ver.outputs.tag }}
TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
set -euo pipefail
# Try to find an existing release for this tag (the .NET workflow may have created it).
EXISTING=$(curl -sS \
-H "Authorization: token ${TOKEN}" \
"${GITEA_API}/repos/${REPO}/releases/tags/${TAG}" || echo "")
RELEASE_ID=$(echo "$EXISTING" | jq -r '.id // empty')
if [ -z "$RELEASE_ID" ] || [ "$RELEASE_ID" = "null" ]; then
BODY=$(jq -n \
--arg tag "$TAG" \
--arg name "$TAG" \
'{tag_name:$tag, name:$name, body:"", draft:false, prerelease:false, target_commitish:"main"}')
RESP=$(curl -sS -X POST \
-H "Authorization: token ${TOKEN}" \
-H "Content-Type: application/json" \
-d "$BODY" \
"${GITEA_API}/repos/${REPO}/releases")
RELEASE_ID=$(echo "$RESP" | jq -r '.id // empty')
fi
if [ -z "$RELEASE_ID" ] || [ "$RELEASE_ID" = "null" ]; then
echo "::error::Could not resolve release id" >&2
exit 1
fi
echo "release_id=$RELEASE_ID" >> "$GITHUB_OUTPUT"
- name: Upload tarball + checksums
env:
VERSION: ${{ steps.ver.outputs.version }}
RELEASE_ID: ${{ steps.release.outputs.release_id }}
TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
set -euo pipefail
for f in \
"claude-mailbox-${VERSION}.tgz" \
"checksums.txt"
do
curl -sS --fail-with-body -X POST \
-H "Authorization: token ${TOKEN}" \
-F "attachment=@${f}" \
"${GITEA_API}/repos/${REPO}/releases/${RELEASE_ID}/assets?name=${f}" \
> /dev/null
done

280
README.md
View File

@@ -1,116 +1,148 @@
# ClaudeMailbox # ClaudeMailbox
A standalone MCP mail server that lets parallel Claude sessions coordinate with each other. Any Claude session (plain terminal, ClaudeDo worktree, anything that consumes `.mcp.json`) can send messages to a peer session's inbox, check for pending messages, and discover other active mailboxes. A standalone MCP mail server that lets parallel Claude sessions coordinate with each other. Messages are queued in a tiny SQLite database via a local HTTP daemon. Any Claude session — Claude Code, ClaudeDo worktree, plain MCP client — can send to a peer's inbox, check for pending messages, and discover other active mailboxes.
Not a substitute for `run_in_background: true` — that handles single-session responsiveness. This handles **session-to-session** coordination. Not a substitute for `run_in_background: true` (which handles single-session responsiveness). This handles **session-to-session** coordination.
## Architecture ---
One long-running daemon binds HTTP on loopback, hosts the MCP server at `/mcp` and a small REST API at `/v1/*`, and persists state in a single SQLite file. Sessions declare themselves via an `X-Mailbox` header in their `.mcp.json`. ## Getting started
Pick one path. Most users want path A.
### A. Claude Code plugin (recommended — three prompts)
Inside Claude Code:
``` ```
session-backend session-frontend external sender /plugin marketplace add https://git.kuns.dev/releases/ClaudeMailbox.git
(X-Mailbox: backend) (X-Mailbox: frontend) (CLI / UI / hook) /plugin install claude-mailbox@claude-mailbox
| | | /claude-mailbox:mailbox-doctor
| HTTP | |
+--------------+-----------------+--------------------------+
v
claude-mailbox serve (ASP.NET Core + Kestrel)
/mcp MCP tools
/v1/* REST for non-MCP senders
/health
v
~/.claude-mailbox/mailbox.db (SQLite WAL)
``` ```
## Install The doctor command does the rest:
1. installs the daemon binary via `npm install -g @kuns/claude-mailbox` if missing (asks first)
2. registers the daemon for autostart and starts it
3. optionally lets you pick a base prefix (e.g. `backend`, `frontend`); without one, mailbox names are anonymous (`claude-a8b3c1d2`)
4. runs a self → self smoke test
After that, every Claude Code session automatically:
- gets a **unique mailbox identity** derived from its session UUID (so two parallel sessions never collide),
- announces that identity and the **list of currently active peers** at session start,
- pulls unread mailbox messages into context before every prompt.
You can then say things like:
> "I started a second session, coordinate with it on the refactor."
Claude already has the peer's mailbox name in context from the SessionStart announcement, so it calls `mcp__mailbox__send(from="<my-name>", to="<peer>", body="...")` directly.
See [`plugin/README.md`](./plugin/README.md) for the full walkthrough, including the `mailbox-status` and `mailbox-update` slash commands.
### B. Manual install (no Claude Code plugin)
If you're using a different MCP client, scripts, or you don't want the plugin:
```sh
# one-time per machine: point the @kuns scope at the public Gitea npm registry
npm config set @kuns:registry=https://git.kuns.dev/api/packages/releases/npm/
# install + autostart
npm install -g @kuns/claude-mailbox
claude-mailbox install-autostart
```
Or the bootstrap one-liner:
```powershell ```powershell
dotnet publish -c Release -r win-x64 --self-contained -p:PublishSingleFile=true # Windows
irm https://git.kuns.dev/releases/ClaudeMailbox/raw/branch/main/install.ps1 | iex
``` ```
Put the resulting `claude-mailbox.exe` on your `PATH`. ```sh
# macOS / Linux
## Daemon lifecycle curl -fsSL https://git.kuns.dev/releases/ClaudeMailbox/raw/branch/main/install.sh | sh
Pick whichever level of automation you want:
1. **Manual.** `claude-mailbox serve` in a terminal.
2. **Startup shortcut.** Shortcut to `claude-mailbox serve` in `shell:startup`.
3. **Windows Service (recommended).** See below.
### Windows Service
Install (admin shell):
```
claude-mailbox install-service [--port 47822] [--bind 127.0.0.1] [--db-path <path>]
``` ```
This: Then drop this into your project's `.mcp.json`:
- Creates `%ProgramData%\ClaudeMailbox\` with ACLs for `LocalService`
- Seeds `mailbox.json` with the defaults (or your flag overrides) — only on first install
- Registers the service via `sc.exe create`, running as `NT AUTHORITY\LocalService` with `start= auto`
Control:
```
claude-mailbox start
claude-mailbox stop
claude-mailbox status # prints Running | Stopped | NotInstalled
claude-mailbox uninstall-service [--purge]
```
`--purge` additionally removes `%ProgramData%\ClaudeMailbox\` (config + database).
### Config precedence
```
CLI flag > mailbox.json > built-in defaults
```
The service is invoked with `serve --config C:\ProgramData\ClaudeMailbox\mailbox.json`, so editing that file and restarting the service is enough to change port/bind/db-path.
Interactive (console) runs without `--config` use `%USERPROFILE%\.claude-mailbox\mailbox.db` (unchanged from v0).
### Manual smoke test
```
claude-mailbox install-service
sc query ClaudeMailbox
claude-mailbox start
Invoke-WebRequest http://127.0.0.1:47822/health
claude-mailbox uninstall-service --purge
```
Defaults: port `47822`, bind `127.0.0.1`, database at `%ProgramData%\ClaudeMailbox\mailbox.db` (service) or `%USERPROFILE%\.claude-mailbox\mailbox.db` (console).
## Use from a Claude session
Drop this into your project's `.mcp.json` (one per session, different `X-Mailbox` values):
```json ```json
{ {
"mcpServers": { "mcpServers": {
"mailbox": { "mailbox": {
"type": "http", "type": "http",
"url": "http://127.0.0.1:47822/mcp", "url": "http://127.0.0.1:37849/mcp"
"headers": {
"X-Mailbox": "backend"
}
} }
} }
} }
``` ```
Four MCP tools are exposed: Optionally add a static identity (so your client doesn't need to pass `from` / `name` on every call):
| Tool | Purpose | ```json
"headers": { "X-Mailbox": "backend" }
```
### C. Build the .NET binary from source
The original .NET 8 implementation lives in `src/ClaudeMailbox/`. Wire-compatible with the npm build (same port, same `X-Mailbox` header, same MCP tool names, same SQLite schema).
```powershell
dotnet publish src/ClaudeMailbox -c Release -r win-x64 --self-contained -p:PublishSingleFile=true
```
Put the resulting `claude-mailbox.exe` on `PATH`. Windows-only `install-service` verbs (admin shell):
```
claude-mailbox install-service [--port 37849] [--bind 127.0.0.1] [--db-path <path>]
claude-mailbox uninstall-service [--purge]
```
---
## How identity works
Every Claude Code session gets a unique mailbox name derived from its UUID:
| Setup | Resulting mailbox name |
|---|---| |---|---|
| `mcp__mailbox__send(to, body)` | Send a message to another mailbox | | Default | `claude-<8-hex-of-session-id>` |
| `mcp__mailbox__check_inbox()` | Pull all pending messages for this mailbox (marks delivered) | | `CLAUDE_MAILBOX_NAME=backend` (in `.claude/settings.json` env) | `backend-<8-hex>` |
| `mcp__mailbox__peek_inbox()` | Non-consuming check — returns `{ pending, oldestAt }` | | Manual `.mcp.json` with `X-Mailbox: backend` header (no plugin) | `backend` (legacy mode) |
| `mcp__mailbox__list_mailboxes()` | Discover known mailboxes and who has mail for you |
The plugin's `SessionStart` hook prints the session's identity and the list of peers active in the last hour into the conversation context, so Claude knows who it is and who's around without needing to call any tools first.
---
## Autostart
```sh
claude-mailbox install-autostart # per-user, no admin
claude-mailbox install-autostart --service # Windows only: Windows Service (admin)
claude-mailbox status # Running | Stopped | NotInstalled
claude-mailbox uninstall-autostart [--purge]
```
| Platform | Default mechanism | `--service` mechanism |
|---|---|---|
| Windows | Scheduled Task at logon (no admin); falls back to HKCU Run-key if Group Policy blocks schtasks | Windows Service (admin, via `node-windows`) |
| macOS | launchd LaunchAgent in `~/Library/LaunchAgents/` | n/a |
| Linux | systemd `--user` unit in `~/.config/systemd/user/` | n/a |
---
## MCP tools
| Tool | Required args | Purpose |
|---|---|---|
| `mcp__mailbox__send` | `to`, `body`, `from` | Send a message. `from` falls back to X-Mailbox header. |
| `mcp__mailbox__check_inbox` | `name` | Pull all pending messages and mark delivered. Falls back to header. |
| `mcp__mailbox__peek_inbox` | `name` | Non-consuming `{ pending, oldestAt }`. Falls back to header. |
| `mcp__mailbox__list_mailboxes` | `name` | Discover known mailboxes + `pendingForYou`. Falls back to header. |
The plugin's SessionStart announcement tells Claude exactly which name to pass for the current session, so the args are filled in automatically.
### Suggested CLAUDE.md snippet for poll discipline ### Suggested CLAUDE.md snippet for poll discipline
@@ -120,41 +152,93 @@ after each subagent completes. If pending > 0, call mcp__mailbox__check_inbox
and treat the messages as input with priority over the current plan. and treat the messages as input with priority over the current plan.
``` ```
## CLI client mode ---
Any external process (scripts, UIs, hooks) can talk to a running daemon without needing MCP: ## CLI
Any external process — scripts, UIs, manual debugging — can talk to a running daemon directly:
``` ```
claude-mailbox send --to <mailbox> --from <mailbox> --body <text> [--url http://127.0.0.1:47822] claude-mailbox send --from <mailbox> --to <mailbox> --body <text>
claude-mailbox peek --name <mailbox> [--url ...] claude-mailbox peek --name <mailbox>
claude-mailbox check --name <mailbox> [--url ...] claude-mailbox check --name <mailbox> [--hook]
claude-mailbox list [--url ...] claude-mailbox list
claude-mailbox status
claude-mailbox session-announce # hook helper, reads stdin JSON
claude-mailbox install-hook --name <mailbox> [--user|--project]
claude-mailbox uninstall-hook [--user|--project]
``` ```
The CLI subcommands are thin HTTP clients against the `/v1/*` endpoints. All subcommands accept `--url <url>` to target a non-default daemon address.
---
## REST surface ## REST surface
| Method | Path | Requires `X-Mailbox` | Purpose | | Method | Path | `X-Mailbox` required | Purpose |
|---|---|---|---| |---|---|---|---|
| `GET` | `/health` | no | `{ status, version, dbPath }` | | `GET` | `/health` | no | `{ status, version, dbPath }` |
| `POST` | `/v1/send` | yes (sender) | `{ to, body }` | | `POST` | `/v1/send` | yes (sender) | body: `{ to, body }` |
| `GET` | `/v1/peek?name=<mailbox>` | no | read-only status | | `GET` | `/v1/peek?name=<mailbox>` | no | read-only status |
| `POST` | `/v1/check-inbox?name=<mailbox>` | yes (must match `name`) | consume inbox | | `POST` | `/v1/check-inbox?name=<mailbox>` | yes (must match `name`) | consume inbox |
| `GET` | `/v1/list` | no | list all mailboxes | | `GET` | `/v1/list` | optional (presence registers caller) | list all mailboxes |
---
## Config precedence
```
CLI flag > mailbox.json > built-in defaults
```
`mailbox.json` is searched at `~/.claude-mailbox/mailbox.json` (per-user), and on Windows additionally at `%ProgramData%\ClaudeMailbox\mailbox.json` (machine-wide, written by `--service` install). Override with `--config <path>`.
Defaults: port `37849`, bind `127.0.0.1`, database at `~/.claude-mailbox/mailbox.db`.
---
## Architecture
One long-running daemon binds HTTP on loopback, hosts the MCP server at `/mcp` and a small REST API at `/v1/*`, and persists state in a single SQLite file.
```
session-A session-B external sender
mailbox: claude-a8b3c1d2 mailbox: claude-d4e5f6a7 (CLI / UI / script)
| | |
| HTTP | |
+--------------+-----------------+--------------------------+
v
claude-mailbox serve (npm: Fastify; .NET: Kestrel)
/mcp MCP tools
/v1/* REST for non-MCP senders
/health
v
~/.claude-mailbox/mailbox.db (SQLite WAL)
```
---
## Development ## Development
``` ```sh
# Node port (the recommended runtime)
cd node
npm install
npm run build
npm test
# .NET 8 port (wire-compatible alternative)
dotnet build dotnet build
dotnet test tests/ClaudeMailbox.Tests/ClaudeMailbox.Tests.csproj dotnet test tests/ClaudeMailbox.Tests/ClaudeMailbox.Tests.csproj
dotnet run --project src/ClaudeMailbox -- serve dotnet run --project src/ClaudeMailbox -- serve
``` ```
Test suite covers end-to-end coordination, concurrent `check_inbox` race safety, and schema idempotency. The test suites cover end-to-end coordination, concurrent `check_inbox` race safety, schema idempotency, hook stdin parsing, session-id derivation, and settings-file patching.
---
## Scope ## Scope
- Loopback bind only (v1). Cross-machine coordination is a future extension — swap the middleware for token auth and change the bind address. - Loopback bind only (v1). Cross-machine coordination is a future extension — swap the middleware for token auth and change the bind address.
- No auth on loopback. Local filesystem permissions are the trust boundary. - No auth on loopback. Local filesystem permissions are the trust boundary.
- No message expiry or cleanup. Delivered messages stay as a timeline/audit log. - No message expiry. Delivered messages remain as an audit log.

View File

@@ -0,0 +1,29 @@
# Homebrew formula for ClaudeMailbox.
#
# Publish this file to your tap repo (e.g. kuns/homebrew-tap as
# Formula/claude-mailbox.rb), then on a Mac:
#
# brew tap kuns/tap https://git.kuns.dev/kuns/homebrew-tap.git
# brew install kuns/tap/claude-mailbox
#
# The formula thin-wraps the @kuns/claude-mailbox npm package: it relies on
# Homebrew's `node` formula and runs `npm install -g` into a private libexec,
# then symlinks the bin into Homebrew's prefix so the binary lands on PATH.
class ClaudeMailbox < Formula
desc "Standalone MCP mail server for parallel Claude session coordination"
homepage "https://git.kuns.dev/releases/ClaudeMailbox"
url "https://git.kuns.dev/api/packages/releases/npm/@kuns/claude-mailbox/-/@kuns/claude-mailbox-VERSION.tgz"
sha256 "REPLACE_WITH_SHA256_OF_THE_TARBALL"
license "MIT"
depends_on "node"
def install
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
assert_match "claude-mailbox", shell_output("#{bin}/claude-mailbox --version")
end
end

46
install.ps1 Normal file
View File

@@ -0,0 +1,46 @@
#Requires -Version 5.1
<#
.SYNOPSIS
Bootstrap installer for ClaudeMailbox on Windows.
.DESCRIPTION
Configures the @kuns scoped npm registry to point at the public Gitea
package registry, installs @kuns/claude-mailbox globally, and optionally
registers per-user autostart via Scheduled Task.
.PARAMETER NoAutostart
Skip the install-autostart step.
.PARAMETER Service
Install as a Windows Service (admin shell required) instead of a Scheduled Task.
.EXAMPLE
irm https://git.kuns.dev/releases/ClaudeMailbox/raw/branch/main/install.ps1 | iex
#>
[CmdletBinding()]
param(
[switch] $NoAutostart,
[switch] $Service
)
$ErrorActionPreference = "Stop"
if (-not (Get-Command npm -ErrorAction SilentlyContinue)) {
throw "Node.js / npm not found on PATH. Install Node 20+ from https://nodejs.org and retry."
}
Write-Host "Configuring @kuns scoped npm registry..." -ForegroundColor Cyan
npm config set "@kuns:registry" "https://git.kuns.dev/api/packages/releases/npm/"
Write-Host "Installing @kuns/claude-mailbox globally..." -ForegroundColor Cyan
npm install -g "@kuns/claude-mailbox"
if (-not $NoAutostart) {
$args = @("install-autostart")
if ($Service) { $args += "--service" }
Write-Host "Registering autostart..." -ForegroundColor Cyan
& claude-mailbox @args
}
Write-Host ""
Write-Host "ClaudeMailbox installed. Run 'claude-mailbox status' to verify." -ForegroundColor Green

28
install.sh Normal file
View File

@@ -0,0 +1,28 @@
#!/usr/bin/env sh
# Bootstrap installer for ClaudeMailbox on macOS / Linux.
#
# Usage:
# curl -fsSL https://git.kuns.dev/releases/ClaudeMailbox/raw/branch/main/install.sh | sh
#
# Env vars:
# NO_AUTOSTART=1 skip install-autostart
set -eu
if ! command -v npm >/dev/null 2>&1; then
echo "error: Node.js / npm not found on PATH. Install Node 20+ from https://nodejs.org and retry." >&2
exit 1
fi
echo "Configuring @kuns scoped npm registry..."
npm config set "@kuns:registry" "https://git.kuns.dev/api/packages/releases/npm/"
echo "Installing @kuns/claude-mailbox globally..."
npm install -g "@kuns/claude-mailbox"
if [ -z "${NO_AUTOSTART:-}" ]; then
echo "Registering autostart..."
claude-mailbox install-autostart
fi
echo ""
echo "ClaudeMailbox installed. Run 'claude-mailbox status' to verify."

5
node/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
node_modules
dist
*.log
.DS_Store
coverage

52
node/README.md Normal file
View File

@@ -0,0 +1,52 @@
# @kuns/claude-mailbox
Standalone MCP mail server that lets parallel Claude sessions coordinate with each other. TypeScript / Node port of the .NET `claude-mailbox` daemon — wire-compatible (same port, same `X-Mailbox` header, same MCP tool names, same SQLite schema).
## Install
One-time per machine:
```sh
npm config set @kuns:registry=https://git.kuns.dev/api/packages/releases/npm/
npm install -g @kuns/claude-mailbox
```
Then:
```sh
claude-mailbox install-autostart # registers per-OS autostart, no admin needed by default
```
See the [repository README](https://git.kuns.dev/releases/ClaudeMailbox/src/branch/main/README.md) for the full architecture, MCP tool reference, and `.mcp.json` snippet.
## Claude Code hook (auto-check inbox)
Register a `UserPromptSubmit` hook so Claude pulls pending mailbox messages before every prompt:
```sh
claude-mailbox install-hook --name alice # patches ~/.claude/settings.json
claude-mailbox install-hook --name alice --project # patches <cwd>/.claude/settings.json
claude-mailbox uninstall-hook # remove again
```
The hook is idempotent (running `install-hook` twice does nothing the second time) and only touches the `UserPromptSubmit` block — other hooks and settings are preserved.
Under the hood the hook runs `claude-mailbox check --name <mailbox> --hook`, which:
- prints unread messages in a Claude-friendly format,
- silently exits 0 if the inbox is empty or the daemon is unreachable (no context noise),
- marks the messages delivered so they aren't injected again next prompt.
Cost: one local HTTP round-trip plus Node coldstart per prompt (~100ms on Windows).
## Troubleshooting
`npm install` returns `401 Unauthorized`
: The Gitea registry usually serves the `releases` scope publicly, but if your instance requires auth you'll need a read token:
```sh
npm config set //git.kuns.dev/api/packages/releases/npm/:_authToken=<token>
```
`gyp ERR! find VS` on Windows during install
: `better-sqlite3` ships prebuilt binaries for current Node LTS versions. If yours isn't covered, npm falls back to building from source and needs the Visual Studio Build Tools. Either install them or pin to a Node version with a matching prebuild.

3756
node/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

56
node/package.json Normal file
View File

@@ -0,0 +1,56 @@
{
"name": "@kuns/claude-mailbox",
"version": "1.2.0",
"description": "Standalone MCP mail server that lets parallel Claude sessions coordinate with each other.",
"type": "module",
"bin": {
"claude-mailbox": "dist/cli.js"
},
"files": [
"dist",
"README.md",
"LICENSE"
],
"scripts": {
"build": "tsc -p tsconfig.json",
"pretest": "npm run build",
"test": "vitest run",
"test:watch": "vitest",
"start": "node dist/cli.js serve",
"prepack": "npm run build"
},
"engines": {
"node": ">=20"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"better-sqlite3": "^11.3.0",
"commander": "^12.1.0",
"fastify": "^5.0.0",
"zod": "^3.25.0"
},
"optionalDependencies": {
"node-windows": "^1.0.0-beta.8"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.11",
"@types/node": "^22.7.4",
"typescript": "^5.6.2",
"vitest": "^2.1.1"
},
"keywords": [
"mcp",
"model-context-protocol",
"claude",
"mailbox",
"ipc"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "https://git.kuns.dev/releases/ClaudeMailbox.git"
},
"publishConfig": {
"registry": "https://git.kuns.dev/api/packages/releases/npm/"
}
}

View File

@@ -0,0 +1,121 @@
import { existsSync, mkdirSync, writeFileSync, unlinkSync, rmSync, readFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { homedir } from "node:os";
import { run, cliEntry, type AutostartManager, type AutostartInstallOpts } from "./index.js";
import { userConfigPath } from "../config.js";
const LABEL = "dev.kuns.claude-mailbox";
function plistPath(): string {
return join(homedir(), "Library", "LaunchAgents", `${LABEL}.plist`);
}
function logDir(): string {
return join(homedir(), "Library", "Logs", "ClaudeMailbox");
}
function ensureConfigSeeded(opts: AutostartInstallOpts): string {
const path = userConfigPath();
if (!existsSync(path)) {
mkdirSync(dirname(path), { recursive: true });
const seed: Record<string, unknown> = {};
if (opts.port !== undefined) seed.port = opts.port;
if (opts.bind !== undefined) seed.bind = opts.bind;
if (opts.dbPath !== undefined) seed.dbPath = opts.dbPath;
writeFileSync(path, JSON.stringify(seed, null, 2) + "\n", "utf8");
}
return path;
}
function escapeXml(s: string): string {
return s
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
function buildPlist(node: string, script: string, configPath: string): string {
mkdirSync(logDir(), { recursive: true });
const argv = [node, script, "serve", "--config", configPath];
const argsXml = argv
.map((a) => ` <string>${escapeXml(a)}</string>`)
.join("\n");
const stdout = join(logDir(), "stdout.log");
const stderr = join(logDir(), "stderr.log");
return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>${LABEL}</string>
<key>ProgramArguments</key>
<array>
${argsXml}
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>${escapeXml(stdout)}</string>
<key>StandardErrorPath</key>
<string>${escapeXml(stderr)}</string>
</dict>
</plist>
`;
}
export function darwinManager(): AutostartManager {
return {
mode: "default",
async install(opts) {
const configPath = ensureConfigSeeded(opts);
const { node, script } = cliEntry();
const plist = buildPlist(node, script, configPath);
const path = plistPath();
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, plist, "utf8");
run("launchctl", ["unload", path]);
const r = run("launchctl", ["load", "-w", path]);
if (r.status !== 0) {
throw new Error(`launchctl load failed: ${r.stderr || r.stdout}`);
}
},
async uninstall(purge) {
const path = plistPath();
if (existsSync(path)) {
run("launchctl", ["unload", path]);
unlinkSync(path);
}
if (purge) {
const cfg = userConfigPath();
if (existsSync(cfg)) {
try {
const parsed = JSON.parse(readFileSync(cfg, "utf8")) as { dbPath?: string };
if (parsed.dbPath && existsSync(parsed.dbPath)) {
rmSync(parsed.dbPath, { force: true });
}
} catch {
// ignore
}
unlinkSync(cfg);
}
}
},
async start() {
const r = run("launchctl", ["start", LABEL]);
if (r.status !== 0) throw new Error(`launchctl start failed: ${r.stderr || r.stdout}`);
},
async stop() {
run("launchctl", ["stop", LABEL]);
},
async status() {
if (!existsSync(plistPath())) return "NotInstalled";
const r = run("launchctl", ["list", LABEL]);
if (r.status !== 0) return "Stopped";
const pidMatch = r.stdout.match(/"PID"\s*=\s*(\d+)/);
return pidMatch ? "Running" : "Stopped";
},
};
}

View File

@@ -0,0 +1,59 @@
import { spawnSync, type SpawnSyncOptionsWithStringEncoding } from "node:child_process";
import { fileURLToPath } from "node:url";
import { dirname, resolve } from "node:path";
export interface AutostartInstallOpts {
port?: number;
bind?: string;
dbPath?: string;
}
export interface AutostartManager {
readonly mode: "default" | "service";
install(opts: AutostartInstallOpts): Promise<void>;
uninstall(purge: boolean): Promise<void>;
start(): Promise<void>;
stop(): Promise<void>;
status(): Promise<"Running" | "Stopped" | "NotInstalled">;
}
export interface RunResult {
status: number;
stdout: string;
stderr: string;
}
export function run(file: string, args: string[]): RunResult {
const opts: SpawnSyncOptionsWithStringEncoding = {
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
shell: false,
};
const r = spawnSync(file, args, opts);
return {
status: r.status ?? -1,
stdout: typeof r.stdout === "string" ? r.stdout : "",
stderr: typeof r.stderr === "string" ? r.stderr : "",
};
}
export function cliEntry(): { node: string; script: string } {
const here = dirname(fileURLToPath(import.meta.url));
return {
node: process.execPath,
script: resolve(here, "..", "cli.js"),
};
}
export async function autostartManager(mode: "default" | "service" = "default"): Promise<AutostartManager> {
if (process.platform === "win32") {
const mod = await import("./windows.js");
return mod.windowsManager(mode);
}
if (process.platform === "darwin") {
const mod = await import("./darwin.js");
return mod.darwinManager();
}
const mod = await import("./linux.js");
return mod.linuxManager();
}

104
node/src/autostart/linux.ts Normal file
View File

@@ -0,0 +1,104 @@
import { existsSync, mkdirSync, writeFileSync, unlinkSync, rmSync, readFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { homedir } from "node:os";
import { run, cliEntry, type AutostartManager, type AutostartInstallOpts } from "./index.js";
import { userConfigPath } from "../config.js";
const UNIT_NAME = "claude-mailbox.service";
function unitPath(): string {
const xdg = process.env["XDG_CONFIG_HOME"] || join(homedir(), ".config");
return join(xdg, "systemd", "user", UNIT_NAME);
}
function ensureConfigSeeded(opts: AutostartInstallOpts): string {
const path = userConfigPath();
if (!existsSync(path)) {
mkdirSync(dirname(path), { recursive: true });
const seed: Record<string, unknown> = {};
if (opts.port !== undefined) seed.port = opts.port;
if (opts.bind !== undefined) seed.bind = opts.bind;
if (opts.dbPath !== undefined) seed.dbPath = opts.dbPath;
writeFileSync(path, JSON.stringify(seed, null, 2) + "\n", "utf8");
}
return path;
}
function shellQuote(s: string): string {
return `'${s.replace(/'/g, `'\\''`)}'`;
}
function buildUnit(node: string, script: string, configPath: string): string {
const exec = `${shellQuote(node)} ${shellQuote(script)} serve --config ${shellQuote(configPath)}`;
return `[Unit]
Description=ClaudeMailbox MCP mail daemon
After=network.target
[Service]
Type=simple
ExecStart=${exec}
Restart=on-failure
RestartSec=2
[Install]
WantedBy=default.target
`;
}
function systemctl(args: string[]): { status: number; stdout: string; stderr: string } {
return run("systemctl", ["--user", ...args]);
}
export function linuxManager(): AutostartManager {
return {
mode: "default",
async install(opts) {
const configPath = ensureConfigSeeded(opts);
const { node, script } = cliEntry();
const path = unitPath();
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, buildUnit(node, script, configPath), "utf8");
const reload = systemctl(["daemon-reload"]);
if (reload.status !== 0) {
throw new Error(`systemctl daemon-reload failed: ${reload.stderr || reload.stdout}`);
}
const enable = systemctl(["enable", "--now", UNIT_NAME]);
if (enable.status !== 0) {
throw new Error(`systemctl enable --now failed: ${enable.stderr || enable.stdout}`);
}
},
async uninstall(purge) {
systemctl(["disable", "--now", UNIT_NAME]);
const path = unitPath();
if (existsSync(path)) unlinkSync(path);
systemctl(["daemon-reload"]);
if (purge) {
const cfg = userConfigPath();
if (existsSync(cfg)) {
try {
const parsed = JSON.parse(readFileSync(cfg, "utf8")) as { dbPath?: string };
if (parsed.dbPath && existsSync(parsed.dbPath)) {
rmSync(parsed.dbPath, { force: true });
}
} catch {
// ignore
}
unlinkSync(cfg);
}
}
},
async start() {
const r = systemctl(["start", UNIT_NAME]);
if (r.status !== 0) throw new Error(`systemctl start failed: ${r.stderr || r.stdout}`);
},
async stop() {
systemctl(["stop", UNIT_NAME]);
},
async status() {
if (!existsSync(unitPath())) return "NotInstalled";
const r = systemctl(["is-active", UNIT_NAME]);
if (r.stdout.trim() === "active") return "Running";
return "Stopped";
},
};
}

View File

@@ -0,0 +1,353 @@
import { existsSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs";
import { dirname, join } from "node:path";
import { run, cliEntry, type AutostartManager, type AutostartInstallOpts } from "./index.js";
import { userConfigPath } from "../config.js";
function markerPath(): string {
return join(dirname(userConfigPath()), MARKER_FILE);
}
function readActiveMode(): "task" | "run-key" | null {
const path = markerPath();
if (!existsSync(path)) return null;
const raw = readFileSync(path, "utf8").trim();
if (raw === "task" || raw === "run-key") return raw;
return null;
}
function writeActiveMode(mode: "task" | "run-key"): void {
const path = markerPath();
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, mode, "utf8");
}
function clearActiveMode(): void {
const path = markerPath();
if (existsSync(path)) rmSync(path, { force: true });
}
function isAccessDenied(stderr: string): boolean {
return /access is denied|0x80070005/i.test(stderr);
}
const TASK_NAME = "ClaudeMailbox";
const SERVICE_NAME = "ClaudeMailbox";
const RUN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
const RUN_VALUE = "ClaudeMailbox";
const MARKER_FILE = "autostart-mode";
function ensureConfigSeeded(opts: AutostartInstallOpts): string {
const path = userConfigPath();
if (!existsSync(path)) {
mkdirSync(join(path, ".."), { recursive: true });
const seed: Record<string, unknown> = {};
if (opts.port !== undefined) seed.port = opts.port;
if (opts.bind !== undefined) seed.bind = opts.bind;
if (opts.dbPath !== undefined) seed.dbPath = opts.dbPath;
writeFileSync(path, JSON.stringify(seed, null, 2) + "\n", "utf8");
}
return path;
}
function buildServeCommand(): { node: string; script: string; configPath: string } {
const { node, script } = cliEntry();
return { node, script, configPath: userConfigPath() };
}
function buildServeCommandString(configPath: string): string {
const { node, script } = buildServeCommand();
return `"${node}" "${script}" serve --config "${configPath}"`;
}
function tryScheduledTaskInstall(opts: AutostartInstallOpts): { ok: boolean; stderr: string } {
const configPath = ensureConfigSeeded(opts);
const tr = buildServeCommandString(configPath);
const r = run("schtasks.exe", [
"/Create",
"/SC",
"ONLOGON",
"/TN",
TASK_NAME,
"/TR",
tr,
"/RL",
"LIMITED",
"/F",
]);
if (r.status !== 0) return { ok: false, stderr: r.stderr || r.stdout };
run("schtasks.exe", ["/Run", "/TN", TASK_NAME]);
return { ok: true, stderr: "" };
}
function runKeyInstall(opts: AutostartInstallOpts): void {
const configPath = ensureConfigSeeded(opts);
const cmd = buildServeCommandString(configPath);
const r = run("reg.exe", [
"add",
RUN_KEY,
"/v",
RUN_VALUE,
"/t",
"REG_SZ",
"/d",
cmd,
"/f",
]);
if (r.status !== 0) {
throw new Error(`reg add (HKCU Run) failed (exit ${r.status}): ${r.stderr || r.stdout}`);
}
spawnRunKeyDaemon(configPath);
}
function spawnRunKeyDaemon(configPath: string): void {
if (runKeyDaemonRunning()) return;
const { node, script } = buildServeCommand();
const ps = `Start-Process -WindowStyle Hidden -FilePath "${node}" -ArgumentList @('"${script}"','serve','--config','"${configPath}"')`;
run("powershell.exe", ["-NoProfile", "-Command", ps]);
}
function runKeyDaemonRunning(): boolean {
const ps = `Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object { $_.CommandLine -like '*claude-mailbox*serve*' } | Select-Object -First 1 -ExpandProperty ProcessId`;
const r = run("powershell.exe", ["-NoProfile", "-Command", ps]);
return r.status === 0 && r.stdout.trim().length > 0;
}
function killRunKeyDaemon(): void {
const ps = `Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object { $_.CommandLine -like '*claude-mailbox*serve*' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }`;
run("powershell.exe", ["-NoProfile", "-Command", ps]);
}
function runKeyUninstall(): void {
const r = run("reg.exe", ["delete", RUN_KEY, "/v", RUN_VALUE, "/f"]);
if (r.status !== 0 && !/unable to find/i.test(r.stderr)) {
throw new Error(`reg delete failed (exit ${r.status}): ${r.stderr || r.stdout}`);
}
killRunKeyDaemon();
}
function scheduledTaskInstall(opts: AutostartInstallOpts): void {
const attempt = tryScheduledTaskInstall(opts);
if (attempt.ok) {
writeActiveMode("task");
return;
}
if (isAccessDenied(attempt.stderr)) {
console.warn(
"schtasks /Create denied by Windows policy — falling back to HKCU Run-key autostart (per-user, no admin).",
);
runKeyInstall(opts);
writeActiveMode("run-key");
return;
}
throw new Error(`schtasks /Create failed: ${attempt.stderr}`);
}
function scheduledTaskUninstall(purge: boolean): void {
const mode = readActiveMode();
if (mode === "run-key") {
runKeyUninstall();
clearActiveMode();
if (purge) purgeData();
return;
}
// Default to task uninstall, also clean up Run-key in case of mixed state
run("schtasks.exe", ["/End", "/TN", TASK_NAME]);
const r = run("schtasks.exe", ["/Delete", "/TN", TASK_NAME, "/F"]);
if (r.status !== 0 && !/cannot find/i.test(r.stderr) && !/does not exist/i.test(r.stderr)) {
// Fall through — try Run-key cleanup anyway
}
// Best-effort Run-key cleanup
run("reg.exe", ["delete", RUN_KEY, "/v", RUN_VALUE, "/f"]);
killRunKeyDaemon();
clearActiveMode();
if (purge) purgeData();
}
function scheduledTaskStatus(): "Running" | "Stopped" | "NotInstalled" {
const mode = readActiveMode();
if (mode === "run-key") {
const r = run("reg.exe", ["query", RUN_KEY, "/v", RUN_VALUE]);
if (r.status !== 0) return "NotInstalled";
return runKeyDaemonRunning() ? "Running" : "Stopped";
}
const r = run("schtasks.exe", ["/Query", "/TN", TASK_NAME, "/FO", "LIST", "/V"]);
if (r.status !== 0) {
if (/cannot find/i.test(r.stderr) || /does not exist/i.test(r.stderr)) {
// Maybe a Run-key install happened without a marker (legacy / manual). Check reg.
const reg = run("reg.exe", ["query", RUN_KEY, "/v", RUN_VALUE]);
if (reg.status === 0) return runKeyDaemonRunning() ? "Running" : "Stopped";
return "NotInstalled";
}
return "Stopped";
}
if (/Status:\s*Running/i.test(r.stdout)) return "Running";
return "Stopped";
}
function scheduledTaskRun(): void {
const mode = readActiveMode();
if (mode === "run-key") {
const cfgPath = userConfigPath();
spawnRunKeyDaemon(cfgPath);
return;
}
const r = run("schtasks.exe", ["/Run", "/TN", TASK_NAME]);
if (r.status !== 0) throw new Error(`schtasks /Run failed: ${r.stderr || r.stdout}`);
}
function scheduledTaskEnd(): void {
const mode = readActiveMode();
if (mode === "run-key") {
killRunKeyDaemon();
return;
}
run("schtasks.exe", ["/End", "/TN", TASK_NAME]);
}
interface NodeWindowsService {
on(event: "install" | "uninstall" | "alreadyinstalled" | "start" | "stop", cb: () => void): void;
install(): void;
uninstall(): void;
start(): void;
stop(): void;
exists?: boolean;
}
interface NodeWindowsModule {
Service: new (opts: {
name: string;
description?: string;
script: string;
nodeOptions?: string[];
workingDirectory?: string;
}) => NodeWindowsService;
}
async function loadNodeWindows(): Promise<NodeWindowsModule> {
try {
return (await import("node-windows")) as unknown as NodeWindowsModule;
} catch (err) {
throw new Error(
"node-windows is not installed. Install it with `npm i -g node-windows` or use the default Scheduled Task autostart instead.",
);
}
}
function isAdministrator(): boolean {
const r = run("net.exe", ["session"]);
return r.status === 0;
}
async function serviceInstall(opts: AutostartInstallOpts): Promise<void> {
if (!isAdministrator()) {
throw new Error("install-autostart --service requires an Administrator shell.");
}
ensureConfigSeeded(opts);
const { script, configPath } = buildServeCommand();
const nw = await loadNodeWindows();
await new Promise<void>((resolveFn, rejectFn) => {
const svc = new nw.Service({
name: SERVICE_NAME,
description: "ClaudeMailbox MCP mail daemon for parallel Claude session coordination.",
script,
nodeOptions: [],
});
svc.on("install", () => {
svc.start();
resolveFn();
});
svc.on("alreadyinstalled", () => resolveFn());
try {
svc.install();
} catch (e) {
rejectFn(e);
}
void configPath;
});
}
async function serviceUninstall(purge: boolean): Promise<void> {
if (!isAdministrator()) {
throw new Error("uninstall-autostart --service requires an Administrator shell.");
}
const { script } = buildServeCommand();
const nw = await loadNodeWindows();
await new Promise<void>((resolveFn, rejectFn) => {
const svc = new nw.Service({ name: SERVICE_NAME, script });
svc.on("uninstall", () => resolveFn());
try {
svc.uninstall();
} catch (e) {
rejectFn(e);
}
});
if (purge) purgeData();
}
function serviceStatus(): "Running" | "Stopped" | "NotInstalled" {
const r = run("sc.exe", ["query", SERVICE_NAME]);
if (r.status !== 0) return "NotInstalled";
if (/STATE\s*:\s*\d+\s+RUNNING/i.test(r.stdout)) return "Running";
return "Stopped";
}
function serviceStart(): void {
const r = run("sc.exe", ["start", SERVICE_NAME]);
if (r.status !== 0) throw new Error(`sc start failed: ${r.stderr || r.stdout}`);
}
function serviceStop(): void {
const r = run("sc.exe", ["stop", SERVICE_NAME]);
if (r.status !== 0 && !/has not been started/i.test(r.stdout)) {
throw new Error(`sc stop failed: ${r.stderr || r.stdout}`);
}
}
function purgeData(): void {
const cfg = userConfigPath();
if (existsSync(cfg)) {
try {
const parsed = JSON.parse(readFileSync(cfg, "utf8")) as { dbPath?: string };
void parsed;
} catch {
// ignore
}
}
}
export function windowsManager(mode: "default" | "service"): AutostartManager {
if (mode === "service") {
return {
mode,
install: serviceInstall,
uninstall: serviceUninstall,
async start() {
serviceStart();
},
async stop() {
serviceStop();
},
async status() {
return serviceStatus();
},
};
}
return {
mode,
async install(opts) {
scheduledTaskInstall(opts);
},
async uninstall(purge) {
scheduledTaskUninstall(purge);
},
async start() {
scheduledTaskRun();
},
async stop() {
scheduledTaskEnd();
},
async status() {
return scheduledTaskStatus();
},
};
}

433
node/src/cli.ts Normal file
View File

@@ -0,0 +1,433 @@
#!/usr/bin/env node
import { Command } from "commander";
import { existsSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { resolveConfig, baseUrl, DEFAULT_PORT } from "./config.js";
import { startServer } from "./server.js";
import { autostartManager } from "./autostart/index.js";
import { runStdioMcp } from "./mcp-stdio.js";
import {
applyInstall,
applyUninstall,
buildHookCommand,
deriveSessionName,
formatActivePeerList,
formatMessagesForHook,
parseHookStdin,
readSettings,
readStdinIfPiped,
settingsPathFor,
writeSettings,
type HookMessage,
type HookScope,
type PeerEntry,
} from "./hook.js";
function readVersion(): string {
try {
const here = dirname(fileURLToPath(import.meta.url));
const pkg = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8")) as {
version?: string;
};
return pkg.version ?? "unknown";
} catch {
return "unknown";
}
}
const HARDCODED_DEFAULT_URL = `http://127.0.0.1:${DEFAULT_PORT}`;
const ENV_URL = (process.env["CLAUDE_MAILBOX_URL"] ?? "").trim();
const DEFAULT_URL = ENV_URL || HARDCODED_DEFAULT_URL;
async function callJson(
method: string,
url: string,
init: { headers?: Record<string, string>; body?: unknown } = {},
): Promise<unknown> {
const headers: Record<string, string> = { Accept: "application/json", ...(init.headers ?? {}) };
let body: string | undefined;
if (init.body !== undefined) {
headers["Content-Type"] = "application/json";
body = JSON.stringify(init.body);
}
const res = await fetch(url, { method, headers, body });
const text = await res.text();
if (!res.ok) {
throw new Error(`${method} ${url}${res.status}: ${text}`);
}
return text.length ? JSON.parse(text) : null;
}
function reportClientError(err: unknown, url: string): never {
const msg = err instanceof Error ? err.message : String(err);
console.error(`Could not reach daemon at ${url}: ${msg}`);
console.error("Is 'claude-mailbox serve' running?");
process.exit(2);
}
const program = new Command();
program
.name("claude-mailbox")
.description("MCP mail server that lets parallel Claude sessions coordinate.")
.version(readVersion(), "-V, --version");
program
.command("serve")
.description("Run the daemon in the foreground.")
.option("--port <port>", "Port to listen on", (v) => parseInt(v, 10))
.option("--bind <address>", "Bind address")
.option("--db-path <path>", "SQLite database path")
.option("--config <path>", "Path to mailbox.json")
.action(async (opts: { port?: number; bind?: string; dbPath?: string; config?: string }) => {
const cfg = resolveConfig(opts);
try {
const { app } = await startServer(cfg);
app.log.info(`ClaudeMailbox listening on ${baseUrl(cfg)} (db: ${cfg.dbPath})`);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
if (/EADDRINUSE|already in use/i.test(msg)) {
console.error(
`Port ${cfg.port} is already in use. Another claude-mailbox instance may be running.`,
);
process.exit(3);
}
console.error(msg);
process.exit(1);
}
});
program
.command("send")
.description("Send a message via REST.")
.requiredOption("--to <name>", "Recipient mailbox")
.requiredOption("--from <name>", "Sender mailbox (X-Mailbox header)")
.requiredOption("--body <text>", "Message body")
.option("--url <url>", "Daemon base URL", DEFAULT_URL)
.action(async (opts: { to: string; from: string; body: string; url: string }) => {
try {
const out = await callJson("POST", `${opts.url}/v1/send`, {
headers: { "X-Mailbox": opts.from },
body: { to: opts.to, body: opts.body },
});
console.log(JSON.stringify(out, null, 2));
} catch (err) {
reportClientError(err, opts.url);
}
});
program
.command("peek")
.description("Non-consuming inbox status.")
.requiredOption("--name <name>", "Mailbox name")
.option("--url <url>", "Daemon base URL", DEFAULT_URL)
.action(async (opts: { name: string; url: string }) => {
try {
const out = await callJson(
"GET",
`${opts.url}/v1/peek?name=${encodeURIComponent(opts.name)}`,
);
console.log(JSON.stringify(out, null, 2));
} catch (err) {
reportClientError(err, opts.url);
}
});
function resolveHookMailboxName(explicit: string | undefined): string | null {
if (explicit && explicit.trim()) return explicit.trim();
const stdin = parseHookStdin(readStdinIfPiped());
const sid = stdin?.session_id?.trim();
if (sid) {
const base = (process.env["CLAUDE_MAILBOX_NAME"] ?? "").trim() || null;
return deriveSessionName(sid, base);
}
const envName = (process.env["CLAUDE_MAILBOX_NAME"] ?? "").trim();
return envName || null;
}
program
.command("check")
.description(
"Pull pending messages and mark delivered. In --hook mode the name is auto-derived from the SessionStart/UserPromptSubmit stdin (session_id), optionally flavored by $CLAUDE_MAILBOX_NAME.",
)
.option(
"--name <name>",
"Explicit mailbox name. Overrides hook stdin and $CLAUDE_MAILBOX_NAME.",
)
.option("--url <url>", "Daemon base URL", DEFAULT_URL)
.option(
"--hook",
"Hook mode: human-readable output, silent when no mailbox configured or daemon unreachable. Emits a one-line setup hint when name resolves but daemon is unreachable.",
)
.action(async (opts: { name?: string; url: string; hook?: boolean }) => {
const name = opts.hook
? resolveHookMailboxName(opts.name)
: (opts.name ?? process.env["CLAUDE_MAILBOX_NAME"] ?? "").trim() || null;
if (!name) {
if (opts.hook) return;
console.error("Missing --name (or set CLAUDE_MAILBOX_NAME).");
process.exit(1);
}
try {
const out = await callJson(
"POST",
`${opts.url}/v1/check-inbox?name=${encodeURIComponent(name)}`,
{ headers: { "X-Mailbox": name } },
);
if (opts.hook) {
const messages = (Array.isArray(out) ? out : []) as HookMessage[];
const text = formatMessagesForHook(name, messages);
if (text) process.stdout.write(text);
return;
}
console.log(JSON.stringify(out, null, 2));
} catch (err) {
if (opts.hook) {
const msg = err instanceof Error ? err.message : String(err);
if (/ECONNREFUSED|fetch failed|ENOTFOUND|connect/i.test(msg)) {
process.stdout.write(
`[Claude-Mailbox] Daemon not reachable at ${opts.url}. Run \`claude-mailbox install-autostart\` (one-time) or \`claude-mailbox start\`.\n`,
);
}
return;
}
reportClientError(err, opts.url);
}
});
program
.command("session-announce")
.description(
"SessionStart-hook helper: derives the session's mailbox name from stdin session_id, registers it with the daemon, and announces the identity + currently active peers to context.",
)
.option("--url <url>", "Daemon base URL", DEFAULT_URL)
.option(
"--peer-window-minutes <minutes>",
"Only show peers seen within this many minutes (default 60)",
(v) => parseInt(v, 10),
60,
)
.option(
"--max-peers <n>",
"Maximum number of peers to list (default 10)",
(v) => parseInt(v, 10),
10,
)
.action(async (opts: { url: string; peerWindowMinutes: number; maxPeers: number }) => {
const stdin = parseHookStdin(readStdinIfPiped());
const sid = stdin?.session_id?.trim();
if (!sid) return;
const base = (process.env["CLAUDE_MAILBOX_NAME"] ?? "").trim() || null;
const name = deriveSessionName(sid, base);
const lines = [
`Claude-Mailbox: your mailbox name this session is \`${name}\`.`,
`When using mcp__mailbox__* tools, ALWAYS pass this name explicitly:`,
` - mcp__mailbox__send: from="${name}"`,
` - mcp__mailbox__check_inbox: name="${name}"`,
` - mcp__mailbox__peek_inbox: name="${name}"`,
` - mcp__mailbox__list_mailboxes: name="${name}"`,
`Peers reach you with: mcp__mailbox__send(from="<their-name>", to="${name}", body="...")`,
];
try {
const out = await callJson("GET", `${opts.url}/v1/list`, {
headers: { "X-Mailbox": name },
});
const all = (Array.isArray(out) ? out : []) as PeerEntry[];
lines.push(
"",
...formatActivePeerList(all, name, {
windowMinutes: opts.peerWindowMinutes,
maxPeers: opts.maxPeers,
}),
);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
if (/ECONNREFUSED|fetch failed|ENOTFOUND|connect/i.test(msg)) {
lines.push(
"",
`[Claude-Mailbox] Daemon not reachable at ${opts.url}. Run \`claude-mailbox install-autostart\` (one-time) or \`claude-mailbox start\`.`,
);
}
}
lines.push("");
process.stdout.write(lines.join("\n"));
});
program
.command("list")
.description("List known mailboxes.")
.option("--url <url>", "Daemon base URL", DEFAULT_URL)
.action(async (opts: { url: string }) => {
try {
const out = await callJson("GET", `${opts.url}/v1/list`);
console.log(JSON.stringify(out, null, 2));
} catch (err) {
reportClientError(err, opts.url);
}
});
program
.command("mcp-stdio")
.description(
"Run a stdio MCP server that proxies tool calls to the local daemon's REST API. The daemon URL comes from $CLAUDE_MAILBOX_URL (default http://127.0.0.1:37849). Used by the Claude Code plugin's .mcp.json so the URL is configurable per machine without env-substitution in the URL field.",
)
.action(async () => {
try {
await runStdioMcp();
} catch (err) {
console.error(err instanceof Error ? err.message : String(err));
process.exit(1);
}
});
program
.command("install-hook")
.description(
"Install a Claude Code UserPromptSubmit hook that checks the mailbox on every prompt. Idempotent.",
)
.requiredOption("--name <name>", "Mailbox name to check")
.option("--user", "Patch ~/.claude/settings.json (default)")
.option("--project", "Patch <cwd>/.claude/settings.json")
.option("--url <url>", "Daemon base URL to embed in the hook command")
.action(async (opts: { name: string; user?: boolean; project?: boolean; url?: string }) => {
if (opts.user && opts.project) {
console.error("Pick either --user or --project, not both.");
process.exit(1);
}
const scope: HookScope = opts.project ? "project" : "user";
const path = settingsPathFor(scope);
const settings = readSettings(path);
const command = buildHookCommand(opts.name, opts.url);
const result = applyInstall(settings, command);
if (result.changed) {
writeSettings(path, settings);
console.log(`Hook installed in ${path}`);
console.log(`Command: ${command}`);
} else {
console.log(`Hook already present in ${path}; nothing to do.`);
}
});
program
.command("uninstall-hook")
.description("Remove the claude-mailbox UserPromptSubmit hook from Claude Code settings.")
.option("--user", "Patch ~/.claude/settings.json (default)")
.option("--project", "Patch <cwd>/.claude/settings.json")
.action(async (opts: { user?: boolean; project?: boolean }) => {
if (opts.user && opts.project) {
console.error("Pick either --user or --project, not both.");
process.exit(1);
}
const scope: HookScope = opts.project ? "project" : "user";
const path = settingsPathFor(scope);
if (!existsSync(path)) {
console.log(`No settings file at ${path}; nothing to remove.`);
return;
}
const settings = readSettings(path);
const result = applyUninstall(settings);
if (result.changed) {
writeSettings(path, settings);
console.log(`Hook removed from ${path}`);
} else {
console.log(`No claude-mailbox hook found in ${path}; nothing to remove.`);
}
});
program
.command("install-autostart")
.description(
"Register autostart for the current OS (Scheduled Task / launchd / systemd-user). Use --service on Windows for a Windows Service (admin).",
)
.option("--service", "Windows: install as a Windows Service (requires admin) instead of a Scheduled Task")
.option("--port <port>", "Port to listen on", (v) => parseInt(v, 10))
.option("--bind <address>", "Bind address")
.option("--db-path <path>", "SQLite database path")
.option(
"--skip-port-check",
"Skip the pre-install probe for a foreign occupant on the daemon's port",
)
.action(
async (opts: {
service?: boolean;
port?: number;
bind?: string;
dbPath?: string;
skipPortCheck?: boolean;
}) => {
if (!opts.skipPortCheck) {
const cfg = resolveConfig({ port: opts.port, bind: opts.bind, dbPath: opts.dbPath });
const probeUrl = `http://${cfg.bind}:${cfg.port}/health`;
try {
const res = await fetch(probeUrl, { headers: { Accept: "application/json" } });
const text = await res.text();
let parsed: { status?: string; version?: string } | null = null;
try {
parsed = text.length ? (JSON.parse(text) as { status?: string; version?: string }) : null;
} catch {
parsed = null;
}
if (res.ok && parsed?.status === "ok" && parsed.version) {
console.log(
`Port ${cfg.port} already serves a claude-mailbox daemon (version ${parsed.version}). Autostart will manage that one.`,
);
} else {
console.error(
`Port ${cfg.port} is held by a non-claude-mailbox service (status ${res.status}). Pick a free port via \`--port <n>\` or write {"port": <n>} to ~/.claude-mailbox/mailbox.json. Use --skip-port-check to bypass.`,
);
process.exit(4);
}
} catch {
// Connection refused or similar — port is free, proceed.
}
}
const mgr = await autostartManager(opts.service ? "service" : "default");
await mgr.install({ port: opts.port, bind: opts.bind, dbPath: opts.dbPath });
console.log("Autostart installed.");
},
);
program
.command("uninstall-autostart")
.description("Remove autostart for the current OS.")
.option("--service", "Windows: uninstall the Windows Service variant")
.option("--purge", "Also delete database and config")
.action(async (opts: { service?: boolean; purge?: boolean }) => {
const mgr = await autostartManager(opts.service ? "service" : "default");
await mgr.uninstall(!!opts.purge);
console.log("Autostart removed.");
});
program
.command("start")
.description("Start the autostart-managed daemon.")
.option("--service", "Windows: target the Windows Service variant")
.action(async (opts: { service?: boolean }) => {
const mgr = await autostartManager(opts.service ? "service" : "default");
await mgr.start();
});
program
.command("stop")
.description("Stop the autostart-managed daemon.")
.option("--service", "Windows: target the Windows Service variant")
.action(async (opts: { service?: boolean }) => {
const mgr = await autostartManager(opts.service ? "service" : "default");
await mgr.stop();
});
program
.command("status")
.description("Print autostart status (Running | Stopped | NotInstalled).")
.option("--service", "Windows: target the Windows Service variant")
.action(async (opts: { service?: boolean }) => {
const mgr = await autostartManager(opts.service ? "service" : "default");
console.log(await mgr.status());
});
program.parseAsync(process.argv).catch((err) => {
console.error(err instanceof Error ? err.message : String(err));
process.exit(1);
});

91
node/src/config.ts Normal file
View File

@@ -0,0 +1,91 @@
import { existsSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
export const DEFAULT_PORT = 37849;
export const DEFAULT_BIND = "127.0.0.1";
export interface FileConfig {
port?: number;
bind?: string;
dbPath?: string;
}
export interface DaemonConfig {
port: number;
bind: string;
dbPath: string;
}
export function defaultDbPath(): string {
return join(homedir(), ".claude-mailbox", "mailbox.db");
}
export function userConfigPath(): string {
return join(homedir(), ".claude-mailbox", "mailbox.json");
}
export function machineConfigPath(): string | null {
if (process.platform === "win32") {
const programData = process.env["ProgramData"] ?? "C:\\ProgramData";
return join(programData, "ClaudeMailbox", "mailbox.json");
}
if (process.platform === "darwin") {
return "/Library/Application Support/ClaudeMailbox/mailbox.json";
}
return "/etc/claude-mailbox/mailbox.json";
}
function expandPath(p: string): string {
let out = p;
if (out.startsWith("~")) out = join(homedir(), out.slice(1));
out = out.replace(/%([^%]+)%/g, (_, name) => process.env[name] ?? "");
out = out.replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g, (_, name) => process.env[name] ?? "");
return resolve(out);
}
export function loadFileConfig(explicitPath?: string): FileConfig {
const candidates: string[] = [];
if (explicitPath) {
if (!existsSync(explicitPath)) {
throw new Error(`Config file not found: ${explicitPath}`);
}
candidates.push(explicitPath);
} else {
candidates.push(userConfigPath());
const machine = machineConfigPath();
if (machine) candidates.push(machine);
}
for (const path of candidates) {
if (existsSync(path)) {
const raw = readFileSync(path, "utf8");
const parsed = JSON.parse(raw) as FileConfig;
return {
port: typeof parsed.port === "number" ? parsed.port : undefined,
bind: typeof parsed.bind === "string" ? parsed.bind : undefined,
dbPath: typeof parsed.dbPath === "string" ? parsed.dbPath : undefined,
};
}
}
return {};
}
export interface ServeOverrides {
port?: number;
bind?: string;
dbPath?: string;
config?: string;
}
export function resolveConfig(overrides: ServeOverrides): DaemonConfig {
const file = loadFileConfig(overrides.config);
const port = overrides.port ?? file.port ?? DEFAULT_PORT;
const bind = overrides.bind ?? file.bind ?? DEFAULT_BIND;
const dbPathRaw = overrides.dbPath ?? file.dbPath ?? defaultDbPath();
return { port, bind, dbPath: expandPath(dbPathRaw) };
}
export function baseUrl(cfg: { port: number; bind: string }): string {
return `http://${cfg.bind}:${cfg.port}`;
}

182
node/src/db.ts Normal file
View File

@@ -0,0 +1,182 @@
import Database from "better-sqlite3";
import { mkdirSync } from "node:fs";
import { dirname } from "node:path";
export interface MailboxRow {
name: string;
created_at: string;
last_seen_at: string;
}
export interface MessageRow {
id: number;
to_mailbox: string;
from_mailbox: string;
body: string;
created_at: string;
delivered_at: string | null;
}
export interface InboxStatus {
pending: number;
oldestAt: Date | null;
}
export interface MailboxInfo {
name: string;
lastSeenAt: Date;
pendingForYou: number;
}
const DDL_STATEMENTS: string[] = [
`CREATE TABLE IF NOT EXISTS mailboxes (
name TEXT NOT NULL PRIMARY KEY,
created_at TEXT NOT NULL,
last_seen_at TEXT NOT NULL
)`,
`CREATE TABLE IF NOT EXISTS messages (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
to_mailbox TEXT NOT NULL REFERENCES mailboxes(name) ON DELETE RESTRICT,
from_mailbox TEXT NOT NULL REFERENCES mailboxes(name) ON DELETE RESTRICT,
body TEXT NOT NULL,
created_at TEXT NOT NULL,
delivered_at TEXT NULL
)`,
`CREATE INDEX IF NOT EXISTS ix_messages_to_delivered
ON messages (to_mailbox, delivered_at)`,
];
function nowIso(): string {
return new Date().toISOString();
}
function parseDate(s: string | null | undefined): Date | null {
if (!s) return null;
const normalized = s.includes("T") ? s : s.replace(" ", "T") + (s.endsWith("Z") ? "" : "Z");
const d = new Date(normalized);
return isNaN(d.getTime()) ? null : d;
}
export class MailboxStore {
private readonly db: Database.Database;
private readonly stmts: {
findMailbox: Database.Statement;
insertMailbox: Database.Statement;
touchMailbox: Database.Statement;
listMailboxes: Database.Statement;
insertMessage: Database.Statement;
countPending: Database.Statement;
oldestPending: Database.Statement;
selectPending: Database.Statement;
markDelivered: Database.Statement;
pendingByRecipient: Database.Statement;
};
constructor(public readonly dbPath: string) {
mkdirSync(dirname(dbPath), { recursive: true });
this.db = new Database(dbPath);
this.db.pragma("journal_mode = WAL");
this.db.pragma("foreign_keys = ON");
for (const sql of DDL_STATEMENTS) this.db.prepare(sql).run();
this.stmts = {
findMailbox: this.db.prepare("SELECT * FROM mailboxes WHERE name = ?"),
insertMailbox: this.db.prepare(
"INSERT INTO mailboxes (name, created_at, last_seen_at) VALUES (?, ?, ?)",
),
touchMailbox: this.db.prepare("UPDATE mailboxes SET last_seen_at = ? WHERE name = ?"),
listMailboxes: this.db.prepare("SELECT * FROM mailboxes ORDER BY name"),
insertMessage: this.db.prepare(
"INSERT INTO messages (to_mailbox, from_mailbox, body, created_at, delivered_at) VALUES (?, ?, ?, ?, NULL)",
),
countPending: this.db.prepare(
"SELECT COUNT(*) AS n FROM messages WHERE to_mailbox = ? AND delivered_at IS NULL",
),
oldestPending: this.db.prepare(
"SELECT created_at FROM messages WHERE to_mailbox = ? AND delivered_at IS NULL ORDER BY id LIMIT 1",
),
selectPending: this.db.prepare(
"SELECT * FROM messages WHERE to_mailbox = ? AND delivered_at IS NULL ORDER BY id",
),
markDelivered: this.db.prepare(
"UPDATE messages SET delivered_at = ? WHERE id IN (SELECT value FROM json_each(?))",
),
pendingByRecipient: this.db.prepare(
"SELECT to_mailbox, COUNT(*) AS n FROM messages WHERE delivered_at IS NULL GROUP BY to_mailbox",
),
};
}
close(): void {
this.db.close();
}
upsertMailbox(name: string): void {
const now = nowIso();
const existing = this.stmts.findMailbox.get(name) as MailboxRow | undefined;
if (existing) {
this.stmts.touchMailbox.run(now, name);
} else {
this.stmts.insertMailbox.run(name, now, now);
}
}
send(from: string, to: string, body: string): { id: number; queuedAt: Date } {
const tx = this.db.transaction(() => {
this.upsertMailbox(from);
this.upsertMailbox(to);
const createdAt = nowIso();
const result = this.stmts.insertMessage.run(to, from, body, createdAt);
return { id: Number(result.lastInsertRowid), queuedAt: new Date(createdAt) };
});
return tx();
}
peek(name: string): InboxStatus {
const row = this.stmts.countPending.get(name) as { n: number };
if (row.n === 0) return { pending: 0, oldestAt: null };
const oldest = this.stmts.oldestPending.get(name) as { created_at: string } | undefined;
return { pending: row.n, oldestAt: parseDate(oldest?.created_at) };
}
checkInbox(name: string): MessageRow[] {
const tx = this.db.transaction(() => {
const pending = this.stmts.selectPending.all(name) as MessageRow[];
if (pending.length > 0) {
const ids = pending.map((m) => m.id);
this.stmts.markDelivered.run(nowIso(), JSON.stringify(ids));
}
return pending;
});
return tx();
}
listMailboxes(forName?: string): MailboxInfo[] {
const rows = this.stmts.listMailboxes.all() as MailboxRow[];
const pendingMap = new Map<string, number>();
if (forName) {
const counts = this.stmts.pendingByRecipient.all() as { to_mailbox: string; n: number }[];
for (const c of counts) pendingMap.set(c.to_mailbox, c.n);
}
return rows.map((r) => ({
name: r.name,
lastSeenAt: parseDate(r.last_seen_at) ?? new Date(0),
pendingForYou: forName ? (pendingMap.get(forName) ?? 0) : 0,
}));
}
}
export function rowToMessage(r: MessageRow): {
id: number;
from: string;
body: string;
sentAt: Date;
} {
return {
id: r.id,
from: r.from_mailbox,
body: r.body,
sentAt: parseDate(r.created_at) ?? new Date(0),
};
}

203
node/src/hook.ts Normal file
View File

@@ -0,0 +1,203 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
export interface HookStdinPayload {
session_id?: string;
hook_event_name?: string;
[key: string]: unknown;
}
export function parseHookStdin(raw: string | null | undefined): HookStdinPayload | null {
if (!raw || !raw.trim()) return null;
try {
const parsed = JSON.parse(raw) as unknown;
if (parsed && typeof parsed === "object") return parsed as HookStdinPayload;
return null;
} catch {
return null;
}
}
export function readStdinIfPiped(): string | null {
if (process.stdin.isTTY) return null;
try {
return readFileSync(0, "utf8");
} catch {
return null;
}
}
export function shortSessionId(sessionId: string): string {
const hex = sessionId.replace(/[^0-9a-fA-F]/g, "").toLowerCase();
if (hex.length >= 8) return hex.slice(0, 8);
return sessionId.toLowerCase().replace(/[^a-z0-9]/g, "").slice(0, 8) || "00000000";
}
export function deriveSessionName(sessionId: string, base?: string | null): string {
const short = shortSessionId(sessionId);
const trimmed = (base ?? "").trim();
if (trimmed) return `${trimmed}-${short}`;
return `claude-${short}`;
}
export interface PeerEntry {
name: string;
lastSeenAt: string;
}
export function formatActivePeerList(
peers: PeerEntry[],
selfName: string,
options: { windowMinutes: number; maxPeers: number; now?: number },
): string[] {
const others = peers.filter((p) => p.name !== selfName);
const cutoff = (options.now ?? Date.now()) - options.windowMinutes * 60_000;
const active = others
.filter((p) => {
const t = new Date(p.lastSeenAt).getTime();
return Number.isFinite(t) && t >= cutoff;
})
.sort((a, b) => b.lastSeenAt.localeCompare(a.lastSeenAt))
.slice(0, options.maxPeers);
if (active.length === 0) {
return [
`No other mailboxes seen within the last ${options.windowMinutes} minutes (${others.length} total registered).`,
];
}
const lines = [
`Active peers (seen within last ${options.windowMinutes} min, ${active.length} of ${others.length} total):`,
];
for (const p of active) {
lines.push(` - ${p.name} (last seen ${p.lastSeenAt})`);
}
return lines;
}
export interface HookMessage {
id: number;
from: string;
body: string;
sentAt: string;
}
export function formatMessagesForHook(name: string, messages: HookMessage[]): string {
if (messages.length === 0) return "";
const header =
messages.length === 1
? `You have 1 new mailbox message for "${name}":`
: `You have ${messages.length} new mailbox messages for "${name}":`;
const lines: string[] = [header, ""];
for (const m of messages) {
lines.push(`[#${m.id}] from ${m.from} (${m.sentAt}):`);
for (const bodyLine of m.body.split(/\r?\n/)) {
lines.push(` ${bodyLine}`);
}
lines.push("");
}
return lines.join("\n").trimEnd() + "\n";
}
export type HookScope = "user" | "project";
export function settingsPathFor(scope: HookScope, cwd: string = process.cwd()): string {
if (scope === "user") return join(homedir(), ".claude", "settings.json");
return join(cwd, ".claude", "settings.json");
}
interface ClaudeHookCommand {
type: "command";
command: string;
timeout?: number;
}
interface ClaudeHookGroup {
matcher?: string;
hooks: ClaudeHookCommand[];
}
interface ClaudeSettings {
hooks?: Record<string, ClaudeHookGroup[]>;
[key: string]: unknown;
}
const HOOK_EVENT = "UserPromptSubmit";
export function buildHookCommand(name: string, url?: string): string {
const parts = ["claude-mailbox", "check", "--name", quoteIfNeeded(name), "--hook"];
if (url) parts.push("--url", quoteIfNeeded(url));
return parts.join(" ");
}
function quoteIfNeeded(value: string): string {
if (/^[A-Za-z0-9._:/@\-]+$/.test(value)) return value;
return `"${value.replace(/(["\\])/g, "\\$1")}"`;
}
function isOurHookCommand(command: string): boolean {
const c = command.trim();
return /(^|\W)claude-mailbox\s+check\s/.test(c) && /(^|\s)--hook(\s|$)/.test(c);
}
export function readSettings(path: string): ClaudeSettings {
if (!existsSync(path)) return {};
const raw = readFileSync(path, "utf8");
if (!raw.trim()) return {};
return JSON.parse(raw) as ClaudeSettings;
}
export function writeSettings(path: string, settings: ClaudeSettings): void {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, JSON.stringify(settings, null, 2) + "\n", "utf8");
}
export interface PatchResult {
changed: boolean;
reason: "added" | "already-present" | "removed" | "not-present";
}
export function applyInstall(settings: ClaudeSettings, command: string): PatchResult {
settings.hooks ??= {};
settings.hooks[HOOK_EVENT] ??= [];
const groups = settings.hooks[HOOK_EVENT];
for (const group of groups) {
for (const hook of group.hooks) {
if (hook.command.trim() === command.trim()) {
return { changed: false, reason: "already-present" };
}
}
}
let target = groups.find((g) => (g.matcher ?? "") === "");
if (!target) {
target = { matcher: "", hooks: [] };
groups.push(target);
}
target.hooks.push({ type: "command", command });
return { changed: true, reason: "added" };
}
export function applyUninstall(settings: ClaudeSettings): PatchResult {
const groups = settings.hooks?.[HOOK_EVENT];
if (!groups || groups.length === 0) return { changed: false, reason: "not-present" };
let removed = false;
for (const group of groups) {
const before = group.hooks.length;
group.hooks = group.hooks.filter((h) => !isOurHookCommand(h.command));
if (group.hooks.length !== before) removed = true;
}
settings.hooks![HOOK_EVENT] = groups.filter((g) => g.hooks.length > 0);
if (settings.hooks![HOOK_EVENT].length === 0) {
delete settings.hooks![HOOK_EVENT];
}
if (settings.hooks && Object.keys(settings.hooks).length === 0) {
delete settings.hooks;
}
return removed ? { changed: true, reason: "removed" } : { changed: false, reason: "not-present" };
}

165
node/src/mcp-stdio.ts Normal file
View File

@@ -0,0 +1,165 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { DEFAULT_PORT } from "./config.js";
const HARDCODED_DEFAULT_URL = `http://127.0.0.1:${DEFAULT_PORT}`;
function resolveDaemonUrl(): string {
const env = (process.env["CLAUDE_MAILBOX_URL"] ?? "").trim();
if (!env || env.includes("${")) return HARDCODED_DEFAULT_URL;
return env.replace(/\/$/, "");
}
function requireIdentity(value: string | undefined, argName: "from" | "name"): string {
const v = (value ?? "").trim();
if (!v) {
throw new Error(
`Pass \`${argName}\` (your mailbox name from the SessionStart announcement).`,
);
}
return v;
}
async function rest(
method: "GET" | "POST",
url: string,
init: { headers?: Record<string, string>; body?: unknown } = {},
): Promise<unknown> {
const headers: Record<string, string> = { Accept: "application/json", ...(init.headers ?? {}) };
let body: string | undefined;
if (init.body !== undefined) {
headers["Content-Type"] = "application/json";
body = JSON.stringify(init.body);
}
const res = await fetch(url, { method, headers, body });
const text = await res.text();
if (!res.ok) {
throw new Error(`${method} ${url}${res.status}: ${text}`);
}
return text.length ? JSON.parse(text) : null;
}
export function buildStdioMcpServer(daemonUrl: string = resolveDaemonUrl()): McpServer {
const server = new McpServer({ name: "claude-mailbox", version: "1.0.0" });
server.registerTool(
"send",
{
title: "Send mail",
description:
"Send a message to another mailbox. Pass `from` with your own mailbox name (see the SessionStart announcement).",
inputSchema: {
to: z.string().describe("Name of the recipient mailbox."),
body: z.string().describe("Message body (plain text or markdown)."),
from: z
.string()
.describe(
"Your mailbox name. Take it from the SessionStart announcement.",
),
},
},
async ({ to, body, from }) => {
const sender = requireIdentity(from, "from");
const out = (await rest("POST", `${daemonUrl}/v1/send`, {
headers: { "X-Mailbox": sender },
body: { to, body },
})) as { id: number; queuedAt: string };
return {
content: [{ type: "text", text: JSON.stringify(out) }],
structuredContent: out,
};
},
);
server.registerTool(
"check_inbox",
{
title: "Check inbox",
description:
"Pull all undelivered messages for your mailbox and mark them delivered. Pass `name` with your own mailbox name.",
inputSchema: {
name: z
.string()
.describe(
"Your mailbox name. Take it from the SessionStart announcement.",
),
},
},
async ({ name }) => {
const me = requireIdentity(name, "name");
const messages = (await rest(
"POST",
`${daemonUrl}/v1/check-inbox?name=${encodeURIComponent(me)}`,
{ headers: { "X-Mailbox": me } },
)) as { id: number; from: string; body: string; sentAt: string }[];
const arr = Array.isArray(messages) ? messages : [];
return {
content: [{ type: "text", text: JSON.stringify(arr) }],
structuredContent: { messages: arr },
};
},
);
server.registerTool(
"peek_inbox",
{
title: "Peek inbox",
description:
"Non-consuming check of your mailbox. Returns pending count and oldest pending timestamp. Pass `name` with your own mailbox name.",
inputSchema: {
name: z
.string()
.describe(
"Your mailbox name. Take it from the SessionStart announcement.",
),
},
},
async ({ name }) => {
const me = requireIdentity(name, "name");
const out = (await rest("GET", `${daemonUrl}/v1/peek?name=${encodeURIComponent(me)}`)) as {
pending: number;
oldestAt: string | null;
};
return {
content: [{ type: "text", text: JSON.stringify(out) }],
structuredContent: out,
};
},
);
server.registerTool(
"list_mailboxes",
{
title: "List mailboxes",
description:
"Discover known mailboxes and how many messages each has waiting for you. Pass `name` with your own mailbox name.",
inputSchema: {
name: z
.string()
.describe(
"Your mailbox name. Take it from the SessionStart announcement.",
),
},
},
async ({ name }) => {
const me = requireIdentity(name, "name");
const list = (await rest("GET", `${daemonUrl}/v1/list`, {
headers: { "X-Mailbox": me },
})) as { name: string; lastSeenAt: string; pendingForYou: number }[];
const arr = Array.isArray(list) ? list : [];
return {
content: [{ type: "text", text: JSON.stringify(arr) }],
structuredContent: { mailboxes: arr },
};
},
);
return server;
}
export async function runStdioMcp(): Promise<void> {
const server = buildStdioMcpServer();
const transport = new StdioServerTransport();
await server.connect(transport);
}

159
node/src/mcp.ts Normal file
View File

@@ -0,0 +1,159 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { z } from "zod";
import type { FastifyInstance } from "fastify";
import { MailboxStore, rowToMessage } from "./db.js";
import { HEADER_NAME } from "./server.js";
function headerFallback(extra: unknown): string {
const headers =
(extra as { requestInfo?: { headers?: Record<string, string | string[] | undefined> } })
?.requestInfo?.headers ?? {};
const raw = headers[HEADER_NAME] ?? headers["X-Mailbox"];
return (Array.isArray(raw) ? raw[0] : raw ?? "").trim();
}
export function resolveIdentity(
argValue: string | undefined,
extra: unknown,
argName: "from" | "name",
): string {
const explicit = (argValue ?? "").trim();
if (explicit) return explicit;
const fallback = headerFallback(extra);
if (fallback) return fallback;
throw new Error(
`Pass \`${argName}\` (your mailbox name from the SessionStart announcement) or set the X-Mailbox header in .mcp.json.`,
);
}
function buildMcpServer(store: MailboxStore): McpServer {
const server = new McpServer({ name: "claude-mailbox", version: "1.0.0" });
server.registerTool(
"send",
{
title: "Send mail",
description:
"Send a message to another mailbox. Pass `from` with your own mailbox name (see the SessionStart announcement); falls back to the X-Mailbox header for single-session HTTP setups.",
inputSchema: {
to: z.string().describe("Name of the recipient mailbox."),
body: z.string().describe("Message body (plain text or markdown)."),
from: z
.string()
.optional()
.describe(
"Your mailbox name (the sender). Take it from the SessionStart announcement. Required unless X-Mailbox is set in .mcp.json.",
),
},
},
async ({ to, body, from }, extra) => {
const sender = resolveIdentity(from, extra, "from");
const r = store.send(sender, to, body);
const out = { id: r.id, queuedAt: r.queuedAt.toISOString() };
return {
content: [{ type: "text", text: JSON.stringify(out) }],
structuredContent: out,
};
},
);
server.registerTool(
"check_inbox",
{
title: "Check inbox",
description:
"Pull all undelivered messages for your mailbox and mark them delivered. Pass `name` with your own mailbox name (from the SessionStart announcement); falls back to X-Mailbox header.",
inputSchema: {
name: z
.string()
.optional()
.describe(
"Your mailbox name. Take it from the SessionStart announcement. Required unless X-Mailbox is set in .mcp.json.",
),
},
},
async ({ name }, extra) => {
const me = resolveIdentity(name, extra, "name");
const messages = store.checkInbox(me).map((m) => {
const x = rowToMessage(m);
return { id: x.id, from: x.from, body: x.body, sentAt: x.sentAt.toISOString() };
});
return {
content: [{ type: "text", text: JSON.stringify(messages) }],
structuredContent: { messages },
};
},
);
server.registerTool(
"peek_inbox",
{
title: "Peek inbox",
description:
"Non-consuming check of your mailbox. Returns pending count and oldest pending timestamp. Pass `name` with your own mailbox name; falls back to X-Mailbox header.",
inputSchema: {
name: z
.string()
.optional()
.describe(
"Your mailbox name. Take it from the SessionStart announcement. Required unless X-Mailbox is set in .mcp.json.",
),
},
},
async ({ name }, extra) => {
const me = resolveIdentity(name, extra, "name");
const status = store.peek(me);
const out = { pending: status.pending, oldestAt: status.oldestAt?.toISOString() ?? null };
return {
content: [{ type: "text", text: JSON.stringify(out) }],
structuredContent: out,
};
},
);
server.registerTool(
"list_mailboxes",
{
title: "List mailboxes",
description:
"Discover known mailboxes and how many messages each has waiting for you. Pass `name` with your own mailbox name to get accurate `pendingForYou` counts; falls back to X-Mailbox header.",
inputSchema: {
name: z
.string()
.optional()
.describe(
"Your mailbox name. Take it from the SessionStart announcement. Required unless X-Mailbox is set in .mcp.json.",
),
},
},
async ({ name }, extra) => {
const me = resolveIdentity(name, extra, "name");
const list = store.listMailboxes(me).map((m) => ({
name: m.name,
lastSeenAt: m.lastSeenAt.toISOString(),
pendingForYou: m.pendingForYou,
}));
return {
content: [{ type: "text", text: JSON.stringify(list) }],
structuredContent: { mailboxes: list },
};
},
);
return server;
}
export async function registerMcp(app: FastifyInstance, store: MailboxStore): Promise<void> {
const mcpServer = buildMcpServer(store);
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
await mcpServer.connect(transport);
const handle = async (req: import("fastify").FastifyRequest, reply: import("fastify").FastifyReply) => {
await transport.handleRequest(req.raw, reply.raw, req.body);
};
app.post("/mcp", handle);
app.get("/mcp", handle);
app.delete("/mcp", handle);
}

113
node/src/server.ts Normal file
View File

@@ -0,0 +1,113 @@
import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify";
import { readFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { MailboxStore, rowToMessage } from "./db.js";
import type { DaemonConfig } from "./config.js";
import { registerMcp } from "./mcp.js";
export const HEADER_NAME = "x-mailbox";
declare module "fastify" {
interface FastifyRequest {
mailboxName?: string;
}
}
function readVersion(): string {
try {
const here = dirname(fileURLToPath(import.meta.url));
const pkg = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8")) as {
version?: string;
};
return pkg.version ?? "unknown";
} catch {
return "unknown";
}
}
const ANONYMOUS_PATHS = new Set(["/v1/list", "/v1/peek"]);
export async function buildServer(cfg: DaemonConfig, store: MailboxStore): Promise<FastifyInstance> {
const app = Fastify({ logger: true });
const version = readVersion();
app.addHook("onRequest", async (req: FastifyRequest, reply: FastifyReply) => {
const url = req.url.split("?")[0] ?? "/";
if (url === "/health" || url === "/mcp" || url.startsWith("/mcp/")) return;
const headerValue = req.headers[HEADER_NAME];
const name = (Array.isArray(headerValue) ? headerValue[0] : headerValue ?? "").trim();
if (!name) {
if (ANONYMOUS_PATHS.has(url)) return;
reply.code(400).send({ error: `Missing ${HEADER_NAME} header.` });
return reply;
}
req.mailboxName = name;
store.upsertMailbox(name);
});
app.get("/health", async () => ({
status: "ok",
version,
dbPath: cfg.dbPath,
}));
app.post<{ Body: { to?: string; body?: string } }>("/v1/send", async (req, reply) => {
const { to, body } = req.body ?? {};
if (!to || !body) {
reply.code(400);
return { error: "to and body are required" };
}
const from = req.mailboxName!;
const result = store.send(from, to, body);
return { id: result.id, queuedAt: result.queuedAt.toISOString() };
});
app.get<{ Querystring: { name?: string } }>("/v1/peek", async (req, reply) => {
const name = (req.query.name ?? "").trim();
if (!name) {
reply.code(400);
return { error: "name is required" };
}
const status = store.peek(name);
return {
pending: status.pending,
oldestAt: status.oldestAt?.toISOString() ?? null,
};
});
app.post<{ Querystring: { name?: string } }>("/v1/check-inbox", async (req, reply) => {
const name = (req.query.name ?? "").trim();
if (name !== req.mailboxName) {
reply.code(403);
return { error: "X-Mailbox header must match name." };
}
return store.checkInbox(name).map((m) => {
const msg = rowToMessage(m);
return { ...msg, sentAt: msg.sentAt.toISOString() };
});
});
app.get("/v1/list", async (req) => {
const name = req.mailboxName;
return store.listMailboxes(name).map((m) => ({
name: m.name,
lastSeenAt: m.lastSeenAt.toISOString(),
pendingForYou: m.pendingForYou,
}));
});
await registerMcp(app, store);
return app;
}
export async function startServer(cfg: DaemonConfig): Promise<{ app: FastifyInstance; store: MailboxStore }> {
const store = new MailboxStore(cfg.dbPath);
const app = await buildServer(cfg, store);
await app.listen({ host: cfg.bind, port: cfg.port });
return { app, store };
}

21
node/src/types/node-windows.d.ts vendored Normal file
View File

@@ -0,0 +1,21 @@
declare module "node-windows" {
export interface ServiceOpts {
name: string;
description?: string;
script: string;
nodeOptions?: string[];
workingDirectory?: string;
}
export class Service {
constructor(opts: ServiceOpts);
on(
event: "install" | "uninstall" | "alreadyinstalled" | "start" | "stop" | "error",
cb: (err?: unknown) => void,
): void;
install(): void;
uninstall(): void;
start(): void;
stop(): void;
}
}

144
node/tests/cli-hook.test.ts Normal file
View File

@@ -0,0 +1,144 @@
import { describe, it, expect, beforeAll } from "vitest";
import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { resolve } from "node:path";
const cliPath = resolve(__dirname, "..", "dist", "cli.js");
function runCli(
args: string[],
opts: { env?: Record<string, string | undefined>; stdin?: string } = {},
): { status: number; stdout: string; stderr: string } {
const r = spawnSync(process.execPath, [cliPath, ...args], {
encoding: "utf8",
env: { ...process.env, ...(opts.env ?? {}) },
input: opts.stdin,
});
return {
status: r.status ?? -1,
stdout: typeof r.stdout === "string" ? r.stdout : "",
stderr: typeof r.stderr === "string" ? r.stderr : "",
};
}
const HOOK_STDIN = JSON.stringify({
session_id: "abc12345-de67-89f0-1234-567890abcdef",
hook_event_name: "UserPromptSubmit",
cwd: "/tmp",
prompt: "test",
});
describe("`check --hook` CLI behavior", () => {
beforeAll(() => {
if (!existsSync(cliPath)) {
throw new Error(`CLI not built. Run \`npm run build\` first. Missing: ${cliPath}`);
}
});
it("exits 0 silently when no stdin, no --name, no env", () => {
const r = runCli(["check", "--hook"], { env: { CLAUDE_MAILBOX_NAME: undefined } });
expect(r.status).toBe(0);
expect(r.stdout).toBe("");
expect(r.stderr).toBe("");
});
it("derives session-id-based name from stdin and emits daemon hint when down", () => {
const r = runCli(["check", "--hook", "--url", "http://127.0.0.1:1"], {
env: { CLAUDE_MAILBOX_NAME: undefined },
stdin: HOOK_STDIN,
});
expect(r.status).toBe(0);
expect(r.stdout).toContain("[Claude-Mailbox] Daemon not reachable");
});
it("uses base prefix from CLAUDE_MAILBOX_NAME when both env and stdin present", () => {
// We can't directly assert the name from --hook output (it's only in the unreachable hint URL).
// The hint always contains the URL we passed, so this just confirms the path runs without error.
const r = runCli(["check", "--hook", "--url", "http://127.0.0.1:1"], {
env: { CLAUDE_MAILBOX_NAME: "backend" },
stdin: HOOK_STDIN,
});
expect(r.status).toBe(0);
expect(r.stdout).toContain("[Claude-Mailbox] Daemon not reachable");
});
it("explicit --name overrides session-id derivation", () => {
const r = runCli(
["check", "--hook", "--name", "explicit", "--url", "http://127.0.0.1:1"],
{ env: { CLAUDE_MAILBOX_NAME: "ignored" }, stdin: HOOK_STDIN },
);
expect(r.status).toBe(0);
expect(r.stdout).toContain("[Claude-Mailbox] Daemon not reachable");
});
it("uses CLAUDE_MAILBOX_URL env as default base URL when --url is not given", () => {
const r = runCli(["check", "--hook"], {
env: { CLAUDE_MAILBOX_NAME: undefined, CLAUDE_MAILBOX_URL: "http://127.0.0.1:1" },
stdin: HOOK_STDIN,
});
expect(r.status).toBe(0);
expect(r.stdout).toContain("[Claude-Mailbox] Daemon not reachable at http://127.0.0.1:1");
});
it("non-hook mode errors out when no name resolved", () => {
const r = runCli(["check"], { env: { CLAUDE_MAILBOX_NAME: undefined } });
expect(r.status).not.toBe(0);
expect(r.stderr).toContain("CLAUDE_MAILBOX_NAME");
});
});
describe("`session-announce` CLI behavior", () => {
const UNREACHABLE = "http://127.0.0.1:1";
beforeAll(() => {
if (!existsSync(cliPath)) {
throw new Error(`CLI not built. Run \`npm run build\` first. Missing: ${cliPath}`);
}
});
it("prints the derived mailbox name from a SessionStart payload", () => {
const r = runCli(["session-announce", "--url", UNREACHABLE], {
env: { CLAUDE_MAILBOX_NAME: undefined },
stdin: HOOK_STDIN,
});
expect(r.status).toBe(0);
expect(r.stdout).toContain("`claude-abc12345`");
expect(r.stdout).toContain("mcp__mailbox__send");
expect(r.stdout).toContain(`from="claude-abc12345"`);
});
it("uses base prefix when set", () => {
const r = runCli(["session-announce", "--url", UNREACHABLE], {
env: { CLAUDE_MAILBOX_NAME: "backend" },
stdin: HOOK_STDIN,
});
expect(r.status).toBe(0);
expect(r.stdout).toContain("`backend-abc12345`");
});
it("emits daemon-not-reachable hint when daemon is down", () => {
const r = runCli(["session-announce", "--url", UNREACHABLE], {
env: { CLAUDE_MAILBOX_NAME: undefined },
stdin: HOOK_STDIN,
});
expect(r.status).toBe(0);
expect(r.stdout).toContain("[Claude-Mailbox] Daemon not reachable");
});
it("stays silent when no session_id in stdin", () => {
const r = runCli(["session-announce", "--url", UNREACHABLE], {
env: { CLAUDE_MAILBOX_NAME: undefined },
stdin: JSON.stringify({ hook_event_name: "SessionStart" }),
});
expect(r.status).toBe(0);
expect(r.stdout).toBe("");
});
it("stays silent when no stdin at all", () => {
const r = runCli(["session-announce", "--url", UNREACHABLE], {
env: { CLAUDE_MAILBOX_NAME: undefined },
});
expect(r.status).toBe(0);
expect(r.stdout).toBe("");
});
});

94
node/tests/db.test.ts Normal file
View File

@@ -0,0 +1,94 @@
import { describe, it, expect, afterEach, beforeEach } from "vitest";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { MailboxStore } from "../src/db.js";
let dir: string;
let dbPath: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "claude-mailbox-test-"));
dbPath = join(dir, "test.db");
});
afterEach(() => {
rmSync(dir, { recursive: true, force: true });
});
describe("schema", () => {
it("creates fresh tables and is idempotent on re-open", () => {
const a = new MailboxStore(dbPath);
a.upsertMailbox("alice");
a.close();
const b = new MailboxStore(dbPath);
const list = b.listMailboxes();
expect(list.map((m) => m.name)).toEqual(["alice"]);
b.close();
});
});
describe("send / peek / check round-trip", () => {
it("delivers a message exactly once", () => {
const store = new MailboxStore(dbPath);
try {
const result = store.send("alice", "bob", "hello bob");
expect(result.id).toBeGreaterThan(0);
const peek1 = store.peek("bob");
expect(peek1.pending).toBe(1);
expect(peek1.oldestAt).toBeInstanceOf(Date);
const pulled = store.checkInbox("bob");
expect(pulled).toHaveLength(1);
expect(pulled[0]!.from_mailbox).toBe("alice");
expect(pulled[0]!.body).toBe("hello bob");
const peek2 = store.peek("bob");
expect(peek2.pending).toBe(0);
expect(peek2.oldestAt).toBeNull();
const empty = store.checkInbox("bob");
expect(empty).toEqual([]);
} finally {
store.close();
}
});
it("checkInbox returns all pending in order and marks them delivered atomically", () => {
const store = new MailboxStore(dbPath);
try {
for (let i = 0; i < 10; i++) {
store.send("alice", "bob", `msg ${i}`);
}
const first = store.checkInbox("bob");
expect(first).toHaveLength(10);
expect(first.map((m) => m.body)).toEqual(
Array.from({ length: 10 }, (_, i) => `msg ${i}`),
);
const second = store.checkInbox("bob");
expect(second).toEqual([]);
} finally {
store.close();
}
});
});
describe("listMailboxes", () => {
it("returns mailboxes alphabetically with pendingForYou for the caller", () => {
const store = new MailboxStore(dbPath);
try {
store.send("alice", "bob", "x");
store.send("alice", "bob", "y");
store.send("carol", "bob", "z");
const fromBob = store.listMailboxes("bob");
expect(fromBob.map((m) => m.name)).toEqual(["alice", "bob", "carol"]);
const bobRow = fromBob.find((m) => m.name === "bob");
expect(bobRow?.pendingForYou).toBe(3);
} finally {
store.close();
}
});
});

365
node/tests/hook.test.ts Normal file
View File

@@ -0,0 +1,365 @@
import { describe, it, expect } from "vitest";
import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
applyInstall,
applyUninstall,
buildHookCommand,
deriveSessionName,
formatActivePeerList,
formatMessagesForHook,
parseHookStdin,
readSettings,
shortSessionId,
writeSettings,
type PeerEntry,
} from "../src/hook.js";
describe("formatMessagesForHook", () => {
it("returns empty string for empty inbox", () => {
expect(formatMessagesForHook("bob", [])).toBe("");
});
it("formats a single message", () => {
const out = formatMessagesForHook("bob", [
{ id: 1, from: "alice", body: "hi bob", sentAt: "2026-05-19T10:00:00.000Z" },
]);
expect(out).toContain("1 new mailbox message");
expect(out).toContain("[#1] from alice (2026-05-19T10:00:00.000Z):");
expect(out).toContain(" hi bob");
});
it("formats multiple messages with plural header", () => {
const out = formatMessagesForHook("bob", [
{ id: 1, from: "alice", body: "one", sentAt: "2026-05-19T10:00:00.000Z" },
{ id: 2, from: "carol", body: "two", sentAt: "2026-05-19T10:01:00.000Z" },
]);
expect(out).toContain("2 new mailbox messages");
expect(out).toContain("[#1] from alice");
expect(out).toContain("[#2] from carol");
});
it("preserves multi-line bodies with indentation", () => {
const out = formatMessagesForHook("bob", [
{ id: 1, from: "alice", body: "line1\nline2", sentAt: "2026-05-19T10:00:00.000Z" },
]);
expect(out).toContain(" line1");
expect(out).toContain(" line2");
});
});
describe("buildHookCommand", () => {
it("builds a basic command", () => {
expect(buildHookCommand("alice")).toBe("claude-mailbox check --name alice --hook");
});
it("appends --url when provided", () => {
expect(buildHookCommand("alice", "http://127.0.0.1:9000")).toBe(
"claude-mailbox check --name alice --hook --url http://127.0.0.1:9000",
);
});
it("quotes names with spaces", () => {
const cmd = buildHookCommand("my mailbox");
expect(cmd).toContain('--name "my mailbox"');
});
});
describe("applyInstall", () => {
it("creates hooks structure from empty settings", () => {
const s: Record<string, unknown> = {};
const r = applyInstall(s, "claude-mailbox check --name bob --hook");
expect(r).toEqual({ changed: true, reason: "added" });
expect(s).toMatchObject({
hooks: {
UserPromptSubmit: [
{
matcher: "",
hooks: [{ type: "command", command: "claude-mailbox check --name bob --hook" }],
},
],
},
});
});
it("is idempotent — does not duplicate the same command", () => {
const s: Record<string, unknown> = {};
applyInstall(s, "claude-mailbox check --name bob --hook");
const r = applyInstall(s, "claude-mailbox check --name bob --hook");
expect(r).toEqual({ changed: false, reason: "already-present" });
const groups = (s.hooks as { UserPromptSubmit: { hooks: unknown[] }[] }).UserPromptSubmit;
expect(groups[0]!.hooks).toHaveLength(1);
});
it("preserves existing unrelated hooks", () => {
const s: Record<string, unknown> = {
hooks: {
UserPromptSubmit: [
{
matcher: "",
hooks: [{ type: "command", command: "echo something-else" }],
},
],
PostToolUse: [{ matcher: "Bash", hooks: [{ type: "command", command: "logger" }] }],
},
};
applyInstall(s, "claude-mailbox check --name bob --hook");
const hooks = s.hooks as { UserPromptSubmit: { hooks: { command: string }[] }[] };
expect(hooks.UserPromptSubmit[0]!.hooks).toHaveLength(2);
expect(hooks.UserPromptSubmit[0]!.hooks[0]!.command).toBe("echo something-else");
expect(hooks.UserPromptSubmit[0]!.hooks[1]!.command).toBe(
"claude-mailbox check --name bob --hook",
);
expect((s.hooks as Record<string, unknown>).PostToolUse).toBeDefined();
});
it("adds a new empty-matcher group when only non-empty matchers exist", () => {
const s: Record<string, unknown> = {
hooks: {
UserPromptSubmit: [
{ matcher: "Bash", hooks: [{ type: "command", command: "echo bash-only" }] },
],
},
};
applyInstall(s, "claude-mailbox check --name bob --hook");
const groups = (s.hooks as { UserPromptSubmit: { matcher?: string }[] }).UserPromptSubmit;
expect(groups).toHaveLength(2);
expect(groups[1]!.matcher).toBe("");
});
});
describe("applyUninstall", () => {
it("removes the hook and cleans up empty structures", () => {
const s: Record<string, unknown> = {};
applyInstall(s, "claude-mailbox check --name bob --hook");
const r = applyUninstall(s);
expect(r).toEqual({ changed: true, reason: "removed" });
expect(s.hooks).toBeUndefined();
});
it("preserves unrelated hooks in the same group", () => {
const s: Record<string, unknown> = {
hooks: {
UserPromptSubmit: [
{
matcher: "",
hooks: [
{ type: "command", command: "echo something-else" },
{ type: "command", command: "claude-mailbox check --name bob --hook" },
],
},
],
},
};
applyUninstall(s);
const hooks = s.hooks as { UserPromptSubmit: { hooks: { command: string }[] }[] };
expect(hooks.UserPromptSubmit[0]!.hooks).toHaveLength(1);
expect(hooks.UserPromptSubmit[0]!.hooks[0]!.command).toBe("echo something-else");
});
it("returns not-present when there is nothing to remove", () => {
const s: Record<string, unknown> = {
hooks: { UserPromptSubmit: [{ matcher: "", hooks: [{ type: "command", command: "x" }] }] },
};
const r = applyUninstall(s);
expect(r).toEqual({ changed: false, reason: "not-present" });
});
it("removes hooks installed with --url arg", () => {
const s: Record<string, unknown> = {};
applyInstall(s, "claude-mailbox check --name bob --hook --url http://x");
applyUninstall(s);
expect(s.hooks).toBeUndefined();
});
});
describe("parseHookStdin", () => {
it("returns null for empty or whitespace input", () => {
expect(parseHookStdin(null)).toBeNull();
expect(parseHookStdin("")).toBeNull();
expect(parseHookStdin(" \n ")).toBeNull();
});
it("returns null for non-JSON input", () => {
expect(parseHookStdin("not json")).toBeNull();
expect(parseHookStdin("{")).toBeNull();
});
it("returns null for JSON primitives (only objects allowed)", () => {
expect(parseHookStdin("42")).toBeNull();
expect(parseHookStdin("\"foo\"")).toBeNull();
expect(parseHookStdin("null")).toBeNull();
});
it("parses a hook payload", () => {
const out = parseHookStdin(
JSON.stringify({
session_id: "abc12345-de67-89f0-1234-567890abcdef",
hook_event_name: "UserPromptSubmit",
prompt: "hi",
}),
);
expect(out?.session_id).toBe("abc12345-de67-89f0-1234-567890abcdef");
expect(out?.hook_event_name).toBe("UserPromptSubmit");
});
});
describe("shortSessionId / deriveSessionName", () => {
it("takes first 8 hex chars from a UUID", () => {
expect(shortSessionId("abc12345-de67-89f0-1234-567890abcdef")).toBe("abc12345");
});
it("normalizes case and ignores hyphens", () => {
expect(shortSessionId("ABC12345-DE67-89F0-1234-567890ABCDEF")).toBe("abc12345");
});
it("falls back to a sanitized prefix for non-hex ids", () => {
expect(shortSessionId("session-Test123")).toBe("sessiont");
});
it("derives anonymous name when no base", () => {
expect(deriveSessionName("abc12345-de67-89f0-1234-567890abcdef")).toBe("claude-abc12345");
});
it("prepends base prefix when given", () => {
expect(deriveSessionName("abc12345-de67-89f0-1234-567890abcdef", "backend")).toBe(
"backend-abc12345",
);
});
it("treats whitespace-only base as no base", () => {
expect(deriveSessionName("abc12345-de67-89f0-1234-567890abcdef", " ")).toBe(
"claude-abc12345",
);
});
it("derives different names for different sessions with the same base", () => {
const a = deriveSessionName("aaaa1111-de67-89f0-1234-567890abcdef", "shared");
const b = deriveSessionName("bbbb2222-de67-89f0-1234-567890abcdef", "shared");
expect(a).not.toBe(b);
});
});
describe("formatActivePeerList", () => {
const NOW = new Date("2026-05-19T12:00:00.000Z").getTime();
const peer = (name: string, isoOffsetMinutes: number): PeerEntry => ({
name,
lastSeenAt: new Date(NOW - isoOffsetMinutes * 60_000).toISOString(),
});
it("excludes self from the list", () => {
const out = formatActivePeerList(
[peer("self", 1), peer("alice", 1)],
"self",
{ windowMinutes: 60, maxPeers: 10, now: NOW },
);
const joined = out.join("\n");
expect(joined).not.toContain("self");
expect(joined).toContain("alice");
});
it("filters out peers older than the window", () => {
const out = formatActivePeerList(
[peer("recent", 5), peer("stale", 120)],
"self",
{ windowMinutes: 60, maxPeers: 10, now: NOW },
);
const joined = out.join("\n");
expect(joined).toContain("recent");
expect(joined).not.toContain("stale");
expect(out[0]).toContain("1 of 2 total");
});
it("returns a no-peers message when nothing is active", () => {
const out = formatActivePeerList(
[peer("ancient", 9999)],
"self",
{ windowMinutes: 60, maxPeers: 10, now: NOW },
);
expect(out).toHaveLength(1);
expect(out[0]).toMatch(/No other mailboxes seen within the last 60 minutes/);
expect(out[0]).toContain("1 total registered");
});
it("caps at maxPeers and sorts most-recent first", () => {
const out = formatActivePeerList(
[peer("p1", 30), peer("p2", 20), peer("p3", 10)],
"self",
{ windowMinutes: 60, maxPeers: 2, now: NOW },
);
const joined = out.join("\n");
expect(joined).toContain("p3");
expect(joined).toContain("p2");
expect(joined).not.toContain("p1");
expect(out[0]).toContain("2 of 3 total");
expect(joined.indexOf("p3")).toBeLessThan(joined.indexOf("p2"));
});
it("ignores peers with invalid lastSeenAt", () => {
const out = formatActivePeerList(
[{ name: "garbage", lastSeenAt: "not-a-date" }, peer("ok", 5)],
"self",
{ windowMinutes: 60, maxPeers: 10, now: NOW },
);
const joined = out.join("\n");
expect(joined).toContain("ok");
expect(joined).not.toContain("garbage");
});
});
describe("readSettings / writeSettings roundtrip", () => {
it("survives an install → write → read cycle", () => {
const dir = mkdtempSync(join(tmpdir(), "claude-mailbox-hook-"));
try {
const path = join(dir, "settings.json");
const s = readSettings(path);
expect(s).toEqual({});
applyInstall(s, "claude-mailbox check --name bob --hook");
writeSettings(path, s);
const reloaded = readSettings(path);
expect(reloaded.hooks?.UserPromptSubmit?.[0]?.hooks[0]?.command).toBe(
"claude-mailbox check --name bob --hook",
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("creates parent .claude directory when missing", () => {
const dir = mkdtempSync(join(tmpdir(), "claude-mailbox-hook-"));
try {
const path = join(dir, "nested", ".claude", "settings.json");
writeSettings(path, { hooks: {} });
expect(readFileSync(path, "utf8")).toContain('"hooks"');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("preserves non-hook settings keys", () => {
const dir = mkdtempSync(join(tmpdir(), "claude-mailbox-hook-"));
try {
const path = join(dir, "settings.json");
mkdirSync(dir, { recursive: true });
writeFileSync(
path,
JSON.stringify({ model: "sonnet", permissions: { allow: ["Bash"] } }, null, 2),
);
const s = readSettings(path);
applyInstall(s, "claude-mailbox check --name bob --hook");
writeSettings(path, s);
const reloaded = readSettings(path) as {
model?: string;
permissions?: { allow?: string[] };
hooks?: unknown;
};
expect(reloaded.model).toBe("sonnet");
expect(reloaded.permissions?.allow).toEqual(["Bash"]);
expect(reloaded.hooks).toBeDefined();
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});

44
node/tests/mcp.test.ts Normal file
View File

@@ -0,0 +1,44 @@
import { describe, it, expect } from "vitest";
import { resolveIdentity } from "../src/mcp.js";
function fakeExtra(header?: string): unknown {
if (header === undefined) return {};
return { requestInfo: { headers: { "x-mailbox": header } } };
}
describe("resolveIdentity", () => {
it("prefers the explicit argument when present", () => {
expect(resolveIdentity("alice", fakeExtra("bob"), "from")).toBe("alice");
});
it("falls back to X-Mailbox header when arg missing", () => {
expect(resolveIdentity(undefined, fakeExtra("bob"), "from")).toBe("bob");
});
it("trims whitespace from explicit arg and header", () => {
expect(resolveIdentity(" alice ", fakeExtra(), "from")).toBe("alice");
expect(resolveIdentity(undefined, fakeExtra(" bob "), "name")).toBe("bob");
});
it("treats empty arg as missing and falls back", () => {
expect(resolveIdentity("", fakeExtra("bob"), "name")).toBe("bob");
expect(resolveIdentity(" ", fakeExtra("bob"), "name")).toBe("bob");
});
it("throws with a helpful message when neither is provided", () => {
expect(() => resolveIdentity(undefined, fakeExtra(), "from")).toThrow(
/Pass `from`.*SessionStart announcement/i,
);
});
it("throws referencing the correct arg name", () => {
expect(() => resolveIdentity(undefined, fakeExtra(), "name")).toThrow(
/Pass `name`/,
);
});
it("handles extra without requestInfo", () => {
expect(() => resolveIdentity(undefined, {}, "from")).toThrow(/Pass `from`/);
expect(() => resolveIdentity(undefined, null, "from")).toThrow(/Pass `from`/);
});
});

109
node/tests/server.test.ts Normal file
View File

@@ -0,0 +1,109 @@
import { describe, it, expect, afterEach, beforeEach } from "vitest";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { MailboxStore } from "../src/db.js";
import { buildServer } from "../src/server.js";
import type { FastifyInstance } from "fastify";
let dir: string;
let dbPath: string;
let store: MailboxStore;
let app: FastifyInstance;
let baseUrl: string;
beforeEach(async () => {
dir = mkdtempSync(join(tmpdir(), "claude-mailbox-srv-"));
dbPath = join(dir, "test.db");
store = new MailboxStore(dbPath);
app = await buildServer({ port: 0, bind: "127.0.0.1", dbPath }, store);
await app.listen({ host: "127.0.0.1", port: 0 });
const addr = app.server.address();
if (!addr || typeof addr === "string") throw new Error("no address");
baseUrl = `http://127.0.0.1:${addr.port}`;
});
afterEach(async () => {
await app.close();
store.close();
rmSync(dir, { recursive: true, force: true });
});
async function call(
method: string,
path: string,
init: { headers?: Record<string, string>; body?: unknown } = {},
): Promise<{ status: number; body: unknown }> {
const headers: Record<string, string> = { Accept: "application/json", ...(init.headers ?? {}) };
let body: string | undefined;
if (init.body !== undefined) {
headers["Content-Type"] = "application/json";
body = JSON.stringify(init.body);
}
const res = await fetch(`${baseUrl}${path}`, { method, headers, body });
const text = await res.text();
return { status: res.status, body: text.length ? JSON.parse(text) : null };
}
describe("REST surface", () => {
it("/health is anonymous", async () => {
const r = await call("GET", "/health");
expect(r.status).toBe(200);
expect(r.body).toMatchObject({ status: "ok", dbPath });
});
it("POST /v1/send requires X-Mailbox", async () => {
const r = await call("POST", "/v1/send", { body: { to: "bob", body: "hi" } });
expect(r.status).toBe(400);
});
it("POST /v1/send → /v1/check-inbox round-trip", async () => {
const send = await call("POST", "/v1/send", {
headers: { "X-Mailbox": "alice" },
body: { to: "bob", body: "hi bob" },
});
expect(send.status).toBe(200);
expect(send.body).toMatchObject({ id: expect.any(Number), queuedAt: expect.any(String) });
const peek = await call("GET", "/v1/peek?name=bob");
expect(peek.status).toBe(200);
expect(peek.body).toMatchObject({ pending: 1 });
const check = await call("POST", "/v1/check-inbox?name=bob", {
headers: { "X-Mailbox": "bob" },
});
expect(check.status).toBe(200);
expect(Array.isArray(check.body)).toBe(true);
const arr = check.body as Array<{ from: string; body: string }>;
expect(arr).toHaveLength(1);
expect(arr[0]!.from).toBe("alice");
expect(arr[0]!.body).toBe("hi bob");
const peekAfter = await call("GET", "/v1/peek?name=bob");
expect(peekAfter.body).toMatchObject({ pending: 0, oldestAt: null });
});
it("POST /v1/check-inbox rejects mismatched X-Mailbox", async () => {
await call("POST", "/v1/send", {
headers: { "X-Mailbox": "alice" },
body: { to: "bob", body: "x" },
});
const wrong = await call("POST", "/v1/check-inbox?name=bob", {
headers: { "X-Mailbox": "alice" },
});
expect(wrong.status).toBe(403);
});
it("/v1/list and /v1/peek are anonymous", async () => {
await call("POST", "/v1/send", {
headers: { "X-Mailbox": "alice" },
body: { to: "bob", body: "x" },
});
const list = await call("GET", "/v1/list");
expect(list.status).toBe(200);
expect(Array.isArray(list.body)).toBe(true);
const peek = await call("GET", "/v1/peek?name=bob");
expect(peek.status).toBe(200);
});
});

24
node/tsconfig.json Normal file
View File

@@ -0,0 +1,24 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022"],
"outDir": "dist",
"rootDir": "src",
"declaration": false,
"sourceMap": true,
"strict": true,
"noImplicitAny": true,
"noImplicitOverride": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
"resolveJsonModule": true
},
"include": ["src/**/*.ts", "src/**/*.d.ts"],
"exclude": ["node_modules", "dist", "tests"]
}

9
node/vitest.config.ts Normal file
View File

@@ -0,0 +1,9 @@
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
include: ["tests/**/*.test.ts"],
testTimeout: 15_000,
pool: "forks",
},
});

View File

@@ -0,0 +1,11 @@
{
"name": "claude-mailbox",
"version": "0.1.0",
"description": "Auto-checks the local Claude-Mailbox daemon before every prompt and injects pending messages into the conversation context.",
"author": {
"name": "Mika Kuns"
},
"homepage": "https://git.kuns.dev/releases/ClaudeMailbox",
"license": "MIT",
"keywords": ["mailbox", "ipc", "coordination", "mcp"]
}

9
plugin/.mcp.json Normal file
View File

@@ -0,0 +1,9 @@
{
"mcpServers": {
"mailbox": {
"type": "stdio",
"command": "claude-mailbox",
"args": ["mcp-stdio"]
}
}
}

88
plugin/README.md Normal file
View File

@@ -0,0 +1,88 @@
# claude-mailbox plugin
Lets Claude Code pull unread messages from a local `claude-mailbox` daemon before every prompt and inject them into the conversation context. Each Claude session gets a **unique mailbox identity** auto-derived from its session id, so two sessions in the same project never collide.
## Setup (three prompts, all inside Claude Code)
```
/plugin marketplace add https://git.kuns.dev/releases/ClaudeMailbox.git
/plugin install claude-mailbox@claude-mailbox
/claude-mailbox:mailbox-doctor
```
The doctor walks the rest:
1. installs the `claude-mailbox` binary via `npm install -g @kuns/claude-mailbox` if missing (asks first)
2. registers the daemon for autostart and starts it if needed
3. health-probes `http://127.0.0.1:37849/health`
4. optionally lets you set a **base prefix** (e.g., `backend`) — without one, mailbox names are anonymous (`claude-XXXXXXXX`)
5. runs a self → self smoke test
Restart Claude Code only if step 4 wrote a new prefix. After that, every prompt auto-pulls unread messages.
## Mailbox identity (the important bit)
Each Claude Code session gets its own mailbox name, derived from the session's UUID:
| Configuration | Resulting mailbox name |
|---|---|
| No `CLAUDE_MAILBOX_NAME` set | `claude-a8b3c1d2` (first 8 hex chars of session_id) |
| `CLAUDE_MAILBOX_NAME=backend` in `.claude/settings.json` env | `backend-a8b3c1d2` |
So if you open two Claude Code sessions in the same project, they'll be e.g. `backend-a8b3c1d2` and `backend-d4e5f6a7` — distinct, addressable, no manual setup.
The `SessionStart` hook announces the current session's mailbox name in the conversation context on startup. Peers discover each other via `claude-mailbox list` or the `mcp__mailbox__list_mailboxes` MCP tool.
## What the hooks do
| Hook | Command | Effect |
|---|---|---|
| `SessionStart` | `claude-mailbox session-announce` | Registers the session with the daemon, then prints (a) this session's mailbox name, (b) the exact `from` / `name` args to pass to MCP tools, and (c) a list of other mailboxes active in the last hour — so Claude knows who's around without needing to call `list_mailboxes` first. |
| `UserPromptSubmit` | `claude-mailbox check --hook` | Pulls unread messages for the session's mailbox and injects them as context. Silent on empty inbox; emits a one-line setup hint when the daemon is unreachable. |
Cost: one local HTTP round-trip per prompt + Node coldstart (~100ms on Windows).
## MCP tools
The plugin ships a `.mcp.json` that spawns a **stdio MCP wrapper** (`claude-mailbox mcp-stdio`) so the daemon URL is configurable per machine via the `CLAUDE_MAILBOX_URL` env var (Claude Code doesn't yet support env substitution in HTTP MCP URLs — see issue #46889). The wrapper proxies tool calls to the daemon's REST API.
Each MCP tool takes the caller's mailbox name as an explicit argument (from the SessionStart announcement):
| Tool | Required args | Purpose |
|---|---|---|
| `mcp__mailbox__send` | `from`, `to`, `body` | Send a message to another mailbox. |
| `mcp__mailbox__check_inbox` | `name` | Pull all undelivered messages for your mailbox (marks delivered). |
| `mcp__mailbox__peek_inbox` | `name` | Non-consuming count of pending messages. |
| `mcp__mailbox__list_mailboxes` | `name` | Discover known mailboxes and `pendingForYou` counts. |
The SessionStart announcement spells out the exact args to pass, so Claude picks them up automatically.
## Slash commands
| Command | What it does |
|---|---|
| `/claude-mailbox:mailbox-doctor` | Diagnose + auto-fix the full setup. |
| `/claude-mailbox:mailbox-status` | Read-only health check. No changes. |
| `/claude-mailbox:mailbox-update` | Update the daemon to the latest npm version and restart it. |
## Coordinating two Claude Code sessions
1. Open two Claude Code sessions in the same (or different) project.
2. Each session's SessionStart hook registers itself with the daemon and prints both its own mailbox name and the **list of currently active peers** into context.
3. In session A you can simply say: *"I started a second session, coordinate with it."* Because the peer's mailbox name is already in context, Claude can call `mcp__mailbox__send(from="<my-name>", to="<peer-name>", body="...")` straight away — no manual `list_mailboxes` step needed.
4. Session B's `UserPromptSubmit` hook pulls the message on its next prompt and injects it as context.
You can also send from any shell:
```sh
claude-mailbox list
claude-mailbox send --from probe --to backend-a8b3c1d2 --body "hi"
```
## Uninstall
```
/plugin uninstall claude-mailbox@claude-mailbox
npm uninstall -g @kuns/claude-mailbox
claude-mailbox uninstall-autostart # if you registered it
```

View File

@@ -0,0 +1,113 @@
---
description: Diagnose and auto-fix the Claude-Mailbox setup (binary install, port-conflict detection, daemon autostart, smoke test, optional base-prefix).
allowed-tools: Bash, Read, Edit, Write
---
You are running the **Claude-Mailbox doctor**. Walk through these checks in order. After each step, print a one-line `✓` / `✗` with the action you took. End with a summary block.
Use `Bash` only for `claude-mailbox` subcommands, `npm`, `where`/`which`, and HTTP probes. Use `Read`/`Edit`/`Write` for `.claude/settings.json` and `mailbox.json`. Never run `sudo` automatically — if elevation is needed, stop and ask.
## Step 1 — daemon binary on PATH
Run: `claude-mailbox --version`
- **Exit 0** → ✓ record the version. Continue.
- **Command not found** → binary missing. Install path:
| Platform | Command |
|---|---|
| Windows | `npm install -g @kuns/claude-mailbox` (no admin) |
| macOS / Linux | `npm install -g @kuns/claude-mailbox` (may fail with EACCES — never run sudo automatically; ask the user) |
Prerequisite: `npm config get @kuns:registry` must point at `https://git.kuns.dev/api/packages/releases/npm/`. If not:
```
npm config set @kuns:registry=https://git.kuns.dev/api/packages/releases/npm/
```
After install, re-run `claude-mailbox --version`. If it still fails, stop and report.
## Step 2 — port-conflict check (before autostart!)
Default port is 37849. Probe whether anything is already on it:
```
curl -sf http://127.0.0.1:37849/health
```
- **Returns a JSON body with `"status":"ok"` and a `version` field that matches `claude-mailbox --version`** → it's already our daemon, ✓ skip to Step 4.
- **Returns 200 with `"status":"ok"` but a different `version`** → it's an older claude-mailbox; treat as running, ✓.
- **Returns non-200, non-JSON, or any other foreign response** → **port conflict**. Some other process owns 37849.
- **Connection refused** → port is free, ✓ continue to Step 3.
If port conflict detected:
1. Tell the user which process holds the port (Windows: `Get-NetTCPConnection -LocalPort 37849 | Select-Object OwningProcess`, then `Get-Process -Id <pid>`; macOS/Linux: `lsof -i :37849`).
2. Pick a free port. Default suggestion: **47900**. Verify it's free: `curl -sf http://127.0.0.1:47900/health` should fail with connection refused.
3. Read `~/.claude-mailbox/mailbox.json` (create empty `{}` if missing) and merge `{"port": <chosen>}`. Write back.
4. Also write the override into `.claude/settings.json` env so the plugin's hooks find the right URL:
```json
"env": { "CLAUDE_MAILBOX_URL": "http://127.0.0.1:<chosen>" }
```
Merge into existing env, preserving other keys.
5. Mark `restart_needed = true`.
## Step 3 — daemon autostart and running state
Run: `claude-mailbox status`
- `Running` → ✓ continue.
- `Stopped` → `claude-mailbox start`, re-check.
- `NotInstalled` → `claude-mailbox install-autostart`, then `claude-mailbox start`, re-check.
**Behavior on `install-autostart`:** The CLI tries a Scheduled Task first (`schtasks /RL LIMITED`, no admin). If Windows Group Policy returns "Access is denied", it falls back transparently to an `HKCU\Software\Microsoft\Windows\CurrentVersion\Run` registry entry plus a hidden `node serve` process — same per-user persistence, no admin needed. The chosen mechanism is recorded in `~/.claude-mailbox/autostart-mode` and respected by `status`/`start`/`stop`/`uninstall-autostart`.
If `install-autostart` still fails after both attempts (very rare — would mean both `schtasks` and `reg add` are blocked), stop and report what `status` and `start` printed.
## Step 4 — health probe
Hit `http://127.0.0.1:<port>/health` (use the configured port, not necessarily 37849). Expect a JSON body with `"status":"ok"` AND a `version` matching `claude-mailbox --version`. If unreachable or version mismatch, stop and report.
## Step 5 — mailbox identity (base prefix)
**No prompt by default.** Each Claude Code session gets a unique mailbox name auto-derived from its `session_id` (e.g., `claude-a8b3c1d2`).
Read `.claude/settings.json` and look for `env.CLAUDE_MAILBOX_NAME`.
- If set → ✓ "Mailbox prefix is `<X>`." (real name will be `<X>-<short_session_id>`).
- If unset → ✓ "Mailbox name will be auto-derived (`claude-<short_session_id>`)."
Ask once: *"Want to flavor your mailbox names with a memorable prefix (e.g., `backend`, `frontend`)? (yes / no / `<name>`)"*
On yes/explicit name: merge `env.CLAUDE_MAILBOX_NAME = <name>` into `.claude/settings.json`, preserving other keys. Mark `restart_needed = true`.
## Step 6 — smoke test
Use two ephemeral names — we don't need the real session name here:
```
claude-mailbox send --from doctor-probe-a --to doctor-probe-b --body "ping from doctor"
claude-mailbox check --name doctor-probe-b
```
(If the port was changed in Step 2, pass `--url http://127.0.0.1:<port>` to both.)
The `check` output must be a JSON array with one message: `from: doctor-probe-a`, body matches. ✓ on success, ✗ otherwise.
## Step 7 — summary
```
Claude-Mailbox doctor
binary: <version>
daemon: Running (port: <port>, what you did if anything)
health: ok
port conflict: none | resolved (moved from 37849 to <port>)
base prefix: <name from settings, or "auto-derived (anonymous)">
smoke test: passed | failed
restart hint: yes if restart_needed, otherwise no
```
End with one of:
- All ✓ and no restart needed → "Setup is healthy. Your mailbox name this session will be revealed by the SessionStart hook on next session start."
- All ✓ and restart needed → "Restart Claude Code (or open a new session) so the SessionStart hook picks up the new env values."
- Anything ✗ → "Setup incomplete: <first failure>."

View File

@@ -0,0 +1,23 @@
---
description: Read-only Claude-Mailbox health check. No changes, no installs — just report.
allowed-tools: Bash, Read
---
Report the Claude-Mailbox setup status without making any changes. If something is wrong, **tell** the user but **do not** fix it — suggest `/claude-mailbox:mailbox-doctor` for that.
Print exactly this block, filling in each line:
```
Claude-Mailbox status
binary: <output of `claude-mailbox --version`, or "not installed">
daemon: <output of `claude-mailbox status`>
health: <"ok" if GET http://127.0.0.1:37849/health returns 200, else "unreachable">
mailbox name: <value of env.CLAUDE_MAILBOX_NAME in ./.claude/settings.json, or "unset"; also note if ~/.claude/settings.json has a value>
pending: <integer count from `claude-mailbox peek --name <resolved-name>` if name is set, else "n/a">
```
End with one line:
- All good → `Status: OK`
- Missing daemon or unset name → `Status: Setup incomplete. Run /claude-mailbox:mailbox-doctor to fix.`
- Daemon installed but stopped → `Status: Daemon is not running. Try \`claude-mailbox start\` or run /claude-mailbox:mailbox-doctor.`

View File

@@ -0,0 +1,56 @@
---
description: Update the Claude-Mailbox daemon to the latest published npm version and restart it.
allowed-tools: Bash
---
You are running the **Claude-Mailbox update** command. Update the `@kuns/claude-mailbox` npm package and restart the daemon. Never run `sudo` automatically — if elevation is needed, stop and ask.
## Step 1 — current version
Run: `claude-mailbox --version`
- Exit 0 → record the version string as `CURRENT`.
- Non-zero → tell the user the daemon binary is not installed yet. Suggest `/claude-mailbox:mailbox-doctor` to do a full setup and stop.
## Step 2 — latest published version
Run: `npm view @kuns/claude-mailbox version`
If the npm registry config is missing, the call may fail with a 404. Fall back to:
```
npm view --registry=https://git.kuns.dev/api/packages/releases/npm/ @kuns/claude-mailbox version
```
Record the result as `LATEST`.
## Step 3 — compare
- If `CURRENT === LATEST`: print "Already up to date (vX.Y.Z)." and stop. Do not run any further steps.
- Otherwise: tell the user `CURRENT``LATEST` and ask for confirmation before proceeding.
## Step 4 — perform the update
On user confirmation, run these in order. Stop on the first failure and report it:
1. `claude-mailbox stop`
2. `npm install -g @kuns/claude-mailbox@latest`
- On Linux/macOS this may fail with EACCES. **Do not run sudo automatically.** Ask the user how they want to proceed (e.g., `sudo npm install -g …`, or switch to a user-scoped Node setup with nvm/fnm).
3. `claude-mailbox start`
4. `claude-mailbox --version` to verify the upgrade landed.
5. `claude-mailbox status` to verify the daemon is `Running`.
## Step 5 — summary
Print exactly this block:
```
Claude-Mailbox update
previous version: <CURRENT>
new version: <whatever --version now reports>
daemon: Running | Stopped | NotInstalled
pending messages survived: <count of messages still in inbox via `claude-mailbox list`, if applicable>
```
If the new version matches `LATEST` and daemon is `Running`, end with: "Update complete."
Otherwise, end with the first thing that went wrong.

24
plugin/hooks/hooks.json Normal file
View File

@@ -0,0 +1,24 @@
{
"hooks": {
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "claude-mailbox session-announce"
}
]
}
],
"UserPromptSubmit": [
{
"hooks": [
{
"type": "command",
"command": "claude-mailbox check --hook"
}
]
}
]
}
}

View File

@@ -5,7 +5,7 @@ namespace ClaudeMailbox.Cli;
public static class ClientCommands public static class ClientCommands
{ {
private const string DefaultUrl = "http://127.0.0.1:47822"; private const string DefaultUrl = "http://127.0.0.1:37849";
public static async Task<int> RunAsync(string[] args) public static async Task<int> RunAsync(string[] args)
{ {

View File

@@ -61,7 +61,7 @@ public static class ServiceCommands
if (!File.Exists(configPath)) if (!File.Exists(configPath))
{ {
var portStr = ClientCommands.GetOption(args, "--port"); var portStr = ClientCommands.GetOption(args, "--port");
var port = int.TryParse(portStr, out var p) ? p : 47822; var port = int.TryParse(portStr, out var p) ? p : 37849;
var bind = ClientCommands.GetOption(args, "--bind") ?? "127.0.0.1"; var bind = ClientCommands.GetOption(args, "--bind") ?? "127.0.0.1";
var dbPath = ClientCommands.GetOption(args, "--db-path") ?? defaultDbPath; var dbPath = ClientCommands.GetOption(args, "--db-path") ?? defaultDbPath;

View File

@@ -2,7 +2,7 @@ namespace ClaudeMailbox.Config;
public sealed class DaemonConfig public sealed class DaemonConfig
{ {
public const int DefaultPort = 47822; public const int DefaultPort = 37849;
public const string DefaultBindAddress = "127.0.0.1"; public const string DefaultBindAddress = "127.0.0.1";
public int Port { get; init; } = DefaultPort; public int Port { get; init; } = DefaultPort;