import { v as validateAuth } from './auth-DuunT7Cg.js';
import { r as resolveOpenCodeDbPath, d as detectActiveCodexSessions, a as detectActiveGeminiSessions, b as detectActiveQwenSessions, c as detectActiveCursorSessions, e as detectActiveCopilotSessions, f as detectActiveAmpSessions } from './qwen-reader-DGfUbKaJ.js';
import Database from 'better-sqlite3';
import { execSync } from 'child_process';
import { readdirSync, readFileSync, existsSync } from 'fs';
import { homedir } from 'os';
import { join } from 'path';
import { t as toErrorMessage } from './error-DDXB3duW.js';
import { j as json } from './index-CoD1IJuy.js';
import './shared-server-DaWdgxVh.js';
import 'crypto';

function cwdToProjectPath(cwd) {
  return cwd.replace(/\//g, "-");
}
function isOpenCodeRunning() {
  try {
    execSync("pgrep -x opencode", { stdio: "ignore" });
    return true;
  } catch {
    return false;
  }
}
function isProcessAlive(pid) {
  try {
    process.kill(pid, 0);
    return true;
  } catch {
    return false;
  }
}
const CLAUDE_SESSIONS_DIR = join(homedir(), ".claude", "sessions");
const OPENCODE_ACTIVE_THRESHOLD_MS = 3 * 6e4;
const FILE_PROVIDER_ACTIVE_THRESHOLD_MS = 3 * 6e4;
const FILE_PROVIDER_DETECTORS = [
  { command: "codex", detect: detectActiveCodexSessions },
  { command: "gemini", detect: detectActiveGeminiSessions },
  { command: "qwen", detect: detectActiveQwenSessions },
  { command: "cursor-agent", detect: detectActiveCursorSessions },
  { command: "copilot", detect: detectActiveCopilotSessions },
  { command: "amp", detect: detectActiveAmpSessions }
];
function detectRunningAISessions() {
  const results = [];
  try {
    const files = readdirSync(CLAUDE_SESSIONS_DIR).filter((f) => f.endsWith(".json"));
    for (const file of files) {
      try {
        const raw = readFileSync(join(CLAUDE_SESSIONS_DIR, file), "utf-8");
        const data = JSON.parse(raw);
        if (!data.pid || !data.sessionId || !data.cwd) {
          continue;
        }
        if (!isProcessAlive(data.pid)) {
          continue;
        }
        results.push({
          command: "claude",
          cwd: data.cwd,
          kind: data.kind || "interactive",
          pid: data.pid,
          projectPath: cwdToProjectPath(data.cwd),
          sessionId: data.sessionId,
          startedAt: data.startedAt || 0
        });
      } catch {
      }
    }
  } catch {
  }
  if (isOpenCodeRunning()) {
    try {
      const dbPath = resolveOpenCodeDbPath();
      if (existsSync(dbPath)) {
        const db = new Database(dbPath, { readonly: true });
        try {
          const cutoff = Date.now() - OPENCODE_ACTIVE_THRESHOLD_MS;
          const cutoffSec = Math.floor(cutoff / 1e3);
          const rows = db.prepare(
            `SELECT id, directory, time_created, time_updated
               FROM session
               WHERE (time_archived IS NULL OR time_archived = 0)
                 AND (
                   (time_updated >= 1e12 AND time_updated > ?)
                   OR (time_updated < 1e12 AND time_updated > ?)
                 )
               ORDER BY time_updated DESC
               LIMIT 20`
          ).all(cutoff, cutoffSec);
          for (const row of rows) {
            const startMs = row.time_created >= 1e12 ? row.time_created : row.time_created * 1e3;
            results.push({
              command: "opencode",
              cwd: row.directory || "",
              kind: "interactive",
              pid: 0,
              // OpenCode doesn't expose per-session PIDs
              projectPath: cwdToProjectPath(row.directory || ""),
              sessionId: row.id,
              startedAt: startMs
            });
          }
        } finally {
          db.close();
        }
      }
    } catch {
    }
  }
  for (const { command, detect } of FILE_PROVIDER_DETECTORS) {
    try {
      for (const s of detect(FILE_PROVIDER_ACTIVE_THRESHOLD_MS)) {
        results.push({
          command,
          cwd: s.cwd,
          kind: "interactive",
          pid: 0,
          projectPath: cwdToProjectPath(s.cwd),
          sessionId: s.id,
          startedAt: s.startedAt
        });
      }
    } catch {
    }
  }
  results.sort((a, b) => b.startedAt - a.startedAt);
  return results;
}
const GET = ({ request }) => {
  const authError = validateAuth(request);
  if (authError) {
    return authError;
  }
  try {
    const processes = detectRunningAISessions();
    return json({
      count: processes.length,
      processes,
      timestamp: (/* @__PURE__ */ new Date()).toISOString()
    });
  } catch (error) {
    console.error("[sessions/detect] Failed to detect running sessions:", toErrorMessage(error));
    return json({ error: "Failed to detect running sessions" }, { status: 500 });
  }
};

export { GET };
//# sourceMappingURL=_server.ts-MbnroWEF.js.map
