import { v as validateAuth } from './auth-DuunT7Cg.js';
import { P as PROVIDER_COMMANDS } 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 ALLOWED_COMMANDS = ["zsh", "bash", "sh", "fish", ...PROVIDER_COMMANDS];
function lastScrollbackLine(scrollback) {
  if (!scrollback) {
    return null;
  }
  const lines = scrollback.trimEnd().split("\n");
  for (let i = lines.length - 1; i >= 0; i--) {
    const line = lines[i].trim();
    if (line) {
      return line.slice(0, 200);
    }
  }
  return null;
}
const GET = ({ request }) => {
  const authError = validateAuth(request);
  if (authError) {
    return authError;
  }
  try {
    const terminals = ptyManager.list().map((t) => ({
      args: t.args,
      clientCount: t.clients.size,
      command: t.command,
      createdAt: t.createdAt.toISOString(),
      currentCwd: t.currentCwd,
      cwd: t.cwd,
      exitCode: t.exitCode,
      exitedAt: t.exitedAt?.toISOString() ?? null,
      id: t.id,
      isActive: t.isActive,
      lastOutput: lastScrollbackLine(t.scrollback),
      pid: t.pid,
      status: t.status
    }));
    return json({
      count: terminals.length,
      terminals,
      timestamp: (/* @__PURE__ */ new Date()).toISOString()
    });
  } catch (error) {
    console.error("[terminals] Failed to list terminals:", toErrorMessage(error));
    return json({ error: "Failed to list terminals" }, { status: 500 });
  }
};
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 });
  }
  try {
    const { args, cols, command, cwd, rows } = body;
    if (!command) {
      return json({ error: "command is required" }, { status: 400 });
    }
    if (command.includes("/") || command.includes("\\") || !ALLOWED_COMMANDS.includes(command)) {
      return json(
        { error: `Command not allowed. Allowed: ${ALLOWED_COMMANDS.join(", ")}` },
        { status: 400 }
      );
    }
    if (!cwd) {
      return json({ error: "cwd is required" }, { status: 400 });
    }
    let realCwd;
    try {
      realCwd = realpathSync(cwd);
      if (!statSync(realCwd).isDirectory()) {
        return json({ error: "cwd must be a directory" }, { status: 400 });
      }
    } catch {
      return json({ error: "cwd must be a 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 });
      }
    }
    if (args !== void 0 && !Array.isArray(args)) {
      return json({ error: "args must be an array of strings" }, { status: 400 });
    }
    if (args && !args.every((a) => typeof a === "string")) {
      return json({ error: "All args must be strings" }, { status: 400 });
    }
    if (cols !== void 0 && (typeof cols !== "number" || cols < 1)) {
      return json({ error: "cols must be a positive number" }, { status: 400 });
    }
    if (rows !== void 0 && (typeof rows !== "number" || rows < 1)) {
      return json({ error: "rows must be a positive number" }, { status: 400 });
    }
    const terminal = await ptyManager.create(command, args ?? [], realCwd, cols ?? 80, rows ?? 24);
    console.log(
      `[terminals] Created terminal ${terminal.id} (pid=${terminal.pid}, command=${command})`
    );
    return json(
      {
        command: terminal.command,
        createdAt: terminal.createdAt instanceof Date ? terminal.createdAt.toISOString() : terminal.createdAt,
        cwd: terminal.cwd,
        id: terminal.id,
        pid: terminal.pid,
        sessionWs: `/ws/session/${terminal.id}`,
        ws: `/ws/terminal/${terminal.id}`
      },
      { status: 201 }
    );
  } catch (error) {
    console.error("[terminals] Failed to create terminal:", toErrorMessage(error));
    return json({ error: "Failed to create terminal" }, { status: 500 });
  }
};

export { GET, POST };
//# sourceMappingURL=_server.ts-l3cd4Cto.js.map
