Skip to content

Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.

7.3 KB
Raw Blame
// Chế độ "claude": chạy Claude Code headless (claude -p) trong thư mục job với quyền hẹp.
// KHÔNG dùng cờ bỏ qua quyền. Chạy khoá (mặc định, xem engine/sandbox.mjs restrictMode): Read/Write/Edit chỉ trong
// thư mục job (./**) và đúng 1 lệnh preview; env không mang khoá/token; LUMREELS_JAIL = thư mục job cho preview.mjs.
// LUMREELS_RESTRICT=off (hoặc community với mẫu gốc): bộ tool cũ (Read/Write/Edit trần + preview/render).
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn, spawnSync } from 'node:child_process';
import { stripSecrets } from '../engine/sandbox.mjs';

export function findClaude() {
  if (process.env.CLAUDE_BIN && fs.existsSync(process.env.CLAUDE_BIN)) return process.env.CLAUDE_BIN;
  const which = spawnSync(process.platform === 'win32' ? 'where.exe' : 'which', ['claude'], { encoding: 'utf8' });
  const hits = (which.stdout || '').split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
  // Windows: `where claude` liệt kê cả shim bash không đuôi của npm (spawn ra ENOENT) → ưu tiên .exe, rồi .cmd
  const hit = hits.find((h) => /\.exe$/i.test(h)) || hits.find((h) => /\.cmd$/i.test(h)) || hits[0];
  if (hit) return hit;
  const home = os.homedir();
  const cands = [path.join(home, '.local', 'bin', 'claude.exe'), path.join(home, '.local', 'bin', 'claude')];
  return cands.find((c) => fs.existsSync(c)) || null;
}

/**
 * Lệnh thật để chạy Claude Code: { cmd, pre }. Trên Windows, Node không spawn được shim .cmd / shim không đuôi
 * của npm nếu không qua shell (ENOENT / EINVAL), mà qua shell thì phải tự quote tham số. Nên đọc shim lấy đích thật:
 * cli.js → chạy bằng chính node đang chạy LumReels; .exe → chạy thẳng.
 */
export function claudeCommand() {
  const bin = findClaude();
  if (!bin) return null;
  if (process.platform !== 'win32' || /\.exe$/i.test(bin)) return { cmd: bin, pre: [] };
  const dir = path.dirname(bin);
  const asCmd = (t) => (/\.exe$/i.test(t) ? { cmd: t, pre: [] } : { cmd: process.execPath, pre: [t] });
  const base = bin.replace(/\.(cmd|ps1)$/i, '');
  for (const shim of [base + '.cmd', base + '.ps1', base]) {
    let txt = '';
    try { txt = fs.readFileSync(shim, 'utf8'); } catch { continue; }
    // npm cmd-shim: "%dp0%\node_modules\...\cli.js" | ps1/sh: "$basedir/node_modules/.../cli.js"
    const m = txt.match(/(?:%~?dp0%?|\$basedir)[\\/]([^"'\r\n%]+?\.(?:c?js|mjs|exe))/i);
    if (m) {
      const t = path.join(dir, ...m[1].split(/[\\/]/));
      if (fs.existsSync(t)) return asCmd(t);
    }
  }
  for (const rel of [['node_modules', '@anthropic-ai', 'claude-code', 'cli.js'], ['node_modules', '@anthropic-ai', 'claude-code', 'bin', 'claude.exe']]) {
    const t = path.join(dir, ...rel);
    if (fs.existsSync(t)) return asCmd(t);
  }
  return { cmd: bin, pre: [] };
}

/** spawn Claude Code với tham số đã cho (qua claudeCommand). */
export function spawnClaude(args, opts) {
  const c = claudeCommand();
  if (!c) throw new Error('Không tìm thấy lệnh claude (cài Claude Code hoặc đặt CLAUDE_BIN)');
  return spawn(c.cmd, [...c.pre, ...args], opts);
}

/** Bộ tool chạy khoá (L1): đọc/ghi/sửa chỉ trong cwd = thư mục job, Bash chỉ đúng lệnh preview. */
export const ALLOWED_TOOLS = [
  'Read(./**)',
  'Write(./**)',
  'Edit(./**)',
  'Bash(node ../../engine/preview.mjs:*)',
];
/** Bộ tool cũ (LUMREELS_RESTRICT=off, hoặc mẫu gốc khi cờ = community). */
export const LEGACY_TOOLS = [
  'Read',
  'Write',
  'Edit',
  'Bash(node ../../engine/preview.mjs:*)',
  'Bash(node ../../engine/render.mjs:*)',
];

/** Env cho tiến trình Claude có tool: bỏ mọi biến tên chứa KEY/TOKEN/SECRET/PASSWORD (L2), giữ token đăng nhập của chính Claude Code. */
export function claudeEnv(extra = {}) {
  return { ...stripSecrets(process.env, { keep: ['CLAUDE_CODE_OAUTH_TOKEN'] }), ...extra };
}

export function claudeArgs({ maxTurns = 40, model, restricted = true } = {}) {
  return [
    ...(model ? ['--model', model] : []),
    '-p',
    '--output-format', 'stream-json', '--verbose',
    '--permission-mode', 'default',
    // chạy khoá: chỉ nạp 4 tool lõi (không thấy cả Artifact/WebFetch/… để khỏi thử rồi bị từ chối — job đối chứng 018 từng gọi Artifact)
    ...(restricted ? ['--tools', 'Read,Write,Edit,Bash'] : []),
    '--allowedTools', ...(restricted ? ALLOWED_TOOLS : LEGACY_TOOLS),
    '--disallowedTools', 'WebFetch', 'WebSearch', 'Agent', 'NotebookEdit',
    '--setting-sources', 'project',
    '--strict-mcp-config',
    '--no-session-persistence',
    '--max-turns', String(maxTurns),
  ];
}

/** Chạy claude headless, prompt qua stdin. Trả {ok, error?, result?}. */
export function runClaude(cwd, prompt, log = console.log, { timeoutMs = 25 * 60 * 1000, model, restricted = true } = {}) {
  const bin = findClaude();
  if (!bin) return Promise.resolve({ ok: false, error: 'Không tìm thấy lệnh claude (đặt CLAUDE_BIN hoặc thêm vào PATH)' });
  return new Promise((resolve) => {
    log(`claude: ${bin}${model ? ' · model ' + model : ''}${restricted ? ' · chạy khoá' : ''} (cwd ${cwd})`);
    const env = restricted ? claudeEnv({ LUMREELS_JAIL: path.resolve(cwd) }) : (({ ANTHROPIC_API_KEY, LUMREELS_JAIL, ...e }) => e)(process.env);
    const p = spawnClaude(claudeArgs({ model, restricted }), { cwd, windowsHide: true, env });
    const raw = fs.createWriteStream(path.join(cwd, 'claude.stream.jsonl'));
    let buf = '';
    let result = null;
    let errText = '';
    const timer = setTimeout(() => { log('claude: quá thời gian, dừng'); p.kill(); }, timeoutMs);
    p.stdout.on('data', (d) => {
      raw.write(d);
      buf += d.toString();
      let i;
      while ((i = buf.indexOf('\n')) >= 0) {
        const line = buf.slice(0, i); buf = buf.slice(i + 1);
        try {
          const ev = JSON.parse(line);
          if (ev.type === 'assistant') {
            for (const c of ev.message?.content || []) {
              if (c.type === 'tool_use') log(`claude → ${c.name} ${JSON.stringify(c.input).slice(0, 140)}`);
              else if (c.type === 'text' && c.text.trim()) log('claude: ' + c.text.trim().slice(0, 300));
            }
          } else if (ev.type === 'result') result = ev;
        } catch { /* dòng không phải JSON */ }
      }
    });
    p.stderr.on('data', (d) => { errText += d.toString(); });
    p.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, error: 'spawn claude lỗi: ' + e.message }); });
    p.on('close', (code) => {
      clearTimeout(timer);
      raw.end();
      if (errText.trim()) log('claude stderr: ' + errText.trim().slice(-1500));
      for (const d of result?.permission_denials || []) log(`claude: bị từ chối ${d.tool_name} ${JSON.stringify(d.tool_input || {}).slice(0, 200)}`);
      const sceneOk = fs.existsSync(path.join(cwd, 'scene', 'index.html'));
      if (code !== 0 || result?.is_error) {
        return resolve({ ok: false, error: `claude thoát mã ${code}: ${(result?.result || errText || '').toString().trim().slice(-800)}` });
      }
      if (!sceneOk) return resolve({ ok: false, error: 'claude chạy xong nhưng không có scene/index.html' });
      resolve({ ok: true, result: result?.result });
    });
    p.stdin.end(prompt);
  });
}