claude-code-session-manager 0.126.0 → 0.128.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/bin/cli.cjs +71 -9
- package/bin/supervise.cjs +84 -0
- package/dist/assets/{AgentLibrary-bzeuZN4F.js → AgentLibrary-cNQU5YWy.js} +1 -1
- package/dist/assets/{Button-8dWfDDuQ.js → Button-9dIPAOBg.js} +1 -1
- package/dist/assets/{DataModel-D4ybBPZN.js → DataModel-DrDJ6ysw.js} +1 -1
- package/dist/assets/{History-hsztE6yh.js → History-4rrDdWNP.js} +1 -1
- package/dist/assets/{Hooks-CRmZMQaW.js → Hooks-Bj_jF5Pa.js} +1 -1
- package/dist/assets/{Library-Czt3Bojd.js → Library-D-Wsxrh7.js} +1 -1
- package/dist/assets/{ListDetail-Cr6Ct_WX.js → ListDetail-D7Om0H8j.js} +1 -1
- package/dist/assets/{McpServers-CeXJ2bng.js → McpServers-CbIbSd5o.js} +1 -1
- package/dist/assets/{Memory-caujO8O3.js → Memory-DgQlvQrO.js} +1 -1
- package/dist/assets/{Panel-D64i9tGz.js → Panel-DZHiD8Ar.js} +1 -1
- package/dist/assets/{Permissions-DpWOIrvr.js → Permissions-CfzduF4B.js} +1 -1
- package/dist/assets/{Plugins-Bd1ekP5P.js → Plugins-D-AG5nAo.js} +2 -2
- package/dist/assets/{ProvenanceBadge-B96A_uZf.js → ProvenanceBadge-B9JSEjll.js} +1 -1
- package/dist/assets/{SaveBar-D0Y2t-Ao.js → SaveBar-mVKig6hL.js} +1 -1
- package/dist/assets/{Scheduler-Y5_YbNrC.js → Scheduler-DFTCnh60.js} +1 -1
- package/dist/assets/{ScopeSwitcher-BmWA_dP9.js → ScopeSwitcher-s8J-yr7Z.js} +1 -1
- package/dist/assets/{Settings-Bcf65bpL.js → Settings-BTmxRMaP.js} +1 -1
- package/dist/assets/{SkillReferenceGraph-BeSNXloA.js → SkillReferenceGraph-C5lKqf5y.js} +1 -1
- package/dist/assets/{Skills-DwnQKJVc.js → Skills-CxOacq0k.js} +1 -1
- package/dist/assets/{SystemPrompt-Dih6SCmL.js → SystemPrompt-BCWg5FAz.js} +1 -1
- package/dist/assets/{TagLibrary-BZ-Kp10P.js → TagLibrary-BnF0_PkG.js} +1 -1
- package/dist/assets/{TiptapBody-C2nEUmF7.js → TiptapBody-C2Iu6rZd.js} +1 -1
- package/dist/assets/{Toggle-Dw8-zNQo.js → Toggle-C-oD66BG.js} +1 -1
- package/dist/assets/{ViewTabs-CoYPKGN-.js → ViewTabs-Cs4v7vLY.js} +1 -1
- package/dist/assets/{historyTotals-BbKcNpV7.js → historyTotals-CbRSLD8f.js} +1 -1
- package/dist/assets/{index-BnKaYERU.css → index-DtdWBGrI.css} +1 -1
- package/dist/assets/index-DzY_GXYY.js +3081 -0
- package/dist/assets/{settingsSchema-6doG_61l.js → settingsSchema-bSBfHuan.js} +1 -1
- package/dist/assets/{skillFrontmatter-BYMYWDfb.js → skillFrontmatter-BEseWm8r.js} +1 -1
- package/dist/assets/{useAgentsDirWatch-Cqabjieh.js → useAgentsDirWatch-CdyHxKCI.js} +1 -1
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +343 -341
- package/package.json +1 -1
- package/plugins/session-manager-dev/skills/develop/SKILL.md +3 -2
- package/scripts/scheduler-mcp-server.cjs +209 -7
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +37 -4
- package/src/main/crashDiagnostics.cjs +83 -8
- package/src/main/health.cjs +16 -5
- package/src/main/index.cjs +46 -0
- package/src/main/ipcSchemas.cjs +107 -0
- package/src/main/lib/chatBootRecovery.cjs +136 -0
- package/src/main/lib/chatInflight.cjs +88 -0
- package/src/main/lib/claude/agentModelResolve.cjs +26 -7
- package/src/main/lib/claude/personaToolScope.cjs +40 -2
- package/src/main/lib/demo-video-kit/capture.cjs +113 -0
- package/src/main/lib/demo-video-kit/character.cjs +97 -0
- package/src/main/lib/demo-video-kit/checks.cjs +150 -0
- package/src/main/lib/demo-video-kit/frames.cjs +200 -0
- package/src/main/lib/demo-video-kit/seedKit.cjs +52 -0
- package/src/main/lib/demo-video-kit/sound.cjs +312 -0
- package/src/main/lib/epic/epicDelegationStats.cjs +1 -0
- package/src/main/lib/epic/epicSweepValidator.cjs +60 -6
- package/src/main/lib/epic/epicValidationHook.cjs +31 -3
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +71 -15
- package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +185 -34
- package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +15 -0
- package/src/main/lib/mcpToolCatalog.cjs +93 -14
- package/src/main/lib/opsOwnership.cjs +9 -5
- package/src/main/lib/persona-macro/builtinMacros.cjs +30 -5
- package/src/main/lib/persona-macro/macroJobDispatch.cjs +116 -0
- package/src/main/lib/persona-macro/macroJobIpc.cjs +50 -0
- package/src/main/lib/persona-macro/macroJobStatus.cjs +112 -0
- package/src/main/lib/persona-macro/macroLibrary.cjs +73 -3
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +100 -0
- package/src/main/lib/prd/prdCreate.cjs +17 -2
- package/src/main/lib/prd/prdFrontmatter.cjs +7 -2
- package/src/main/lib/process/childWithLog.cjs +38 -95
- package/src/main/lib/process/memoryScope.cjs +140 -0
- package/src/main/lib/process/ozonePlatform.cjs +15 -0
- package/src/main/lib/process/procIdentity.cjs +10 -3
- package/src/main/lib/process/scopeOomPolicy.cjs +69 -0
- package/src/main/lib/project-pages/pagesLibrary.cjs +171 -0
- package/src/main/lib/project-pages/playerBridge.cjs +129 -0
- package/src/main/lib/scheduler/cpuSample.cjs +147 -0
- package/src/main/lib/scheduler/definitionOfDone.cjs +40 -0
- package/src/main/lib/scheduler/jobLeftovers.cjs +204 -0
- package/src/main/lib/scheduler/jobSupervisorRecord.cjs +2 -1
- package/src/main/lib/scheduler/loadGate.cjs +116 -45
- package/src/main/lib/scheduler/queueStore.cjs +5 -2
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
- package/src/main/lib/scheduler/schedulerBatch.cjs +10 -3
- package/src/main/lib/scheduler/schedulerConfig.cjs +7 -2
- package/src/main/lib/smfileHeaders.cjs +11 -3
- package/src/main/lib/telemetry/crashTelemetry.cjs +8 -4
- package/src/main/projectPages.cjs +107 -30
- package/src/main/promptSessionsIpc.cjs +131 -0
- package/src/main/scheduler/budget.cjs +31 -0
- package/src/main/scheduler/prdParser.cjs +2 -0
- package/src/main/scheduler/prdPaths.cjs +54 -0
- package/src/main/scheduler/reviewLadder.cjs +17 -0
- package/src/main/scheduler/starvation.cjs +22 -0
- package/src/main/scheduler.cjs +548 -77
- package/src/main/seedSchedulerMcp.cjs +10 -1
- package/src/main/templates/PRD_AUTHORING.md +5 -2
- package/src/main/transcripts.cjs +8 -0
- package/src/main/usage.cjs +4 -2
- package/src/main/webRemote.cjs +3 -1
- package/src/preload/api.d.ts +113 -7
- package/src/preload/apiSurface.json +70 -0
- package/src/preload/index.cjs +13 -0
- package/src/seed/agents/demo-video-builder.md +141 -43
- package/src/seed/agents/project-home-builder.md +26 -13
- package/dist/assets/index-DgPUERhe.js +0 -3079
|
@@ -11,6 +11,11 @@
|
|
|
11
11
|
* prompt, CLAUDE.md, `--append-system-prompt` and `--disallowedTools` keep
|
|
12
12
|
* working.
|
|
13
13
|
*
|
|
14
|
+
* Scoping is focus, not containment: the scope decides which tools a job is
|
|
15
|
+
* offered. Every headless job runs as the owner's OS user with
|
|
16
|
+
* --dangerously-skip-permissions, so a job with Bash can still start an MCP
|
|
17
|
+
* server or call the admin API itself.
|
|
18
|
+
*
|
|
14
19
|
* Pure: no fs, and no require of scheduler.cjs (cycle) — the caller passes its
|
|
15
20
|
* HEADLESS_DISALLOWED_TOOLS list in.
|
|
16
21
|
*/
|
|
@@ -45,9 +50,12 @@ function buildPersonaToolScope(tools, { disallowed = [] } = {}) {
|
|
|
45
50
|
|
|
46
51
|
/**
|
|
47
52
|
* @param {{ tools: string[] }|null} scope result of buildPersonaToolScope
|
|
53
|
+
* @param {{ mcpServers?: Record<string, object> }} [opts] known MCP server
|
|
54
|
+
* definitions by name. When EVERY mcp__ tool in scope names a server here,
|
|
55
|
+
* only those servers are passed (--mcp-config <json> --strict-mcp-config).
|
|
48
56
|
* @returns {string[]} argv fragment ([] when unscoped)
|
|
49
57
|
*/
|
|
50
|
-
function personaToolScopeArgs(scope) {
|
|
58
|
+
function personaToolScopeArgs(scope, { mcpServers } = {}) {
|
|
51
59
|
if (!scope) return [];
|
|
52
60
|
const def = {
|
|
53
61
|
description: 'Headless run with a scheduler-enforced tool scope.',
|
|
@@ -60,13 +68,43 @@ function personaToolScopeArgs(scope) {
|
|
|
60
68
|
];
|
|
61
69
|
// A scope naming no MCP tool never uses a server: with --strict-mcp-config and
|
|
62
70
|
// no --mcp-config (variadic; would swallow later args) the CLI boots none.
|
|
63
|
-
|
|
71
|
+
const mcpTools = scope.tools.map(String).filter((t) => t.startsWith('mcp__'));
|
|
72
|
+
if (mcpTools.length === 0) {
|
|
64
73
|
args.push('--strict-mcp-config');
|
|
74
|
+
return args;
|
|
75
|
+
}
|
|
76
|
+
// Server name = the segment between `mcp__` and the next `__`.
|
|
77
|
+
const named = new Set(mcpTools.map((t) => t.slice(5).split('__')[0]));
|
|
78
|
+
const known = mcpServers || {};
|
|
79
|
+
const allKnown = [...named].every((n) => n && Object.prototype.hasOwnProperty.call(known, n));
|
|
80
|
+
if (allKnown) {
|
|
81
|
+
const picked = {};
|
|
82
|
+
for (const n of named) picked[n] = known[n];
|
|
83
|
+
// --mcp-config is variadic: the caller must keep a `--flag` right after.
|
|
84
|
+
args.push('--mcp-config', JSON.stringify({ mcpServers: picked }), '--strict-mcp-config');
|
|
65
85
|
}
|
|
66
86
|
return args;
|
|
67
87
|
}
|
|
68
88
|
|
|
89
|
+
const JOB_MCP_TOOLS_ENV = 'SM_SCHEDULER_JOB_MCP_TOOLS';
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Env fragment a scoped job carries so an out-of-process MCP server can tell
|
|
93
|
+
* which MCP tools the scope admits. scripts/scheduler-mcp-server.cjs reads it
|
|
94
|
+
* to list and serve only in-scope tools. The value is always a JSON array
|
|
95
|
+
* string; '[]' means no MCP tool.
|
|
96
|
+
* @param {{ tools: string[] }|null|undefined} scope
|
|
97
|
+
* @returns {Record<string, string>} {} when unscoped
|
|
98
|
+
*/
|
|
99
|
+
function personaToolScopeEnv(scope) {
|
|
100
|
+
if (!scope) return {};
|
|
101
|
+
const mcp = scope.tools.map(String).filter((t) => t.startsWith('mcp__'));
|
|
102
|
+
return { [JOB_MCP_TOOLS_ENV]: JSON.stringify(mcp) };
|
|
103
|
+
}
|
|
104
|
+
|
|
69
105
|
module.exports = {
|
|
106
|
+
JOB_MCP_TOOLS_ENV,
|
|
107
|
+
personaToolScopeEnv,
|
|
70
108
|
HEADLESS_TOOL_FLOOR,
|
|
71
109
|
HEADLESS_SCOPE_AGENT_NAME,
|
|
72
110
|
buildPersonaToolScope,
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Demo-video kit capture helper: up to 6 size-budgeted screenshots (and optional short clips)
|
|
3
|
+
// of the live product at one URL. Playwright is resolved at runtime (cwd, then global npm
|
|
4
|
+
// root, or an injected loader) and is never installed here. Node builtins only.
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const { spawnSync } = require('child_process');
|
|
8
|
+
|
|
9
|
+
const MAX_SHOTS = 6;
|
|
10
|
+
const IMAGE_BUDGET = 120 * 1024;
|
|
11
|
+
const CLIP_BUDGET = 280 * 1024;
|
|
12
|
+
const QUALITY_STEPS = [80, 65, 52, 40, 30, 20]; // at most 6 tries
|
|
13
|
+
const NAV_TIMEOUT_MS = 30000;
|
|
14
|
+
const VIEWPORT = { width: 1280, height: 720 };
|
|
15
|
+
|
|
16
|
+
function tryRequire(name, paths) {
|
|
17
|
+
try {
|
|
18
|
+
return require(require.resolve(name, { paths }));
|
|
19
|
+
} catch {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function globalNpmRoot() {
|
|
25
|
+
try {
|
|
26
|
+
const r = spawnSync('npm', ['root', '-g'], { encoding: 'utf8', timeout: 15000 });
|
|
27
|
+
return r.status === 0 ? String(r.stdout).trim() : '';
|
|
28
|
+
} catch {
|
|
29
|
+
return '';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Default loader: process.cwd() first, then the global npm root. Never installs. */
|
|
34
|
+
function defaultLoader() {
|
|
35
|
+
for (const name of ['playwright', 'playwright-core']) {
|
|
36
|
+
const m = tryRequire(name, [process.cwd()]);
|
|
37
|
+
if (m) return m;
|
|
38
|
+
}
|
|
39
|
+
const root = globalNpmRoot();
|
|
40
|
+
if (root) {
|
|
41
|
+
for (const name of ['playwright', 'playwright-core']) {
|
|
42
|
+
const m = tryRequire(name, [root]);
|
|
43
|
+
if (m) return m;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function defaultEncode(page, { kind, quality }) {
|
|
50
|
+
if (kind !== 'image') return null; // clips need an injected encoder; dropped otherwise
|
|
51
|
+
return page.screenshot({ type: 'jpeg', quality });
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Step quality down (<= 6 tries) until the buffer fits the budget; null when it never does. */
|
|
55
|
+
async function fitBudget(encode, page, kind, budget) {
|
|
56
|
+
const steps = kind === 'image' ? QUALITY_STEPS : [QUALITY_STEPS[0], QUALITY_STEPS[2], QUALITY_STEPS[4]];
|
|
57
|
+
for (let i = 0; i < steps.length && i < 6; i++) {
|
|
58
|
+
const buf = await encode(page, { kind, quality: steps[i] });
|
|
59
|
+
if (!buf) return null;
|
|
60
|
+
if (buf.length <= budget) return buf;
|
|
61
|
+
}
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function focusFor(page, shot) {
|
|
66
|
+
const sel = shot.focusSelector || shot.selector;
|
|
67
|
+
if (sel) {
|
|
68
|
+
try {
|
|
69
|
+
const b = await page.locator(sel).first().boundingBox();
|
|
70
|
+
if (b) return { x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.width), h: Math.round(b.height) };
|
|
71
|
+
} catch { /* fall through to default */ }
|
|
72
|
+
}
|
|
73
|
+
return { x: Math.round(VIEWPORT.width * 0.25), y: Math.round(VIEWPORT.height * 0.25), w: Math.round(VIEWPORT.width * 0.5), h: Math.round(VIEWPORT.height * 0.5) };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function capture({ url, outDir, shots, max = MAX_SHOTS, loadPlaywright, encode, navTimeoutMs } = {}) {
|
|
77
|
+
if (!url || typeof url !== 'string') return { skipped: 'no-url' };
|
|
78
|
+
const pw = (loadPlaywright || defaultLoader)();
|
|
79
|
+
const resolved = pw && typeof pw.then === 'function' ? await pw : pw;
|
|
80
|
+
const chromium = resolved && resolved.chromium;
|
|
81
|
+
if (!chromium) return { skipped: 'no-playwright' };
|
|
82
|
+
|
|
83
|
+
const cap = Math.max(0, Math.min(Number(max) || MAX_SHOTS, MAX_SHOTS));
|
|
84
|
+
const list = (Array.isArray(shots) && shots.length ? shots : [{}]).slice(0, cap);
|
|
85
|
+
const enc = encode || defaultEncode;
|
|
86
|
+
const timeout = Math.min(Number(navTimeoutMs) || NAV_TIMEOUT_MS, NAV_TIMEOUT_MS);
|
|
87
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
88
|
+
|
|
89
|
+
const items = [];
|
|
90
|
+
const browser = await chromium.launch({ headless: true });
|
|
91
|
+
try {
|
|
92
|
+
const page = await browser.newPage({ viewport: VIEWPORT });
|
|
93
|
+
page.setDefaultTimeout(timeout);
|
|
94
|
+
await page.goto(url, { timeout, waitUntil: 'load' }); // the only navigation, to the given URL
|
|
95
|
+
for (let i = 0; i < list.length; i++) {
|
|
96
|
+
const shot = list[i] || {};
|
|
97
|
+
const kind = shot.kind === 'clip' ? 'clip' : 'image';
|
|
98
|
+
if (shot.selector) {
|
|
99
|
+
try { await page.locator(shot.selector).first().scrollIntoViewIfNeeded({ timeout }); } catch { /* keep going */ }
|
|
100
|
+
}
|
|
101
|
+
const buf = await fitBudget(enc, page, kind, kind === 'image' ? IMAGE_BUDGET : CLIP_BUDGET);
|
|
102
|
+
if (!buf) continue;
|
|
103
|
+
const file = path.join(outDir, `shot-${String(i + 1).padStart(2, '0')}.${kind === 'image' ? 'jpg' : 'webm'}`);
|
|
104
|
+
fs.writeFileSync(file, buf);
|
|
105
|
+
items.push({ file, kind, bytes: buf.length, focus: await focusFor(page, shot) });
|
|
106
|
+
}
|
|
107
|
+
} finally {
|
|
108
|
+
await browser.close().catch(() => {});
|
|
109
|
+
}
|
|
110
|
+
return { items };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
module.exports = { capture, IMAGE_BUDGET, CLIP_BUDGET, QUALITY_STEPS };
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Demo-video kit character: a project's mascot lives in
|
|
3
|
+
// <ops>/project-pages/videos/_character/{character.json,character.js}.
|
|
4
|
+
// Reading is plain file reading; writing goes only through the
|
|
5
|
+
// POST /admin/project-home/character/write route (writer 'project-home').
|
|
6
|
+
// speakWithCommand spawns the user's TTS argv directly — never through a shell.
|
|
7
|
+
const fs = require('node:fs');
|
|
8
|
+
const path = require('node:path');
|
|
9
|
+
const { spawnSync } = require('node:child_process');
|
|
10
|
+
const { opsPath } = require('../opsOwnership.cjs');
|
|
11
|
+
|
|
12
|
+
const MAX_JS_BYTES = 300 * 1024;
|
|
13
|
+
const MAX_JSON_BYTES = 16 * 1024;
|
|
14
|
+
const COMMAND_TIMEOUT_MS = 120000;
|
|
15
|
+
|
|
16
|
+
/** -> null when `c` is a valid character.json object, else a reason string. */
|
|
17
|
+
function validateCharacterJson(c) {
|
|
18
|
+
if (!c || typeof c !== 'object' || Array.isArray(c)) return 'character.json must be an object';
|
|
19
|
+
if (typeof c.name !== 'string' || !c.name.trim()) return 'name must be a non-empty string';
|
|
20
|
+
if (!Array.isArray(c.palette) || c.palette.length === 0 || !c.palette.every((p) => typeof p === 'string' && p)) {
|
|
21
|
+
return 'palette must be a non-empty array of strings';
|
|
22
|
+
}
|
|
23
|
+
const v = c.voice;
|
|
24
|
+
if (!v || typeof v !== 'object') return 'voice is required';
|
|
25
|
+
if (v.engine === 'kokoro') {
|
|
26
|
+
if (typeof v.id !== 'string' || !v.id) return 'voice.id must be a non-empty string for engine kokoro';
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
if (v.engine === 'command') {
|
|
30
|
+
const cmd = v.command;
|
|
31
|
+
if (!Array.isArray(cmd) || cmd.length === 0 || !cmd.every((a) => typeof a === 'string')) {
|
|
32
|
+
return 'voice.command must be a non-empty string[]';
|
|
33
|
+
}
|
|
34
|
+
if (!cmd[0]) return 'voice.command[0] must be a program name';
|
|
35
|
+
if (!cmd.some((a) => a.includes('{text}'))) return 'voice.command must contain a {text} placeholder';
|
|
36
|
+
if (!cmd.some((a) => a.includes('{out}'))) return 'voice.command must contain an {out} placeholder';
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
return "voice.engine must be 'kokoro' or 'command'";
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** -> null when `js` is acceptable character.js source, else a reason. Needs the
|
|
43
|
+
* route's network checks, so they are injected (avoids a require cycle). */
|
|
44
|
+
function validateCharacterJs(js, networkChecks = []) {
|
|
45
|
+
if (typeof js !== 'string' || !js.trim()) return 'js must be a non-empty string';
|
|
46
|
+
if (Buffer.byteLength(js, 'utf8') > MAX_JS_BYTES) return `js exceeds the ${MAX_JS_BYTES}-byte limit`;
|
|
47
|
+
for (const { re, message } of networkChecks) {
|
|
48
|
+
if (re.test(js)) return `js must not be network-capable: ${message}`;
|
|
49
|
+
}
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function characterDir(projectRoot) {
|
|
54
|
+
return opsPath(projectRoot, 'project-pages', 'videos', '_character');
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** -> {json, js} | null (absent or invalid). */
|
|
58
|
+
function readCharacter(projectRoot) {
|
|
59
|
+
try {
|
|
60
|
+
const dir = characterDir(projectRoot);
|
|
61
|
+
const jsonRaw = fs.readFileSync(path.join(dir, 'character.json'), 'utf8');
|
|
62
|
+
if (Buffer.byteLength(jsonRaw, 'utf8') > MAX_JSON_BYTES) return null;
|
|
63
|
+
const json = JSON.parse(jsonRaw);
|
|
64
|
+
if (validateCharacterJson(json)) return null;
|
|
65
|
+
const js = fs.readFileSync(path.join(dir, 'character.js'), 'utf8');
|
|
66
|
+
if (!js.trim()) return null;
|
|
67
|
+
return { json, js };
|
|
68
|
+
} catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Substitute {text}/{out} into each argv element; the argv is never joined. */
|
|
74
|
+
function buildCommandArgv(voice, text, out) {
|
|
75
|
+
return voice.command.map((a) => a.split('{text}').join(text).split('{out}').join(out));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Run the voice command (no shell). -> {ok, status, error?} */
|
|
79
|
+
function speakWithCommand(voice, text, out) {
|
|
80
|
+
if (!voice || voice.engine !== 'command' || validateCharacterJson({ name: 'x', palette: ['x'], voice })) {
|
|
81
|
+
return { ok: false, status: null, error: 'not a valid command voice' };
|
|
82
|
+
}
|
|
83
|
+
const [bin, ...args] = buildCommandArgv(voice, String(text), String(out));
|
|
84
|
+
const r = spawnSync(bin, args, { shell: false, stdio: 'ignore', timeout: COMMAND_TIMEOUT_MS });
|
|
85
|
+
if (r.error) return { ok: false, status: r.status, error: r.error.message };
|
|
86
|
+
return { ok: r.status === 0, status: r.status, ...(r.status === 0 ? {} : { error: `exit ${r.status}` }) };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
module.exports = {
|
|
90
|
+
readCharacter,
|
|
91
|
+
speakWithCommand,
|
|
92
|
+
buildCommandArgv,
|
|
93
|
+
validateCharacterJson,
|
|
94
|
+
validateCharacterJs,
|
|
95
|
+
characterDir,
|
|
96
|
+
MAX_JS_BYTES,
|
|
97
|
+
};
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Pure, dependency-free analyzers a demo-video builder must pass before saving.
|
|
3
|
+
// Node builtins only: this folder is copied to ~/.claude/session-manager/demo-video-kit/.
|
|
4
|
+
// Each check returns {id, ok, detail}. CLI: node checks.cjs <input.json> -> JSON, exit 1 on failure.
|
|
5
|
+
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
|
|
8
|
+
const BANNED_WORDS = Object.freeze([
|
|
9
|
+
'MCP', 'API', 'SDK', 'CLI', 'repo', 'cron', 'pipeline', 'automation', 'npm', 'pnpm', 'deploy',
|
|
10
|
+
'backend', 'frontend', 'local-first', 'headless', 'leverage', 'utilize', 'seamless', 'robust',
|
|
11
|
+
'facilitate', 'sign up now', "don't miss", 'game-changer', 'revolutionary', 'unlock', 'level up',
|
|
12
|
+
'supercharge', 'best-in-class', 'world-class', 'cutting-edge', 'limited time', 'act now',
|
|
13
|
+
'buy now', 'skyrocket', 'must-have',
|
|
14
|
+
]);
|
|
15
|
+
|
|
16
|
+
const MAX_CAPTION_WORDS = 12;
|
|
17
|
+
const MAX_SENTENCE_WORDS = 14;
|
|
18
|
+
const MAX_GRADE = 8;
|
|
19
|
+
const VOICE_FIT_RATIO = 1.2;
|
|
20
|
+
const MIN_SPEECH_COVERAGE = 0.4;
|
|
21
|
+
const BLANK_AFTER_S = 0.5;
|
|
22
|
+
const DEFAULT_BLANK_STDDEV = 3;
|
|
23
|
+
const HTML_MB_PER_30S = 2 * 1024 * 1024;
|
|
24
|
+
|
|
25
|
+
const result = (id, ok, detail) => ({ id, ok: !!ok, detail });
|
|
26
|
+
const words = (s) => String(s || '').split(/\s+/).filter(Boolean);
|
|
27
|
+
const escRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
28
|
+
|
|
29
|
+
// Syllable heuristic: count vowel groups (aeiouy), drop a trailing silent "e"
|
|
30
|
+
// (but not "-le"), minimum 1 per word. Approximate, good enough for grade lint.
|
|
31
|
+
function countSyllables(word) {
|
|
32
|
+
let w = String(word).toLowerCase().replace(/[^a-z]/g, '');
|
|
33
|
+
if (!w) return 0;
|
|
34
|
+
if (w.length > 2 && /e$/.test(w) && !/[aeiouy]le$/.test(w) && !/[^aeiouy]le$/.test(w)) w = w.slice(0, -1);
|
|
35
|
+
const groups = w.match(/[aeiouy]+/g);
|
|
36
|
+
return Math.max(1, groups ? groups.length : 0);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function splitSentences(text) {
|
|
40
|
+
return String(text || '').split(/[.!?]+(?:\s+|$)|\n+/).map((s) => s.trim()).filter((s) => words(s).length);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function checkCaptions(captions) {
|
|
44
|
+
const list = Array.isArray(captions) ? captions : [];
|
|
45
|
+
const bad = list.map((c, i) => ({ i, n: words(c).length })).filter((x) => x.n > MAX_CAPTION_WORDS);
|
|
46
|
+
return result('captions', bad.length === 0,
|
|
47
|
+
bad.length ? `caption(s) over ${MAX_CAPTION_WORDS} words: ${bad.map((b) => `#${b.i + 1} (${b.n})`).join(', ')}`
|
|
48
|
+
: `${list.length} caption(s) within ${MAX_CAPTION_WORDS} words`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function findBanned(text) {
|
|
52
|
+
const t = String(text || '');
|
|
53
|
+
return BANNED_WORDS.filter((b) => new RegExp(`(?<![A-Za-z0-9])${escRe(b)}(?![A-Za-z0-9])`, 'i').test(t));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function lintLanguage(text) {
|
|
57
|
+
const t = Array.isArray(text) ? text.join('. ') : String(text || '');
|
|
58
|
+
const problems = [];
|
|
59
|
+
const sentences = splitSentences(t);
|
|
60
|
+
const ws = words(t);
|
|
61
|
+
const long = sentences.filter((s) => words(s).length > MAX_SENTENCE_WORDS);
|
|
62
|
+
if (long.length) problems.push(`${long.length} sentence(s) over ${MAX_SENTENCE_WORDS} words`);
|
|
63
|
+
let grade = 0;
|
|
64
|
+
if (ws.length && sentences.length) {
|
|
65
|
+
const syl = ws.reduce((n, w) => n + countSyllables(w), 0);
|
|
66
|
+
grade = 0.39 * (ws.length / sentences.length) + 11.8 * (syl / ws.length) - 15.59;
|
|
67
|
+
if (grade > MAX_GRADE) problems.push(`Flesch-Kincaid grade ${grade.toFixed(1)} > ${MAX_GRADE}`);
|
|
68
|
+
}
|
|
69
|
+
const banned = findBanned(t);
|
|
70
|
+
if (banned.length) problems.push(`banned: ${banned.join(', ')}`);
|
|
71
|
+
return result('language', problems.length === 0,
|
|
72
|
+
problems.length ? problems.join('; ') : `grade ${grade.toFixed(1)}, sentences <= ${MAX_SENTENCE_WORDS} words, no banned words`);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const SHELL_CMD = /(?<![A-Za-z0-9-])(npm|npx|pnpm|yarn|git|curl|wget|pip|pip3|brew|sudo|apt|docker)\s+[A-Za-z-]/i;
|
|
76
|
+
function checkClosing(closing) {
|
|
77
|
+
const t = String(closing || '');
|
|
78
|
+
const lead = /^\s*\$/.test(t) || /(^|\n)\s*\$\s/.test(t);
|
|
79
|
+
const m = t.match(SHELL_CMD);
|
|
80
|
+
const ok = !lead && !m;
|
|
81
|
+
return result('closing', ok, ok ? 'closing has no shell command' : `closing contains a shell command (${lead ? 'leading $' : m[0].trim()})`);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// lines: [{text?, speechS, sceneS}]
|
|
85
|
+
function checkVoiceFit(lines) {
|
|
86
|
+
const list = Array.isArray(lines) ? lines : [];
|
|
87
|
+
const bad = list.map((l, i) => ({ i, r: l.sceneS > 0 ? l.speechS / l.sceneS : Infinity }))
|
|
88
|
+
.filter((x) => x.r > VOICE_FIT_RATIO);
|
|
89
|
+
return result('voiceFit', bad.length === 0,
|
|
90
|
+
bad.length ? `line(s) need more than ${VOICE_FIT_RATIO}x scene time: ${bad.map((b) => `#${b.i + 1} (${b.r.toFixed(2)}x)`).join(', ')}`
|
|
91
|
+
: `${list.length} line(s) fit within ${VOICE_FIT_RATIO}x`);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function checkSpeechCoverage(speechS, lengthS) {
|
|
95
|
+
const total = Number(lengthS) || 0;
|
|
96
|
+
const ratio = total > 0 ? (Number(speechS) || 0) / total : 0;
|
|
97
|
+
return result('speechCoverage', ratio >= MIN_SPEECH_COVERAGE,
|
|
98
|
+
`speech covers ${(ratio * 100).toFixed(0)}% of ${total}s (min ${MIN_SPEECH_COVERAGE * 100}%)`);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// frames: [{t, lumaStddev}]; frames after 0.5 s whose stddev < threshold are blank.
|
|
102
|
+
function checkBlankFrames(frames, threshold = DEFAULT_BLANK_STDDEV) {
|
|
103
|
+
const list = Array.isArray(frames) ? frames : [];
|
|
104
|
+
const bad = list.filter((f) => f.t > BLANK_AFTER_S && f.lumaStddev < threshold);
|
|
105
|
+
return result('blankFrames', bad.length === 0,
|
|
106
|
+
bad.length ? `blank frame(s) at ${bad.map((f) => `${f.t}s`).join(', ')}` : `${list.length} frame(s) non-blank`);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function checkHtmlLimits({ html, bytes, lengthS } = {}) {
|
|
110
|
+
const h = String(html || '');
|
|
111
|
+
const size = Number.isFinite(bytes) ? bytes : Buffer.byteLength(h);
|
|
112
|
+
const cap = Math.ceil((Number(lengthS) || 0) / 30) * HTML_MB_PER_30S;
|
|
113
|
+
const problems = [];
|
|
114
|
+
if (size > cap) problems.push(`${size} bytes exceeds cap ${cap}`);
|
|
115
|
+
const dur = h.match(/<meta[^>]*name=["']sm-demo-duration["'][^>]*content=["']([^"']*)["']/i)
|
|
116
|
+
|| h.match(/<meta[^>]*content=["']([^"']*)["'][^>]*name=["']sm-demo-duration["']/i);
|
|
117
|
+
if (!dur) problems.push('sm-demo-duration meta missing');
|
|
118
|
+
else if (Number(dur[1]) !== Number(lengthS)) problems.push(`sm-demo-duration ${dur[1]} != ${lengthS}`);
|
|
119
|
+
if (!/window\.smDemo\s*=/.test(h) || !/scenes\s*:/.test(h)) problems.push('window.smDemo with scenes missing');
|
|
120
|
+
return result('htmlLimits', problems.length === 0, problems.length ? problems.join('; ') : `${size} bytes within cap ${cap}`);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// input: {captions, narration (string|string[]), closing, lines, speechS, lengthS, frames, blankThreshold, html, bytes}
|
|
124
|
+
function runChecks(input = {}) {
|
|
125
|
+
const out = [];
|
|
126
|
+
if (input.captions) out.push(checkCaptions(input.captions));
|
|
127
|
+
if (input.narration != null) out.push(lintLanguage(input.narration));
|
|
128
|
+
if (input.closing != null) out.push(checkClosing(input.closing));
|
|
129
|
+
if (input.lines) out.push(checkVoiceFit(input.lines));
|
|
130
|
+
if (input.speechS != null) out.push(checkSpeechCoverage(input.speechS, input.lengthS));
|
|
131
|
+
if (input.frames) out.push(checkBlankFrames(input.frames, input.blankThreshold));
|
|
132
|
+
if (input.html != null) out.push(checkHtmlLimits({ html: input.html, bytes: input.bytes, lengthS: input.lengthS }));
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
module.exports = {
|
|
137
|
+
BANNED_WORDS, countSyllables, checkCaptions, lintLanguage, checkClosing, checkVoiceFit,
|
|
138
|
+
checkSpeechCoverage, checkBlankFrames, checkHtmlLimits, runChecks,
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
if (require.main === module) {
|
|
142
|
+
try {
|
|
143
|
+
const report = runChecks(JSON.parse(fs.readFileSync(process.argv[2], 'utf8')));
|
|
144
|
+
process.stdout.write(JSON.stringify(report, null, 2) + '\n');
|
|
145
|
+
process.exit(report.some((c) => !c.ok) ? 1 : 0);
|
|
146
|
+
} catch (e) {
|
|
147
|
+
process.stderr.write(`checks: ${e.message}\n`);
|
|
148
|
+
process.exit(2);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Demo-video kit frame sampler: open a finished video document in headless Chromium, seek
|
|
3
|
+
// window.smDemo every stepS seconds, compute per-frame luma stats (input for checkBlankFrames)
|
|
4
|
+
// and write a contact sheet PNG for the persona to review. Playwright is resolved at runtime
|
|
5
|
+
// (same resolution as capture.cjs) and never installed here. Node builtins only.
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
const path = require('path');
|
|
8
|
+
const zlib = require('zlib');
|
|
9
|
+
const { spawnSync } = require('child_process');
|
|
10
|
+
const { pathToFileURL } = require('url');
|
|
11
|
+
|
|
12
|
+
const MAX_FRAMES = 120;
|
|
13
|
+
const VIEWPORT = { width: 1280, height: 720 };
|
|
14
|
+
const TILE_W = 160;
|
|
15
|
+
const SHEET_COLS = 8;
|
|
16
|
+
const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
|
17
|
+
|
|
18
|
+
function tryRequire(name, paths) {
|
|
19
|
+
try { return require(require.resolve(name, { paths })); } catch { return null; }
|
|
20
|
+
}
|
|
21
|
+
function globalNpmRoot() {
|
|
22
|
+
try {
|
|
23
|
+
const r = spawnSync('npm', ['root', '-g'], { encoding: 'utf8', timeout: 15000 });
|
|
24
|
+
return r.status === 0 ? String(r.stdout).trim() : '';
|
|
25
|
+
} catch { return ''; }
|
|
26
|
+
}
|
|
27
|
+
/** Same resolution as capture.cjs: process.cwd() first, then the global npm root. */
|
|
28
|
+
function defaultLoader() {
|
|
29
|
+
for (const name of ['playwright', 'playwright-core']) {
|
|
30
|
+
const m = tryRequire(name, [process.cwd()]);
|
|
31
|
+
if (m) return m;
|
|
32
|
+
}
|
|
33
|
+
const root = globalNpmRoot();
|
|
34
|
+
if (root) {
|
|
35
|
+
for (const name of ['playwright', 'playwright-core']) {
|
|
36
|
+
const m = tryRequire(name, [root]);
|
|
37
|
+
if (m) return m;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// ---- minimal PNG codec -------------------------------------------------------------------
|
|
44
|
+
const CHANNELS = { 0: 1, 2: 3, 4: 2, 6: 4 };
|
|
45
|
+
|
|
46
|
+
/** Decode a non-interlaced 8-bit PNG (gray, RGB, gray+alpha, RGBA) -> {width, height, channels, data}. */
|
|
47
|
+
function decodePng(buf) {
|
|
48
|
+
if (!Buffer.isBuffer(buf) || buf.length < 8 || !buf.subarray(0, 8).equals(PNG_SIG)) throw new Error('not a PNG');
|
|
49
|
+
let pos = 8; let ihdr = null; const idat = [];
|
|
50
|
+
while (pos + 8 <= buf.length) {
|
|
51
|
+
const len = buf.readUInt32BE(pos);
|
|
52
|
+
const type = buf.toString('latin1', pos + 4, pos + 8);
|
|
53
|
+
const body = buf.subarray(pos + 8, pos + 8 + len);
|
|
54
|
+
if (type === 'IHDR') ihdr = body;
|
|
55
|
+
else if (type === 'IDAT') idat.push(body);
|
|
56
|
+
else if (type === 'IEND') break;
|
|
57
|
+
pos += 12 + len;
|
|
58
|
+
}
|
|
59
|
+
if (!ihdr) throw new Error('PNG missing IHDR');
|
|
60
|
+
const width = ihdr.readUInt32BE(0); const height = ihdr.readUInt32BE(4);
|
|
61
|
+
const depth = ihdr[8]; const ctype = ihdr[9]; const interlace = ihdr[12];
|
|
62
|
+
if (depth !== 8 || !CHANNELS[ctype] || interlace !== 0) throw new Error(`unsupported PNG (depth ${depth}, type ${ctype}, interlace ${interlace})`);
|
|
63
|
+
const ch = CHANNELS[ctype];
|
|
64
|
+
const raw = zlib.inflateSync(Buffer.concat(idat));
|
|
65
|
+
const stride = width * ch;
|
|
66
|
+
if (raw.length < (stride + 1) * height) throw new Error('PNG data truncated');
|
|
67
|
+
const out = Buffer.alloc(stride * height);
|
|
68
|
+
for (let y = 0; y < height; y++) {
|
|
69
|
+
const f = raw[y * (stride + 1)];
|
|
70
|
+
const src = y * (stride + 1) + 1; const dst = y * stride;
|
|
71
|
+
for (let i = 0; i < stride; i++) {
|
|
72
|
+
const x = raw[src + i];
|
|
73
|
+
const a = i >= ch ? out[dst + i - ch] : 0;
|
|
74
|
+
const b = y > 0 ? out[dst - stride + i] : 0;
|
|
75
|
+
const c = i >= ch && y > 0 ? out[dst - stride + i - ch] : 0;
|
|
76
|
+
let v;
|
|
77
|
+
if (f === 0) v = x;
|
|
78
|
+
else if (f === 1) v = x + a;
|
|
79
|
+
else if (f === 2) v = x + b;
|
|
80
|
+
else if (f === 3) v = x + ((a + b) >> 1);
|
|
81
|
+
else if (f === 4) {
|
|
82
|
+
const p = a + b - c; const pa = Math.abs(p - a); const pb = Math.abs(p - b); const pc = Math.abs(p - c);
|
|
83
|
+
v = x + (pa <= pb && pa <= pc ? a : pb <= pc ? b : c);
|
|
84
|
+
} else throw new Error(`bad PNG filter ${f}`);
|
|
85
|
+
out[dst + i] = v & 255;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return { width, height, channels: ch, data: out };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
let crcTable = null;
|
|
92
|
+
function crc32(buf) {
|
|
93
|
+
if (!crcTable) {
|
|
94
|
+
crcTable = new Int32Array(256);
|
|
95
|
+
for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; crcTable[n] = c; }
|
|
96
|
+
}
|
|
97
|
+
let c = -1;
|
|
98
|
+
for (let i = 0; i < buf.length; i++) c = crcTable[(c ^ buf[i]) & 255] ^ (c >>> 8);
|
|
99
|
+
return (c ^ -1) >>> 0;
|
|
100
|
+
}
|
|
101
|
+
function chunk(type, body) {
|
|
102
|
+
const t = Buffer.from(type, 'latin1');
|
|
103
|
+
const len = Buffer.alloc(4); len.writeUInt32BE(body.length);
|
|
104
|
+
const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(Buffer.concat([t, body])));
|
|
105
|
+
return Buffer.concat([len, t, body, crc]);
|
|
106
|
+
}
|
|
107
|
+
/** Encode 8-bit RGB pixels (width*height*3) as a PNG. */
|
|
108
|
+
function encodePng(width, height, rgb) {
|
|
109
|
+
const stride = width * 3;
|
|
110
|
+
const raw = Buffer.alloc((stride + 1) * height);
|
|
111
|
+
for (let y = 0; y < height; y++) rgb.copy(raw, y * (stride + 1) + 1, y * stride, (y + 1) * stride);
|
|
112
|
+
const ihdr = Buffer.alloc(13);
|
|
113
|
+
ihdr.writeUInt32BE(width, 0); ihdr.writeUInt32BE(height, 4); ihdr[8] = 8; ihdr[9] = 2;
|
|
114
|
+
return Buffer.concat([PNG_SIG, chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Rec.601 luma of every pixel (alpha ignored) -> {mean, stdDev}. */
|
|
118
|
+
function lumaStats(img) {
|
|
119
|
+
const { width, height, channels: ch, data } = img;
|
|
120
|
+
const n = width * height;
|
|
121
|
+
if (!n) return { mean: 0, stdDev: 0 };
|
|
122
|
+
let sum = 0; let sumSq = 0;
|
|
123
|
+
for (let p = 0; p < n; p++) {
|
|
124
|
+
const o = p * ch;
|
|
125
|
+
const l = ch >= 3 ? 0.299 * data[o] + 0.587 * data[o + 1] + 0.114 * data[o + 2] : data[o];
|
|
126
|
+
sum += l; sumSq += l * l;
|
|
127
|
+
}
|
|
128
|
+
const mean = sum / n;
|
|
129
|
+
return { mean, stdDev: Math.sqrt(Math.max(0, sumSq / n - mean * mean)) };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function toRgb(img, x, y) {
|
|
133
|
+
const o = (y * img.width + x) * img.channels;
|
|
134
|
+
return img.channels >= 3 ? [img.data[o], img.data[o + 1], img.data[o + 2]] : [img.data[o], img.data[o], img.data[o]];
|
|
135
|
+
}
|
|
136
|
+
/** Nearest-neighbour tile grid of decoded images -> PNG buffer. */
|
|
137
|
+
function buildContactSheet(images) {
|
|
138
|
+
const cols = Math.max(1, Math.min(SHEET_COLS, images.length));
|
|
139
|
+
const rows = Math.max(1, Math.ceil(images.length / cols));
|
|
140
|
+
const first = images[0];
|
|
141
|
+
const tileH = first ? Math.max(1, Math.round(TILE_W * first.height / first.width)) : Math.round(TILE_W * 9 / 16);
|
|
142
|
+
const W = cols * TILE_W; const H = rows * tileH;
|
|
143
|
+
const out = Buffer.alloc(W * H * 3);
|
|
144
|
+
images.forEach((img, i) => {
|
|
145
|
+
const ox = (i % cols) * TILE_W; const oy = Math.floor(i / cols) * tileH;
|
|
146
|
+
for (let y = 0; y < tileH; y++) {
|
|
147
|
+
const sy = Math.min(img.height - 1, Math.floor(y * img.height / tileH));
|
|
148
|
+
for (let x = 0; x < TILE_W; x++) {
|
|
149
|
+
const [r, g, b] = toRgb(img, Math.min(img.width - 1, Math.floor(x * img.width / TILE_W)), sy);
|
|
150
|
+
const o = ((oy + y) * W + ox + x) * 3;
|
|
151
|
+
out[o] = r; out[o + 1] = g; out[o + 2] = b;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
return encodePng(W, H, out);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Seek the video document every stepS seconds and report per-frame luma spread.
|
|
160
|
+
* Returns {frames:[{t, lumaStdDev, lumaStddev}], contactSheet} | {skipped} | {error}.
|
|
161
|
+
* `lumaStddev` mirrors `lumaStdDev` because checkBlankFrames reads that spelling.
|
|
162
|
+
*/
|
|
163
|
+
async function sampleFrames({ htmlPath, lengthS, stepS = 0.5, outDir, loadPlaywright } = {}) {
|
|
164
|
+
const length = Number(lengthS); const step = Number(stepS);
|
|
165
|
+
if (!htmlPath || !outDir || !(length > 0) || !(step > 0)) return { error: 'htmlPath, outDir, lengthS > 0 and stepS > 0 are required' };
|
|
166
|
+
const count = Math.floor(length / step + 1e-9) + 1;
|
|
167
|
+
if (count > MAX_FRAMES) return { error: `refused: ${count} frames exceeds the ${MAX_FRAMES} frame cap` };
|
|
168
|
+
const pw = (loadPlaywright || defaultLoader)();
|
|
169
|
+
const resolved = pw && typeof pw.then === 'function' ? await pw : pw;
|
|
170
|
+
const chromium = resolved && resolved.chromium;
|
|
171
|
+
if (!chromium) return { skipped: 'no-playwright' };
|
|
172
|
+
|
|
173
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
174
|
+
const frames = []; const images = [];
|
|
175
|
+
let browser;
|
|
176
|
+
try { browser = await chromium.launch({ headless: true }); } catch { return { skipped: 'no-playwright' }; } // package without a browser binary
|
|
177
|
+
try {
|
|
178
|
+
const page = await browser.newPage({ viewport: VIEWPORT });
|
|
179
|
+
page.setDefaultTimeout(30000);
|
|
180
|
+
await page.goto(pathToFileURL(path.resolve(htmlPath)).href, { timeout: 30000, waitUntil: 'load' });
|
|
181
|
+
await page.evaluate(() => { const d = window.smDemo; if (d && typeof d.pause === 'function') d.pause(); });
|
|
182
|
+
for (let i = 0; i < count; i++) {
|
|
183
|
+
const t = Math.round(i * step * 1000) / 1000;
|
|
184
|
+
await page.evaluate((s) => { const d = window.smDemo; if (d && typeof d.seek === 'function') d.seek(s); }, t);
|
|
185
|
+
await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
|
|
186
|
+
const img = decodePng(await page.screenshot({ type: 'png' }));
|
|
187
|
+
const { stdDev } = lumaStats(img);
|
|
188
|
+
const v = Math.round(stdDev * 100) / 100;
|
|
189
|
+
frames.push({ t, lumaStdDev: v, lumaStddev: v });
|
|
190
|
+
images.push(img);
|
|
191
|
+
}
|
|
192
|
+
} finally {
|
|
193
|
+
await browser.close();
|
|
194
|
+
}
|
|
195
|
+
const contactSheet = path.join(outDir, 'contact-sheet.png');
|
|
196
|
+
fs.writeFileSync(contactSheet, buildContactSheet(images));
|
|
197
|
+
return { frames, contactSheet };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
module.exports = { MAX_FRAMES, sampleFrames, decodePng, encodePng, lumaStats, buildContactSheet };
|