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>
This commit is contained in:
mika kuns
2026-04-30 14:06:46 +02:00
parent 757a095c10
commit 05d87d2aa7
26 changed files with 5638 additions and 40 deletions

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,226 @@
import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { run, cliEntry, type AutostartManager, type AutostartInstallOpts } from "./index.js";
import { userConfigPath } from "../config.js";
const TASK_NAME = "ClaudeMailbox";
const SERVICE_NAME = "ClaudeMailbox";
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 scheduledTaskInstall(opts: AutostartInstallOpts): void {
const configPath = ensureConfigSeeded(opts);
const { node, script } = buildServeCommand();
const tr = `"${node}" "${script}" serve --config "${configPath}"`;
const r = run("schtasks.exe", [
"/Create",
"/SC",
"ONLOGON",
"/TN",
TASK_NAME,
"/TR",
tr,
"/RL",
"LIMITED",
"/F",
]);
if (r.status !== 0) {
throw new Error(`schtasks /Create failed (exit ${r.status}): ${r.stderr || r.stdout}`);
}
const start = run("schtasks.exe", ["/Run", "/TN", TASK_NAME]);
if (start.status !== 0) {
console.warn(`Task created but /Run returned ${start.status}: ${start.stderr.trim()}`);
}
}
function scheduledTaskUninstall(purge: boolean): void {
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)) {
throw new Error(`schtasks /Delete failed (exit ${r.status}): ${r.stderr || r.stdout}`);
}
if (purge) purgeData();
}
function scheduledTaskStatus(): "Running" | "Stopped" | "NotInstalled" {
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)) return "NotInstalled";
return "Stopped";
}
if (/Status:\s*Running/i.test(r.stdout)) return "Running";
return "Stopped";
}
function scheduledTaskRun(): void {
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 {
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();
},
};
}