import { v as validateAuth } from './auth-DuunT7Cg.js';
import { P as PROVIDER_COMMANDS, r as resumeArgsForCommand } from './registry-D4J_CuzW.js';
import { p as ptyManager } from './pty-manager-DDjG7DlH.js';
import { t as toErrorMessage } from './error-DDXB3duW.js';
import { j as json } from './index-CoD1IJuy.js';
import { realpathSync, statSync } from 'fs';
import { relative, isAbsolute } from 'path';
import './shared-server-DaWdgxVh.js';
import 'crypto';
import './qwen-reader-DGfUbKaJ.js';
import 'os';
import 'better-sqlite3';
import 'child_process';
import 'url';
import './guest-registry-Dxvd7p-g.js';
import './super-session-handler-DPyxFgmz.js';
import './coordinator-DMU_ADXf.js';
import 'net';
import 'node:module';
import './shooter-home-4f_HkdGI.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 (!/^[A-Za-z0-9_.-]+$/.test(sessionId)) {
    return json({ error: "Invalid sessionId format" }, { status: 400 });
  }
  if (!cwd || typeof cwd !== "string") {
    return json({ error: "cwd is required (string)" }, { status: 400 });
  }
  if (!command || !PROVIDER_COMMANDS.includes(command)) {
    return json(
      { error: `command must be one of: ${PROVIDER_COMMANDS.join(", ")}` },
      { 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" && // Claude / Cursor / Qwen: <id>.jsonl ; Codex rollout: rollout-<ts>-<id>.jsonl ;
    // Copilot: <id>.jsonl OR <id>/events.jsonl ; Amp: T-<id>.json ; OpenCode: session id
    (t.sessionFile?.endsWith(`/${sessionId}.jsonl`) || t.sessionFile?.endsWith(`-${sessionId}.jsonl`) || t.sessionFile?.endsWith(`/${sessionId}/events.jsonl`) || t.sessionFile?.endsWith(`/T-${sessionId}.json`) || 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 = resumeArgsForCommand(command, 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-CYWXjihn.js.map
