import { v as validateAuth } from './auth-DeCdZ83n.js';
import { readdirSync, readFileSync } from 'fs';
import { homedir } from 'os';
import { join } from 'path';
import { t as toErrorMessage } from './error-DDXB3duW.js';
import { j as json } from './shared-server-sSGG17Df.js';
import 'crypto';

function cwdToProjectPath(cwd) {
  return cwd.replace(/\//g, "-");
}
function isProcessAlive(pid) {
  try {
    process.kill(pid, 0);
    return true;
  } catch {
    return false;
  }
}
const CLAUDE_SESSIONS_DIR = join(homedir(), ".claude", "sessions");
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 {
  }
  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-CtH0dhUp.js.map
