// ../dist/daemon/index.js
import { createServer as createServer2 } from "node:http";
import { writeFileSync as writeFileSync3, existsSync as existsSync3, readFileSync as readFileSync6 } from "node:fs";
import { join as join5, dirname as dirname5 } from "node:path";
import { fileURLToPath as fileURLToPath5 } from "node:url";
import { homedir as homedir3 } from "node:os";

// ../dist/engine/bypass.js
import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { homedir } from "node:os";
var __filename = fileURLToPath(import.meta.url);
var __dirname = dirname(__filename);
function resolveStateDir() {
  if (process.env.CRYPT_STATE_DIR)
    return process.env.CRYPT_STATE_DIR;
  const home = homedir();
  const dragonConfig = join(home, ".dragon", "config.json");
  if (existsSync(dragonConfig)) {
    try {
      const cfg = JSON.parse(readFileSync(dragonConfig, "utf-8"));
      const cryptRoot = cfg?.platforms?.CRYPT_ROOT;
      if (cryptRoot) {
        const resolved = cryptRoot.startsWith("~") ? join(home, cryptRoot.slice(1)) : join(cryptRoot);
        if (existsSync(resolved))
          return join(resolved, ".crypt-state");
      }
    } catch {
    }
  }
  const appSupport = join(home, "Library", "Application Support", "DragonCrypt");
  if (existsSync(appSupport))
    return join(appSupport, ".crypt-state");
  return join(__dirname, "..", "..", ".crypt-state");
}
var STATE_DIR = resolveStateDir();
var STATE_FILE = join(STATE_DIR, "bypass.json");
var DEFAULT_STATE = {
  bypass: true,
  lastToggled: (/* @__PURE__ */ new Date()).toISOString(),
  toggledBy: "init"
};
function ensureStateDir() {
  if (!existsSync(STATE_DIR)) {
    mkdirSync(STATE_DIR, { recursive: true });
  }
}
function readState() {
  ensureStateDir();
  if (!existsSync(STATE_FILE)) {
    const initial = { ...DEFAULT_STATE, lastToggled: (/* @__PURE__ */ new Date()).toISOString() };
    writeFileSync(STATE_FILE, JSON.stringify(initial, null, 2), "utf-8");
    return initial;
  }
  try {
    const raw = readFileSync(STATE_FILE, "utf-8");
    const parsed = JSON.parse(raw);
    if (typeof parsed.bypass !== "boolean") {
      throw new Error("Corrupted state: bypass field is not boolean");
    }
    return parsed;
  } catch {
    const reset = { ...DEFAULT_STATE, lastToggled: (/* @__PURE__ */ new Date()).toISOString() };
    writeFileSync(STATE_FILE, JSON.stringify(reset, null, 2), "utf-8");
    return reset;
  }
}
function persistState(state) {
  ensureStateDir();
  writeFileSync(STATE_FILE, JSON.stringify(state, null, 2), "utf-8");
}
function isBypassed() {
  return readState().bypass;
}
function getBypassState() {
  return readState();
}
function toggle(by = "cli") {
  const current = readState();
  const next = {
    bypass: !current.bypass,
    lastToggled: (/* @__PURE__ */ new Date()).toISOString(),
    toggledBy: by
  };
  persistState(next);
  return next;
}
function setBypass(value, by = "cli") {
  const next = {
    bypass: value,
    lastToggled: (/* @__PURE__ */ new Date()).toISOString(),
    toggledBy: by
  };
  persistState(next);
  return next;
}

// ../dist/engine/masker.js
import { readFileSync as readFileSync2 } from "node:fs";
import { join as join2, dirname as dirname2 } from "node:path";
import { randomBytes } from "node:crypto";
import { fileURLToPath as fileURLToPath2 } from "node:url";
var __filename2 = fileURLToPath2(import.meta.url);
var __dirname2 = dirname2(__filename2);
var PROJECT_ROOT = join2(__dirname2, "..", "..");
var DEFAULT_PATTERNS_PATH = join2(PROJECT_ROOT, "rules", "patterns.json");
var CATEGORY_PREFIX = {
  secrets: "SECRET",
  infrastructure: "INFRA",
  ip: "IP",
  custom: "CUSTOM"
};
var sessions = /* @__PURE__ */ new Map();
var loadedPatterns = null;
function loadPatterns(patternsPath = DEFAULT_PATTERNS_PATH) {
  if (loadedPatterns)
    return loadedPatterns;
  try {
    const raw = readFileSync2(patternsPath, "utf-8");
    const config = JSON.parse(raw);
    loadedPatterns = config.patterns;
    return loadedPatterns;
  } catch (err) {
    console.error(`[CRYPT] Failed to load patterns from ${patternsPath}:`, err);
    loadedPatterns = [];
    return loadedPatterns;
  }
}
function generateSessionId() {
  return `crypt_${Date.now()}_${randomBytes(4).toString("hex")}`;
}
function getSession(sessionId) {
  return sessions.get(sessionId);
}
function purgeSession(sessionId) {
  return sessions.delete(sessionId);
}
function activeSessionCount() {
  return sessions.size;
}
function mask(content, source, sessionId) {
  const originalByteSize = Buffer.byteLength(content, "utf-8");
  if (isBypassed()) {
    const sid2 = sessionId ?? generateSessionId();
    return {
      sessionId: sid2,
      masked: content,
      redactionCount: 0,
      originalByteSize,
      maskedByteSize: originalByteSize
    };
  }
  const sid = sessionId ?? generateSessionId();
  let session = sessions.get(sid);
  if (!session) {
    session = {
      id: sid,
      entries: /* @__PURE__ */ new Map(),
      createdAt: Date.now(),
      source
    };
    sessions.set(sid, session);
  }
  const patterns = loadPatterns();
  let masked = content;
  let globalIndex = session.entries.size;
  for (const pattern of patterns) {
    try {
      const regex = new RegExp(pattern.regex, pattern.flags);
      const prefix = CATEGORY_PREFIX[pattern.category] ?? "REDACTED";
      masked = masked.replace(regex, (fullMatch, ...args) => {
        const capturedValue = pattern.captureGroup !== void 0 ? args[pattern.captureGroup - 1] : void 0;
        const secretValue = capturedValue ?? fullMatch;
        for (const [alias2, entry2] of session.entries) {
          if (entry2.original === secretValue) {
            return capturedValue ? fullMatch.replace(capturedValue, alias2) : alias2;
          }
        }
        const index = globalIndex++;
        const alias = `[CRYPT_${prefix}_${index}]`;
        const entry = {
          alias,
          original: secretValue,
          patternId: pattern.id,
          category: pattern.category,
          index
        };
        session.entries.set(alias, entry);
        return capturedValue ? fullMatch.replace(capturedValue, alias) : alias;
      });
    } catch (err) {
      console.error(`[CRYPT] Pattern "${pattern.id}" failed:`, err);
    }
  }
  const maskedByteSize = Buffer.byteLength(masked, "utf-8");
  return {
    sessionId: sid,
    masked,
    redactionCount: session.entries.size,
    originalByteSize,
    maskedByteSize
  };
}

// ../dist/audit/shadow.js
import Database from "better-sqlite3";
import { mkdirSync as mkdirSync2, existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
import { join as join3, dirname as dirname3 } from "node:path";
import { fileURLToPath as fileURLToPath3 } from "node:url";
import { homedir as homedir2 } from "node:os";
var __filename3 = fileURLToPath3(import.meta.url);
var __dirname3 = dirname3(__filename3);
function resolveStateDir2() {
  if (process.env.CRYPT_STATE_DIR)
    return process.env.CRYPT_STATE_DIR;
  const home = homedir2();
  const dragonConfig = join3(home, ".dragon", "config.json");
  if (existsSync2(dragonConfig)) {
    try {
      const cfg = JSON.parse(readFileSync3(dragonConfig, "utf-8"));
      const cryptRoot = cfg?.platforms?.CRYPT_ROOT;
      if (cryptRoot) {
        const resolved = cryptRoot.startsWith("~") ? join3(home, cryptRoot.slice(1)) : join3(cryptRoot);
        if (existsSync2(resolved))
          return join3(resolved, ".crypt-state");
      }
    } catch {
    }
  }
  const appSupport = join3(home, "Library", "Application Support", "DragonCrypt");
  if (existsSync2(appSupport))
    return join3(appSupport, ".crypt-state");
  return join3(__dirname3, "..", "..", ".crypt-state");
}
var STATE_DIR2 = resolveStateDir2();
var DB_PATH = join3(STATE_DIR2, "shadow.db");
var db = null;
function getDb() {
  if (db)
    return db;
  if (!existsSync2(STATE_DIR2)) {
    mkdirSync2(STATE_DIR2, { recursive: true });
  }
  db = new Database(DB_PATH);
  db.pragma("journal_mode = WAL");
  db.exec(`
    CREATE TABLE IF NOT EXISTS audit_log (
      id              INTEGER PRIMARY KEY AUTOINCREMENT,
      timestamp       TEXT    NOT NULL,
      destination     TEXT    NOT NULL CHECK(destination IN ('antigravity', 'claude', 'glyph')),
      payload_bytes   INTEGER NOT NULL,
      masked_content  TEXT    NOT NULL,
      session_id      TEXT    NOT NULL,
      redaction_count INTEGER NOT NULL DEFAULT 0
    );

    CREATE INDEX IF NOT EXISTS idx_audit_timestamp ON audit_log(timestamp);
    CREATE INDEX IF NOT EXISTS idx_audit_destination ON audit_log(destination);
    CREATE INDEX IF NOT EXISTS idx_audit_session ON audit_log(session_id);
  `);
  return db;
}
var insertStmt = null;
function getInsertStmt() {
  if (insertStmt)
    return insertStmt;
  insertStmt = getDb().prepare(`
    INSERT INTO audit_log (timestamp, destination, payload_bytes, masked_content, session_id, redaction_count)
    VALUES (@timestamp, @destination, @payloadByteSize, @maskedContent, @sessionId, @redactionCount)
  `);
  return insertStmt;
}
function logPayload(destination, maskedContent, sessionId, redactionCount) {
  const entry = {
    timestamp: (/* @__PURE__ */ new Date()).toISOString(),
    destination,
    payloadByteSize: Buffer.byteLength(maskedContent, "utf-8"),
    maskedContent,
    sessionId,
    redactionCount
  };
  getInsertStmt().run(entry);
  return entry;
}
function getRecentLogs(limit = 50) {
  const stmt = getDb().prepare("SELECT * FROM audit_log ORDER BY id DESC LIMIT ?");
  return stmt.all(limit);
}
function getTotalBytes(destination) {
  if (destination) {
    const stmt2 = getDb().prepare("SELECT COALESCE(SUM(payload_bytes), 0) as total FROM audit_log WHERE destination = ?");
    const row2 = stmt2.get(destination);
    return row2.total;
  }
  const stmt = getDb().prepare("SELECT COALESCE(SUM(payload_bytes), 0) as total FROM audit_log");
  const row = stmt.get();
  return row.total;
}
function closeAuditDb() {
  if (db) {
    db.close();
    db = null;
    insertStmt = null;
  }
}

// ../dist/router/antigravity.js
import { readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
import { createServer } from "node:http";

// ../dist/engine/unmasker.js
function unmask(content, sessionId, keepSession = false) {
  if (isBypassed()) {
    return {
      restored: content,
      restorationCount: 0
    };
  }
  const session = getSession(sessionId);
  if (!session) {
    console.warn(`[CRYPT] No session found for ID "${sessionId}" \u2014 returning content as-is`);
    return {
      restored: content,
      restorationCount: 0
    };
  }
  let restored = content;
  let restorationCount = 0;
  const sortedEntries = [...session.entries.entries()].sort(([a], [b]) => b.length - a.length);
  for (const [alias, entry] of sortedEntries) {
    const before = restored;
    restored = restored.split(alias).join(entry.original);
    if (restored !== before) {
      restorationCount++;
    }
  }
  if (!keepSession) {
    purgeSession(sessionId);
  }
  return {
    restored,
    restorationCount
  };
}
function containsAliases(content) {
  return /\[CRYPT_(?:SECRET|INFRA|IP|CUSTOM|REDACTED)_\d+\]/.test(content);
}

// ../dist/engine/pathguard.js
import { resolve, relative, isAbsolute } from "node:path";
import { readFileSync as readFileSync4 } from "node:fs";
import { join as join4, dirname as dirname4 } from "node:path";
import { fileURLToPath as fileURLToPath4 } from "node:url";
var __filename4 = fileURLToPath4(import.meta.url);
var __dirname4 = dirname4(__filename4);
var PROJECT_ROOT2 = join4(__dirname4, "..", "..");
var CRYPTIGNORE_PATH = join4(PROJECT_ROOT2, "rules", "default.cryptignore");
var blockedPatterns = null;
function loadCryptignore() {
  if (blockedPatterns)
    return blockedPatterns;
  try {
    const raw = readFileSync4(CRYPTIGNORE_PATH, "utf-8");
    blockedPatterns = raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
    return blockedPatterns;
  } catch {
    blockedPatterns = [];
    return blockedPatterns;
  }
}
function globToRegex(glob) {
  let regex = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]").replace(/\{\{GLOBSTAR\}\}/g, ".*");
  return new RegExp(`^${regex}$`);
}
function validatePath(requestedPath, allowedRoots) {
  const resolved = resolve(requestedPath);
  const isUnderAllowedRoot = allowedRoots.some((root) => {
    const resolvedRoot = resolve(root);
    const rel = relative(resolvedRoot, resolved);
    return !rel.startsWith("..") && !isAbsolute(rel);
  });
  if (!isUnderAllowedRoot) {
    throw new Error(`[CRYPT BLOCKED] Path traversal detected: "${requestedPath}" is outside allowed roots`);
  }
  const patterns = loadCryptignore();
  for (const pattern of patterns) {
    const regex = globToRegex(pattern);
    if (regex.test(resolved)) {
      throw new Error(`[CRYPT BLOCKED] Path matches cryptignore rule: "${pattern}"`);
    }
    const segments = resolved.split("/");
    for (let i = 0; i < segments.length; i++) {
      const partial = segments.slice(i).join("/");
      if (regex.test(partial)) {
        throw new Error(`[CRYPT BLOCKED] Path matches cryptignore rule: "${pattern}"`);
      }
    }
  }
  return resolved;
}

// ../dist/router/antigravity.js
var ALLOWED_ROOTS = process.env.CRYPT_ALLOWED_ROOTS ? process.env.CRYPT_ALLOWED_ROOTS.split(":") : [process.cwd()];
var DEFAULT_PORT = 7600;
var fileSessionMap = /* @__PURE__ */ new Map();
var TOOLS = [
  {
    name: "read_file",
    description: "Read file contents (may be redacted for IP protection)",
    inputSchema: {
      type: "object",
      properties: {
        path: { type: "string", description: "Absolute path to the file" }
      },
      required: ["path"]
    }
  },
  {
    name: "write_file",
    description: "Write content to a file (redaction aliases are auto-restored)",
    inputSchema: {
      type: "object",
      properties: {
        path: { type: "string", description: "Absolute path to the file" },
        content: { type: "string", description: "Content to write" }
      },
      required: ["path", "content"]
    }
  }
];
function handleReadFile(params) {
  const filePath = params.path;
  if (!filePath)
    throw new Error("Missing required parameter: path");
  const validPath = validatePath(filePath, ALLOWED_ROOTS);
  const raw = readFileSync5(validPath, "utf-8");
  const result = mask(raw, "antigravity");
  fileSessionMap.set(validPath, result.sessionId);
  logPayload("antigravity", result.masked, result.sessionId, result.redactionCount);
  return { content: [{ type: "text", text: result.masked }] };
}
function handleWriteFile(params) {
  const filePath = params.path;
  const content = params.content;
  if (!filePath || content === void 0)
    throw new Error("Missing required parameters");
  const validPath = validatePath(filePath, ALLOWED_ROOTS);
  let finalContent = content;
  const sessionId = fileSessionMap.get(validPath);
  if (sessionId) {
    const result = unmask(content, sessionId);
    finalContent = result.restored;
    fileSessionMap.delete(validPath);
  } else if (containsAliases(content)) {
    throw new Error("[CRYPT] Aliases found but no session exists \u2014 aborting write");
  }
  writeFileSync2(validPath, finalContent, "utf-8");
  return { content: [{ type: "text", text: `Wrote ${Buffer.byteLength(finalContent)} bytes to ${filePath}` }] };
}
function handleRequest(request) {
  try {
    switch (request.method) {
      case "initialize":
        return {
          jsonrpc: "2.0",
          id: request.id,
          result: {
            protocolVersion: "2024-11-05",
            capabilities: { tools: {} },
            serverInfo: { name: "dragon-crypt-antigravity", version: "0.1.0" }
          }
        };
      case "notifications/initialized":
        return { jsonrpc: "2.0", id: request.id, result: {} };
      case "tools/list":
        return { jsonrpc: "2.0", id: request.id, result: { tools: TOOLS } };
      case "tools/call": {
        const p = request.params;
        const toolName = p?.name;
        const toolArgs = p?.arguments ?? {};
        const result = toolName === "read_file" ? handleReadFile(toolArgs) : toolName === "write_file" ? handleWriteFile(toolArgs) : (() => {
          throw new Error(`Unknown tool: ${toolName}`);
        })();
        return { jsonrpc: "2.0", id: request.id, result };
      }
      default:
        return { jsonrpc: "2.0", id: request.id, error: { code: -32601, message: `Unknown method: ${request.method}` } };
    }
  } catch (err) {
    return {
      jsonrpc: "2.0",
      id: request.id,
      error: { code: -32e3, message: err instanceof Error ? err.message : String(err) }
    };
  }
}
function readBody(req) {
  return new Promise((resolve2, reject) => {
    const chunks = [];
    req.on("data", (chunk) => chunks.push(chunk));
    req.on("end", () => resolve2(Buffer.concat(chunks).toString("utf-8")));
    req.on("error", reject);
  });
}
function startAntigravityRouter(port = DEFAULT_PORT) {
  const bypassed = isBypassed();
  const server = createServer(async (req, res) => {
    if (req.method !== "POST" || req.url !== "/mcp") {
      res.writeHead(404, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ error: "Not found. Use POST /mcp" }));
      return;
    }
    try {
      const body = await readBody(req);
      const request = JSON.parse(body);
      const response = handleRequest(request);
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify(response));
    } catch (err) {
      const errorResponse = {
        jsonrpc: "2.0",
        id: null,
        error: { code: -32700, message: "Parse error: " + (err instanceof Error ? err.message : String(err)) }
      };
      res.writeHead(400, { "Content-Type": "application/json" });
      res.end(JSON.stringify(errorResponse));
    }
  });
  server.listen(port, "127.0.0.1", () => {
    console.error(`[CRYPT] Antigravity router listening on http://127.0.0.1:${port}/mcp | mode: ${bypassed ? "PASSTHROUGH \u26A1" : "SECURE \u{1F512}"}`);
  });
}

// ../dist/daemon/index.js
var __filename5 = fileURLToPath5(import.meta.url);
var __dirname5 = dirname5(__filename5);
function resolveProjectRoot() {
  const home = homedir3();
  const dragonConfig = join5(home, ".dragon", "config.json");
  if (existsSync3(dragonConfig)) {
    try {
      const cfg = JSON.parse(readFileSync6(dragonConfig, "utf-8"));
      const cryptRoot = cfg?.platforms?.CRYPT_ROOT;
      if (cryptRoot) {
        const resolved = cryptRoot.startsWith("~") ? join5(home, cryptRoot.slice(1)) : join5(cryptRoot);
        if (existsSync3(resolved))
          return resolved;
      }
    } catch {
    }
  }
  const appSupport = join5(home, "Library", "Application Support", "DragonCrypt");
  if (existsSync3(appSupport))
    return appSupport;
  return join5(__dirname5, "..", "..");
}
var PROJECT_ROOT3 = resolveProjectRoot();
var STATE_DIR3 = join5(PROJECT_ROOT3, ".crypt-state");
var PID_FILE = join5(STATE_DIR3, "daemon.pid");
var IPC_PORT = parseInt(process.env.CRYPT_IPC_PORT ?? "7601", 10);
var MCP_PORT = parseInt(process.env.CRYPT_MCP_PORT ?? "7600", 10);
function readBody2(req) {
  return new Promise((resolve2, reject) => {
    const chunks = [];
    req.on("data", (c) => chunks.push(c));
    req.on("end", () => resolve2(Buffer.concat(chunks).toString("utf-8")));
    req.on("error", reject);
  });
}
function json(res, status, data) {
  res.writeHead(status, { "Content-Type": "application/json" });
  res.end(JSON.stringify(data, null, 2));
}
function createIpcServer() {
  return createServer2(async (req, res) => {
    const url = req.url ?? "/";
    if (req.method === "GET" && url === "/health") {
      json(res, 200, { status: "alive", pid: process.pid, uptime: process.uptime() });
      return;
    }
    if (req.method === "GET" && url === "/status") {
      const state = getBypassState();
      json(res, 200, {
        bypass: state.bypass,
        mode: state.bypass ? "PASSTHROUGH \u26A1" : "SECURE \u{1F512}",
        lastToggled: state.lastToggled,
        toggledBy: state.toggledBy,
        activeSessions: activeSessionCount(),
        totalBytesLogged: getTotalBytes(),
        pid: process.pid
      });
      return;
    }
    if (req.method === "POST" && url === "/toggle") {
      const body = await readBody2(req);
      let by = "ipc";
      try {
        const parsed = JSON.parse(body);
        if (parsed.by)
          by = parsed.by;
      } catch {
      }
      const newState = toggle(by);
      console.error(`[CRYPT] Toggled \u2192 ${newState.bypass ? "PASSTHROUGH \u26A1" : "SECURE \u{1F512}"} (by ${by})`);
      json(res, 200, {
        bypass: newState.bypass,
        mode: newState.bypass ? "PASSTHROUGH \u26A1" : "SECURE \u{1F512}",
        lastToggled: newState.lastToggled
      });
      return;
    }
    if (req.method === "POST" && url === "/set") {
      const body = await readBody2(req);
      try {
        const parsed = JSON.parse(body);
        if (typeof parsed.bypass !== "boolean") {
          json(res, 400, { error: 'Body must include { "bypass": true|false }' });
          return;
        }
        const newState = setBypass(parsed.bypass, parsed.by ?? "ipc");
        json(res, 200, { bypass: newState.bypass, mode: newState.bypass ? "PASSTHROUGH \u26A1" : "SECURE \u{1F512}" });
      } catch {
        json(res, 400, { error: "Invalid JSON body" });
      }
      return;
    }
    if (req.method === "GET" && url.startsWith("/logs")) {
      const logs = getRecentLogs(25);
      json(res, 200, { count: logs.length, logs });
      return;
    }
    json(res, 404, { error: "Not found" });
  });
}
function writePidFile() {
  writeFileSync3(PID_FILE, String(process.pid), "utf-8");
}
function isAlreadyRunning() {
  if (!existsSync3(PID_FILE))
    return false;
  try {
    const pid = parseInt(readFileSync6(PID_FILE, "utf-8").trim(), 10);
    process.kill(pid, 0);
    return true;
  } catch {
    return false;
  }
}
function startDaemon() {
  if (isAlreadyRunning()) {
    console.error("[CRYPT] Daemon is already running. Use `crypt stop` first.");
    process.exit(1);
  }
  const state = getBypassState();
  console.error("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557");
  console.error("\u2551        \u{1F409} Dragon Crypt Daemon v0.1.0        \u2551");
  console.error("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");
  console.error(`\u2551  Mode:  ${state.bypass ? "PASSTHROUGH \u26A1 (inactive)       " : "SECURE \u{1F512} (masking active)      "}\u2551`);
  console.error(`\u2551  IPC:   http://127.0.0.1:${IPC_PORT}              \u2551`);
  console.error(`\u2551  MCP:   http://127.0.0.1:${MCP_PORT}              \u2551`);
  console.error(`\u2551  PID:   ${String(process.pid).padEnd(36)}\u2551`);
  console.error("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D");
  writePidFile();
  const ipcServer = createIpcServer();
  ipcServer.listen(IPC_PORT, "127.0.0.1", () => {
    console.error(`[CRYPT] IPC control plane on http://127.0.0.1:${IPC_PORT}`);
  });
  startAntigravityRouter(MCP_PORT);
  const shutdown = () => {
    console.error("\n[CRYPT] Shutting down gracefully...");
    closeAuditDb();
    ipcServer.close();
    try {
      writeFileSync3(PID_FILE, "", "utf-8");
    } catch {
    }
    process.exit(0);
  };
  process.on("SIGINT", shutdown);
  process.on("SIGTERM", shutdown);
}
var isMain = process.argv[1] && import.meta.url === `file://${process.argv[1]}` || import.meta.url === new URL(process.argv[1], "file://").href;
if (isMain) {
  startDaemon();
}
export {
  startDaemon
};
