// src/server/index.ts
import { dirname, resolve } from "path";
import { fileURLToPath } from "url";
import { createServer } from "http";
import { Hono as Hono2 } from "hono";
import { cors } from "hono/cors";
import { serveStatic } from "@hono/node-server/serve-static";
import { existsSync, readFileSync } from "fs";
import { createAgentX } from "agentxjs";
import { homedir } from "os";
import { join } from "path";
import { mkdirSync } from "fs";

// src/server/auth.ts
import { Hono } from "hono";
import { createMiddleware } from "hono/factory";
import * as jose from "jose";
var TOKEN_EXPIRY = "7d";
function isValidInviteCode(code) {
  const timestamp = parseInt(code, 10);
  if (isNaN(timestamp)) return false;
  const now = /* @__PURE__ */ new Date();
  const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 1);
  const expectedTimestamp = Math.floor(todayStart.getTime() / 1e3);
  return timestamp === expectedTimestamp;
}
async function createToken(secret, userId) {
  const secretKey = new TextEncoder().encode(secret);
  const token = await new jose.SignJWT({ sub: userId }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(TOKEN_EXPIRY).sign(secretKey);
  return token;
}
async function verifyToken(secret, token) {
  try {
    const secretKey = new TextEncoder().encode(secret);
    const { payload } = await jose.jwtVerify(token, secretKey);
    return { userId: payload.sub };
  } catch {
    return null;
  }
}
function toUserInfo(user) {
  return {
    userId: user.userId,
    username: user.username,
    email: user.email,
    containerId: user.containerId,
    displayName: user.displayName,
    avatar: user.avatar,
    createdAt: user.createdAt
  };
}
function authRoutes(userRepository, jwtSecret, agentx, config = {}) {
  const app = new Hono();
  const { inviteCodeRequired = true } = config;
  app.get("/config", (c) => {
    return c.json({ inviteCodeRequired });
  });
  app.post("/register", async (c) => {
    try {
      const body = await c.req.json();
      if (!body.username || !body.password) {
        return c.json({ error: "Username and password are required" }, 400);
      }
      if (inviteCodeRequired && (!body.inviteCode || !isValidInviteCode(body.inviteCode))) {
        return c.json({ error: "Invalid invite code" }, 400);
      }
      if (body.username.length < 3) {
        return c.json({ error: "Username must be at least 3 characters" }, 400);
      }
      if (body.password.length < 6) {
        return c.json({ error: "Password must be at least 6 characters" }, 400);
      }
      if (body.email && !body.email.includes("@")) {
        return c.json({ error: "Invalid email format" }, 400);
      }
      const containerId = `user-${crypto.randomUUID()}`;
      const containerRes = await agentx.request("container_create_request", { containerId });
      if (containerRes.data.error) {
        return c.json({ error: "Failed to create user container" }, 500);
      }
      const user = await userRepository.createUser({
        username: body.username,
        email: body.email,
        password: body.password,
        containerId,
        displayName: body.displayName,
        avatar: body.avatar
      });
      const token = await createToken(jwtSecret, user.userId);
      return c.json(
        {
          token,
          user: toUserInfo(user),
          expiresIn: TOKEN_EXPIRY
        },
        201
      );
    } catch (error) {
      const message = error instanceof Error ? error.message : "Registration failed";
      return c.json({ error: message }, 400);
    }
  });
  app.post("/login", async (c) => {
    try {
      const body = await c.req.json();
      if (!body.usernameOrEmail || !body.password) {
        return c.json({ error: "Username/email and password are required" }, 400);
      }
      const user = await userRepository.verifyPassword(body.usernameOrEmail, body.password);
      if (!user) {
        return c.json({ error: "Invalid credentials" }, 401);
      }
      const token = await createToken(jwtSecret, user.userId);
      return c.json({
        token,
        user: toUserInfo(user),
        expiresIn: TOKEN_EXPIRY
      });
    } catch (error) {
      const message = error instanceof Error ? error.message : "Login failed";
      return c.json({ error: message }, 500);
    }
  });
  app.get("/verify", async (c) => {
    const authHeader = c.req.header("Authorization");
    if (!authHeader || !authHeader.startsWith("Bearer ")) {
      return c.json({ valid: false }, 401);
    }
    const token = authHeader.slice(7);
    const result = await verifyToken(jwtSecret, token);
    if (!result) {
      return c.json({ valid: false }, 401);
    }
    const user = await userRepository.findUserById(result.userId);
    if (!user || !user.isActive) {
      return c.json({ valid: false }, 401);
    }
    return c.json({ valid: true, user: toUserInfo(user) });
  });
  app.post("/logout", (c) => {
    return c.json({ success: true });
  });
  return app;
}
function createAuthMiddleware(jwtSecret) {
  return createMiddleware(async (c, next) => {
    const url = new URL(c.req.url);
    const queryToken = url.searchParams.get("token");
    const authHeader = c.req.header("Authorization");
    let token = null;
    if (authHeader && authHeader.startsWith("Bearer ")) {
      token = authHeader.slice(7);
    } else if (queryToken) {
      token = queryToken;
    }
    if (!token) {
      return c.json({ error: "Unauthorized" }, 401);
    }
    const result = await verifyToken(jwtSecret, token);
    if (!result) {
      return c.json({ error: "Invalid token" }, 401);
    }
    c.set("userId", result.userId);
    c.header("X-User-Id", result.userId);
    await next();
  });
}

// src/server/database/SQLiteUserRepository.ts
import Database from "better-sqlite3";
import { randomUUID } from "crypto";
import { hash, compare } from "bcrypt";
var SALT_ROUNDS = 10;
var SQLiteUserRepository = class {
  db;
  constructor(dbPath) {
    this.db = new Database(dbPath);
    this.initDatabase();
  }
  /**
   * Initialize database schema
   */
  initDatabase() {
    this.db.pragma("foreign_keys = ON");
    this.db.exec(`
      CREATE TABLE IF NOT EXISTS users (
        userId TEXT PRIMARY KEY,
        username TEXT UNIQUE NOT NULL,
        email TEXT UNIQUE NOT NULL,
        passwordHash TEXT NOT NULL,
        containerId TEXT NOT NULL,
        displayName TEXT,
        avatar TEXT,
        isActive INTEGER NOT NULL DEFAULT 1,
        createdAt INTEGER NOT NULL,
        updatedAt INTEGER NOT NULL
      );

      CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
      CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
      CREATE INDEX IF NOT EXISTS idx_users_containerId ON users(containerId);
    `);
  }
  /**
   * Create a new user
   */
  async createUser(input) {
    if (await this.usernameExists(input.username)) {
      throw new Error(`Username '${input.username}' already exists`);
    }
    if (input.email && await this.emailExists(input.email)) {
      throw new Error(`Email '${input.email}' already exists`);
    }
    const passwordHash = await hash(input.password, SALT_ROUNDS);
    const userId = randomUUID();
    const now = Date.now();
    const email = input.email || `${userId}@noemail.portagent`;
    const user = {
      userId,
      username: input.username,
      email,
      passwordHash,
      containerId: input.containerId,
      displayName: input.displayName,
      avatar: input.avatar,
      isActive: true,
      createdAt: now,
      updatedAt: now
    };
    const stmt = this.db.prepare(`
      INSERT INTO users (
        userId, username, email, passwordHash, containerId, displayName, avatar, isActive, createdAt, updatedAt
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `);
    stmt.run(
      user.userId,
      user.username,
      user.email,
      user.passwordHash,
      user.containerId,
      user.displayName,
      user.avatar,
      user.isActive ? 1 : 0,
      user.createdAt,
      user.updatedAt
    );
    return user;
  }
  /**
   * Find user by ID
   */
  async findUserById(userId) {
    const stmt = this.db.prepare(`
      SELECT * FROM users WHERE userId = ?
    `);
    const row = stmt.get(userId);
    return row ? this.rowToUser(row) : null;
  }
  /**
   * Find user by username
   */
  async findUserByUsername(username) {
    const stmt = this.db.prepare(`
      SELECT * FROM users WHERE username = ?
    `);
    const row = stmt.get(username);
    return row ? this.rowToUser(row) : null;
  }
  /**
   * Find user by email
   */
  async findUserByEmail(email) {
    const stmt = this.db.prepare(`
      SELECT * FROM users WHERE email = ?
    `);
    const row = stmt.get(email);
    return row ? this.rowToUser(row) : null;
  }
  /**
   * Find user by username or email
   */
  async findUserByUsernameOrEmail(usernameOrEmail) {
    const stmt = this.db.prepare(`
      SELECT * FROM users WHERE username = ? OR email = ?
    `);
    const row = stmt.get(usernameOrEmail, usernameOrEmail);
    return row ? this.rowToUser(row) : null;
  }
  /**
   * Update user
   */
  async updateUser(userId, updates) {
    const user = await this.findUserById(userId);
    if (!user) {
      throw new Error(`User ${userId} not found`);
    }
    const fields = [];
    const values = [];
    if (updates.username !== void 0) {
      fields.push("username = ?");
      values.push(updates.username);
    }
    if (updates.email !== void 0) {
      fields.push("email = ?");
      values.push(updates.email);
    }
    if (updates.passwordHash !== void 0) {
      fields.push("passwordHash = ?");
      values.push(updates.passwordHash);
    }
    if (updates.displayName !== void 0) {
      fields.push("displayName = ?");
      values.push(updates.displayName);
    }
    if (updates.avatar !== void 0) {
      fields.push("avatar = ?");
      values.push(updates.avatar);
    }
    if (updates.isActive !== void 0) {
      fields.push("isActive = ?");
      values.push(updates.isActive ? 1 : 0);
    }
    fields.push("updatedAt = ?");
    values.push(Date.now());
    if (fields.length === 0) {
      return user;
    }
    values.push(userId);
    const stmt = this.db.prepare(`
      UPDATE users SET ${fields.join(", ")} WHERE userId = ?
    `);
    stmt.run(...values);
    return await this.findUserById(userId);
  }
  /**
   * Delete user
   */
  async deleteUser(userId) {
    const stmt = this.db.prepare(`
      DELETE FROM users WHERE userId = ?
    `);
    const result = stmt.run(userId);
    return result.changes > 0;
  }
  /**
   * List all users
   */
  async listUsers() {
    const stmt = this.db.prepare(`
      SELECT * FROM users ORDER BY createdAt DESC
    `);
    const rows = stmt.all();
    return rows.map((row) => this.rowToUser(row));
  }
  /**
   * Check if username exists
   */
  async usernameExists(username) {
    const stmt = this.db.prepare(`
      SELECT 1 FROM users WHERE username = ?
    `);
    return stmt.get(username) !== void 0;
  }
  /**
   * Check if email exists
   */
  async emailExists(email) {
    const stmt = this.db.prepare(`
      SELECT 1 FROM users WHERE email = ?
    `);
    return stmt.get(email) !== void 0;
  }
  /**
   * Verify password for login
   *
   * @param usernameOrEmail - Username or email
   * @param password - Plain text password
   * @returns User record if valid, null if invalid
   */
  async verifyPassword(usernameOrEmail, password) {
    const user = await this.findUserByUsernameOrEmail(usernameOrEmail);
    if (!user) {
      return null;
    }
    if (!user.isActive) {
      return null;
    }
    const isValid = await compare(password, user.passwordHash);
    return isValid ? user : null;
  }
  /**
   * Close database connection
   */
  close() {
    this.db.close();
  }
  // ============================================================================
  // Private Helpers
  // ============================================================================
  rowToUser(row) {
    return {
      userId: row.userId,
      username: row.username,
      email: row.email,
      passwordHash: row.passwordHash,
      containerId: row.containerId,
      displayName: row.displayName,
      avatar: row.avatar,
      isActive: row.isActive === 1,
      createdAt: row.createdAt,
      updatedAt: row.updatedAt
    };
  }
};

// src/server/logger.ts
import pino from "pino";
import fs from "fs";
import path from "path";
var LEVEL_MAP = {
  debug: "debug",
  info: "info",
  warn: "warn",
  error: "error",
  silent: "silent"
};
var PinoLoggerAdapter = class {
  constructor(name, level, pino2) {
    this.name = name;
    this.level = level;
    this.pino = pino2;
  }
  debug(message, context) {
    this.pino.debug(context || {}, message);
  }
  info(message, context) {
    this.pino.info(context || {}, message);
  }
  warn(message, context) {
    this.pino.warn(context || {}, message);
  }
  error(message, context) {
    if (message instanceof Error) {
      this.pino.error({ ...context, err: message }, message.message);
    } else {
      this.pino.error(context || {}, message);
    }
  }
  isDebugEnabled() {
    return this.pino.isLevelEnabled("debug");
  }
  isInfoEnabled() {
    return this.pino.isLevelEnabled("info");
  }
  isWarnEnabled() {
    return this.pino.isLevelEnabled("warn");
  }
  isErrorEnabled() {
    return this.pino.isLevelEnabled("error");
  }
};
var PinoLoggerFactory = class {
  rootLogger;
  constructor(options) {
    const { level, logDir, pretty = process.env.NODE_ENV !== "production" } = options;
    if (!fs.existsSync(logDir)) {
      fs.mkdirSync(logDir, { recursive: true });
    }
    const getLogFilePath = () => {
      const now = /* @__PURE__ */ new Date();
      const dateStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
      return path.join(logDir, `portagent-${dateStr}.log`);
    };
    const targets = [];
    targets.push({
      target: "pino/file",
      level: LEVEL_MAP[level],
      options: {
        destination: getLogFilePath(),
        mkdir: true
      }
    });
    if (pretty) {
      targets.push({
        target: "pino-pretty",
        level: LEVEL_MAP[level],
        options: {
          colorize: true,
          translateTime: "SYS:standard",
          ignore: "pid,hostname"
        }
      });
    } else {
      targets.push({
        target: "pino/file",
        level: LEVEL_MAP[level],
        options: { destination: 1 }
        // stdout
      });
    }
    this.rootLogger = pino({
      level: LEVEL_MAP[level],
      transport: {
        targets
      }
    });
  }
  getLogger(name) {
    const childLogger = this.rootLogger.child({ name });
    return new PinoLoggerAdapter(name, this.rootLogger.level, childLogger);
  }
};

// src/server/index.ts
var __filename = fileURLToPath(import.meta.url);
var __dirname = dirname(__filename);
function getDataPaths() {
  const dataDir = process.env.AGENTX_DIR || join(homedir(), ".agentx");
  const dataDirPath = join(dataDir, "data");
  const logsDirPath = join(dataDir, "logs");
  mkdirSync(dataDirPath, { recursive: true });
  mkdirSync(logsDirPath, { recursive: true });
  return {
    dataDir,
    dataDirPath,
    logsDirPath,
    userDbPath: join(dataDirPath, "portagent.db"),
    agentxDbPath: join(dataDirPath, "agentx.db"),
    logFilePath: join(logsDirPath, "portagent.log")
  };
}
var PORT = parseInt(process.env.PORT || "5200", 10);
var JWT_SECRET = process.env.JWT_SECRET || crypto.randomUUID();
var INVITE_CODE_REQUIRED = process.env.INVITE_CODE_REQUIRED === "true";
async function createApp() {
  const paths = getDataPaths();
  const app = new Hono2();
  app.use(
    "*",
    cors({
      origin: "*",
      allowMethods: ["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"],
      allowHeaders: ["Content-Type", "Authorization"]
    })
  );
  const apiKey = process.env.LLM_PROVIDER_KEY;
  if (!apiKey) {
    console.error("Error: LLM_PROVIDER_KEY is required");
    console.log("\nSet it via environment variable:");
    console.log("  export LLM_PROVIDER_KEY=sk-ant-xxx");
    process.exit(1);
  }
  const { getRequestListener } = await import("@hono/node-server");
  const listener = getRequestListener(app.fetch);
  const server = createServer(listener);
  const logLevel = process.env.LOG_LEVEL || "info";
  const loggerFactory = new PinoLoggerFactory({
    level: logLevel,
    logDir: paths.logsDirPath,
    pretty: process.env.NODE_ENV !== "production"
  });
  const agentx = await createAgentX({
    llm: {
      apiKey,
      baseUrl: process.env.LLM_PROVIDER_URL,
      model: process.env.LLM_PROVIDER_MODEL
    },
    logger: {
      level: logLevel,
      factory: loggerFactory
    },
    agentxDir: paths.dataDir,
    // Auto-configures storage at {dataDir}/data/agentx.db
    server
    // Attach to existing HTTP server
  });
  const userRepository = new SQLiteUserRepository(paths.userDbPath);
  const authMiddleware = createAuthMiddleware(JWT_SECRET);
  app.get("/health", (c) => c.json({ status: "ok", timestamp: Date.now() }));
  app.route(
    "/api/auth",
    authRoutes(userRepository, JWT_SECRET, agentx, { inviteCodeRequired: INVITE_CODE_REQUIRED })
  );
  app.use("/agentx/*", authMiddleware);
  app.get("/agentx/info", (c) => {
    return c.json({
      version: "0.1.0",
      wsPath: "/ws"
    });
  });
  const publicDir = resolve(__dirname, "../public");
  const isDev = process.env.NODE_ENV !== "production";
  if (existsSync(publicDir)) {
    app.use("/*", serveStatic({ root: publicDir }));
    app.get("*", (c) => {
      const indexPath = resolve(publicDir, "index.html");
      if (existsSync(indexPath)) {
        const html = readFileSync(indexPath, "utf-8");
        return c.html(html);
      }
      return c.text("Not Found", 404);
    });
  } else if (isDev) {
    app.get("*", (c) => {
      return c.text(
        "Static files not found. Run 'pnpm build:client' first, or use 'pnpm dev' for development.",
        404
      );
    });
  }
  return { app, server, agentx, userRepository, paths };
}
async function startServer() {
  const { server, agentx, userRepository, paths } = await createApp();
  console.log(`
  ____            _                         _
 |  _ \\ ___  _ __| |_ __ _  __ _  ___ _ __ | |_
 | |_) / _ \\| '__| __/ _\` |/ _\` |/ _ \\ '_ \\| __|
 |  __/ (_) | |  | || (_| | (_| |  __/ | | | |_
 |_|   \\___/|_|   \\__\\__,_|\\__, |\\___|_| |_|\\__|
                           |___/

  AgentX Portal - Your AI Agent Gateway (Multi-User Mode)
`);
  console.log("Configuration:");
  console.log(`  Port: ${PORT}`);
  console.log(`  Data Dir: ${paths.dataDir}`);
  console.log(`  API Key: ${process.env.LLM_PROVIDER_KEY.substring(0, 15)}...`);
  console.log(`  User DB: ${paths.userDbPath}`);
  console.log(`  AgentX DB: ${paths.agentxDbPath}`);
  console.log(`  Logs: ${paths.logsDirPath}`);
  console.log(`  Invite Code: ${INVITE_CODE_REQUIRED ? "required" : "disabled"}`);
  console.log(`
Endpoints:`);
  console.log(`  GET  /health                    - Health check`);
  console.log(`  POST /api/auth/register         - Register new user`);
  console.log(`  POST /api/auth/login            - Login`);
  console.log(`  GET  /api/auth/verify           - Verify token`);
  console.log(`  GET  /agentx/info               - Platform info`);
  console.log(`  WS   /ws                        - WebSocket connection`);
  server.listen(PORT, "0.0.0.0", () => {
    console.log(`
\u{1F680} Server running at http://localhost:${PORT}`);
    console.log(`\u{1F50C} WebSocket available at ws://localhost:${PORT}/ws`);
  });
  const shutdown = async () => {
    console.log("\nShutting down...");
    await agentx.dispose();
    userRepository.close();
    server.close();
    console.log("Server stopped");
    process.exit(0);
  };
  process.on("SIGINT", shutdown);
  process.on("SIGTERM", shutdown);
}
export {
  createApp,
  startServer
};
//# sourceMappingURL=index.js.map