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.

29.6 KB
Raw Blame
#!/usr/bin/env node
// CLI cho người và AI agent.
//   node cli.mjs make --template 009[,045,062] --content <file|chuỗi> [--duration 8] [--ratio 9:16|16:9|4:3|3:4] [--mode manual|agent|claude|api|auto] [--at 2026-11-28T07:00] [--json]
//   node cli.mjs rewrite --template 009 --content <file|chuỗi> [--duration 30] [--engine auto|api|claude] [--json]
//   node cli.mjs run-due            (chạy các job hẹn giờ đã tới giờ — cho Windows Task Scheduler)
//   node cli.mjs render <jobId> [--quality draft|looks|delivery] [--audio file]
//   node cli.mjs audio <jobId> [--export]   (trộn + ghép tiếng theo scene/audio.json, không render lại hình)
//   node cli.mjs list [--json]
//   node cli.mjs show <jobId>
//   node cli.mjs templates [--json]
//   node cli.mjs edit <video> --style <id> [--music file] [--content "dặn thêm"] [--names "Lumfin, …"] [--target 45] [--draft] [--llm off] [--json]
//   node cli.mjs edit-revise <editId> "<lời sửa>" [--file f]   ·   edit-show <editId>   ·   edit-run <editId>   ·   edit-rm <editId>
//   node cli.mjs pack inspect|install|list|rm|export …   (gói mẫu .lumpack, xem: node cli.mjs pack)
//   node cli.mjs learn <video> --kind template --consent [--name "…"] [--from 0] [--note "…"] [--no-test] [--json]
//   node cli.mjs drafts [--json]  ·  draft-show <id>  ·  draft-save <id> --slug <slug> --name "…"  ·  draft-rm <id>
//   node cli.mjs voices [--json]   ·   voice-add <file> --name "Tên" --consent [--text "lời đoạn mẫu"]   ·   voice-rename <id> "Tên"   ·   voice-rm <id>
import fs from 'node:fs';
import path from 'node:path';
import { createJob, createJobs, parseTemplateIds, MAX_BATCH, runJob, renderJob, runDue, listJobs, readJob, readLog, jobPaths, loadCatalog, hasGuidance, exportOutput } from './generator/jobs.mjs';
import { parseArgs, probe } from './engine/lib.mjs';
import { rewriteScript } from './generator/rewrite.mjs';

const [cmd, ...rest] = process.argv.slice(2);
const { pos, opt } = parseArgs(rest);
const out = (o) => console.log(opt.json ? JSON.stringify(o, null, 2) : o);
/** --music <style|auto|none> --voice <tên|auto|none> --no-sfx → {music, voice, sfx}; trường không truyền = undefined (giữ như cũ). */
const audioOpts = () => ({ music: opt.music === true ? undefined : opt.music, voice: opt.voice === true ? undefined : opt.voice, sfx: opt['no-sfx'] ? false : opt.sfx ? true : undefined });

function usage() {
  console.log(`LumReels CLI
  make --template <id>[,<id>…] --content <file|chuỗi> [--duration 8] [--ratio 9:16] [--mode manual|claude|api|auto] [--model auto|opus|sonnet|haiku] [--at <giờ>] [--json]
       --template 009,045,062 : nhiều mẫu (tối đa ${MAX_BATCH}) → 1 job mỗi mẫu, cùng nội dung + tuỳ chọn, chạy lần lượt.
                                Kiểm hết trước: 1 id sai / chưa có guidance thì không tạo job nào.
       --music <style|auto|none> --voice <tên giọng|vc-…|auto|none> --no-sfx : âm thanh (mặc định auto, auto, có sfx)
                                vc-xxxxxxxx = giọng nhân bản của bạn (xem: node cli.mjs voices), chỉ đọc tiếng Việt
       --duration: 3 giây → 10 phút, số giây (90) hoặc phút:giây (1:30, 10:00). Mặc định 8.
       --ratio: tỉ lệ khung 9:16 (1080×1920, mặc định) · 16:9 (1920×1080) · 4:3 (1440×1080) · 3:4 (1080×1440)
       manual (mặc định): ghi jobs/<id>/PROMPT.md, job ở trạng thái waiting_agent. Agent viết
                          jobs/<id>/brief.json + scene/index.html rồi gọi: node cli.mjs render <id>
       claude: chạy Claude Code headless sinh cảnh, rồi tự render.
       api: gọi Anthropic API (ANTHROPIC_API_KEY trong .env). auto: api → claude → manual.
       --at 2026-11-28T07:00 : hẹn giờ (giờ máy). Job ở trạng thái scheduled; server đang bật tự chạy,
                              hoặc Task Scheduler gọi: node cli.mjs run-due
  rewrite --template <id> --content <file|chuỗi> [--duration 8] [--engine auto|api|claude] [--json]
                       viết lại nội dung thành kịch bản hợp mẫu + thời lượng (in ra, không tạo job)
  run-due              chạy mọi job hẹn giờ đã tới giờ
  run <jobId>          chạy trọn 1 job (sinh cảnh + render), bỏ qua giờ hẹn
  render <jobId> [--quality draft|looks|delivery] [--audio file]   preview.jpg + out.mp4
                       (có scene/audio.json thì tự trộn nhạc + sfx + lời và ghép vào out.mp4)
  audio <jobId> [--music <style|auto|none>] [--voice <tên|auto|none>] [--no-sfx] [--export] [--json]
                       trộn tiếng mới theo scene/audio.json (+ tuỳ chọn) và ghép vào hình đã dựng, KHÔNG render lại hình.
                       out.mp4 = bản mới nhất, bản cũ → versions/out-<n>.mp4, hình không tiếng: out.silent.mp4.
                       Chọn giọng mà chưa có lời đọc → AI viết lời ngắn. --export: chép ra OUTPUT_DIR
  audio-options [--json]   style nhạc + giọng đọc có trên máy
  list [--json]        danh sách job
  show <jobId>         trạng thái + log + đường dẫn
  templates [--json]   mẫu nào đã có guidance (gốc + gói đã cài; cột nguồn)
  pack inspect <file.lumpack> [--json]             kiểm gói, in báo cáo, không cài
  pack install <file.lumpack> [--yes] [--replace]  cài (không --yes thì in báo cáo rồi hỏi)
  pack list [--json]  ·  pack rm <packId>
  pack export --id <tac-gia.ten-goi> --name "…" --author "…" [--license CC-BY-4.0] [--version 1.0.0]
              [--provenance original|own-video|style-study] [--description "…"]
              --items <ref,ref…> | --all-templates | --all-styles | --mine   -o <file.lumpack>
                       ref: 009 · sach-gon · tac-gia.ten-goi/slug (ghi rõ template:… / style:… nếu trùng)
                       Gói lạ chạy ở chế độ khoá: AI chỉ đọc/ghi trong thư mục job. Mẫu gói dùng: make --template tac-gia.ten-goi/slug
  edit <video> --style <id> [--ratio 9:16|16:9|4:3|3:4] [--music file] [--content "dặn thêm"] [--names "tên riêng, …"] [--target 45] [--draft] [--llm off] [--json]
                       dựng lại video tự quay theo thẻ kiểu edit (edit-styles/<id>.md) → edits/<id>/out.mp4
                       cắt ngập ngừng/nói lại (LLM), phụ đề tiếng Việt, zoom, reframe theo mặt về khung --ratio (mặc định 9:16;
                       clip ngang + 16:9 thì giữ nguyên khung), nhạc tự hạ, sfx, −14 LUFS.
                       --draft: phụ đề PIL vẽ thẳng (nhanh), mặc định phụ đề HyperFrames. Cài trước: node edit/setup.mjs
                       --target 45: clip dài (5–20 phút) → LLM chọn đoạn hay nhất (hook … kết) thành short ≈ 45 s
  edit-revise <editId> "<lời>" | --file <f>   sửa bằng lời ("bỏ 3 giây đầu", "zoom ít lại") rồi render lại, không phân tích lại
  edit-show <editId> [--json]     trạng thái, tiến độ, chữ LLM đã sửa, log
  edit-run <editId>               chạy 1 edit đã tạo (MCP/REST dùng)
  edit-rm <editId>                xoá hẳn 1 edit (thư mục edits/<id>)
  edit-styles [--json]            các kiểu edit (edit-styles/<id>.md): id, tên, độ dài mặc định, có ảnh minh hoạ chưa
  voices [--json]                 liệt kê giọng có sẵn + "Giọng của tôi" (giọng nhân bản, id vc-…)
  voice-add <file> --name "Tên" --consent [--text "lời đoạn mẫu"] [--json]
                                  nhân bản giọng từ 1 file (wav/mp3/m4a/ogg/webm, 10 giây – 3 phút, ≤ 30 MB).
                                  --consent: xác nhận đây là giọng của bạn, hoặc bạn được người đó cho phép dùng.
                                  Lưu ở ~/.lumreels/voices/<id>/ (đổi bằng LUMREELS_VOICES_DIR). Dùng: make … --voice <id>
  voice-rename <id> "Tên"  ·  voice-rm <id>
  learn <video> --kind template --consent [--name "Tên mẫu"] [--from 0] [--note "đây là video gì"] [--category faceless|ads|multi-style|viet-nam] [--no-test] [--json]
                       tạo mẫu dựng từ 1 video trên máy (mp4/mov/webm, 4 giây – 3 phút, ≤ 200 MB): đo → AI viết guidance
                       → dựng thử 1 lần (chạy khoá) → so với gốc → sửa 1 vòng → nháp. Học PHONG CÁCH, không chép chữ/logo/nhân vật.
                       --consent: xác nhận video này của bạn, hoặc bạn chỉ dùng để học phong cách dựng.
                       --from: giây bắt đầu đoạn 8 giây được học (mặc định 0). --no-test: bỏ dựng thử (tự chịu rủi ro).
                       Nháp ở ~/.lumreels/drafts/<id>/ (đổi bằng LUMREELS_HOME); video tham khảo không bao giờ vào gói.
  drafts [--json]      danh sách nháp  ·  draft-show <id> [--json] [--text]  (in guidance nháp với --text)
  draft-save <id> --slug <ten-ma> --name "Tên"   lưu thành mẫu "Của tôi": make --template local.mine/<ten-ma>
  draft-rm <id>        bỏ nháp (xoá video tham khảo + bản nháp)`);
}

async function learnCmd() {
  const D = await import('./packs/drafts.mjs');
  const fmtS = (ms) => `${Math.floor(ms / 60000)}:${String(Math.round((ms % 60000) / 1000)).padStart(2, '0')}`;
  const summary = (v) => {
    console.log(`Nháp ${v.id}  ${v.status}${v.error ? '  — ' + v.error : ''}`);
    for (const k of v.stepOrder) { const s = v.steps[k]; if (s) console.log(`  ${k.padEnd(10)} ${fmtS(s.ms).padStart(6)}  $${(s.costUSD || 0).toFixed(3)}${s.engine ? `  ${s.engine}/${s.model}` : ''}${s.note ? '  ' + s.note : ''}`); }
    console.log(`  tổng       ${fmtS(v.totals.ms).padStart(6)}  $${v.totals.costUSD.toFixed(3)}${v.tested === false ? '  (chưa dựng thử)' : ''}`);
    if (v.compare) for (const r of v.compare.rows) console.log(`  ${r.off ? '≠' : '='} ${r.label}: gốc ${r.ref ?? '-'} · thử ${r.test ?? '-'}${r.dev != null ? ` (lệch ${Math.round(r.dev * 100)}%)` : ''}`);
    if (v.review?.diffs?.length) console.log('  điểm lệch AI thấy:\n' + v.review.diffs.map((x) => '   - ' + x).join('\n'));
    if (v.lint) { for (const e of v.lint.errors) console.log('  LỖI: ' + e); for (const w of v.lint.warnings) console.log('  Cảnh báo: ' + w); }
    if (v.testJobId) console.log(`  dựng thử: jobs/${v.testJobId}/out.mp4`);
    if (v.savedAs) console.log(`  đã lưu: ${v.savedAs} "${v.savedName}"  (make --template ${v.savedAs})`);
  };
  if (cmd === 'learn') {
    if (!pos[0]) { usage(); process.exit(2); }
    if (opt.kind && opt.kind !== 'template') { console.error('Bản này chỉ có --kind template (cách dựng Edit làm sau)'); process.exit(2); }
    if (!opt.consent) { console.error(`Cần --consent: "${D.CONSENT_TEXT}"`); process.exit(2); }
    const src = path.resolve(pos[0]);
    const d = await D.prepareDraft({ src, filename: path.basename(src), consent: true, name: typeof opt.name === 'string' ? opt.name : undefined, from: opt.from, note: typeof opt.note === 'string' ? opt.note : undefined, category: opt.category, skipTest: !!opt['no-test'] });
    if (!opt.json) console.log(`Nháp ${d.id} — ${D.draftDir(d.id)}`);
    const r = await D.runDraft(d.id, { log: (l) => { if (!opt.json) console.log('  ' + l); } });
    const v = D.draftView(r);
    if (opt.json) out(v); else { summary(v); if (r.status === 'ready') console.log(`Xem guidance: node cli.mjs draft-show ${r.id} --text · Lưu: node cli.mjs draft-save ${r.id} --slug <ten-ma> --name "Tên"`); }
    process.exit(r.status === 'ready' ? 0 : 1);
  }
  if (cmd === 'drafts') {
    const list = D.listDrafts().map((d) => D.draftView(d));
    if (opt.json) return out(list);
    if (!list.length) console.log('(chưa có nháp nào)');
    for (const v of list) console.log(`${v.id}  ${v.status.padEnd(10)} ${fmtS(v.totals.ms).padStart(6)}  $${v.totals.costUSD.toFixed(3)}  ${v.savedAs || v.name || v.video?.filename || ''}`);
    return;
  }
  const v = D.draftView(D.readDraft(pos[0] || ''), { withText: !!opt.text || opt.json, withLog: !!opt.json });
  if (!v) { console.error('Không thấy nháp'); process.exit(1); }
  if (cmd === 'draft-show') { if (opt.json) out(v); else { summary(v); if (opt.text) console.log('\n' + (v.guidance || '(không có guidance)')); } return; }
  if (cmd === 'draft-save') {
    const r = D.saveDraft(v.id, { slug: opt.slug, name: typeof opt.name === 'string' ? opt.name : undefined });
    if (opt.json) out(r); else console.log(`Đã lưu vào Của tôi: ${r.ref} "${r.name}"${r.thumb ? ` (ảnh từ job ${r.thumbFrom})` : ''}. Dựng: node cli.mjs make --template ${r.ref} --content "…"`);
    return;
  }
  if (cmd === 'draft-rm') { D.discardDraft(v.id); console.log(`Đã bỏ nháp ${v.id} (xoá video tham khảo + bản nháp)`); }
}

async function packCmd() {
  const P = await import('./packs/pack.mjs');
  const R = await import('./packs/registry.mjs');
  const sub = pos[0];
  const printReport = (pk) => {
    const m = pk.manifest;
    if (m) {
      console.log(`Gói: ${m.id} ${m.version} — ${m.name}`);
      console.log(`Tác giả: ${m.author?.name || '?'}${m.author?.contact ? ' (' + m.author.contact + ')' : ''} · giấy phép ${m.license} · nguồn ${m.provenance} · cần LumReels ≥ ${m.engine?.min}`);
      const k = (kind) => pk.items.filter((x) => x.kind === kind).length;
      console.log(`Mục: ${k('template')} mẫu dựng, ${k('edit-style')} cách dựng · sha256 file ${pk.fileSha256}`);
    }
    for (const e of pk.report.errors.slice(0, 30)) console.log('LỖI: ' + e);
    if (pk.report.errors.length > 30) console.log(`… và ${pk.report.errors.length - 30} lỗi nữa`);
    for (const w of pk.report.warnings.slice(0, 30)) console.log('Cảnh báo: ' + w);
    console.log(pk.report.errors.length ? `TỪ CHỐI (${pk.report.errors.length} lỗi)` : 'QUA KIỂM — mẫu cộng đồng chạy ở chế độ khoá: AI chỉ đọc/ghi trong thư mục của video này');
  };
  if (sub === 'inspect' || sub === 'install') {
    if (!pos[1]) { usage(); process.exit(2); }
    const pk = P.readPack(pos[1], { source: 'file' });
    if (opt.json && sub === 'inspect') out({ manifest: pk.manifest, fileSha256: pk.fileSha256, report: pk.report, items: pk.items.map((x) => ({ kind: x.kind, slug: x.slug, warnings: x.warnings })) });
    else if (!opt.json) printReport(pk);
    if (sub === 'inspect') process.exit(pk.report.errors.length ? 1 : 0);
    if (pk.report.errors.length) { if (opt.json) out({ ok: false, errors: pk.report.errors }); process.exit(1); }
    if (!opt.yes) {
      if (!process.stdin.isTTY) { console.error('Thêm --yes để cài (không có bàn phím để hỏi)'); process.exit(2); }
      const rl = (await import('node:readline/promises')).createInterface({ input: process.stdin, output: process.stdout });
      const a = (await rl.question('Cài gói này? (c/k) ')).trim().toLowerCase(); rl.close();
      if (!['c', 'co', 'có', 'y', 'yes'].includes(a)) { console.log('Huỷ.'); process.exit(0); }
    }
    const m = P.installPack(pk, { source: 'file', replace: !!opt.replace });
    if (opt.json) out(m); else console.log(`Đã cài ${m.id} ${m.version} vào ${R.packDir(m.id)}`);
    process.exit(0);
  }
  if (sub === 'list') {
    const list = R.listPacks();
    if (opt.json) return out(list.map(({ id, version, name, author, license, items, source, verified, installedAt }) => ({ id, version, name, author, license, items: items.length, source, verified, installedAt })));
    if (!list.length) console.log(`(chưa cài gói nào) — ${R.packsDir()}`);
    for (const m of list) console.log(`${m.id.padEnd(30)} ${m.version.padEnd(8)} ${String(m.items.length).padStart(3)} mục  ${m.license.padEnd(12)} ${m.name}`);
    return;
  }
  if (sub === 'rm') {
    if (!pos[1]) { usage(); process.exit(2); }
    P.uninstallPack(pos[1]);
    console.log('đã gỡ gói ' + pos[1]);
    return;
  }
  if (sub === 'export') {
    const str = (k) => (typeof opt[k] === 'string' ? opt[k] : undefined);
    let items = [];
    if (str('items')) items.push(...str('items').split(',').map((x) => x.trim()).filter(Boolean));
    if (opt['all-templates']) items.push(...loadCatalog().filter((t) => hasGuidance(t.id)).map((t) => 'template:' + t.id));
    if (opt['all-styles']) items.push(...R.BUILTIN_STYLES.map((x) => 'style:' + x));
    if (opt.mine) items.push(...P.mineRefs());
    items = [...new Set(items)];
    const file = str('o') || str('out');
    if (!str('id') || !str('name') || !str('author') || !file || !items.length) { usage(); process.exit(2); }
    const r = P.exportPack({ id: str('id'), version: str('version') || '1.0.0', name: str('name'), nameEn: str('name-en'), description: str('description'),
      author: { name: str('author'), ...(str('contact') ? { contact: str('contact') } : {}) }, license: str('license') || 'CC-BY-4.0', provenance: str('provenance') || 'original', items });
    fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true });
    fs.writeFileSync(file, r.buffer);
    if (opt.json) out({ file: path.resolve(file), bytes: r.buffer.length, fileSha256: r.fileSha256, items: r.manifest.items.length, warnings: r.report.warnings.length });
    else console.log(`Đã xuất ${r.manifest.items.length} mục → ${path.resolve(file)} (${(r.buffer.length / 1024 / 1024).toFixed(2)} MB, sha256 ${r.fileSha256}, ${r.report.warnings.length} cảnh báo chữ)`);
    return;
  }
  usage(); process.exit(2);
}

const readContent = (c) => (fs.existsSync(c) && fs.statSync(c).isFile() ? fs.readFileSync(c, 'utf8') : c);

try {
  if (cmd === 'rewrite') {
    if (!opt.template || !opt.content) { usage(); process.exit(2); }
    const r = await rewriteScript({ templateId: String(opt.template), content: readContent(String(opt.content)), durationS: opt.duration === true ? undefined : opt.duration, engine: typeof opt.engine === 'string' ? opt.engine : undefined });
    if (opt.json) out(r);
    else {
      console.log(r.script + (r.notes ? `\n\n--- ghi chú ---\n${r.notes}` : ''));
      console.error(`\n(engine ${r.engine}${r.fallbackFrom ? ', sau khi ' + r.fallbackFrom : ''}${r.usage ? `, ${r.usage.inputTokens} token vào / ${r.usage.outputTokens} ra${r.usage.costUSD != null ? ` ≈ $${r.usage.costUSD}` : ''}` : ''})`);
    }
    process.exit(0);
  } else if (cmd === 'make') {
    if (!opt.template || opt.template === true || !opt.content) { usage(); process.exit(2); }
    const content = readContent(String(opt.content));
    const mode = opt.mode || process.env.VIDEOAI_CLI_MODE || 'manual';
    const ids = parseTemplateIds(String(opt.template));
    const input = { content, durationS: opt.duration === true ? undefined : opt.duration, aspect: typeof opt.ratio === 'string' ? opt.ratio : undefined, mode, model: typeof opt.model === 'string' ? opt.model : undefined, runAt: opt.at, source: 'cli',
      audio: (({ music, voice, sfx }) => ({ music: music ?? 'auto', voice: voice ?? 'auto', sfx: sfx ?? true }))(audioOpts()) };
    // 1 mẫu: như cũ. Nhiều mẫu: kiểm cả lô rồi tạo hết, sau đó chạy lần lượt từng job.
    const jobs = ids.length > 1 ? createJobs({ ...input, templateIds: ids }) : [createJob({ ...input, templateId: ids[0] || String(opt.template) })];
    const results = [];
    for (const [i, job] of jobs.entries()) {
      const p = jobPaths(job.id);
      const done = await runJob(job.id);
      results.push({ ...done, paths: p });
      if (opt.json) continue;
      if (jobs.length > 1) console.log(`\n[${i + 1}/${jobs.length}] mẫu ${job.templateId}`);
      console.log(`job: ${job.id}  trạng thái: ${done.status}`);
      if (done.status === 'scheduled') console.log(`Hẹn chạy lúc: ${new Date(done.runAt).toLocaleString('vi-VN')} — server đang bật sẽ tự chạy, hoặc: node cli.mjs run-due`);
      else if (done.status === 'waiting_agent') {
        console.log(`Prompt: ${p.prompt}\nViết: ${p.scene}\\index.html (+ brief.json)\nRồi chạy: node cli.mjs render ${job.id}`);
      } else if (done.status === 'done') console.log(`MP4: ${p.mp4}\nPreview: ${p.preview}`);
      else if (done.error) console.log('Lỗi: ' + done.error);
    }
    if (opt.json) out(jobs.length > 1 ? { jobs: results } : results[0]);
    process.exit(results.some((d) => d.status === 'error') ? 1 : 0);
  } else if (['edit', 'edit-run', 'edit-revise', 'edit-show', 'edit-rm'].includes(cmd)) {
    const E = await import('./edit/jobs.mjs');
    const log = opt.json ? () => {} : console.log;
    let r;
    if (cmd === 'edit-rm') {
      if (!pos[0]) { usage(); process.exit(2); }
      E.deleteEdit(pos[0]);
      console.log('đã xoá edit ' + pos[0]);
      process.exit(0);
    }
    if (cmd === 'edit-show') {
      const v = pos[0] && E.editView(pos[0]);
      if (!v) { console.error('không thấy edit ' + (pos[0] || '')); process.exit(1); }
      if (opt.json) out(v);
      else {
        console.log(`${v.id} · ${v.status}${v.step ? ` · ${v.step} ${v.pct}%` : ''}`);
        console.log(`MP4: ${v.files.out || '-'}`);
        if (v.fixes.length) console.log('Chữ LLM sửa: ' + v.fixes.map((f) => `${f.heard} → ${f.text || '(ẩn)'}`).join(', '));
        if (v.checks?.figures?.length) console.log('Số không chắc (không in lên đồ hoạ): ' + v.checks.figures.map((f) => `${f.text}: ${f.why}`).join('; '));
        console.log((v.log || []).slice(-8).join('\n'));
      }
      process.exit(0);
    }
    if (cmd === 'edit') {
      if (!pos[0]) { usage(); process.exit(2); }
      const job = await E.createEdit({ video: pos[0], style: typeof opt.style === 'string' ? opt.style : 'sach-gon', ratio: typeof opt.ratio === 'string' ? opt.ratio : undefined, music: typeof opt.music === 'string' ? opt.music : undefined,
        content: typeof opt.content === 'string' ? readContent(opt.content) : undefined, names: typeof opt.names === 'string' ? opt.names : undefined,
        draft: !!opt.draft, llm: opt.llm === 'off' ? 'off' : 'on', target: opt.target === undefined || opt.target === true ? undefined : opt.target });
      r = await E.runEditJob(job.id, { log });
    } else if (cmd === 'edit-run') {
      if (!pos[0]) { usage(); process.exit(2); }
      r = await E.runEditJob(pos[0], { log });
    } else {
      // lời sửa: đối số, hoặc --file <đường dẫn> (MCP dùng: lời bắt đầu bằng "--" không bị hiểu nhầm thành cờ)
      const text = typeof opt.file === 'string' ? fs.readFileSync(opt.file, 'utf8') : pos.slice(1).join(' ');
      if (!pos[0] || !text.trim()) { usage(); process.exit(2); }
      r = await E.reviseEditJob(pos[0], text, { log });
    }
    if (opt.json) out(E.editView(r.id));
    else {
      console.log(r.ok ? [`edit: ${r.id}`, `MP4: ${r.out}`, `EDL: ${r.edl}`, `Xem trước: ${path.join(r.dir, 'preview.jpg')}`].join('\n') : 'Lỗi: ' + r.error);
      for (const f of r.checks?.figures || []) console.log(`Số không chắc, không in lên đồ hoạ: ${f.text} — ${f.why}`);
      for (const w of (r.warnings || []).filter((x) => x.startsWith('còn lẹm chữ'))) console.log(w);
    }
    process.exit(r.ok ? 0 : 1);
  } else if (cmd === 'render') {
    if (!pos[0]) { usage(); process.exit(2); }
    const done = await renderJob(pos[0], { quality: opt.quality || 'looks', audio: opt.audio });
    const p = jobPaths(pos[0]);
    if (opt.json) out({ ...done, paths: p });
    else {
      console.log(`job: ${done.id}  trạng thái: ${done.status}${done.error ? '  lỗi: ' + done.error : ''}`);
      if (done.status === 'done') console.log(`MP4: ${p.mp4}\nPreview: ${p.preview}`);
    }
    process.exit(done.status === 'done' ? 0 : 1);
  } else if (cmd === 'audio') {
    // Trộn tiếng mới + ghép vào hình đã dựng, KHÔNG render lại hình. Bản cũ (nếu có tiếng) → versions/out-<n>.mp4.
    if (!pos[0]) { usage(); process.exit(2); }
    const { reAudio } = await import('./generator/audio-job.mjs');
    const res = await reAudio(pos[0], audioOpts(), { log: (l) => console.log(l), exportOut: !!opt.export });
    if (opt.json) out(res);
    else console.log(`MP4: ${jobPaths(pos[0]).mp4} (bản ${res.version})${res.warnings.length ? `
${res.warnings.length} cảnh báo âm thanh (xem trên)` : ''}`);
    process.exit(0);
  } else if (cmd === 'audio-options') {
    const { audioOptions } = await import('./engine/audio/prefs.mjs');
    const o = audioOptions();
    if (opt.json) out(o);
    else {
      console.log('Nhạc: ' + o.music.map((m) => m.id).join(', '));
      console.log('Giọng: ' + o.voices.map((v) => v.id).join(', '));
      if (o.hint) console.log(o.hint);
    }
  } else if (['voices', 'voice-add', 'voice-rm', 'voice-rename'].includes(cmd)) {
    const S = await import('./engine/audio/voice-store.mjs');
    if (cmd === 'voices') {
      const { audioOptions } = await import('./engine/audio/prefs.mjs');
      const mine = S.listClones().map(S.cloneView);
      const preset = audioOptions().voices.filter((v) => v.engine && !v.mine);
      if (opt.json) out({ mine, preset: preset.map((v) => ({ id: v.id, name: v.name, engine: v.engine, lang: v.lang })) });
      else {
        console.log(`Giọng của tôi (${mine.length}) — lưu ở ${S.VOICES_DIR}`);
        for (const c of mine) console.log(`  ${c.id}  ${c.status.padEnd(10)} ${c.name}${c.refText ? `  · mẫu: "${c.refText.slice(0, 60)}"` : ''}${c.error ? '  · lỗi: ' + c.error : ''}`);
        if (!mine.length) console.log('  (chưa có) — node cli.mjs voice-add <file> --name "Tên" --consent');
        console.log('Giọng có sẵn: ' + preset.map((v) => v.id).join(', '));
      }
    } else if (cmd === 'voice-add') {
      if (!pos[0] || typeof opt.name !== 'string') { usage(); process.exit(2); }
      if (!opt.consent) { console.error('Lỗi: thêm --consent để xác nhận đây là giọng của bạn, hoặc bạn được người đó cho phép dùng'); process.exit(2); }
      const C = await import('./engine/audio/voice-clone.mjs');
      if (!C.cloneSupport().vieneu) { console.error('Lỗi: máy chưa có VieNeu-TTS (pip install vieneu)'); process.exit(1); }
      const log = opt.json ? () => {} : console.log;
      const meta = await C.prepareClone({ src: pos[0], filename: pos[0], name: opt.name, consent: true, refText: typeof opt.text === 'string' ? opt.text : undefined });
      log(`giọng ${meta.id}: đoạn mẫu ${meta.ref.durS}s từ giây ${meta.ref.startS} (file ${meta.source.durS}s). Đang chép lời + mã hoá + đọc câu nghe thử…`);
      const done = await C.finishClone(meta.id, { log });
      const v = S.cloneView(done);
      if (opt.json) out({ ...v, dir: S.cloneDir(meta.id) });
      else console.log(done?.status === 'ready' ? `Xong: ${v.id} "${v.name}"\nNghe thử: ${path.join(S.cloneDir(v.id), 'sample.wav')}\nDùng: node cli.mjs make --template <id> --content … --voice ${v.id}` : 'Lỗi: ' + (done?.error || 'không rõ'));
      process.exit(done?.status === 'ready' ? 0 : 1);
    } else if (cmd === 'voice-rename') {
      if (!pos[0] || !pos[1]) { usage(); process.exit(2); }
      const m = S.renameClone(pos[0], pos.slice(1).join(' '));
      console.log(`đã đổi tên ${m.id} → ${m.name}`);
    } else {
      if (!pos[0]) { usage(); process.exit(2); }
      S.deleteClone(pos[0]);
      console.log('đã xoá giọng ' + pos[0]);
    }
    process.exit(0);
  } else if (cmd === 'run') {
    // Chạy trọn 1 job (sinh cảnh theo chế độ + render). MCP dùng lệnh này ở tiến trình tách riêng.
    if (!pos[0]) { usage(); process.exit(2); }
    const done = await runJob(pos[0], { force: true });
    if (opt.json) out(done); else console.log(`job: ${done.id}  trạng thái: ${done.status}${done.error ? '  lỗi: ' + done.error : ''}`);
    process.exit(done.status === 'error' ? 1 : 0);
  } else if (cmd === 'run-due') {
    const res = await runDue({ log: (l) => console.log(l) });
    if (opt.json) out(res); else if (!res.length) console.log('Không có job hẹn giờ nào tới giờ.'); else for (const r of res) console.log(`${r.id}  ${r.status}${r.error ? '  ' + r.error : ''}`);
    process.exit(res.some((r) => r.status === 'error') ? 1 : 0);
  } else if (cmd === 'list') {
    const jobs = listJobs();
    if (opt.json) out(jobs);
    else for (const j of jobs) console.log(`${j.id}  ${j.status.padEnd(13)} ${j.templateId}  ${j.content.slice(0, 50).replace(/\s+/g, ' ')}`);
  } else if (cmd === 'show') {
    const j = readJob(pos[0] || '');
    if (!j) { console.error('Không thấy job'); process.exit(1); }
    out({ ...j, paths: jobPaths(j.id), log: readLog(j.id, 40) });
  } else if (cmd === 'pack') {
    await packCmd();
  } else if (['learn', 'drafts', 'draft-show', 'draft-save', 'draft-rm'].includes(cmd)) {
    await learnCmd();
  } else if (cmd === 'edit-styles') {
    const { editStyles } = await import('./edit/jobs.mjs');
    const list = editStyles();
    if (opt.json) out(list);
    else for (const s of list) console.log(`${String(s.order).padStart(2)} ${s.id.padEnd(20)} ${(s.source === 'builtin' ? 'gốc' : s.source === 'local' ? 'tự tạo' : 'cộng đồng').padEnd(9)} ${s.thumb ? '▣' : '·'} ${s.target ? `${s.target} s` : '   -'}  ${s.name} · ${s.summary}`);
  } else if (cmd === 'templates') {
    const { listTemplates } = await import('./packs/registry.mjs');
    const list = listTemplates().map((t) => ({ id: t.ref, name: t.name, category: t.category, genre: t.genre, technique: t.technique, difficulty: t.difficulty, guidance: t.hasGuidance, source: t.source, ...(t.packId ? { packId: t.packId } : {}), restricted: t.restricted }));
    const label = { builtin: 'Gốc', local: 'Tự tạo', pack: 'Cộng đồng' };
    if (opt.json) out(list);
    else for (const t of list) console.log(`${t.id} ${t.guidance ? '✓' : ' '} ${(label[t.source] || t.source).padEnd(9)} [${t.category}] ${t.name}`);
  } else usage();
} catch (e) {
  console.error('Lỗi: ' + e.message);
  process.exit(1);
}