import { v as validateAuth } from './auth-DeCdZ83n.js';
import { p as ptyManager } from './pty-manager-BQVB7IVj.js';
import { t as toErrorMessage } from './error-DDXB3duW.js';
import { j as json } from './shared-server-sSGG17Df.js';
import { realpathSync, statSync } from 'fs';
import { relative, isAbsolute } from 'path';
import 'crypto';
import 'child_process';
import 'url';
import 'net';
import 'better-sqlite3';
import './opencode-db-path-DcfhJtJy.js';

const POST = async ({ request }) => {
  const authError = validateAuth(request);
  if (authError) {
    return authError;
  }
  let body;
  try {
    body = await request.json();
  } catch {
    return json({ error: "Invalid JSON in request body" }, { status: 400 });
  }
  const { command, cwd, noCreate, sessionId } = body;
  if (!sessionId || typeof sessionId !== "string") {
    return json({ error: "sessionId is required (string)" }, { status: 400 });
  }
  if (!cwd || typeof cwd !== "string") {
    return json({ error: "cwd is required (string)" }, { status: 400 });
  }
  if (!command || command !== "claude" && command !== "opencode") {
    return json({ error: 'command must be "claude" or "opencode"' }, { status: 400 });
  }
  let realCwd;
  try {
    realCwd = realpathSync(cwd);
    if (!statSync(realCwd).isDirectory()) {
      return json({ error: "Invalid working directory" }, { status: 400 });
    }
  } catch {
    return json({ error: "Invalid working directory" }, { status: 400 });
  }
  const home = process.env.HOME || "";
  if (home) {
    const rel = relative(home, realCwd);
    if (rel.startsWith("..") || isAbsolute(rel)) {
      return json({ error: "Working directory must be under home directory" }, { status: 400 });
    }
  }
  const existing = ptyManager.list().find((t) => t.status === "running" && (t.sessionFile?.endsWith(`/${sessionId}.jsonl`) || t.openCodeSessionId === sessionId));
  if (existing) {
    console.log(
      `[sessions/connect] Reusing terminal ${existing.id} for ${command} session ${sessionId}`
    );
    return json({
      command: existing.command,
      createdAt: existing.createdAt.toISOString(),
      cwd: existing.cwd,
      id: existing.id,
      pid: existing.pid,
      reused: true,
      sessionId,
      sessionWs: `/ws/session/${existing.id}`,
      terminalId: existing.id,
      ws: `/ws/terminal/${existing.id}`
    });
  }
  if (noCreate) {
    return json({ error: "No existing terminal for this session" }, { status: 404 });
  }
  const args = command === "claude" ? ["--resume", sessionId] : ["--session", sessionId];
  try {
    const terminal = await ptyManager.create(command, args, realCwd, 120, 40);
    console.log(
      `[sessions/connect] Created terminal ${terminal.id} for ${command} session ${sessionId} (pid=${terminal.pid})`
    );
    return json(
      {
        command: terminal.command,
        createdAt: terminal.createdAt instanceof Date ? terminal.createdAt.toISOString() : terminal.createdAt,
        cwd: terminal.cwd,
        id: terminal.id,
        pid: terminal.pid,
        sessionId,
        sessionWs: `/ws/session/${terminal.id}`,
        terminalId: terminal.id,
        ws: `/ws/terminal/${terminal.id}`
      },
      { status: 201 }
    );
  } catch (error) {
    console.error("[sessions/connect] Failed to create terminal:", toErrorMessage(error));
    return json({ error: "Failed to create terminal for session" }, { status: 500 });
  }
};

export { POST };
//# sourceMappingURL=_server.ts-DYpJImqd.js.map
