seoanything-cli 2.2.0 → 2.4.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.
package/src/cli.test.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { readFileSync } from "node:fs";
2
- import { describe, expect, it } from "vitest";
2
+ import { describe, expect, it, vi } from "vitest";
3
3
  import { EXIT, main, parse } from "./cli.js";
4
4
  import { exitCodeFor } from "./api.js";
5
5
 
@@ -28,6 +28,23 @@ describe("exit codes (TRD §17.1)", () => {
28
28
  expect((await run(["--help"])).code).toBe(0);
29
29
  expect((await run(["--version"])).out).toContain(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
30
30
  });
31
+ it("sites task refuses a bad rule or status before calling the server", async () => {
32
+ const id = "0123456789abcdef01234567";
33
+ expect((await run(["sites", "task", id, "title_missing"])).code).toBe(2);
34
+ expect((await run(["sites", "task", id, "title_missing", "done", "--server", "http://127.0.0.1:9"])).code).toBe(2);
35
+ expect((await run(["sites", "task", id, "../crawls", "fixed", "--server", "http://127.0.0.1:9"])).code).toBe(2);
36
+ expect((await run(["sites", "crawl", "../x"])).code).toBe(2);
37
+ });
38
+ it("sites sync walks the parts the server names, then stops", async () => {
39
+ const seen = [];
40
+ vi.stubGlobal("fetch", async (url, init) => { const { part } = JSON.parse(init.body); seen.push(`${init.method} ${url} ${part}`); return new Response(JSON.stringify({ part, next: part < 5 ? part + 1 : null, rows: 2 }), { headers: { "content-type": "application/json" } }); });
41
+ try {
42
+ const r = await run(["sites", "sync", "0123456789abcdef01234567", "--server", "http://sa.test", "--json"]);
43
+ expect(r.code).toBe(0);
44
+ expect(JSON.parse(r.out).rows).toBe(10);
45
+ expect(seen).toEqual([1, 2, 3, 4, 5].map((n) => `POST http://sa.test/api/v1/visibility/sites/0123456789abcdef01234567/sync ${n}`));
46
+ } finally { vi.unstubAllGlobals(); }
47
+ });
31
48
  it("whoami without credentials exits 3; unreachable server exits 5", async () => {
32
49
  const env = { ...process.env }; delete process.env.SEOANYTHING_API_KEY; delete process.env.SEOANYTHING_TOKEN;
33
50
  process.env.XDG_CONFIG_HOME = "/nonexistent-seoanything-test";
@@ -37,3 +54,98 @@ describe("exit codes (TRD §17.1)", () => {
37
54
  process.env = env;
38
55
  });
39
56
  });
57
+
58
+ describe("B2 and B3 commands: live links, results by channel, topics, keyword map, CrUX, Bing", () => {
59
+ const post = "0123456789abcdef01234567", key = "linkedin:linkedin.com/posts/abc";
60
+ const results = { manualOnly: true, copies: [{ key, channel: "linkedin", label: "LinkedIn", url: "https://www.linkedin.com/posts/abc", totals: { days: 1, views: 120, clicks: 4, reactions: null, comments: null, shares: null }, days: [] }] };
61
+ const withFetch = async (body, fn) => {
62
+ const seen = [];
63
+ vi.stubGlobal("fetch", async (url, init) => { seen.push(`${init.method} ${url.replace("http://sa.test/api/v1", "")}${init.body ? ` ${init.body}` : ""}`); return new Response(JSON.stringify(body), { headers: { "content-type": "application/json" } }); });
64
+ try { await fn(); } finally { vi.unstubAllGlobals(); }
65
+ return seen;
66
+ };
67
+ const srv = ["--server", "http://sa.test"];
68
+ it("refuse bad ids, keys, days and numbers before calling the server", async () => {
69
+ for (const argv of [
70
+ ["blog", "results", "../x"], ["blog", "results", post, "set", key, "yesterday", "--views", "1"], ["blog", "results", post, "set", key, "2026-11-16"],
71
+ ["blog", "results", post, "set", key, "2026-11-16", "--views", "-3"], ["blog", "results", post, "drop", key, "2026-11-16"], ["blog", "unlink", post, "has spaces"],
72
+ ["blog", "link", post, "linkedin"], ["blog", "video", "../x"], ["keywords", "target", post, "../x", "none"], ["keywords", "lists", "../x"], ["plan"], ["sites", "crux", "../x"], ["bing", "key"],
73
+ ]) expect((await run([...argv, "--server", "http://127.0.0.1:9"])).code, argv.join(" ")).toBe(2);
74
+ });
75
+ it("call the routes, a copy key as one encoded path segment", async () => {
76
+ const seen = await withFetch(results, async () => {
77
+ expect((await run(["blog", "results", post, ...srv])).out).toContain("views 120 · clicks 4 · reactions –");
78
+ await run(["blog", "results", post, "set", key, "2026-11-16", "--views", "120", "--clicks", "4", ...srv]);
79
+ await run(["blog", "results", post, "remove", key, "2026-11-16", ...srv]);
80
+ await run(["blog", "link", post, "linkedin", "https://www.linkedin.com/posts/abc", "--replaces", "linkedin:linkedin.com/posts/old", ...srv]);
81
+ await run(["blog", "unlink", post, key, ...srv]);
82
+ });
83
+ const k = encodeURIComponent(key);
84
+ expect(seen).toEqual([
85
+ `GET /blog/posts/${post}/results`,
86
+ `PUT /blog/posts/${post}/results {"copyKey":"${key}","day":"2026-11-16","views":120,"clicks":4}`,
87
+ `DELETE /blog/posts/${post}/results/${k}/2026-11-16`,
88
+ `PUT /blog/posts/${post}/links {"channel":"linkedin","url":"https://www.linkedin.com/posts/abc","replaces":"linkedin:linkedin.com/posts/old"}`,
89
+ `DELETE /blog/posts/${post}/links/${k}`,
90
+ ]);
91
+ });
92
+ it("plan topics, keyword lists and targets, suggest with engines, crux and bing", async () => {
93
+ const seen = [];
94
+ const answer = (path) => path.endsWith("/plan/topics") ? { searchConsole: true, topics: [{ topic: "trail shoes", keywords: 3, written: 1, published: 1, clicks: 12, impressions: 300, position: 8.4, hasData: true, channels: ["linkedin"], items: [] }] }
95
+ : path.includes("/keywords/suggest") ? { q: "shoes", found: [{ text: "shoes for trail", engines: ["google", "youtube"] }], suggestions: ["shoes for trail"], engines: ["google", "youtube"] }
96
+ : path.includes("/keywords/") ? { targetUrl: null }
97
+ : path.endsWith("/crux") ? { origin: { origin: "https://example.com", url: null, phone: { ok: true, weeks: [{ end: "2026-11-15", lcp: 2100, inp: 180, cls: 0.05 }] }, desktop: { ok: false, reason: "no_data", message: "not enough data" } }, pages: [] }
98
+ : path.endsWith("/bing/stats") ? { days: 28, more: 0, sites: [{ url: "https://example.com/", clicks: 9, impressions: 80, daily: [], queries: [{ query: "trail shoes", clicks: 5 }] }, { url: "https://other.com/", error: "Couldn't read this site from Bing." }] }
99
+ : { items: [] };
100
+ const outs = [];
101
+ vi.stubGlobal("fetch", async (url, init) => { const path = url.replace("http://sa.test/api/v1", ""); seen.push(`${init.method} ${path}${init.body ? ` ${init.body}` : ""}`); return new Response(JSON.stringify(answer(path)), { headers: { "content-type": "application/json" } }); });
102
+ try {
103
+ for (const argv of [["plan", "topics"], ["keywords", "suggest", "shoes"], ["keywords", "lists"], ["keywords", "target", post, post, "none"], ["sites", "crux", post], ["bing"]]) { const r = await run([...argv, ...srv]); expect(r.code, argv.join(" ")).toBe(0); outs.push(r.out); }
104
+ } finally { vi.unstubAllGlobals(); }
105
+ expect(seen).toEqual(["GET /plan/topics", "GET /keywords/suggest?q=shoes&hl=en&geo=US", "GET /keyword-lists", `PATCH /keyword-lists/${post}/keywords/${post} {"targetUrl":null}`, `GET /visibility/sites/${post}/crux`, "GET /connections/bing/stats"]);
106
+ expect(outs[0]).toContain("12 clicks · 300 impressions · position 8.4 · on linkedin");
107
+ expect(outs[1]).toContain("shoes for trail · google, youtube");
108
+ expect(outs[3]).toBe("target page cleared.");
109
+ expect(outs[4]).toContain("LCP 2100 ms · INP 180 ms · CLS 0.05");
110
+ expect(outs[4]).toContain("not enough data");
111
+ expect(outs[5]).toContain("trail shoes (5)");
112
+ expect(outs[5]).toContain("Couldn't read this site from Bing.");
113
+ });
114
+ });
115
+
116
+ describe("blog video", () => {
117
+ const post = "0123456789abcdef01234567", srv = ["--server", "http://sa.test"];
118
+ const brief = { prompt: "Make this post into a 75 second film.", install: { skill: "npx skills add Moh4696/cinematic-skill", python: "pip install skia-python numpy pillow", ffmpeg: "brew install ffmpeg" }, script: { title: "Trail shoes", takes: [], fact_notes: [] } };
119
+ const withBrief = async (fn) => {
120
+ const seen = [];
121
+ vi.stubGlobal("fetch", async (url, init) => { seen.push(`${init.method} ${url.replace("http://sa.test/api/v1", "")}`); return new Response(JSON.stringify(brief), { headers: { "content-type": "application/json" } }); });
122
+ try { await fn(); } finally { vi.unstubAllGlobals(); }
123
+ return seen;
124
+ };
125
+ it("prints the install lines and the prompt, --json the full answer", async () => {
126
+ const seen = await withBrief(async () => {
127
+ const r = await run(["blog", "video", post, ...srv]);
128
+ expect(r.code).toBe(0);
129
+ expect(r.out).toContain(" npx skills add Moh4696/cinematic-skill\n pip install skia-python numpy pillow\n brew install ffmpeg");
130
+ expect(r.out).toContain("Make this post into a 75 second film.");
131
+ expect(JSON.parse((await run(["blog", "video", post, "--json", ...srv])).out)).toEqual(brief);
132
+ });
133
+ expect(seen).toEqual([`GET /blog/posts/${post}/video-brief`, `GET /blog/posts/${post}/video-brief`]);
134
+ });
135
+ it("--out writes script.json and replaces an existing file only with --force", async () => {
136
+ const { mkdtempSync, writeFileSync } = await import("node:fs");
137
+ const { tmpdir } = await import("node:os");
138
+ const file = `${mkdtempSync(`${tmpdir()}/sa-video-`)}/script.json`;
139
+ await withBrief(async () => {
140
+ expect((await run(["blog", "video", post, "--out", file, ...srv])).code).toBe(0);
141
+ expect(JSON.parse(readFileSync(file, "utf8"))).toEqual(brief.script);
142
+ writeFileSync(file, "mine");
143
+ const again = await run(["blog", "video", post, "--out", file, ...srv]);
144
+ expect(again.code).toBe(2);
145
+ expect(again.err).toContain("already exists");
146
+ expect(readFileSync(file, "utf8")).toBe("mine");
147
+ expect((await run(["blog", "video", post, "--out", file, "--force", ...srv])).code).toBe(0);
148
+ expect(JSON.parse(readFileSync(file, "utf8"))).toEqual(brief.script);
149
+ });
150
+ });
151
+ });
package/src/connect.js CHANGED
@@ -5,10 +5,11 @@
5
5
  // (`connect --code`, which the settings page hands to your own AI app) that can only open this computer's link.
6
6
  import { spawn } from "node:child_process";
7
7
  import { randomBytes } from "node:crypto";
8
- import { accessSync, closeSync, constants, mkdirSync, mkdtempSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
8
+ import { accessSync, closeSync, constants, copyFileSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
9
9
  import os from "node:os";
10
10
  import path from "node:path";
11
11
  import { StringDecoder } from "node:string_decoder";
12
+ import { fileURLToPath } from "node:url";
12
13
  import { CliError, client, exitCodeFor } from "./api.js";
13
14
  import { configDir, loadConfig, saveConfig } from "./config.js";
14
15
  import { VERSION } from "./mcp.js";
@@ -55,17 +56,37 @@ export function findBinary(command, env = process.env, platform = process.platfo
55
56
  return null;
56
57
  }
57
58
 
58
- /** Installed CLIs with their versions. */
59
+ /** Installed CLIs with their versions and the models each offers, looked up side by side. */
59
60
  export async function detect(env = ownEnv(), run = runProcess) {
60
- const found = [];
61
- for (const [kind, { command }] of Object.entries(KINDS)) {
61
+ const found = await Promise.all(Object.entries(KINDS).map(async ([kind, { command }]) => {
62
62
  const bin = findBinary(command, env);
63
- if (!bin) continue;
63
+ if (!bin) return null;
64
64
  let version = "";
65
65
  try { version = (await run([bin, "--version"], { env, timeoutMs: 20_000 })).stdout.trim().split("\n")[0].slice(0, 80); } catch { /* still usable */ }
66
- found.push({ kind, path: bin, version });
67
- }
68
- return found;
66
+ return { kind, path: bin, version, models: await listModels(kind, bin, env, run) };
67
+ }));
68
+ return found.filter(Boolean);
69
+ }
70
+
71
+ // Claude Code has no command that lists models; these aliases always mean its latest of each.
72
+ const CLAUDE_MODELS = [{ id: "fable", label: "Fable (latest)" }, { id: "opus", label: "Opus (latest)" }, { id: "sonnet", label: "Sonnet (latest)" }, { id: "haiku", label: "Haiku (latest)" }];
73
+
74
+ /** The models a CLI offers, from its own list where it has one. None when the list can't be read; the app then offers the CLI's default. */
75
+ export async function listModels(kind, bin, env = ownEnv(), run = runProcess) {
76
+ if (kind === "claude") return CLAUDE_MODELS;
77
+ try { return parseModels(kind, (await run(kind === "codex" ? [bin, "debug", "models"] : [bin, "models"], { env, timeoutMs: 20_000 })).stdout); }
78
+ catch { return []; }
79
+ }
80
+
81
+ /** `codex debug models` prints a JSON catalog (hidden ones skipped, in its own order); `agy models` prints `id<TAB>name` lines. */
82
+ export function parseModels(kind, stdout) {
83
+ let rows = [];
84
+ if (kind === "codex") {
85
+ const list = safeJson(stdout.trim())?.models;
86
+ rows = (Array.isArray(list) ? list : []).filter((m) => m && m.visibility !== "hide").sort((a, b) => (a.priority ?? 99) - (b.priority ?? 99)).map((m) => ({ id: m.slug, label: m.display_name }));
87
+ } else rows = stdout.split("\n").map((l) => l.split("\t")).filter((c) => c.length >= 2).map(([id, label]) => ({ id: id.trim(), label: label.trim() }));
88
+ // only ids this connector would pass on as --model
89
+ return rows.filter((m) => typeof m.id === "string" && MODEL.test(m.id)).slice(0, 40).map((m) => ({ id: m.id, label: String(m.label || m.id).slice(0, 80) }));
69
90
  }
70
91
 
71
92
  export function checkJob(job) {
@@ -205,6 +226,174 @@ export async function runJob(job, { binaries, env = ownEnv(), signal, run = runP
205
226
  } finally { rmSync(root, { recursive: true, force: true }); }
206
227
  }
207
228
 
229
+ // ---------------------------------------------------------------- video: the cinematic-film skill's own scripts, run here
230
+ const VIDEO_MS = 40 * 60_000;
231
+ const VIDEO_LOOKS = ["wall", "studio", "blueprint", "night"];
232
+ const VIDEO_SIZES = ["1080x1920", "1920x1080"];
233
+ const SCENE_FILE = fileURLToPath(new URL("./film/scene_auto.py", import.meta.url));
234
+
235
+ /** Where the cinematic-film skill may be installed, first match wins. */
236
+ export function filmSkillDirs(source = process.env, home = os.homedir()) {
237
+ return [source.SEOANYTHING_FILM_SKILL, ...[".claude", ".agents", ".codex"].map((d) => path.join(home, d, "skills", "cinematic-film")), path.join(home, ".cinematic-skill", "skills", "cinematic-film")].filter(Boolean);
238
+ }
239
+
240
+ /** The skill folder plus python3 (with skia-python, numpy, pillow), ffmpeg/ffprobe and a free voice, or what is missing. */
241
+ export async function detectVideo({ env = ownEnv(), source = process.env, home = os.homedir(), run = runProcess } = {}) {
242
+ const missing = [];
243
+ const skill = filmSkillDirs(source, home).find((d) => existsSync(path.join(d, "scripts", "render.py")) && existsSync(path.join(d, "scripts", "engine.py")));
244
+ if (!skill) missing.push("the cinematic-film skill (https://github.com/Moh4696/cinematic-skill, or set SEOANYTHING_FILM_SKILL)");
245
+ const python = findBinary("python3", env);
246
+ let pyOk = false;
247
+ if (python) try { pyOk = (await run([python, "-c", "import skia, numpy, PIL"], { env, timeoutMs: 60_000 })).code === 0; } catch { /* stays false */ }
248
+ if (!pyOk) missing.push(python ? "skia-python, numpy or pillow (python3 -m pip install skia-python numpy pillow)" : "python3");
249
+ const ffmpeg = findBinary("ffmpeg", env);
250
+ if (!ffmpeg || !findBinary("ffprobe", env)) missing.push("ffmpeg");
251
+ if (!findBinary("say", env) && !findBinary("espeak-ng", env)) missing.push("a free voice (macOS say or espeak-ng)");
252
+ return missing.length ? { missing } : { skill, python, ffmpeg };
253
+ }
254
+
255
+ // one line of narration text: no control characters, no leading dash (never read as a flag), no say/SSML markup
256
+ const clean = (v, max) => String(v ?? "").replace(/[\u0000-\u001f\u007f<>]|\[\[|\]\]/g, " ").replace(/\s+/g, " ").replace(/^[\s-]+/, "").trim().slice(0, max);
257
+
258
+ /** A {"type":"video"} message, checked, with a rebuilt script.json (fresh ids and take names, every field capped). */
259
+ export function checkVideo(m) {
260
+ const bad = (msg) => new JobError("failed", msg);
261
+ if (typeof m?.id !== "string" || !/^[0-9a-f]{8,64}$/.test(m.id)) throw bad("invalid job id.");
262
+ if (!VIDEO_LOOKS.includes(m.look)) throw bad("unknown look.");
263
+ if (!VIDEO_SIZES.includes(m.size)) throw bad("unknown size.");
264
+ const s = m.script;
265
+ if (!s || typeof s !== "object" || !Array.isArray(s.takes)) throw bad("the script has no takes.");
266
+ let id = 0;
267
+ const takes = [];
268
+ for (const t of s.takes) {
269
+ if (!t || !Array.isArray(t.lines)) throw bad("a take has no lines.");
270
+ const lines = [];
271
+ for (const l of t.lines) {
272
+ if (!l || typeof l.text !== "string" || ["spoken", "typed", "hero"].some((k) => l[k] != null && typeof l[k] !== "string")) throw bad("each line needs text, and spoken, typed and hero must be text.");
273
+ const text = clean(l.text, 300), spoken = clean(l.spoken || l.text, 400);
274
+ if (!text || !spoken) throw bad("a line is empty.");
275
+ if (++id > 40) throw bad("a script can have at most 40 lines.");
276
+ const gap = typeof l.gap_after === "number" && l.gap_after >= 0 && l.gap_after <= 3 ? { gap_after: l.gap_after } : {};
277
+ lines.push({ id, text, spoken, hero: clean(l.hero, 160), typed: clean(l.typed, 80), ...gap });
278
+ }
279
+ if (lines.length) takes.push(lines);
280
+ }
281
+ if (!id) throw bad("the script has no lines.");
282
+ const dropped = fitWords(takes);
283
+ id = 0; // ids and take names again from 1, after any dropped lines
284
+ const named = takes.map((lines, i) => ({ take: `T${String(i + 1).padStart(2, "0")}`, lines: lines.map((l) => ({ ...l, id: ++id })) }));
285
+ const title = clean(m.title || s.title, 120) || "Video";
286
+ return { id: m.id, title, slug: typeof m.slug === "string" ? m.slug : title, look: m.look, size: m.size, script: { title, takes: named }, dropped };
287
+ }
288
+
289
+ // about 90 s of the free voice (~145 words a minute): Shorts, Reels and TikTok want under 90 s
290
+ export const MAX_WORDS = 215;
291
+ const words = (l) => l.spoken.split(" ").filter(Boolean).length;
292
+
293
+ /** Drop whole lines from the middle takes (never the first or last take) until the spoken words fit. Changes `takes` (arrays of lines); returns how many lines went. */
294
+ export function fitWords(takes, max = MAX_WORDS) {
295
+ let total = takes.flat().reduce((n, l) => n + words(l), 0), dropped = 0;
296
+ while (total > max) {
297
+ // the middle take with the most lines (the later one on a tie) gives up its last line
298
+ let pick = -1;
299
+ for (let i = 1; i < takes.length - 1; i++) if (takes[i].length && (pick < 0 || takes[i].length >= takes[pick].length)) pick = i;
300
+ if (pick < 0) break; // only the first and last takes are left: they stay whole
301
+ total -= words(takes[pick].pop());
302
+ dropped++;
303
+ }
304
+ for (let i = takes.length - 1; i >= 0; i--) if (!takes[i].length) takes.splice(i, 1);
305
+ return dropped;
306
+ }
307
+
308
+ /** A new folder ~/SEOAnything/videos/<slug>-<YYYYMMDD-HHMMSS> (slug [a-z0-9-], 60 chars at most), never an existing one. */
309
+ export function videoFolder(slug, now = new Date(), root = path.join(os.homedir(), "SEOAnything", "videos")) {
310
+ const s = String(slug ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+/, "").slice(0, 60).replace(/-+$/, "") || "video";
311
+ const p2 = (n) => String(n).padStart(2, "0");
312
+ const base = path.join(root, `${s}-${now.getFullYear()}${p2(now.getMonth() + 1)}${p2(now.getDate())}-${p2(now.getHours())}${p2(now.getMinutes())}${p2(now.getSeconds())}`);
313
+ let dir = base;
314
+ for (let n = 2; existsSync(dir); n++) dir = `${base}-${n}`;
315
+ return dir;
316
+ }
317
+
318
+ /** The skill's steps after the project exists, in order, each with the progress it reports when done. */
319
+ export function videoSteps(dir, size) {
320
+ const p = ["--project", dir];
321
+ return [
322
+ { stage: "voice", pct: 15, args: ["tts_say.py", ...p] },
323
+ { stage: "timing", pct: 22, args: ["split_takes.py", ...p] },
324
+ { stage: "timing", pct: 28, args: ["build_narration.py", ...p] },
325
+ { stage: "assets", pct: 33, args: ["prep_assets.py", ...p] },
326
+ { stage: "sound", pct: 36, args: ["render.py", ...p, "--cues"] },
327
+ { stage: "sound", pct: 40, args: ["build_sfx.py", ...p] },
328
+ { stage: "sound", pct: 45, args: ["mix_soundtrack.py", ...p] },
329
+ { stage: "render", pct: 88, args: ["render.py", ...p, "--size", size, "--out", "out/film.mp4", "--audio", "audio/mix.m4a"] },
330
+ { stage: "captions", pct: 97, args: ["burn_captions.py", ...p, "--video", "out/film.mp4", "--audio", "audio/mix.m4a", "--out", "out/film_captions.mp4"], optional: true },
331
+ ];
332
+ }
333
+
334
+ /** Make one film in a new folder with the skill's scripts and the free voice. Resolves { path, seconds, bytes }. */
335
+ export async function runVideo(msg, { setup, env = ownEnv(), run = runProcess, signal, onProgress = () => {}, log = () => {}, root, now = new Date() } = {}) {
336
+ const job = checkVideo(msg);
337
+ if (job.dropped) log(` video: the script was over ${MAX_WORDS} words (about 90 s), so ${job.dropped} middle line${job.dropped > 1 ? "s were" : " was"} left out.`);
338
+ const dir = videoFolder(job.slug, now, root);
339
+ mkdirSync(path.dirname(dir), { recursive: true });
340
+ const scripts = path.join(setup.skill, "scripts");
341
+ const deadline = Date.now() + VIDEO_MS;
342
+ const exec = async (name, argv) => {
343
+ const left = deadline - Date.now();
344
+ if (left <= 0) throw new JobError("timeout", "the video took longer than 40 minutes.");
345
+ let r;
346
+ // idle limit = what is left: a render prints nothing while its chunks encode
347
+ try { r = await run(argv, { cwd: scripts, env, timeoutMs: left, idleMs: left, signal }); }
348
+ catch (e) {
349
+ if (e.code === "timeout") throw new JobError("timeout", "the video took longer than 40 minutes.");
350
+ if (e.code === "cancelled") throw new JobError("cancelled", "the video was cancelled.");
351
+ throw new JobError("failed", `${name}: ${e.message}`);
352
+ }
353
+ if (r.code !== 0) throw new JobError("failed", `${name} failed: ${(r.stderr.trim() || r.stdout.trim()).slice(-400)}`);
354
+ };
355
+ const py = ([script, ...args]) => exec(script, [setup.python, path.join(scripts, script), ...args]);
356
+ await py(["new_project.py", dir]);
357
+ mkdirSync(dir, { recursive: true });
358
+ const put = (name, data) => writeFileSync(path.join(dir, name), JSON.stringify(data, null, 1) + "\n");
359
+ put("script.json", job.script);
360
+ put("photos.json", { grade: "natural", photos: [], recreations: [] });
361
+ put("map.json", { maps: [] });
362
+ put("film.json", { look: job.look, size: job.size });
363
+ copyFileSync(SCENE_FILE, path.join(dir, "scene.py"));
364
+ onProgress("setup", 5);
365
+ let captioned = false;
366
+ for (const step of videoSteps(dir, job.size)) {
367
+ try { await py(step.args); }
368
+ catch (e) { if (!step.optional || e.code !== "failed") throw e; continue; } // no captions: the clean film is still a film
369
+ if (step.optional) captioned = true;
370
+ onProgress(step.stage, step.pct);
371
+ }
372
+ let file = path.join(dir, "out", captioned ? "film_captions.mp4" : "film.mp4");
373
+ if (!existsSync(file)) throw new JobError("failed", "the render finished without a film file.");
374
+ // a phone-sized copy (H.264 high, CRF 23, AAC 128k, faststart, same frame size); the big masters stay only if this fails.
375
+ // the 3 Mbit/s cap: the look's film grain kept CRF 23 alone at 11 Mbit/s (139 MB for 101 s); capped it is 35 MB
376
+ const small = path.join(dir, "out", "film_final.mp4");
377
+ if (setup.ffmpeg) {
378
+ try {
379
+ await exec("ffmpeg", [setup.ffmpeg, "-hide_banner", "-nostdin", "-loglevel", "error", "-y", "-i", file, "-c:v", "libx264", "-profile:v", "high", "-preset", "medium", "-crf", "23",
380
+ "-maxrate", "3M", "-bufsize", "6M", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", small]);
381
+ if (!statSync(small).size) throw new JobError("failed", "empty");
382
+ for (const f of ["film.mp4", "film_captions.mp4"]) rmSync(path.join(dir, "out", f), { force: true });
383
+ file = small;
384
+ } catch (e) {
385
+ if (e.code === "timeout" || e.code === "cancelled") throw e;
386
+ rmSync(small, { force: true });
387
+ log(` video: the phone-sized copy failed, keeping the full-size film (${String(e.message).slice(0, 200)})`);
388
+ }
389
+ }
390
+ onProgress("captions", 100);
391
+ const bytes = statSync(file).size;
392
+ let seconds = 0;
393
+ try { seconds = Math.round(JSON.parse(readFileSync(path.join(dir, "audio", "timing.json"), "utf8")).total_duration * 10) / 10 || 0; } catch { /* unknown length */ }
394
+ return { path: file, seconds, bytes };
395
+ }
396
+
208
397
  /** This computer's stable id, made once and kept in the config file. */
209
398
  export function deviceIdFor() {
210
399
  const cfg = loadConfig();
@@ -231,12 +420,12 @@ export async function pair({ server, code, deviceId = deviceIdFor(), hostname =
231
420
  }
232
421
 
233
422
  /** Re-run `connect` detached from this terminal or AI app, logging to a file, and return at once. */
234
- export function startBackground(server, { script = process.argv[1], spawnImpl = spawn } = {}) {
423
+ export function startBackground(server, { script = process.argv[1], spawnImpl = spawn, video = false } = {}) {
235
424
  mkdirSync(configDir(), { recursive: true, mode: 0o700 });
236
425
  const log = path.join(configDir(), "connect.log");
237
426
  const out = openSync(log, "w", 0o600);
238
427
  try {
239
- const child = spawnImpl(process.execPath, [script, "connect", "--server", server], { detached: true, stdio: ["ignore", out, out], windowsHide: true });
428
+ const child = spawnImpl(process.execPath, [script, "connect", "--server", server, ...(video ? ["--video"] : [])], { detached: true, stdio: ["ignore", out, out], windowsHide: true });
240
429
  child.unref();
241
430
  return { pid: child.pid, log };
242
431
  } finally { closeSync(out); }
@@ -246,7 +435,8 @@ export function startBackground(server, { script = process.argv[1], spawnImpl =
246
435
  * Connect and serve until the user stops it or the server disconnects this computer. Resolves with the reason.
247
436
  * `deviceToken` (from a setup code) wins over `token` (the user's login); `onUnlinked` runs when the cloud no longer accepts it.
248
437
  */
249
- export async function connect({ server, token, deviceToken, onUnlinked, log = console.error, hostname = os.hostname(), signal, WebSocketImpl = globalThis.WebSocket } = {}) {
438
+ export async function connect({ server, token, deviceToken, onUnlinked, log = console.error, hostname = os.hostname(), signal, WebSocketImpl = globalThis.WebSocket,
439
+ video = false, detectVideoImpl = detectVideo, runVideoImpl = runVideo } = {}) {
250
440
  if (!WebSocketImpl) throw new CliError("seoanything connect needs Node 22 or newer (built-in WebSocket).", 1);
251
441
  const api = client({ server, token });
252
442
  const deviceId = deviceIdFor();
@@ -255,7 +445,14 @@ export async function connect({ server, token, deviceToken, onUnlinked, log = co
255
445
  if (!found.length) throw new CliError("no AI CLI found on PATH. install claude, codex or agy, sign in to it once, then run connect again.", 1);
256
446
  for (const f of found) log(`✓ found ${KINDS[f.kind].label} ${f.version} at ${f.path}`);
257
447
  let binaries = Object.fromEntries(found.map((f) => [f.kind, f.path]));
258
- const hello = () => ({ type: "hello", deviceId, name: hostname.slice(0, 80), platform: process.platform, version: VERSION, clis: found.map((f) => ({ kind: f.kind, version: f.version })), features: ["rescan"] });
448
+ // --video: offered only when the skill and its tools are all here
449
+ let film = null;
450
+ if (video) {
451
+ const v = await detectVideoImpl({ env });
452
+ if (v.missing) log(`! video is off: missing ${v.missing.join("; ")}.`);
453
+ else { film = v; log(`✓ video: cinematic-film at ${v.skill}, films go to ${path.join(os.homedir(), "SEOAnything", "videos")}`); }
454
+ }
455
+ const hello = () => ({ type: "hello", deviceId, name: hostname.slice(0, 80), platform: process.platform, version: VERSION, clis: found.map((f) => ({ kind: f.kind, version: f.version, models: f.models })), features: film ? ["rescan", "video"] : ["rescan"] });
259
456
  // asked from the settings page: pick up a CLI installed since this connector started, without a restart
260
457
  async function rescan(ws) {
261
458
  const now = await detect(env);
@@ -268,7 +465,9 @@ export async function connect({ server, token, deviceToken, onUnlinked, log = co
268
465
  const jobs = new Map();
269
466
  let socket, attempt = 0, stopped = false, finish;
270
467
  const done = new Promise((r) => (finish = r));
271
- const stop = (reason) => { if (stopped) return; stopped = true; for (const j of jobs.values()) j.abort(); try { socket?.close(1000); } catch { /* closed */ } finish(reason); };
468
+ let videoJob = null; // { id, ac, last }: one film at a time, beside the chat jobs (it never takes one of their MAX_JOBS slots)
469
+ let unsentVideo = null; // a film's last word (done or failed) that went out while the link was down: sent again on the next welcome
470
+ const stop = (reason) => { if (stopped) return; stopped = true; for (const j of jobs.values()) j.abort(); videoJob?.ac.abort(); try { socket?.close(1000); } catch { /* closed */ } finish(reason); };
272
471
  signal?.addEventListener("abort", () => stop("connector closed. your chats fall back to the cloud models until you run connect again."), { once: true });
273
472
  const send = (ws, m) => { if (ws.readyState === 1) ws.send(JSON.stringify(m)); };
274
473
 
@@ -296,6 +495,31 @@ export async function connect({ server, token, deviceToken, onUnlinked, log = co
296
495
  } finally { clearTimeout(flushTimer); jobs.delete(job.id); }
297
496
  }
298
497
 
498
+ // a film outlives a dropped link: it reports on whichever socket is open, and repeats its progress so the cloud knows it is alive
499
+ async function startVideo(m) {
500
+ if (typeof m.id !== "string") return;
501
+ const tell = (msg) => socket && send(socket, msg);
502
+ // the link can drop mid-film (Wi-Fi, DNS): the final answer is kept until a socket takes it
503
+ const final = (msg) => { if (socket?.readyState === 1) send(socket, msg); else unsentVideo = msg; };
504
+ const fail = (code, message) => final({ type: "video_failed", id: m.id, code, message });
505
+ if (!film) return fail("missing_setup", "this computer was not started with --video, or is missing the film tools.");
506
+ if (videoJob) return fail("busy", "this computer is already making a video.");
507
+ const ac = new AbortController();
508
+ videoJob = { id: m.id, ac, last: { type: "video_progress", id: m.id, stage: "setup", pct: 0 } };
509
+ const job = videoJob;
510
+ const beat = setInterval(() => tell(job.last), 60_000);
511
+ log(`→ video: making "${String(m.title ?? "").slice(0, 80)}"…`);
512
+ try {
513
+ const r = await runVideoImpl(m, { setup: film, env, signal: ac.signal, log, onProgress: (stage, pct) => { job.last = { type: "video_progress", id: m.id, stage, pct }; tell(job.last); } });
514
+ final({ type: "video_done", id: m.id, ...r });
515
+ log(`✓ video: ${r.path}`);
516
+ } catch (e) {
517
+ const code = ["timeout", "cancelled", "missing_setup"].includes(e.code) ? e.code : "failed";
518
+ fail(code, String(e.message ?? "the video failed").slice(0, 400));
519
+ log(`✗ video: ${e.message}`);
520
+ } finally { clearInterval(beat); videoJob = null; }
521
+ }
522
+
299
523
  async function open() {
300
524
  if (stopped) return;
301
525
  let url;
@@ -313,10 +537,18 @@ export async function connect({ server, token, deviceToken, onUnlinked, log = co
313
537
  });
314
538
  ws.addEventListener("message", (ev) => {
315
539
  let m; try { m = JSON.parse(String(ev.data)); } catch { return; }
316
- if (m.type === "welcome") { attempt = 0; log(`✓ linked to ${server} as "${hostname}". chats and blog posts can now use your CLI while this keeps running.`); }
540
+ if (m.type === "welcome") {
541
+ attempt = 0;
542
+ // back after a drop: say where the film is, or how it ended, so the website doesn't give up on it
543
+ if (videoJob) send(ws, videoJob.last);
544
+ if (unsentVideo) { send(ws, unsentVideo); unsentVideo = null; }
545
+ log(`✓ linked to ${server} as "${hostname}". chats and blog posts can now use your CLI while this keeps running.`);
546
+ }
317
547
  else if (m.type === "run") startJob(ws, m);
318
548
  else if (m.type === "rescan") rescan(ws);
319
549
  else if (m.type === "cancel") jobs.get(m.id)?.abort();
550
+ else if (m.type === "video") startVideo(m);
551
+ else if (m.type === "video_cancel") { if (videoJob?.id === m.id) videoJob.ac.abort(); }
320
552
  else if (m.type === "revoked") { if (deviceToken) onUnlinked?.(); stop("this computer was disconnected in SEOAnything settings."); }
321
553
  });
322
554
  ws.addEventListener("close", (ev) => {