Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
support direction quotas for variant slates
rponea1c911fa1c71
diff --git a/.agents/skills/hypit/references/variant-expansion/route.md b/.agents/skills/hypit/references/variant-expansion/route.mdindex b42f4870..921a365f 100644--- a/.agents/skills/hypit/references/variant-expansion/route.md+++ b/.agents/skills/hypit/references/variant-expansion/route.md@@ -88,19 +88,34 @@ caption/overlay behavior, audio relationship and what must remain invariant. Che## 3. Draft the Slate-Write `slate.json` with exactly N distinct, decision-complete entries. Each entry must provide at-least:+Write `slate.json` as a set of distinct direction quotas. Do not hand-write N full briefs when the+request asks for a large batch. The quotas must add up to exactly N, and each direction provides the+shared brief and allowed scope inherited by its concrete variants:```json{- "slug": "short-unique-slug",- "brief": { "direction": "the complete variant decision" },- "component_class": "svml-only",- "allowed_changes": ["main.svml"],- "vocabulary": { "mode": "inherited", "packages": [] }+ "count": 100,+ "directions": [+ {+ "id": "ranking-host",+ "slug": "ranking-host",+ "count": 20,+ "brief": { "direction": "vary the host-led ranking presentation" },+ "component_class": "svml-only",+ "allowed_changes": ["main.svml"],+ "vocabulary": { "mode": "inherited", "packages": [] }+ }+ ]}```+The main agent chooses the directions from the examples and divides the requested count among them.+`variant_init` expands each direction deterministically into numbered concrete variants (for example,+`ranking-host-01` through `ranking-host-20`) and persists each generated brief in that child's+`.hypit/variant-brief.json`. A child may make its concrete creative choice within the direction, but+must keep the inherited scope and its unique direction/ordinal identity. The older expanded+`variants` form remains readable for already-created batches.+`component_class` is one of `svml-only`, `existing-component`, `composed-components` or`new-package`. Use `vocabulary.mode: "inspect"` and list the assigned packages whenever a variantswitches to a package the base did not use. A validated staging package can be injected once copied:diff --git a/docs/guide/skill.md b/docs/guide/skill.mdindex 30362310..c420b5e4 100644--- a/docs/guide/skill.md+++ b/docs/guide/skill.md@@ -316,7 +316,7 @@ Tools and outputs are:1. `variant_state start` records the base, count, request and delivery mode.2. `brief-intake.md`, examples and playbooks produce `format-plan.json`.-3. The main agent writes exactly N distinct entries in `slate.json`, each with an allowed file scope.+3. The main agent writes distinct direction quotas in `slate.json`; their counts add up to N. Each direction carries a shared brief and allowed file scope. `variant_init` expands the quotas into numbered concrete variants when dispatching, so a 100-item batch does not require 100 hand-written briefs.4. `list_svml_packages` and `inspect_svml_vocabulary` produce global vocabulary evidence and`component-plan.json`.5. The workload disclosure tells the author how many variants are SVML-only, medium-scope or require@@ -342,7 +342,7 @@ The batch is intentionally “copy first, then edit”:| Step | Main agent or child work | Tool or document | Durable result and reason ||---|---|---|---|| 1. Validate base | Confirm the parent creation/revision final gate and record its digest. | `route_state/revision_state reconcile`, `variant_state start` | Every child starts from the same known-good Film graph. |-| 2. Decide the slate | Inspect examples, choose each format/Format DNA, draft exactly N distinct briefs and allowed scopes. | `brief-intake.md`, `playbooks/index.md`, `format-plan.json`, `slate.json` | Creative direction is decided once globally; children do not invent incompatible formats. |+| 2. Decide the slate | Inspect examples, choose the expansion directions and quotas whose total is N, and freeze each direction's Format DNA and allowed scope. | `brief-intake.md`, `playbooks/index.md`, `format-plan.json`, `slate.json` | Creative directions are decided once globally; dispatch expands each quota into a unique numbered child brief. || 3. Decide vocabulary/workload | Inspect packages and public vocabulary, choose reuse/composition/new package, then disclose fast/medium/new-package counts. | `list_svml_packages`, `inspect_svml_vocabulary`, `component-plan.json`, `variant_state checkpoint` | The author knows the cost/time impact before agents start; no child discovers a package gap halfway through. || 4. Stage new packages | Develop each distinct local package once, validate it in staging, freeze its digest and mark it ready. | `route_state --route variant-package`, `local-author-package.md`, `validate_local_author_packages`, `preview_check`, `layout_check` | Shared package work is reused safely and cannot mutate installed packages. || 5. Copy the base | Clone the project with copy-on-write where possible, retain authored assets/source, remove generated state/results and old Build bindings, inject only ready packages. | `variant_init` | Each child is independent, reproducible and free of stale paid/generated artifacts. |diff --git a/docs/zh/guide/skill.md b/docs/zh/guide/skill.mdindex b641d151..a1c7848c 100644--- a/docs/zh/guide/skill.md+++ b/docs/zh/guide/skill.md@@ -280,7 +280,7 @@ baseline-validated → examples-inspected → format-plan-frozen → slate-draft1. `variant_state start` 记录母项目、数量、请求和交付模式。2. `brief-intake.md`、examples 和 playbooks 生成 `format-plan.json`。-3. 主 agent 在 `slate.json` 中写出正好 N 个不重复条目,每个条目声明允许修改的文件范围。+3. 主 agent 在 `slate.json` 中写出若干个不重复的变体方向和数量配额,所有配额之和正好为 N;每个方向声明共享 brief 和允许修改的文件范围。`variant_init` 在派发时再确定性展开成带编号的具体变体,因此 100 个变体不需要主 agent 手写 100 个 brief。4. `list_svml_packages` 与 `inspect_svml_vocabulary` 形成全局词汇证据和 `component-plan.json`。5. 工作量披露快速(只改 SVML)、中等(改 SVS/Run 或切换组件)和新包任务;每种新包只在 staging 开发一次,并以 digest 冻结。6. `variant_init` 先复制母项目,保留作者资产和 Source,排除生成状态/结果,只注入已就绪的包,并建立每个子项目的 route state。@@ -300,7 +300,7 @@ baseline-copied → brief-frozen → change-scope-frozen → guidance-loaded| 步骤 | 主 agent 或子 agent 的工作 | 工具或文档 | 持久化结果与作用 ||---|---|---|---|| 1. 验证母项目 | 确认父路线/Revision 已通过最终门禁并记录 digest。 | `route_state/revision_state reconcile`、`variant_state start` | 所有子项目从同一个已知良好的 Film graph 出发。 |-| 2. 决定 Slate | 检查 examples,决定每个变体的格式/Format DNA,写出正好 N 个 brief 和允许范围。 | `brief-intake.md`、`playbooks/index.md`、`format-plan.json`、`slate.json` | 创意方向一次全局决定,子 agent 不会临时发明互不兼容的格式。 |+| 2. 决定 Slate | 检查 examples,决定变体方向及数量配额(总和为 N),冻结每个方向的 Format DNA 和允许范围。 | `brief-intake.md`、`playbooks/index.md`、`format-plan.json`、`slate.json` | 创意方向一次全局决定;派发时按方向配额展开唯一编号的子项目。 || 3. 决定词汇和工作量 | 检查包与公开词汇,决定复用/组合/新包,并披露快速、中等、新包数量。 | `list_svml_packages`、`inspect_svml_vocabulary`、`component-plan.json`、`variant_state checkpoint` | 子 agent 启动前用户就知道时间和成本影响,不会做到一半才发现缺包。 || 4. 预先开发新包 | 每个不同缺口只开发一次,在 staging 验证、冻结 digest、标记 ready。 | `route_state --route variant-package`、`local-author-package.md`、`validate_local_author_packages`、`preview_check`、`layout_check` | 多个变体安全复用同一个包,且不会修改安装包。 || 5. 先复制母项目 | 尽可能 copy-on-write,保留作者资产和 Source,删除生成状态/结果和旧 Build 绑定,只注入已 ready 的包。 | `variant_init` | 每个子项目独立、可复现,没有过期的付费产物或生成结果。 |diff --git a/packages/reference-video-tools/src/index.ts b/packages/reference-video-tools/src/index.tsindex dbbbf810..831a1c4b 100644--- a/packages/reference-video-tools/src/index.ts+++ b/packages/reference-video-tools/src/index.ts@@ -69,4 +69,5 @@ export {removeGeneratedRunBindings,snapshotProject,} from "./variant-project.js";-export type { ApprovedVariantPackage, InitializedVariant, SlatePackageInjection, SlateVariant, VariantProjectManifest, VariantSlate } from "./variant-project.js";+export type { ApprovedVariantPackage, InitializedVariant, SlateDirection, SlatePackageInjection, SlateVariant, VariantProjectManifest, VariantSlate } from "./variant-project.js";+export { expandVariantSlate } from "./variant-project.js";diff --git a/packages/reference-video-tools/src/tools.ts b/packages/reference-video-tools/src/tools.tsindex e3a6c854..37a479de 100644--- a/packages/reference-video-tools/src/tools.ts+++ b/packages/reference-video-tools/src/tools.ts@@ -2689,9 +2689,22 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVcatch (error) { throw new Error(`cannot read ${key} at ${path}: ${error instanceof Error ? error.message : String(error)}`); }};const [formatPlan, componentPlan] = await Promise.all([readPlan("format_plan"), readPlan("component_plan")]);- const selectedPlan = (plan: unknown, id: string): unknown => {+ const selectedPlan = async (plan: unknown, item: { readonly id: string; readonly brief: string }): Promise<unknown> => {if (plan !== null && typeof plan === "object" && Array.isArray((plan as { variants?: unknown }).variants)) {- const entry = ((plan as { variants: unknown[] }).variants).find((candidate) => candidate !== null && typeof candidate === "object" && (candidate as { id?: unknown }).id === id);+ const entry = ((plan as { variants: unknown[] }).variants).find((candidate) => candidate !== null && typeof candidate === "object" && (candidate as { id?: unknown }).id === item.id);+ if (entry !== undefined) return entry;+ }+ let directionId: string | undefined;+ try {+ const brief = JSON.parse(await readFile(item.brief, "utf8")) as {+ direction_id?: unknown;+ brief?: { direction_id?: unknown };+ };+ const value = brief.direction_id ?? brief.brief?.direction_id;+ directionId = typeof value === "string" ? value : undefined;+ } catch { directionId = undefined; }+ if (directionId !== undefined && plan !== null && typeof plan === "object" && Array.isArray((plan as { directions?: unknown }).directions)) {+ const entry = ((plan as { directions: unknown[] }).directions).find((candidate) => candidate !== null && typeof candidate === "object" && (candidate as { id?: unknown }).id === directionId);if (entry !== undefined) return entry;}return plan;@@ -2700,8 +2713,8 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceVfor (const item of initialized.variants) {const formatPlanPath = join(item.project_root, ".hypit", "format-plan.json");const componentPlanPath = join(item.project_root, ".hypit", "component-plan.json");- await writeVariantJson(formatPlanPath, { variant_id: item.id, source: batch.artifacts.format_plan, plan: selectedPlan(formatPlan, item.id) });- await writeVariantJson(componentPlanPath, { variant_id: item.id, source: batch.artifacts.component_plan, plan: selectedPlan(componentPlan, item.id) });+ await writeVariantJson(formatPlanPath, { variant_id: item.id, source: batch.artifacts.format_plan, plan: await selectedPlan(formatPlan, item) });+ await writeVariantJson(componentPlanPath, { variant_id: item.id, source: batch.artifacts.component_plan, plan: await selectedPlan(componentPlan, item) });await startRouteState({ projectRoot: item.project_root, route: "variant", run: item.run });await checkpointRouteState({ projectRoot: item.project_root, route: "variant", step: 1, status: "complete", artifacts: { baseline_manifest: item.manifest } });await checkpointRouteState({ projectRoot: item.project_root, route: "variant", step: 2, status: "complete", artifacts: { variant_brief: item.brief } });diff --git a/packages/reference-video-tools/src/variant-project.ts b/packages/reference-video-tools/src/variant-project.tsindex c6500654..ed3dac7b 100644--- a/packages/reference-video-tools/src/variant-project.ts+++ b/packages/reference-video-tools/src/variant-project.ts@@ -46,7 +46,19 @@ export type SlateVariant = {readonly inject_packages?: readonly SlatePackageInjection[];readonly [key: string]: unknown;};-export type VariantSlate = { readonly variants: readonly SlateVariant[]; readonly [key: string]: unknown };+export type SlateDirection = Omit<SlateVariant, "id" | "slug"> & {+ readonly id: string;+ readonly slug: string;+ readonly count: number;+};+/** The authored slate contains direction quotas; concrete variants are expanded at dispatch time. */+export type VariantSlate = {+ readonly count?: number;+ readonly directions?: readonly SlateDirection[];+ /** Legacy expanded form remains readable for already-created batches. */+ readonly variants?: readonly SlateVariant[];+ readonly [key: string]: unknown;+};export type InitializedVariant = {readonly id: string;@@ -206,9 +218,7 @@ function safeSlug(value: string): string {return slug.slice(0, 64);}-function assertSlate(value: unknown, path: string): asserts value is VariantSlate {- if (value === null || typeof value !== "object" || !Array.isArray((value as { variants?: unknown }).variants)) throw new Error(`${path} must contain a variants array`);- const variants = (value as { variants: unknown[] }).variants;+function validateVariantEntries(variants: readonly unknown[], path: string): asserts variants is readonly SlateVariant[] {if (variants.length === 0) throw new Error(`${path} must contain at least one variant`);const slugs = new Set<string>();const ids = new Set<string>();@@ -280,6 +290,61 @@ function assertSlate(value: unknown, path: string): asserts value is VariantSlat}}+function assertSlate(value: unknown, path: string): asserts value is VariantSlate {+ if (value === null || typeof value !== "object") throw new Error(`${path} must contain directions`);+ const slate = value as VariantSlate;+ if (slate.count !== undefined && (!Number.isSafeInteger(slate.count) || slate.count <= 0)) {+ throw new Error(`${path} count must be a positive integer`);+ }+ if (Array.isArray(slate.directions)) {+ if (slate.directions.length === 0) throw new Error(`${path} must contain at least one direction`);+ let total = 0;+ const ids = new Set<string>();+ const slugs = new Set<string>();+ for (const [index, direction] of slate.directions.entries()) {+ if (direction === null || typeof direction !== "object") throw new Error(`${path} directions[${index}] must be an object`);+ if (typeof direction.id !== "string" || direction.id.trim().length === 0) throw new Error(`${path} directions[${index}] has no id`);+ if (typeof direction.slug !== "string" || direction.slug.trim().length === 0) throw new Error(`${path} directions[${index}] has no slug`);+ if (!Number.isSafeInteger(direction.count) || direction.count <= 0) throw new Error(`${path} directions[${index}] count must be a positive integer`);+ const slug = safeSlug(direction.slug);+ if (ids.has(direction.id.trim())) throw new Error(`${path} repeats direction id ${direction.id.trim()}`);+ if (slugs.has(slug)) throw new Error(`${path} repeats direction slug ${slug}`);+ ids.add(direction.id.trim()); slugs.add(slug); total += direction.count;+ validateVariantEntries([{ ...direction, id: `${direction.id}-1`, slug: `${direction.slug}-1` }], `${path} directions[${index}]`);+ }+ if (slate.count !== undefined && slate.count !== total) throw new Error(`${path} count ${slate.count} does not equal direction quotas ${total}`);+ return;+ }+ if (Array.isArray(slate.variants)) {+ validateVariantEntries(slate.variants, path);+ return;+ }+ throw new Error(`${path} must contain directions`);+}++export function expandVariantSlate(slate: VariantSlate, path = "slate.json"): readonly SlateVariant[] {+ assertSlate(slate, path);+ if (slate.directions === undefined) return slate.variants!;+ const total = slate.directions.reduce((sum, direction) => sum + direction.count, 0);+ const variants: SlateVariant[] = [];+ for (const direction of slate.directions) {+ const directionId = direction.id.trim();+ const directionSlug = safeSlug(direction.slug);+ for (let ordinal = 1; ordinal <= direction.count; ordinal += 1) {+ const suffix = String(ordinal).padStart(Math.max(2, String(direction.count).length), "0");+ const { count: _count, id: _directionId, slug: _directionSlug, ...template } = direction;+ const brief = direction.brief !== undefined && direction.brief !== null && typeof direction.brief === "object"+ ? { ...(direction.brief as Record<string, unknown>), direction_id: directionId, direction_index: ordinal }+ : { direction: direction.brief ?? directionId, direction_id: directionId, direction_index: ordinal };+ variants.push({ ...template, id: `${directionId}-${suffix}`, slug: `${directionSlug}-${suffix}`, brief } as SlateVariant);+ }+ }+ const slugs = new Set(variants.map((variant) => safeSlug(variant.slug)));+ if (slugs.size !== variants.length) throw new Error(`${path} direction quotas expand to duplicate variant slugs`);+ if (slate.count !== undefined && slate.count !== variants.length) throw new Error(`${path} count ${slate.count} does not equal expanded variants ${variants.length}`);+ return variants;+}+export async function writeVariantJson(path: string, value: unknown): Promise<void> {await mkdir(dirname(path), { recursive: true });const temporary = `${path}.tmp-${process.pid}-${Date.now()}`;@@ -365,11 +430,12 @@ export async function initializeVariantProjects(input: {catch (error) { throw new Error(`cannot read slate ${slatePath}: ${error instanceof Error ? error.message : String(error)}`); }assertSlate(slateValue, slatePath);const slate = slateValue;- if (input.expectedCount !== undefined && slate.variants.length !== input.expectedCount) {- throw new Error(`slate has ${slate.variants.length} variants, expected ${input.expectedCount}`);+ const variantsInSlate = expandVariantSlate(slate, slatePath);+ if (input.expectedCount !== undefined && variantsInSlate.length !== input.expectedCount) {+ throw new Error(`slate expands to ${variantsInSlate.length} variants, expected ${input.expectedCount}`);}const approvedPackages = new Map((input.approvedPackages ?? []).map((pack) => [pack.id, pack]));- for (const variant of slate.variants) {+ for (const variant of variantsInSlate) {for (const injection of variant.inject_packages ?? []) {if (!approvedPackages.has(injection.package_id)) throw new Error(`slate references package ${injection.package_id}, which is not ready and frozen in batch state`);}@@ -379,7 +445,7 @@ export async function initializeVariantProjects(input: {throw new Error(`base project digest changed: expected ${input.expectedBaseDigest}, found ${base.digest}`);}await mkdir(outputRoot, { recursive: true });- const width = Math.max(3, String(slate.variants.length).length);+ const width = Math.max(3, String(variantsInSlate.length).length);const currentRoute = await readFile(join(projectRoot, ".hypit", "route-state.json"), "utf8").then((text) => JSON.parse(text) as { artifacts?: { vocabulary?: unknown } }, () => undefined).catch(() => undefined);@@ -388,7 +454,7 @@ export async function initializeVariantProjects(input: {: join(projectRoot, ".hypit", "vocabulary.json");const initialized: InitializedVariant[] = [];const assignedIds = new Set<string>();- for (const [index, variant] of slate.variants.entries()) {+ for (const [index, variant] of variantsInSlate.entries()) {const number = String(index + 1).padStart(width, "0");const slug = safeSlug(variant.slug);const id = typeof variant.id === "string" && variant.id.trim().length > 0 ? variant.id.trim() : number;diff --git a/packages/reference-video-tools/src/variant-state.ts b/packages/reference-video-tools/src/variant-state.tsindex a88461ed..6909e6a5 100644--- a/packages/reference-video-tools/src/variant-state.ts+++ b/packages/reference-video-tools/src/variant-state.ts@@ -5,7 +5,8 @@ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "nodimport { checkpointRouteState, readRouteState, reconcileRouteState, routeExecutionStatePath, routeStatePath } from "./route-state.js";import { readRevisionState, revisionExecutionStatePath } from "./revision-state.js";import { persistEvidence } from "./state-files.js";-import { inspectVariantDiff, snapshotProject } from "./variant-project.js";+import { expandVariantSlate, inspectVariantDiff, snapshotProject } from "./variant-project.js";+import type { VariantSlate } from "./variant-project.js";export type VariantExpansionStatus = "active" | "complete" | "blocked";export type VariantExpansionStep =@@ -503,16 +504,19 @@ async function reconcileVariantExpansionUnlocked(projectRoot: string, outputRoot|| (await readRouteState(existing.project_root))?.status === "complete"],[2, async () => await validJson(artifact("examples"))],[3, async () => await validJson(artifact("format_plan"))],- [4, async () => await validJson(artifact("slate"), (value) => Array.isArray((value as { variants?: unknown })?.variants))],+ [4, async () => await validJson(artifact("slate"), (value) => {+ try { return expandVariantSlate(value as VariantSlate, artifact("slate") ?? "slate.json").length > 0; } catch { return false; }+ })],[5, async () => await validJson(artifact("vocabulary"), (value) => Array.isArray((value as { packages?: unknown })?.packages) || Array.isArray((value as { surfaces?: unknown })?.surfaces))],[6, async () => await validJson(artifact("component_plan"))],[7, async () => await validJson(artifact("package_gaps"))],[9, async () => {const slatePath = artifact("slate");if (slatePath === undefined) return false;- let slate: { variants?: readonly { component_class?: unknown; inject_packages?: readonly { package_id?: unknown }[] }[] };+ let slate: VariantSlate;try { slate = JSON.parse(await readFile(slatePath, "utf8")) as typeof slate; } catch { return false; }- const variantsInSlate = slate.variants ?? [];+ let variantsInSlate: readonly { component_class?: unknown; inject_packages?: readonly { package_id?: unknown }[] }[];+ try { variantsInSlate = expandVariantSlate(slate, slatePath); } catch { return false; }if (variantsInSlate.some((variant) => variant.component_class === "new-package" && (variant.inject_packages?.length ?? 0) === 0)) return false;const required = new Set(variantsInSlate.flatMap((variant) => variant.component_class === "new-package"? (variant.inject_packages ?? []).flatMap((injection) => typeof injection.package_id === "string" ? [injection.package_id] : [])@@ -521,8 +525,10 @@ async function reconcileVariantExpansionUnlocked(projectRoot: string, outputRoot&& [...required].every((id) => packages.some((pack) => pack.id === id && pack.status === "ready" && pack.digest !== undefined));}],[10, async () => await validJson(artifact("slate"), (value) => {- const variants = (value as { variants?: unknown[] })?.variants;- return Array.isArray(variants) && (existing.count === undefined || variants.length === existing.count);+ try {+ const variants = expandVariantSlate(value as VariantSlate, artifact("slate") ?? "slate.json");+ return existing.count === undefined || variants.length === existing.count;+ } catch { return false; }})],[11, async () => variants.length > 0 && (await Promise.all(variants.map(async (variant) => await exists(variant.manifest) && await exists(variant.project_root)))).every(Boolean)],[12, async () => variants.length > 0 && (await Promise.all(variants.map(async (variant) => await exists(variant.route_state)))).every(Boolean)],