import { i as defineEventHandler, y as getRouterParam, e as createError, r as getActiveRun, f as createEventStream, c as clearActiveRun, R as setActiveRun } from '../../../../nitro/nitro.mjs';
import { spawn } from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
import 'node:module';
import 'node:os';
import 'dotenv';
import 'node:http';
import 'node:https';
import 'node:events';
import 'node:buffer';
import 'node:crypto';
import 'node:async_hooks';
import 'node:url';
import 'node:net';
import '@iconify/utils';
import 'consola';

const execute_post = defineEventHandler(async (event) => {
  var _a;
  const id = getRouterParam(event, "id");
  if (!id) {
    throw createError({ statusCode: 400, statusMessage: "Missing task id" });
  }
  const cwd = process.env.AIDEV_CWD;
  if (!cwd) {
    throw createError({ statusCode: 500, statusMessage: "AIDEV_CWD not set" });
  }
  const pkgDir = (_a = process.env.AIDEV_PACKAGE_DIR) != null ? _a : cwd;
  const cli = path.join(pkgDir, "dist", "cli.js");
  if (!fs.existsSync(cli)) {
    throw createError({
      statusCode: 503,
      statusMessage: `aidev CLI not found at ${cli}. Run \`npm run build\` in the aidev repo before executing tasks.`
    });
  }
  if (getActiveRun()) {
    throw createError({
      statusCode: 409,
      statusMessage: "Another aidev run is already in progress. Cancel it before starting a new one."
    });
  }
  const stream = createEventStream(event);
  const child = spawn(process.execPath, [cli, "run", "--task", id], {
    cwd,
    env: process.env,
    stdio: ["ignore", "pipe", "pipe"]
  });
  setActiveRun(child, "task", id);
  function pump(source, eventName) {
    let buf = "";
    source.setEncoding("utf8");
    source.on("data", (chunk) => {
      buf += chunk;
      let nl = buf.indexOf("\n");
      while (nl !== -1) {
        const line = buf.slice(0, nl).replace(/\r$/, "");
        buf = buf.slice(nl + 1);
        stream.push({ event: eventName, data: line });
        nl = buf.indexOf("\n");
      }
    });
    source.on("end", () => {
      if (buf.length > 0) stream.push({ event: eventName, data: buf.replace(/\r$/, "") });
    });
  }
  pump(child.stdout, "stdout");
  pump(child.stderr, "stderr");
  child.on("error", (err) => {
    clearActiveRun(child);
    stream.push({ event: "error", data: JSON.stringify({ message: err.message, code: err.code }) });
    stream.close();
  });
  child.on("exit", (code, signal) => {
    clearActiveRun(child);
    stream.push({ event: "exit", data: JSON.stringify({ code, signal }) });
    stream.close();
  });
  stream.onClosed(() => {
    if (!child.killed && child.exitCode === null) {
      child.kill("SIGTERM");
    }
    clearActiveRun(child);
  });
  return stream.send();
});

export { execute_post as default };
//# sourceMappingURL=execute.post.mjs.map
