Skip to content

armgit / hypit

Public Imported from GitHub
0

Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.

4.5 KB
Raw Blame
import { spawn } from "node:child_process";
import { once } from "node:events";
import { mediaProcessEnv } from "./process-env.js";

type ProcessInput = Uint8Array | Iterable<Uint8Array> | AsyncIterable<Uint8Array>;
type ProcessOutput = { readonly stdout: Buffer; readonly stderr: string };

function run(
  executable: string,
  args: readonly string[],
  input: ProcessInput | undefined,
  timeoutMs: number,
  onStderrLine?: (line: string) => void,
  maxStdoutBytes = Number.POSITIVE_INFINITY,
  environment?: NodeJS.ProcessEnv,
): Promise<ProcessOutput> {
  return new Promise((resolveRun, reject) => {
    const child = spawn(executable, [...args], {
      stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
      windowsHide: true,
      ...(environment === undefined ? {} : { env: environment }),
    });
    const out: Buffer[] = [];
    let stdoutBytes = 0;
    let err = "";
    let settled = false;
    const finish = (error?: Error): void => {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      if (error === undefined) resolveRun({ stdout: Buffer.concat(out), stderr: err });
      else reject(error);
    };
    const timer = setTimeout(() => { child.kill("SIGKILL"); finish(new Error(`${executable} timed out after ${timeoutMs} ms`)); }, timeoutMs);
    child.stdout?.on("data", (chunk: Buffer) => {
      stdoutBytes += chunk.byteLength;
      if (stdoutBytes > maxStdoutBytes) {
        child.kill("SIGKILL");
        finish(new Error(`${executable} output exceeded the configured limit`));
        return;
      }
      out.push(chunk);
    });
    let pendingLine = "";
    child.stderr?.on("data", (chunk: Buffer) => {
      const text = chunk.toString("utf8");
      err = `${err}${text}`.slice(-100_000);
      if (onStderrLine !== undefined) {
        const lines = `${pendingLine}${text}`.split(/\r?\n/u);
        pendingLine = lines.pop()!;
        for (const line of lines) onStderrLine(line);
      }
    });
    child.on("error", (error) => finish(new Error(`${executable} could not start: ${error.message}`)));
    child.on("close", (code) => {
      if (code === 0) finish();
      else finish(new Error(`${executable} exited with ${code}: ${err.trim()}`));
    });
    if (input !== undefined && child.stdin !== null) {
      child.stdin.on("error", (error: NodeJS.ErrnoException) => {
        if (error.code !== "EPIPE") finish(new Error(`${executable} input failed: ${error.message}`));
      });
      void (async () => {
        const chunks: Iterable<Uint8Array> | AsyncIterable<Uint8Array> = input instanceof Uint8Array ? [input] : input;
        for await (const chunk of chunks) {
          if (!child.stdin!.write(chunk)) await once(child.stdin!, "drain");
        }
        child.stdin!.end();
      })().catch((error: unknown) => {
        if (!(error instanceof Error && "code" in error && error.code === "EPIPE")) {
          child.kill("SIGKILL");
          finish(error instanceof Error ? error : new Error(String(error)));
        }
      });
    }
  });
}

/** Shared bounded process boundary for the Provider and direct-file ports of local media. */
export async function runBoundedMediaProcess(options: {
  readonly executable: string;
  readonly argv: readonly string[];
  readonly timeoutMs: number;
  readonly maxStdoutBytes: number;
  readonly sharedLibraryPath?: string;
}): Promise<Uint8Array> {
  return (await run(options.executable, options.argv, undefined, options.timeoutMs, undefined,
    options.maxStdoutBytes,
    mediaProcessEnv(options.sharedLibraryPath === undefined ? undefined : {
      LD_LIBRARY_PATH: options.sharedLibraryPath,
    }))).stdout;
}

/** Run one external program to completion and return its stdout; stderr becomes the error text. */
export async function runProcess(executable: string, args: readonly string[], timeoutMs = 300_000): Promise<Buffer> {
  return (await run(executable, args, undefined, timeoutMs)).stdout;
}

/** Successful stderr can carry tool metadata, such as the timestamp of an extracted frame. */
export function runProcessOutput(executable: string, args: readonly string[], timeoutMs = 300_000, onStderrLine?: (line: string) => void): Promise<ProcessOutput> {
  return run(executable, args, undefined, timeoutMs, onStderrLine);
}

/** The same process boundary when a deterministic byte stream is one of the program's inputs. */
export async function runProcessWithInput(
  executable: string,
  args: readonly string[],
  input: ProcessInput,
  timeoutMs = 300_000,
): Promise<Buffer> {
  return (await run(executable, args, input, timeoutMs)).stdout;
}