@esquadrao/cli 1.7.1 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import os from 'node:os';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { execSync } from 'node:child_process';
6
+ import { ensureBundledPath, binaryReport } from '../binaries.js';
6
7
 
7
8
  function checkBinary(name) {
8
9
  try {
@@ -14,20 +15,11 @@ function checkBinary(name) {
14
15
  }
15
16
  }
16
17
 
18
+ // Zero config: o ffmpeg vem como optionalDependency do pacote. Nada de brew,
19
+ // winget ou sudo; apenas expomos os binários no PATH do processo.
17
20
  export function tryAutoInstallFfmpeg() {
18
- if (checkBinary('ffmpeg') && checkBinary('ffprobe')) return true;
19
- try {
20
- if (process.platform === 'darwin') {
21
- execSync('brew install ffmpeg', { stdio: 'ignore', timeout: 60000 });
22
- } else if (process.platform === 'win32') {
23
- execSync('winget install Gyan.FFmpeg --accept-package-agreements --accept-source-agreements', { stdio: 'ignore', timeout: 60000 });
24
- } else {
25
- execSync('which apt-get && (apt-get update -qq && apt-get install -y -qq ffmpeg) || sudo apt-get update -qq && sudo apt-get install -y -qq ffmpeg', { stdio: 'ignore', timeout: 60000 });
26
- }
27
- return checkBinary('ffmpeg') && checkBinary('ffprobe');
28
- } catch {
29
- return false;
30
- }
21
+ ensureBundledPath();
22
+ return checkBinary('ffmpeg') && checkBinary('ffprobe');
31
23
  }
32
24
 
33
25
  const SKILLS = [
@@ -64,6 +56,14 @@ export async function run({ positionals = [], flags = {} } = {}) {
64
56
  const destDir = destArg || path.join(cwd, '.agents', 'skills');
65
57
 
66
58
  fs.mkdirSync(destDir, { recursive: true });
59
+ // RAG local: o catálogo semântico vai para o workspace, separado das skills.
60
+ const workspaceDir = destArg ? path.resolve(destArg) : cwd;
61
+ const catalogSrc = path.join(rootDir, 'assets', 'broll-catalog.json');
62
+ const catalogDest = path.join(workspaceDir, '.esquadrao', 'broll-catalog.json');
63
+ if (fs.existsSync(catalogSrc)) {
64
+ fs.mkdirSync(path.dirname(catalogDest), { recursive: true });
65
+ fs.copyFileSync(catalogSrc, catalogDest);
66
+ }
67
67
  const installed = [];
68
68
  for (const item of [...SKILLS, 'scripts']) {
69
69
  const src = path.join(rootDir, item);
@@ -143,17 +143,14 @@ export async function run({ positionals = [], flags = {} } = {}) {
143
143
  const nodeOk = nodeMajor >= 18;
144
144
 
145
145
  let hasFfmpeg = checkBinary('ffmpeg') && checkBinary('ffprobe');
146
- let autoInstalledFfmpeg = false;
147
- if (!hasFfmpeg) {
148
- autoInstalledFfmpeg = tryAutoInstallFfmpeg();
149
- hasFfmpeg = checkBinary('ffmpeg') && checkBinary('ffprobe');
150
- }
146
+ if (!hasFfmpeg) hasFfmpeg = tryAutoInstallFfmpeg();
147
+ const binaries = binaryReport();
151
148
 
152
149
  const report = {
153
150
  status: nodeOk ? 'ok' : 'degraded',
154
151
  prerequisites: {
155
152
  node: { version: process.version, valid: nodeOk },
156
- ffmpeg: { valid: hasFfmpeg, auto_installed: autoInstalledFfmpeg }
153
+ ffmpeg: { valid: hasFfmpeg, source: binaries.ffmpeg.source }
157
154
  },
158
155
  installation: { destination: destDir, installed },
159
156
  harnesses,
@@ -164,7 +161,12 @@ export async function run({ positionals = [], flags = {} } = {}) {
164
161
  } else {
165
162
  console.log(`Esquadrão Setup: ${report.status.toUpperCase()}`);
166
163
  console.log(`- Node.js: ${process.version} (${nodeOk ? 'OK' : 'Requires >= 18'})`);
167
- console.log(`- FFmpeg & ffprobe: ${hasFfmpeg ? (autoInstalledFfmpeg ? 'Instalado automaticamente com sucesso!' : 'OK') : 'Pendente (peça ao seu agente de IA: "instale o ffmpeg para mim")'}`);
164
+ const ffmpegLabel = !hasFfmpeg
165
+ ? 'indisponível (rode "npm install" novamente para restaurar o binário embutido)'
166
+ : binaries.ffmpeg.source === 'bundled'
167
+ ? 'embutido no pacote (nada a instalar)'
168
+ : 'OK (binário do sistema)';
169
+ console.log(`- FFmpeg & ffprobe: ${ffmpegLabel}`);
168
170
  console.log(`- Installed ${installed.length} items to ${destDir}`);
169
171
  if (harnesses.length) console.log(`- Harnesses detected: ${harnesses.join(', ')}`);
170
172
  }
@@ -11,6 +11,8 @@ import process from 'node:process';
11
11
  import readline from 'node:readline';
12
12
  import { validateEditPlan } from '../roles/mediaProducer.js';
13
13
  import { buildTemplateCaptionFilters, getCaptionTemplate, listCaptionTemplates } from '../captionTemplates.js';
14
+ import { startJobTelemetry } from '../studio/jobTelemetry.js';
15
+ import { summarizePlan } from '../studio/planSummary.js';
14
16
 
15
17
  export function checkBinary(name) {
16
18
  try {
@@ -857,8 +859,13 @@ export function buildAutoClipPlan({ asset, speechIntervals, captions = [], forma
857
859
  return plan;
858
860
  }
859
861
 
862
+ const TELEMETRY_SUBS = new Set(['import', 'detect-silence', 'auto-clip', 'transcribe', 'render', 'batch', 'cutout']);
863
+
860
864
  export async function run({ positionals = [], flags = {} } = {}) {
861
865
  const sub = positionals[0];
866
+ const telemetry = TELEMETRY_SUBS.has(sub)
867
+ ? startJobTelemetry({ command: `studio ${sub}`, argv: positionals.slice(1), workspace: flags.dest || null })
868
+ : null;
862
869
 
863
870
  if (!sub || flags.help || sub === 'help') {
864
871
  console.log(`Esquadrão Studio
@@ -878,6 +885,7 @@ Subcommands:
878
885
  batch <dir> Renderiza todos os planos *.json de um diretório e agrega o QA
879
886
  cutout <video> Recorta a pessoa e compõe sobre um pack (requer Python/rembg)
880
887
  caption-templates [--json] Lista os templates de legenda disponíveis
888
+ serve [--port 4310] Companion visual local (UI + SSE) em 127.0.0.1
881
889
 
882
890
  Options:
883
891
  --dest <path> Custom studio workspace destination directory
@@ -899,11 +907,23 @@ Options:
899
907
  --engine <rembg> Motor de recorte (padrão: rembg)
900
908
  --fps <n> FPS do cutout (padrão: 15)
901
909
  --python <path> Interpretador Python do motor de recorte
910
+ --port <n> Porta do companion visual (padrão: 4310)
911
+ --no-open Não abrir o navegador ao iniciar o serve
902
912
  --json Output results in JSON format
903
913
  -h, --help Show help message`);
904
914
  return;
905
915
  }
906
916
 
917
+ if (sub === 'serve') {
918
+ const { startServer } = await import('../studio/server.js');
919
+ return startServer({
920
+ port: flags.port === undefined ? 4310 : Number(flags.port),
921
+ dest: flags.dest,
922
+ open: !flags['no-open'],
923
+ json: Boolean(flags.json),
924
+ });
925
+ }
926
+
907
927
  if (sub === 'batch') {
908
928
  const dirArg = positionals[1];
909
929
  if (!dirArg) {
@@ -926,11 +946,16 @@ Options:
926
946
  process.exit(1);
927
947
  }
928
948
 
949
+ telemetry?.setWorkspace(wsDir);
950
+ telemetry?.stage('rendering');
929
951
  const cliPath = fileURLToPath(new URL('../../bin/cli.js', import.meta.url));
930
952
  const results = [];
931
953
  const failures = [];
932
954
  for (const planPath of plans) {
933
- const res = spawnSync(process.execPath, [cliPath, 'studio', 'render', planPath, '--dest', wsDir, '--json'], { encoding: 'utf8' });
955
+ const res = spawnSync(process.execPath, [cliPath, 'studio', 'render', planPath, '--dest', wsDir, '--json'], {
956
+ encoding: 'utf8',
957
+ env: { ...process.env, ESQUADRAO_NO_TELEMETRY: '1' },
958
+ });
934
959
  if (res.status !== 0) {
935
960
  failures.push({ plan: path.basename(planPath), error: (res.stderr || res.stdout || `exit ${res.status}`).trim() });
936
961
  if (flags['stop-on-error']) break;
@@ -944,6 +969,7 @@ Options:
944
969
  }
945
970
  }
946
971
 
972
+ telemetry?.stage('qa');
947
973
  const report = { plans: plans.length, rendered: results.length, failed: failures.length, results, failures };
948
974
  if (flags.json) {
949
975
  console.log(JSON.stringify(report, null, 2));
@@ -983,6 +1009,8 @@ Options:
983
1009
  }
984
1010
  const thresh = flags['silence-thresh'] || '-30dB';
985
1011
  const dur = parseFloat(flags['silence-duration'] || '0.8');
1012
+ telemetry?.setWorkspace(flags.dest ? path.resolve(flags.dest) : null);
1013
+ telemetry?.stage('detecting_silence');
986
1014
  const silences = detectSilence(resolvedSrc, { noiseThreshold: thresh, minDurationSec: dur });
987
1015
  const probe = probeMedia(resolvedSrc);
988
1016
  const totalSec = parseFloat(probe.format?.duration || '0');
@@ -1029,6 +1057,8 @@ Options:
1029
1057
 
1030
1058
  const wsDir = findWorkspaceDir(flags.dest);
1031
1059
  fs.mkdirSync(path.join(wsDir, 'packages'), { recursive: true });
1060
+ telemetry?.setWorkspace(wsDir);
1061
+ telemetry?.stage('transcribing');
1032
1062
 
1033
1063
  const probe = probeMedia(resolvedSrc);
1034
1064
  const duration = parseFloat(probe.format?.duration || '0');
@@ -1245,6 +1275,8 @@ Options:
1245
1275
  process.exit(1);
1246
1276
  }
1247
1277
 
1278
+ telemetry?.setWorkspace(wsDir);
1279
+ telemetry?.stage('rendering');
1248
1280
  const child = spawn(python, [
1249
1281
  scriptPath,
1250
1282
  '--input', resolvedSrc,
@@ -1289,11 +1321,13 @@ Options:
1289
1321
  manifest.artifacts.push(artifactRecord);
1290
1322
  saveManifestAtomic(manifestPath, manifest);
1291
1323
 
1324
+ telemetry?.stage('qa');
1292
1325
  const qaReport = verifyArtifact(artifactPath);
1293
1326
  if (!qaReport.passed) {
1294
1327
  console.error(`Error: Post-render QA validation failed:\n${qaReport.errors.map((e) => ` - ${e}`).join('\n')}`);
1295
1328
  process.exit(1);
1296
1329
  }
1330
+ telemetry?.artifact(artifactPath, { engine: 'rembg', fps });
1297
1331
  const result = {
1298
1332
  status: 'ok',
1299
1333
  engine: 'rembg',
@@ -1344,6 +1378,7 @@ Options:
1344
1378
  }
1345
1379
 
1346
1380
  const wsDir = findWorkspaceDir(flags.dest);
1381
+ telemetry?.setWorkspace(wsDir);
1347
1382
  const silentIfJson = async (fn) => {
1348
1383
  if (!flags.json) return await fn();
1349
1384
  const orig = console.log;
@@ -1361,12 +1396,14 @@ Options:
1361
1396
  const totalDurationSec = assetRecord.metadata?.duration_s || 0;
1362
1397
 
1363
1398
  // 2. Silence detection
1399
+ telemetry?.stage('detecting_silence');
1364
1400
  const silenceThresh = flags['silence-thresh'] || '-30dB';
1365
1401
  const silenceDuration = parseFloat(flags['silence-duration'] || '0.8');
1366
1402
  const silences = detectSilence(assetPath, { noiseThreshold: silenceThresh, minDurationSec: silenceDuration });
1367
1403
  const speechIntervals = computeSpeechIntervals(totalDurationSec, silences);
1368
1404
 
1369
1405
  // 3. Transcribe only when captions are enabled
1406
+ telemetry?.stage('transcribing');
1370
1407
  let words = [];
1371
1408
  if (captionSource.mode === 'srt') {
1372
1409
  words = await transcribeAudio(null, { srtPath: captionSource.srtPath });
@@ -1461,6 +1498,7 @@ Options:
1461
1498
  }
1462
1499
 
1463
1500
  // 5. Build and validate EditPlan
1501
+ telemetry?.stage('planning');
1464
1502
  const format = flags.format || '9:16';
1465
1503
  const plan = buildAutoClipPlan({
1466
1504
  asset: assetRecord,
@@ -1472,6 +1510,7 @@ Options:
1472
1510
  });
1473
1511
  if (flags['caption-template']) plan.caption_template = flags['caption-template'];
1474
1512
  validateEditPlan(plan);
1513
+ telemetry?.summary(summarizePlan(plan));
1475
1514
 
1476
1515
  const packagesDir = path.join(wsDir, 'packages');
1477
1516
  fs.mkdirSync(packagesDir, { recursive: true });
@@ -1570,6 +1609,8 @@ Options:
1570
1609
  fs.mkdirSync(path.join(wsDir, 'artifacts'), { recursive: true });
1571
1610
  fs.mkdirSync(path.join(wsDir, 'packages'), { recursive: true });
1572
1611
 
1612
+ telemetry?.setWorkspace(wsDir);
1613
+ telemetry?.stage('importing');
1573
1614
  const assetId = `AST-${crypto.randomBytes(4).toString('hex')}`;
1574
1615
  const ext = path.extname(resolvedSrc) || '.mp4';
1575
1616
  const targetName = `${assetId}${ext}`;
@@ -1639,6 +1680,9 @@ Options:
1639
1680
 
1640
1681
  try {
1641
1682
  validateEditPlan(plan);
1683
+ telemetry?.setWorkspace(findWorkspaceDir(flags.dest));
1684
+ telemetry?.stage('planning');
1685
+ telemetry?.summary(summarizePlan(plan));
1642
1686
  } catch (err) {
1643
1687
  console.error(`Error: EditPlan validation failed: ${err.message}`);
1644
1688
  process.exit(1);
@@ -1675,6 +1719,7 @@ Options:
1675
1719
  const artifactId = `ART-${crypto.randomBytes(4).toString('hex')}`;
1676
1720
  const artifactPath = path.join(wsDir, 'artifacts', `${artifactId}.mp4`);
1677
1721
  const { width, height } = plan.output;
1722
+ telemetry?.stage('rendering');
1678
1723
 
1679
1724
  const tempFiles = [];
1680
1725
  try {
@@ -1845,11 +1890,13 @@ Options:
1845
1890
  manifest.artifacts.push(artifactRecord);
1846
1891
  saveManifestAtomic(manifestPath, manifest);
1847
1892
 
1893
+ telemetry?.stage('qa');
1848
1894
  const qaReport = verifyArtifact(artifactPath, resolvedPlanFile);
1849
1895
  if (!qaReport.passed) {
1850
1896
  console.error(`Error: Post-render QA validation failed:\n${qaReport.errors.map((e) => ` - ${e}`).join('\n')}`);
1851
1897
  process.exit(1);
1852
1898
  }
1899
+ telemetry?.artifact(artifactPath, { mode: plan.mode });
1853
1900
 
1854
1901
  if (flags.json) {
1855
1902
  console.log(JSON.stringify(artifactRecord, null, 2));
@@ -0,0 +1,239 @@
1
+ // Ponte de telemetria local: <stateDir>/jobs/<job_id>/ (job.json, events.ndjson, pid).
2
+ // Escrita atômica, append-only e silenciosa por contrato: nunca altera stdout/stderr.
3
+
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+ import process from 'node:process';
8
+ import { resolveStateDir, ensureStateLayout, writeFileAtomic } from './stateDir.js';
9
+
10
+ export const STAGES = [
11
+ 'queued',
12
+ 'importing',
13
+ 'detecting_silence',
14
+ 'transcribing',
15
+ 'planning',
16
+ 'rendering',
17
+ 'qa',
18
+ 'done',
19
+ 'failed',
20
+ 'canceled',
21
+ ];
22
+
23
+ export const TERMINAL_STAGES = new Set(['done', 'failed', 'canceled']);
24
+
25
+ export function telemetryEnabled(env = process.env) {
26
+ return env.ESQUADRAO_NO_TELEMETRY !== '1';
27
+ }
28
+
29
+ export function createJobId(date = new Date()) {
30
+ const iso = date.toISOString().replace(/[-:]/g, '').replace('T', '-').slice(0, 15);
31
+ return `job-${iso}-${crypto.randomBytes(2).toString('hex')}`;
32
+ }
33
+
34
+ export function sanitizeLog(input, { workspace = null } = {}) {
35
+ let text = String(input ?? '');
36
+ text = text.replace(/\u001B\[[0-9;?]*[ -/]*[@-~]/g, '');
37
+ text = text.replace(/sk-[A-Za-z0-9_-]{10,}/g, 'sk-***');
38
+ text = text.replace(/atlas_[A-Za-z0-9]+/g, 'atlas_***');
39
+ text = text.replace(/mb_[A-Za-z0-9]+/g, 'mb_***');
40
+ text = text.replace(/(Bearer\s+)[A-Za-z0-9._-]+/gi, '$1***');
41
+ text = text.replace(/(OPENAI_API_KEY\s*=\s*)\S+/g, '$1***');
42
+ if (workspace) {
43
+ const variants = new Set([workspace, workspace.replace(/\\/g, '/')]);
44
+ for (const variant of variants) {
45
+ if (variant) text = text.split(variant).join('<workspace>');
46
+ }
47
+ }
48
+ return text.length > 2000 ? `${text.slice(0, 1997)}...` : text;
49
+ }
50
+
51
+ function readEvents(dir) {
52
+ const file = path.join(dir, 'events.ndjson');
53
+ if (!fs.existsSync(file)) return [];
54
+ return fs.readFileSync(file, 'utf8').split('\n').filter(Boolean).flatMap((line) => {
55
+ try { return [JSON.parse(line)]; } catch { return []; }
56
+ });
57
+ }
58
+
59
+ export function readJob(dir) {
60
+ const file = path.join(dir, 'job.json');
61
+ if (!fs.existsSync(file)) return null;
62
+ try {
63
+ const data = JSON.parse(fs.readFileSync(file, 'utf8'));
64
+ const events = readEvents(dir);
65
+ const artifact = [...events].reverse().find((e) => e.type === 'artifact');
66
+ return { ...data, artifact: artifact?.payload || data.artifact || null, events };
67
+ } catch {
68
+ return null;
69
+ }
70
+ }
71
+
72
+ export function listJobs(stateDir, { limit = 100 } = {}) {
73
+ const jobsDir = path.join(stateDir, 'jobs');
74
+ if (!fs.existsSync(jobsDir)) return [];
75
+ return fs.readdirSync(jobsDir)
76
+ .map((name) => path.join(jobsDir, name))
77
+ .filter((dir) => {
78
+ try { return fs.statSync(dir).isDirectory(); } catch { return false; }
79
+ })
80
+ .map((dir) => readJob(dir))
81
+ .filter((job) => job && job.id)
82
+ .sort((a, b) => String(b.created_at || '').localeCompare(String(a.created_at || '')))
83
+ .slice(0, limit);
84
+ }
85
+
86
+ let ACTIVE = null;
87
+
88
+ class JobTelemetry {
89
+ constructor({ command, argv = [], workspace = null, stateDir, jobDir = null, env = process.env, pid = process.pid }) {
90
+ this.command = command;
91
+ this.argv = Array.isArray(argv) ? argv.map((a) => sanitizeLog(a)) : [];
92
+ this.workspace = workspace;
93
+ this.env = env;
94
+ this.pid = pid;
95
+ this.stateDir = stateDir || resolveStateDir(env);
96
+ ensureStateLayout(this.stateDir);
97
+ const inherited = jobDir || env.ESQUADRAO_JOB_DIR || null;
98
+ this.dir = inherited ? path.resolve(inherited) : path.join(this.stateDir, 'jobs', createJobId());
99
+ fs.mkdirSync(this.dir, { recursive: true });
100
+
101
+ const existing = readJob(this.dir);
102
+ this.id = existing?.id || path.basename(this.dir);
103
+ this.createdAt = existing?.created_at || new Date().toISOString();
104
+ this.seq = existing?.events?.length || 0;
105
+ this.terminal = Boolean(existing && TERMINAL_STAGES.has(existing.status));
106
+ this.status = existing?.status || 'queued';
107
+ this.stageName = existing?.stage || 'queued';
108
+
109
+ this.writeJob({ owner: existing?.owner || 'cli' });
110
+ writeFileAtomic(path.join(this.dir, 'pid'), `${pid}\n`);
111
+ if (!existing?.events?.length) this.append({ type: 'stage', stage: 'queued', payload: {} });
112
+ process.once('exit', (code) => this.finalize(code));
113
+ }
114
+
115
+ writeJob(extra = {}) {
116
+ const record = {
117
+ id: this.id,
118
+ command: this.command,
119
+ argv: this.argv,
120
+ workspace: this.workspace,
121
+ status: this.status,
122
+ stage: this.stageName,
123
+ created_at: this.createdAt,
124
+ started_at: this.startedAt || this.createdAt,
125
+ finished_at: this.finishedAt || null,
126
+ exit_code: this.exitCode ?? null,
127
+ error: this.error || null,
128
+ updated_at: new Date().toISOString(),
129
+ ...extra,
130
+ };
131
+ try {
132
+ writeFileAtomic(path.join(this.dir, 'job.json'), JSON.stringify(record, null, 2) + '\n');
133
+ } catch {}
134
+ return record;
135
+ }
136
+
137
+ append(event) {
138
+ this.seq += 1;
139
+ const line = JSON.stringify({ seq: this.seq, ts: new Date().toISOString(), ...event }) + '\n';
140
+ try {
141
+ fs.appendFileSync(path.join(this.dir, 'events.ndjson'), line, 'utf8');
142
+ } catch {}
143
+ }
144
+
145
+ stage(name, payload = {}) {
146
+ if (!STAGES.includes(name)) throw new Error(`Estágio inválido: ${name}`);
147
+ if (this.terminal) return this;
148
+ this.stageName = name;
149
+ this.status = TERMINAL_STAGES.has(name) ? name : 'running';
150
+ if (name !== 'queued' && !this.startedAt) this.startedAt = new Date().toISOString();
151
+ if (TERMINAL_STAGES.has(name)) this.finishedAt = new Date().toISOString();
152
+ this.append({ type: 'stage', stage: name, payload });
153
+ if (TERMINAL_STAGES.has(name)) this.terminal = true;
154
+ this.writeJob();
155
+ return this;
156
+ }
157
+
158
+ log(text) {
159
+ if (this.terminal) return this;
160
+ this.append({ type: 'log', stage: this.stageName, payload: { line: sanitizeLog(text, { workspace: this.workspace }) } });
161
+ return this;
162
+ }
163
+
164
+ summary(text) {
165
+ if (this.terminal) return this;
166
+ const clean = sanitizeLog(text, { workspace: this.workspace });
167
+ if (clean === this.lastSummary) return this;
168
+ this.lastSummary = clean;
169
+ this.append({ type: 'plan_summary', stage: this.stageName, payload: { text: clean } });
170
+ return this;
171
+ }
172
+
173
+ artifact(filePath, meta = {}) {
174
+ if (this.terminal) return this;
175
+ const name = path.basename(String(filePath || ''));
176
+ const id = name.replace(/\.mp4$/i, '');
177
+ const payload = { id, name, path: String(filePath || ''), ...meta };
178
+ this.append({ type: 'artifact', stage: this.stageName, payload });
179
+ this.writeJob({ artifact: payload });
180
+ return this;
181
+ }
182
+
183
+ setWorkspace(workspace) {
184
+ if (!workspace || this.workspace) return this;
185
+ this.workspace = workspace;
186
+ this.writeJob();
187
+ return this;
188
+ }
189
+
190
+ finish(status, { exitCode = null, error = null } = {}) {
191
+ if (this.terminal) return this;
192
+ if (!TERMINAL_STAGES.has(status)) throw new Error(`Status terminal inválido: ${status}`);
193
+ this.error = error;
194
+ this.exitCode = exitCode;
195
+ this.stage(status, error ? { error: sanitizeLog(error) } : {});
196
+ return this;
197
+ }
198
+
199
+ finalize(code) {
200
+ if (this.terminal) return;
201
+ const status = code === 0
202
+ ? 'done'
203
+ : (code === 130 || code === null || code === undefined ? 'canceled' : 'failed');
204
+ this.finish(status, { exitCode: typeof code === 'number' ? code : null });
205
+ }
206
+
207
+ /** Adaptador para comandos aninhados no mesmo processo (ex.: onboard -> auto-clip). */
208
+ child() {
209
+ const parent = this;
210
+ return {
211
+ nested: true,
212
+ dir: parent.dir,
213
+ get id() { return parent.id; },
214
+ stage: (name, payload) => (parent.stageName === name ? parent : parent.stage(name, payload)),
215
+ log: (text) => parent.log(text),
216
+ summary: (text) => parent.summary(text),
217
+ artifact: (file, meta) => parent.artifact(file, meta),
218
+ setWorkspace: (ws) => parent.setWorkspace(ws),
219
+ finish: () => parent,
220
+ finalize: () => parent,
221
+ };
222
+ }
223
+ }
224
+
225
+ export function startJobTelemetry(options = {}) {
226
+ const env = options.env || process.env;
227
+ if (!telemetryEnabled(env)) return null;
228
+ if (ACTIVE) return ACTIVE.child();
229
+ try {
230
+ ACTIVE = new JobTelemetry(options);
231
+ return ACTIVE;
232
+ } catch {
233
+ return null;
234
+ }
235
+ }
236
+
237
+ export function resetTelemetryForTests() {
238
+ ACTIVE = null;
239
+ }
@@ -0,0 +1,76 @@
1
+ // Resumo humano determinístico de um EditPlan v1 (pt-BR), sem LLM.
2
+
3
+ const LAYOUT_ORDER = ['fullscreen', 'pip', 'split_bottom', 'split_top'];
4
+
5
+ function decimal(value) {
6
+ const rounded = Math.round((Number(value) || 0) * 10) / 10;
7
+ return rounded.toFixed(1).replace('.', ',');
8
+ }
9
+
10
+ function plural(count, singular, pluralForm) {
11
+ return `${count} ${count === 1 ? singular : pluralForm}`;
12
+ }
13
+
14
+ export function planDurationSec(plan = {}) {
15
+ const clips = Array.isArray(plan.clips) ? plan.clips : [];
16
+ if (plan.mode === 'dark') {
17
+ const end = clips.reduce((max, c) => Math.max(max, ((c.timeline_start_ms || 0) + (c.duration_ms || 0)) / 1000), 0);
18
+ return Math.max(end, 1);
19
+ }
20
+ return clips.reduce((sum, c) => sum + Math.max(0, ((c.out_ms || 0) - (c.in_ms || 0)) / 1000), 0);
21
+ }
22
+
23
+ export function planStats(plan = {}) {
24
+ const clips = Array.isArray(plan.clips) ? plan.clips : [];
25
+ const captions = Array.isArray(plan.captions) ? plan.captions : [];
26
+ const overlays = Array.isArray(plan.overlays) ? plan.overlays : [];
27
+ const music = Array.isArray(plan.music_tracks) ? plan.music_tracks : [];
28
+ const template = plan.caption_template || captions.find((c) => c.template)?.template || null;
29
+ const layouts = {};
30
+ for (const overlay of overlays) {
31
+ const layout = overlay.layout || 'fullscreen';
32
+ layouts[layout] = (layouts[layout] || 0) + 1;
33
+ }
34
+ return {
35
+ mode: plan.mode || 'unknown',
36
+ clips: clips.length,
37
+ duration_s: Number(planDurationSec(plan).toFixed(1)),
38
+ width: plan.output?.width || null,
39
+ height: plan.output?.height || null,
40
+ captions: captions.length,
41
+ caption_template: template,
42
+ overlays: overlays.length,
43
+ layouts,
44
+ music_tracks: music.length,
45
+ ducking: music.some((m) => m.ducking === true),
46
+ };
47
+ }
48
+
49
+ export function summarizePlan(plan = {}) {
50
+ const stats = planStats(plan);
51
+ const parts = [];
52
+
53
+ if (stats.mode === 'dark') parts.push(plural(stats.clips, 'texto', 'textos'));
54
+ else parts.push(plural(stats.clips, 'clipe', 'clipes'));
55
+
56
+ parts.push(`${decimal(stats.duration_s)} s`);
57
+ if (stats.width && stats.height) parts.push(`${stats.width}x${stats.height}`);
58
+
59
+ if (stats.captions > 0) {
60
+ const label = plural(stats.captions, 'legenda', 'legendas');
61
+ parts.push(stats.caption_template ? `${label} (${stats.caption_template})` : label);
62
+ }
63
+
64
+ for (const layout of LAYOUT_ORDER) {
65
+ const count = stats.layouts[layout];
66
+ if (count) parts.push(`${plural(count, 'B-roll', 'B-rolls')} ${layout}`);
67
+ }
68
+
69
+ if (stats.music_tracks > 0) {
70
+ parts.push(`${plural(stats.music_tracks, 'trilha', 'trilhas')}${stats.ducking ? ' com ducking' : ''}`);
71
+ }
72
+
73
+ return parts.join(' · ');
74
+ }
75
+
76
+ export default summarizePlan;
@@ -0,0 +1,90 @@
1
+ // Cache sob demanda de previews de 5 s por preset de legenda.
2
+ // Reutiliza o motor drawtext, o canvas 640x360 e as fontes de assets/fonts/.
3
+
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+ import { spawn } from 'node:child_process';
8
+ import { ensureBundledPath } from '../binaries.js';
9
+ import { getCaptionTemplate, buildTemplateCaptionFilters } from '../captionTemplates.js';
10
+ import { resolveStateDir, ensureStateLayout } from './stateDir.js';
11
+
12
+ const PKG = JSON.parse(fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
13
+ const WIDTH = 1080;
14
+ const HEIGHT = 1920;
15
+ const DURATION = 5;
16
+ const SAMPLE_TEXT = 'O MAIOR SEGREDO';
17
+
18
+ const INFLIGHT = new Map();
19
+
20
+ export function previewHash(template) {
21
+ return crypto.createHash('sha256')
22
+ .update(`${template.id}|${JSON.stringify(template)}|${PKG.version}`)
23
+ .digest('hex')
24
+ .slice(0, 8);
25
+ }
26
+
27
+ export function previewPathFor(id, stateDir = resolveStateDir()) {
28
+ const template = getCaptionTemplate(id);
29
+ return path.join(stateDir, 'previews', `${template.id}-${previewHash(template)}.mp4`);
30
+ }
31
+
32
+ function runFfmpeg(args) {
33
+ ensureBundledPath();
34
+ return new Promise((resolve, reject) => {
35
+ const child = spawn('ffmpeg', args, { stdio: ['ignore', 'ignore', 'pipe'] });
36
+ let stderr = '';
37
+ child.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
38
+ child.on('error', reject);
39
+ child.on('close', (code) => {
40
+ if (code === 0) resolve();
41
+ else reject(new Error(`ffmpeg falhou ao gerar preview (exit ${code}): ${stderr.split('\n').slice(-3).join(' ').trim()}`));
42
+ });
43
+ });
44
+ }
45
+
46
+ /**
47
+ * Gera (ou reaproveita) o preview de 5 s de um template.
48
+ * @returns {Promise<{path: string, size: number, cached: boolean}>}
49
+ */
50
+ export function getPreview(id, { stateDir = resolveStateDir(), force = false } = {}) {
51
+ const template = getCaptionTemplate(id);
52
+ ensureStateLayout(stateDir);
53
+ const file = previewPathFor(template.id, stateDir);
54
+ const cached = !force && fs.existsSync(file) && fs.statSync(file).size > 1024;
55
+ if (cached) return Promise.resolve({ path: file, size: fs.statSync(file).size, cached: true });
56
+ if (INFLIGHT.has(file)) return INFLIGHT.get(file).then((result) => ({ ...result, cached: true }));
57
+
58
+ const job = (async () => {
59
+ const tempFiles = [];
60
+ try {
61
+ const filters = buildTemplateCaptionFilters(
62
+ { text: SAMPLE_TEXT, timeline_start_ms: 0, duration_ms: DURATION * 1000 },
63
+ template,
64
+ { width: WIDTH, height: HEIGHT, tempFiles },
65
+ );
66
+ const tmp = `${file}.tmp-${crypto.randomBytes(4).toString('hex')}.mp4`;
67
+ await runFfmpeg([
68
+ '-y',
69
+ '-f', 'lavfi',
70
+ '-i', `color=c=black:s=${WIDTH}x${HEIGHT}:r=30:d=${DURATION}`,
71
+ '-vf', filters,
72
+ '-an',
73
+ '-t', String(DURATION),
74
+ '-c:v', 'libx264',
75
+ '-pix_fmt', 'yuv420p',
76
+ '-movflags', '+faststart',
77
+ tmp,
78
+ ]);
79
+ try { fs.renameSync(tmp, file); } catch { fs.copyFileSync(tmp, file); try { fs.unlinkSync(tmp); } catch {} }
80
+ return { path: file, size: fs.statSync(file).size, cached: false };
81
+ } finally {
82
+ for (const temp of tempFiles) {
83
+ try { fs.unlinkSync(temp); } catch {}
84
+ }
85
+ }
86
+ })().finally(() => INFLIGHT.delete(file));
87
+
88
+ INFLIGHT.set(file, job);
89
+ return job;
90
+ }