"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/
Python
[Live2D] Add editing, linting, batch ops, and workflow commands (v0.3.0) (#313)
zyzly0705ce3712a5231a
diff --git a/.gitignore b/.gitignoreindex 1b641a167..211afaef9 100644--- a/.gitignore+++ b/.gitignore@@ -100,6 +100,7 @@!/3MF/!/calibre/!/rekordbox/+!/live2d/!/tigris/!/cc-switch/!/siyuan/@@ -210,6 +211,8 @@/calibre/.*/rekordbox/*/rekordbox/.*+/live2d/*+/live2d/.*/tigris/*/tigris/.*/cc-switch/*@@ -280,6 +283,7 @@!/sbox/agent-harness/!/quietshrink/agent-harness/!/mailchimp/agent-harness/+!/live2d/agent-harness/!/rekordbox/agent-harness/!/tigris/agent-harness/!/cc-switch/agent-harness/diff --git a/live2d/agent-harness/CHANGELOG.md b/live2d/agent-harness/CHANGELOG.mdnew file mode 100644index 000000000..08d13e2bc--- /dev/null+++ b/live2d/agent-harness/CHANGELOG.md@@ -0,0 +1,70 @@+# Changelog++## 0.3.0 (2026-05-29)++### New features++**Edit commands** (all auto-backup before modifying):+- `edit-motion` — Edit motion fade-in/out times or file path+- `add-motion` — Add a motion to a group (creates group if needed)+- `rm-motion` — Remove a motion from a group+- `add-expr` — Add an expression to the model+- `rm-expr` — Remove an expression from the model+- `edit-texture` — Replace a texture file path+- `edit-model` — Edit model-level references (moc3, physics, pose, userdata)+- `param-edit` — Edit parameter values inside .exp3.json files+- `rename-group` — Rename a motion group+- `find-replace` — Batch rename file references across the entire model++**Asset management:**+- `orphan` — Find files in the model directory not referenced by any model+- `restore-file` — Restore a specific file from backup+- `backup-clean` — Clean old backups, keep only the N most recent+- `manifest` — Generate a manifest of all files with SHA256 checksums and sizes+- `stats` — Project overview (model count, motions, expressions, textures, disk usage)++**Generation:**+- `gen-motion` — Generate a skeleton .motion3.json file+- `gen-expr` — Generate a skeleton .exp3.json file+- `init` — Generate a full model template/skeleton++**Analysis:**+- `lint` — Best practice checks (naming, textures, motions, structure)+- `diff` — Detailed diff between two models at field/motion/expression/texture level+- `param-list` — List all unique parameters used across motions and expressions+- `runtime-check` — Check compatibility with specific runtimes (Cubism Viewer, Web SDK, Yoyo)+- `atlas` — Texture atlas analysis with merge/split suggestions++**Workflow:**+- `undo` — Restore model from auto-backup (with `--list` and `--backup` options)+- `batch` — Batch-edit multiple models in a directory (supports `--dry-run`)+- `snapshot` — Generate HTML preview page with dark theme and texture previews+- `watch` — Watch directory for file changes and auto-validate+- `flatten` — Flatten directory structure for deployment (all files in one dir)+- `migrate` — Migrate model format to newer versions++### Changes++- `save_model()` function added to `parser.py` for writing modified models back to disk+- All edit commands create automatic backups before modifying files+- Version bumped to 0.3.0++### New modules++- `core/backup.py` — Auto-backup, snapshot, list, restore+- `core/linter.py` — Best practice lint checks+- `core/differ.py` — Detailed model diffing+- `core/snapshot.py` — HTML preview generation++### Tests++- 40 new tests covering all new features++### Documentation++- Updated LIVE2D.md with all 42 commands+- Updated SKILL.md with full command reference and examples++## 0.2.0++Initial release with read-only commands: inspect, validate, motions, motion-info, expressions, expr-info, textures, physics, moc3, deps, compare, pack, yoyo-check, init, scan, export, params.diff --git a/live2d/agent-harness/LIVE2D.md b/live2d/agent-harness/LIVE2D.mdnew file mode 100644index 000000000..3b75eca97--- /dev/null+++ b/live2d/agent-harness/LIVE2D.md@@ -0,0 +1,124 @@+# Live2D Cubism CLI Harness++## Architecture++This CLI harness provides command-line access to Live2D Cubism model files+(.model3.json, .moc3, .motion3.json, .exp3.json, etc.) without requiring+the Live2D Cubism Editor or runtime.++### What it does++- **Inspect** — Parse .model3.json and display model structure+- **Validate** — Check all referenced files exist+- **Edit** — Modify motions, expressions, textures, and model references+- **Lint** — Best practice checks (naming, texture sizes, structure)+- **Batch** — Edit multiple models at once+- **Diff** — Detailed comparison at field/motion/expression level+- **Preview** — Generate HTML preview of a model+- **Watch** — Auto-validate on file changes+- **Atlas** — Texture atlas analysis (merge/split suggestions)+- **Migrate** — Model format version upgrades+- **Undo** — Auto-backup before edits, with rollback support+- **Scan** — Batch-discover models in a directory tree+- **Export** — Output model summary as JSON or CSV+- **Orphan** — Find unreferenced files+- **Manifest** — File inventory with checksums+- **Runtime** — Compatibility checks for Cubism Viewer, Web SDK, Yoyo+- **Flatten** — Flatten directory for deployment++### File format reference++| File type | Extension | Purpose |+|-----------|-----------|---------|+| Model data | `.moc3` | Binary model mesh + rig |+| Textures | `.png` | Character artwork layers |+| Physics | `.physics3.json` | Hair/clothing simulation |+| Pose | `.pose3.json` | Part switching |+| Motion | `.motion3.json` | Animation keyframes |+| Expression | `.exp3.json` | Expression presets |+| UserData | `.userdata3.json` | Custom metadata |+| DisplayInfo | `.cdi3.json` | Parameter display names |++### Dependencies++- Python 3.10++- Click 8.1+++## Commands (42 total)++### Read++```bash+inspect <model> # Model overview+validate <model> [--strict] # Check files exist+motions <model> [-g group] # List motions+motion-info <file> # Motion analysis+expressions <model> # List expressions+expr-info <file> # Expression analysis+textures <model> # List textures with sizes+physics <file> # Physics config+moc3 <file> # Moc3 binary info+params <model> # Parameter groups+param-list <model> # All params across motions/expressions+deps <model> # Dependency graph+compare <a> <b> # Quick comparison+diff <a> <b> # Detailed diff+scan <dir> [-v] # Find all models+export <model> [--format] # Export as JSON/CSV+stats <dir> # Project overview+manifest <model> # File inventory with checksums+```++### Edit (auto-backup)++```bash+edit-motion <model> -g <group> -i <idx> [--fade-in/--fade-out/--file]+add-motion <model> -g <group> --file <motion>+rm-motion <model> -g <group> -i <idx>+add-expr <model> -n <name> -f <file>+rm-expr <model> -n <name>+edit-texture <model> -i <idx> --path <path>+edit-model <model> [--moc3/--physics/--pose/--userdata]+param-edit <expr> -p <param-id> -v <value>+rename-group <model> --old <name> --new <name>+find-replace <model> -f <find> -r <replace> [--dry-run]+```++### Generation++```bash+init <name> [--dir] # Full model template+gen-motion <name> [--duration/--fps/--loop/--out]+gen-expr <name> [--fade-in/--fade-out/--out]+```++### Analysis++```bash+lint <model> [--level] # Best practice checks+runtime-check <model> [--target cubism-viewer|web-sdk|yoyo|all]+atlas <model> [--merge/--split/--max-size]+orphan <model> # Find unreferenced files+```++### Workflow++```bash+undo <model> [--list/--backup]+backup-clean <model> [--keep/--dry-run]+restore-file <model> --file <path>+batch <dir> [--set-fade-in/--set-fade-out/--add-motion-*/--add-expr-*/--set-moc3/--dry-run]+snapshot <model> [--embed/--out]+watch <dir> [--interval]+flatten <model> --out-dir <dir> [--dry-run]+migrate <model> [--target-version/--dry-run]+pack <model> -o <output.zip>+yoyo-check <model>+```++### Global++```bash+--json # JSON output (any command)+--version # Show version+```diff --git a/live2d/agent-harness/cli_anything/live2d/__init__.py b/live2d/agent-harness/cli_anything/live2d/__init__.pynew file mode 100644index 000000000..0e6ca90a0--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/__init__.py@@ -0,0 +1,2 @@+"""cli-anything-live2d — Live2D Cubism model inspector and manager."""+__version__ = "0.1.0"diff --git a/live2d/agent-harness/cli_anything/live2d/__main__.py b/live2d/agent-harness/cli_anything/live2d/__main__.pynew file mode 100644index 000000000..76485eac9--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/__main__.py@@ -0,0 +1,6 @@+#!/usr/bin/env python3+"""Allow running as `python -m cli_anything.live2d`."""+from cli_anything.live2d.live2d_cli import main++if __name__ == "__main__":+ main()diff --git a/live2d/agent-harness/cli_anything/live2d/core/__init__.py b/live2d/agent-harness/cli_anything/live2d/core/__init__.pynew file mode 100644index 000000000..a1ad1d82e--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/core/__init__.py@@ -0,0 +1 @@+"""Live2D Cubism core modules."""diff --git a/live2d/agent-harness/cli_anything/live2d/core/backup.py b/live2d/agent-harness/cli_anything/live2d/core/backup.pynew file mode 100644index 000000000..e0656290e--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/core/backup.py@@ -0,0 +1,81 @@+"""Auto-backup before edits, with undo support."""++import json+import shutil+import filecmp+from datetime import datetime+from pathlib import Path+++BACKUP_DIR = ".live2d-backups"+++def _backup_dir_for(model_path: Path) -> Path:+ return model_path.parent / BACKUP_DIR / model_path.stem+++def snapshot(model_path: Path) -> Path:+ """Create a timestamped backup of a model file. Returns backup path."""+ if not model_path.exists():+ raise FileNotFoundError(f"Model not found: {model_path}")++ bdir = _backup_dir_for(model_path)+ bdir.mkdir(parents=True, exist_ok=True)++ ts = datetime.now().strftime("%Y%m%d_%H%M%S_%f")+ dest = bdir / f"{ts}.model3.json"+ shutil.copy2(model_path, dest)++ # Also copy a snapshot of the raw JSON for diff+ return dest+++def list_backups(model_path: Path) -> list[dict]:+ """List available backups for a model."""+ bdir = _backup_dir_for(model_path)+ if not bdir.exists():+ return []++ backups = []+ for f in sorted(bdir.glob("*.model3.json"), reverse=True):+ backups.append({+ "file": f.name,+ "path": str(f),+ "time": f.stem,+ "size": f.stat().st_size,+ })+ return backups+++def restore(model_path: Path, backup_name: str | None = None) -> Path:+ """Restore a model from backup. If no name given, restores the latest."""+ bdir = _backup_dir_for(model_path)+ if not bdir.exists():+ raise FileNotFoundError(f"No backups found for {model_path.name}")++ if backup_name:+ src = bdir / backup_name+ else:+ backups = sorted(bdir.glob("*.model3.json"), reverse=True)+ if not backups:+ raise FileNotFoundError(f"No backups found for {model_path.name}")+ src = backups[0]++ if not src.exists():+ raise FileNotFoundError(f"Backup not found: {src}")++ shutil.copy2(src, model_path)+ return src+++def auto_backup(model_path: Path) -> Path | None:+ """Auto-backup before edit. Skips only when content is unchanged."""+ bdir = _backup_dir_for(model_path)+ if bdir.exists():+ backups = sorted(bdir.glob("*.model3.json"), reverse=True)+ if backups:+ last = backups[0]+ if filecmp.cmp(model_path, last, shallow=False):+ return None++ return snapshot(model_path)diff --git a/live2d/agent-harness/cli_anything/live2d/core/comparer.py b/live2d/agent-harness/cli_anything/live2d/core/comparer.pynew file mode 100644index 000000000..2c0498b59--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/core/comparer.py@@ -0,0 +1,118 @@+"""Compare two Live2D models."""++from dataclasses import dataclass, field+from .parser import ModelInfo+++@dataclass+class DiffItem:+ category: str # "texture", "motion", "expression", "physics", etc.+ type: str # "added", "removed", "changed"+ name: str+ detail: str = ""+++@dataclass+class ModelDiff:+ model_a: str+ model_b: str+ items: list[DiffItem] = field(default_factory=list)++ @property+ def has_changes(self) -> bool:+ return len(self.items) > 0++ @property+ def added(self) -> list[DiffItem]:+ return [i for i in self.items if i.type == "added"]++ @property+ def removed(self) -> list[DiffItem]:+ return [i for i in self.items if i.type == "removed"]++ @property+ def changed(self) -> list[DiffItem]:+ return [i for i in self.items if i.type == "changed"]++ def to_dict(self) -> dict:+ return {+ "model_a": self.model_a,+ "model_b": self.model_b,+ "has_changes": self.has_changes,+ "summary": {+ "added": len(self.added),+ "removed": len(self.removed),+ "changed": len(self.changed),+ },+ "items": [+ {"category": i.category, "type": i.type, "name": i.name, "detail": i.detail}+ for i in self.items+ ],+ }+++def compare_models(a: ModelInfo, b: ModelInfo) -> ModelDiff:+ """Compare two models and return differences."""+ diff = ModelDiff(model_a=str(a.path), model_b=str(b.path))++ # Compare textures+ tex_a = set(a.textures)+ tex_b = set(b.textures)+ for t in tex_b - tex_a:+ diff.items.append(DiffItem("texture", "added", t))+ for t in tex_a - tex_b:+ diff.items.append(DiffItem("texture", "removed", t))++ # Compare expressions+ expr_a = {e.name: e for e in a.expressions}+ expr_b = {e.name: e for e in b.expressions}+ for name in set(expr_b) - set(expr_a):+ diff.items.append(DiffItem("expression", "added", name))+ for name in set(expr_a) - set(expr_b):+ diff.items.append(DiffItem("expression", "removed", name))+ for name in set(expr_a) & set(expr_b):+ if expr_a[name].file != expr_b[name].file:+ diff.items.append(DiffItem("expression", "changed", name,+ f"{expr_a[name].file} → {expr_b[name].file}"))++ # Compare motion groups+ groups_a = set(a.motions.keys())+ groups_b = set(b.motions.keys())+ for g in groups_b - groups_a:+ diff.items.append(DiffItem("motion_group", "added", g, f"{len(b.motions[g])} motions"))+ for g in groups_a - groups_b:+ diff.items.append(DiffItem("motion_group", "removed", g, f"{len(a.motions[g])} motions"))++ # Compare motions within shared groups+ for g in groups_a & groups_b:+ files_a = {m.file for m in a.motions[g]}+ files_b = {m.file for m in b.motions[g]}+ for f in files_b - files_a:+ diff.items.append(DiffItem("motion", "added", f"[{g}] {f}"))+ for f in files_a - files_b:+ diff.items.append(DiffItem("motion", "removed", f"[{g}] {f}"))++ # Compare moc3+ if a.moc3 != b.moc3:+ diff.items.append(DiffItem("moc3", "changed", "moc3", f"{a.moc3} → {b.moc3}"))++ # Compare physics+ if bool(a.physics) != bool(b.physics):+ if b.physics:+ diff.items.append(DiffItem("physics", "added", b.physics))+ else:+ diff.items.append(DiffItem("physics", "removed", a.physics))++ # Compare groups+ groups_ids_a = {g.get("Name", ""): g.get("Ids", "") for g in a.groups}+ groups_ids_b = {g.get("Name", ""): g.get("Ids", "") for g in b.groups}+ for name in set(groups_ids_b) - set(groups_ids_a):+ diff.items.append(DiffItem("param_group", "added", name))+ for name in set(groups_ids_a) - set(groups_ids_b):+ diff.items.append(DiffItem("param_group", "removed", name))+ for name in set(groups_ids_a) & set(groups_ids_b):+ if groups_ids_a[name] != groups_ids_b[name]:+ diff.items.append(DiffItem("param_group", "changed", name,+ f"{groups_ids_a[name]} → {groups_ids_b[name]}"))++ return diffdiff --git a/live2d/agent-harness/cli_anything/live2d/core/dependency.py b/live2d/agent-harness/cli_anything/live2d/core/dependency.pynew file mode 100644index 000000000..6e499986f--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/core/dependency.py@@ -0,0 +1,80 @@+"""Build dependency graph between motions, expressions, and parameters."""++from pathlib import Path+from dataclasses import dataclass, field+from collections import defaultdict++from .parser import ModelInfo+from .motion_parser import load_motion, MotionInfo+from .expression_parser import load_expression, ExpressionInfo+++@dataclass+class ParamUsage:+ """Track which motions/expressions use a parameter."""+ param_id: str+ motions: list[str] = field(default_factory=list)+ expressions: list[str] = field(default_factory=list)++ @property+ def total_references(self) -> int:+ return len(self.motions) + len(self.expressions)+++@dataclass+class DependencyGraph:+ model_path: Path+ params: dict[str, ParamUsage] = field(default_factory=dict)+ parse_errors: list[dict] = field(default_factory=list)++ @property+ def param_count(self) -> int:+ return len(self.params)++ def to_dict(self) -> dict:+ return {+ "model": str(self.model_path),+ "param_count": self.param_count,+ "parse_errors": len(self.parse_errors),+ "params": {+ pid: {+ "motions": u.motions,+ "expressions": u.expressions,+ "total_references": u.total_references,+ }+ for pid, u in sorted(self.params.items(), key=lambda x: -x[1].total_references)+ },+ }+++def build_dependency_graph(info: ModelInfo) -> DependencyGraph:+ """Build a dependency graph from a model."""+ graph = DependencyGraph(model_path=info.path)+ model_dir = info.path.parent++ # Process motions+ for group, motions in info.motions.items():+ for m in motions:+ motion_path = model_dir / m.file+ try:+ motion = load_motion(motion_path)+ for pid in motion.parameter_ids:+ if pid not in graph.params:+ graph.params[pid] = ParamUsage(param_id=pid)+ graph.params[pid].motions.append(f"[{group}] {m.file}")+ except Exception as e:+ graph.parse_errors.append({"file": m.file, "error": str(e)})++ # Process expressions+ for expr in info.expressions:+ expr_path = model_dir / expr.file+ try:+ expression = load_expression(expr_path)+ for pid in expression.param_ids:+ if pid not in graph.params:+ graph.params[pid] = ParamUsage(param_id=pid)+ graph.params[pid].expressions.append(expr.name)+ except Exception as e:+ graph.parse_errors.append({"file": expr.file, "error": str(e)})++ return graphdiff --git a/live2d/agent-harness/cli_anything/live2d/core/differ.py b/live2d/agent-harness/cli_anything/live2d/core/differ.pynew file mode 100644index 000000000..d1ce8f302--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/core/differ.py@@ -0,0 +1,147 @@+"""Detailed diff between two Live2D models."""++from dataclasses import dataclass, field+from pathlib import Path++from cli_anything.live2d.core.parser import ModelInfo+++@dataclass+class DiffItem:+ category: str # "texture", "motion", "expression", "field", "param"+ name: str+ detail: str+ value_a: object = None+ value_b: object = None+++@dataclass+class DetailedDiff:+ model_a: Path+ model_b: Path+ items: list[DiffItem] = field(default_factory=list)++ @property+ def has_changes(self) -> bool:+ return len(self.items) > 0++ def to_dict(self) -> dict:+ return {+ "model_a": str(self.model_a),+ "model_b": str(self.model_b),+ "has_changes": self.has_changes,+ "changes": len(self.items),+ "items": [+ {"category": i.category, "name": i.name, "detail": i.detail,+ "value_a": i.value_a, "value_b": i.value_b}+ for i in self.items+ ],+ }+++def diff_models(a: ModelInfo, b: ModelInfo) -> DetailedDiff:+ """Compute a detailed diff between two models."""+ d = DetailedDiff(model_a=a.path, model_b=b.path)++ # ── Top-level fields ───────────────────────────────────++ for field_name in ("moc3", "physics", "pose", "userdata", "version"):+ va = getattr(a, field_name)+ vb = getattr(b, field_name)+ if va != vb:+ d.items.append(DiffItem(+ category="field", name=field_name,+ detail=f"{va!r} → {vb!r}",+ value_a=va, value_b=vb,+ ))++ # ── Textures ───────────────────────────────────────────++ tex_a = set(a.textures)+ tex_b = set(b.textures)+ for t in sorted(tex_b - tex_a):+ d.items.append(DiffItem(category="texture", name=t, detail="added"))+ for t in sorted(tex_a - tex_b):+ d.items.append(DiffItem(category="texture", name=t, detail="removed"))++ # ── Expressions ────────────────────────────────────────++ expr_a = {e.name: e for e in a.expressions}+ expr_b = {e.name: e for e in b.expressions}++ for name in sorted(set(expr_b) - set(expr_a)):+ d.items.append(DiffItem(+ category="expression", name=name,+ detail=f"added → {expr_b[name].file}",+ value_b=expr_b[name].file,+ ))+ for name in sorted(set(expr_a) - set(expr_b)):+ d.items.append(DiffItem(+ category="expression", name=name,+ detail=f"removed (was → {expr_a[name].file})",+ value_a=expr_a[name].file,+ ))+ for name in sorted(set(expr_a) & set(expr_b)):+ ea, eb = expr_a[name], expr_b[name]+ if ea.file != eb.file:+ d.items.append(DiffItem(+ category="expression", name=name,+ detail=f"file: {ea.file} → {eb.file}",+ value_a=ea.file, value_b=eb.file,+ ))++ # ── Motions ────────────────────────────────────────────++ groups_a = set(a.motions.keys())+ groups_b = set(b.motions.keys())++ for g in sorted(groups_b - groups_a):+ for i, m in enumerate(b.motions[g]):+ d.items.append(DiffItem(+ category="motion", name=f"[{g}][{i}] {m.file}",+ detail="added",+ ))+ for g in sorted(groups_a - groups_b):+ for i, m in enumerate(a.motions[g]):+ d.items.append(DiffItem(+ category="motion", name=f"[{g}][{i}] {m.file}",+ detail="removed",+ ))++ for g in sorted(groups_a & groups_b):+ ma = a.motions[g]+ mb = b.motions[g]++ # Compare by index+ max_len = max(len(ma), len(mb))+ for i in range(max_len):+ if i >= len(ma):+ m = mb[i]+ d.items.append(DiffItem(+ category="motion", name=f"[{g}][{i}] {m.file}",+ detail="added",+ ))+ elif i >= len(mb):+ m = ma[i]+ d.items.append(DiffItem(+ category="motion", name=f"[{g}][{i}] {m.file}",+ detail="removed",+ ))+ else:+ m1, m2 = ma[i], mb[i]+ changes = []+ if m1.file != m2.file:+ changes.append(f"file: {m1.file} → {m2.file}")+ if m1.fade_in != m2.fade_in:+ changes.append(f"fade_in: {m1.fade_in} → {m2.fade_in}")+ if m1.fade_out != m2.fade_out:+ changes.append(f"fade_out: {m1.fade_out} → {m2.fade_out}")+ if changes:+ d.items.append(DiffItem(+ category="motion", name=f"[{g}][{i}]",+ detail="; ".join(changes),+ value_a={"file": m1.file, "fade_in": m1.fade_in, "fade_out": m1.fade_out},+ value_b={"file": m2.file, "fade_in": m2.fade_in, "fade_out": m2.fade_out},+ ))++ return ddiff --git a/live2d/agent-harness/cli_anything/live2d/core/expression_parser.py b/live2d/agent-harness/cli_anything/live2d/core/expression_parser.pynew file mode 100644index 000000000..76df0217a--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/core/expression_parser.py@@ -0,0 +1,66 @@+"""Parse Live2D .exp3.json files."""++import json+from pathlib import Path+from dataclasses import dataclass, field+++@dataclass+class ExpressionParam:+ id: str # e.g. "ParamEyeLOpen"+ value: float = 0.0+ fade_in: float = 0.0+ fade_out: float = 0.0+++@dataclass+class ExpressionInfo:+ path: Path+ version: int = 0+ fade_in: float = 0.0+ fade_out: float = 0.0+ params: list[ExpressionParam] = field(default_factory=list)++ @property+ def param_count(self) -> int:+ return len(self.params)++ @property+ def param_ids(self) -> list[str]:+ return [p.id for p in self.params]++ def to_dict(self) -> dict:+ return {+ "file": str(self.path),+ "version": self.version,+ "fade_in": self.fade_in,+ "fade_out": self.fade_out,+ "param_count": self.param_count,+ "params": [{"id": p.id, "value": p.value} for p in self.params],+ }+++def load_expression(path: Path) -> ExpressionInfo:+ """Load and parse a .exp3.json file."""+ if not path.exists():+ raise FileNotFoundError(f"Expression file not found: {path}")++ with open(path, "r", encoding="utf-8") as f:+ data = json.load(f)++ info = ExpressionInfo(+ path=path,+ version=data.get("Version", 0),+ fade_in=data.get("FadeInTime", 0),+ fade_out=data.get("FadeOutTime", 0),+ )++ for param_data in data.get("Parameters", []):+ info.params.append(ExpressionParam(+ id=param_data.get("Id", ""),+ value=param_data.get("Value", 0),+ fade_in=param_data.get("FadeInTime", 0),+ fade_out=param_data.get("FadeOutTime", 0),+ ))++ return infodiff --git a/live2d/agent-harness/cli_anything/live2d/core/linter.py b/live2d/agent-harness/cli_anything/live2d/core/linter.pynew file mode 100644index 000000000..89938905a--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/core/linter.py@@ -0,0 +1,244 @@+"""Lint Live2D models for best practices."""++from dataclasses import dataclass, field+from pathlib import Path+import re++from cli_anything.live2d.core.parser import ModelInfo, load_model+from cli_anything.live2d.core.motion_parser import load_motion+from cli_anything.live2d.core.expression_parser import load_expression+from cli_anything.live2d.core.texture_info import get_texture_info+++@dataclass+class LintIssue:+ level: str # "error", "warning", "info"+ category: str # "naming", "texture", "motion", "expression", "structure"+ message: str+ file: str = ""+ fix_hint: str = ""+++@dataclass+class LintReport:+ model_path: Path+ issues: list[LintIssue] = field(default_factory=list)++ @property+ def errors(self) -> list[LintIssue]:+ return [i for i in self.issues if i.level == "error"]++ @property+ def warnings(self) -> list[LintIssue]:+ return [i for i in self.issues if i.level == "warning"]++ @property+ def infos(self) -> list[LintIssue]:+ return [i for i in self.issues if i.level == "info"]++ @property+ def ok(self) -> bool:+ return len(self.errors) == 0++ def to_dict(self) -> dict:+ return {+ "model": str(self.model_path),+ "ok": self.ok,+ "errors": len(self.errors),+ "warnings": len(self.warnings),+ "infos": len(self.infos),+ "issues": [+ {"level": i.level, "category": i.category, "message": i.message, "file": i.file, "fix_hint": i.fix_hint}+ for i in self.issues+ ],+ }+++def _is_power_of_two(n: int) -> bool:+ return n > 0 and (n & (n - 1)) == 0+++def lint_model(model_path: Path) -> LintReport:+ """Run all lint checks on a model."""+ info = load_model(model_path)+ report = LintReport(model_path=model_path)+ model_dir = model_path.parent++ # ── Naming checks ──────────────────────────────────────++ # Model file naming+ name = model_path.stem+ if not re.match(r'^[a-zA-Z0-9_-]+$', name):+ report.issues.append(LintIssue(+ level="warning", category="naming",+ message=f"Model name '{name}' contains special characters",+ file=model_path.name,+ fix_hint="Use only letters, numbers, hyphens, underscores",+ ))++ # Motion file naming+ for group, motions in info.motions.items():+ for i, m in enumerate(motions):+ fname = Path(m.file).stem+ if not re.match(r'^[a-zA-Z0-9_-]+$', fname):+ report.issues.append(LintIssue(+ level="info", category="naming",+ message=f"Motion file '{fname}' in [{group}][{i}] has special characters",+ file=m.file,+ ))++ # Expression naming+ for expr in info.expressions:+ if not re.match(r'^[a-zA-Z0-9_-]+$', expr.name):+ report.issues.append(LintIssue(+ level="info", category="naming",+ message=f"Expression name '{expr.name}' has special characters",+ file=expr.file,+ ))++ # ── Texture checks ─────────────────────────────────────++ for i, tex in enumerate(info.textures):+ tex_path = model_dir / tex+ if not tex_path.exists():+ report.issues.append(LintIssue(+ level="error", category="texture",+ message=f"Texture [{i}] not found: {tex}",+ file=tex,+ ))+ continue++ tinfo = get_texture_info(tex_path)++ # Size check+ if tinfo.width > 0:+ if not _is_power_of_two(tinfo.width) or not _is_power_of_two(tinfo.height):+ report.issues.append(LintIssue(+ level="warning", category="texture",+ message=f"Texture [{i}] dimensions {tinfo.width}×{tinfo.height} are not powers of 2",+ file=tex,+ fix_hint="Use 512×512, 1024×1024, 2048×2048, etc. for GPU efficiency",+ ))++ if tinfo.width > 4096 or tinfo.height > 4096:+ report.issues.append(LintIssue(+ level="warning", category="texture",+ message=f"Texture [{i}] is very large ({tinfo.width}×{tinfo.height})",+ file=tex,+ fix_hint="Consider reducing to 2048×2048 or smaller for better performance",+ ))++ # Format check+ if tinfo.format and tinfo.format not in ("png", "webp"):+ report.issues.append(LintIssue(+ level="warning", category="texture",+ message=f"Texture [{i}] uses {tinfo.format} format (png or webp recommended)",+ file=tex,+ ))++ # ── Motion checks ──────────────────────────────────────++ for group, motions in info.motions.items():+ for i, m in enumerate(motions):+ motion_path = model_dir / m.file+ if not motion_path.exists():+ report.issues.append(LintIssue(+ level="error", category="motion",+ message=f"Motion file not found: [{group}][{i}] {m.file}",+ file=m.file,+ ))+ continue++ # Fade time check+ if m.fade_in < 0:+ report.issues.append(LintIssue(+ level="error", category="motion",+ message=f"Negative fade_in ({m.fade_in}s) in [{group}][{i}]",+ file=m.file,+ ))+ if m.fade_out < 0:+ report.issues.append(LintIssue(+ level="error", category="motion",+ message=f"Negative fade_out ({m.fade_out}s) in [{group}][{i}]",+ file=m.file,+ ))++ if m.fade_in > 2.0:+ report.issues.append(LintIssue(+ level="warning", category="motion",+ message=f"Very long fade_in ({m.fade_in}s) in [{group}][{i}]",+ file=m.file,+ fix_hint="Most motions use 0-1s fade times",+ ))++ # Try parsing the motion file for deeper checks+ try:+ minfo = load_motion(motion_path)+ if minfo.duration <= 0:+ report.issues.append(LintIssue(+ level="warning", category="motion",+ message=f"Motion [{group}][{i}] has zero duration",+ file=m.file,+ ))+ if minfo.fps < 15:+ report.issues.append(LintIssue(+ level="info", category="motion",+ message=f"Motion [{group}][{i}] has low FPS ({minfo.fps})",+ file=m.file,+ ))+ except Exception:+ pass # parse failure already caught by validator++ # ── Expression checks ──────────────────────────────────++ expr_names = set()+ for expr in info.expressions:+ expr_path = model_dir / expr.file+ if not expr_path.exists():+ report.issues.append(LintIssue(+ level="error", category="expression",+ message=f"Expression file not found: {expr.name} → {expr.file}",+ file=expr.file,+ ))+ continue++ # Duplicate name check+ if expr.name in expr_names:+ report.issues.append(LintIssue(+ level="error", category="expression",+ message=f"Duplicate expression name: '{expr.name}'",+ file=expr.file,+ ))+ expr_names.add(expr.name)++ # ── Structure checks ───────────────────────────────────++ if not info.moc3:+ report.issues.append(LintIssue(+ level="error", category="structure",+ message="No moc3 file referenced",+ ))++ if not info.textures:+ report.issues.append(LintIssue(+ level="error", category="structure",+ message="No textures defined",+ ))++ if not info.motions:+ report.issues.append(LintIssue(+ level="warning", category="structure",+ message="No motions defined",+ ))++ # Common motion groups+ group_names = set(info.motions.keys())+ common_groups = {"Idle", "idle", "TapBody", "tap_body", "TapHead", "tap_head"}+ if not group_names & common_groups:+ report.issues.append(LintIssue(+ level="info", category="structure",+ message="No common motion groups found (Idle, TapBody, TapHead)",+ fix_hint="Most Live2D runtimes expect at least an Idle group",+ ))++ return reportdiff --git a/live2d/agent-harness/cli_anything/live2d/core/moc3_parser.py b/live2d/agent-harness/cli_anything/live2d/core/moc3_parser.pynew file mode 100644index 000000000..b7c774a68--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/core/moc3_parser.py@@ -0,0 +1,56 @@+"""Parse Live2D .moc3 binary file header."""++from pathlib import Path+from dataclasses import dataclass+++@dataclass+class Moc3Info:+ path: Path+ valid: bool = False+ version: int = 0+ file_size: int = 0++ def to_dict(self) -> dict:+ return {+ "file": str(self.path),+ "valid": self.valid,+ "version": self.version,+ "file_size": self.file_size,+ "file_size_display": self._size_display(),+ }++ def _size_display(self) -> str:+ s = self.file_size+ if s < 1024:+ return f"{s}B"+ elif s < 1024 * 1024:+ return f"{s / 1024:.1f}KB"+ else:+ return f"{s / (1024*1024):.1f}MB"+++def load_moc3(path: Path) -> Moc3Info:+ """Load and parse a .moc3 binary file header."""+ info = Moc3Info(path=path)++ if not path.exists():+ return info++ info.file_size = path.stat().st_size++ with open(path, "rb") as f:+ header = f.read(8)++ if len(header) < 8:+ return info++ # Magic: "MOC3"+ magic = header[:4]+ if magic != b"MOC3":+ return info++ info.valid = True+ info.version = int.from_bytes(header[4:8], "little")++ return infodiff --git a/live2d/agent-harness/cli_anything/live2d/core/motion_parser.py b/live2d/agent-harness/cli_anything/live2d/core/motion_parser.pynew file mode 100644index 000000000..8f2937c4b--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/core/motion_parser.py@@ -0,0 +1,152 @@+"""Parse Live2D .motion3.json files."""++import json+from pathlib import Path+from dataclasses import dataclass, field+++@dataclass+class MotionSegment:+ """A single segment in a motion curve.++ Segment types (determined by point count):+ - 2 points (linear): [time, value]+ - 3 points (bezier): [time, cx1, cy1, cx2, cy2, value]+ - 5 points (stepped): [time, value]+ - 7 points (inverse stepped): [time, value]+ """+ points: list[float] = field(default_factory=list)++ @property+ def segment_type(self) -> str:+ n = len(self.points)+ if n <= 2:+ return "linear"+ elif n <= 3:+ return "bezier"+ elif n <= 5:+ return "stepped"+ else:+ return "inverse_stepped"+++@dataclass+class MotionCurve:+ target: str # "Parameter", "Model", "Part", "Opacity"+ id: str # e.g. "ParamAngleX", "ParamBodyAngleX"+ segments: list[MotionSegment] = field(default_factory=list)++ @property+ def keyframe_count(self) -> int:+ return len(self.segments)+++@dataclass+class MotionInfo:+ path: Path+ version: int = 0+ duration: float = 0.0+ fps: float = 0.0+ loop: bool = False+ curve_count: int = 0+ total_segment_count: int = 0+ total_point_count: int = 0+ curves: list[MotionCurve] = field(default_factory=list)++ @property+ def parameter_curves(self) -> list[MotionCurve]:+ return [c for c in self.curves if c.target == "Parameter"]++ @property+ def model_curves(self) -> list[MotionCurve]:+ return [c for c in self.curves if c.target == "Model"]++ @property+ def part_curves(self) -> list[MotionCurve]:+ return [c for c in self.curves if c.target == "Part"]++ @property+ def parameter_ids(self) -> list[str]:+ return [c.id for c in self.parameter_curves]++ def to_dict(self) -> dict:+ return {+ "file": str(self.path),+ "version": self.version,+ "duration": self.duration,+ "fps": self.fps,+ "loop": self.loop,+ "curve_count": self.curve_count,+ "total_segments": self.total_segment_count,+ "total_points": self.total_point_count,+ "parameters": self.parameter_ids,+ "parameter_count": len(self.parameter_curves),+ "model_curves": len(self.model_curves),+ "part_curves": len(self.part_curves),+ "curves": [+ {"target": c.target, "id": c.id, "keyframes": c.keyframe_count}+ for c in self.curves+ ],+ }+++def load_motion(path: Path) -> MotionInfo:+ """Load and parse a .motion3.json file."""+ if not path.exists():+ raise FileNotFoundError(f"Motion file not found: {path}")++ with open(path, "r", encoding="utf-8") as f:+ data = json.load(f)++ meta = data.get("Meta", {})+ info = MotionInfo(+ path=path,+ version=data.get("Version", 0),+ duration=meta.get("Duration", 0),+ fps=meta.get("Fps", 0),+ loop=meta.get("Loop", False),+ curve_count=meta.get("CurveCount", 0),+ total_segment_count=meta.get("TotalSegmentCount", 0),+ total_point_count=meta.get("TotalPointCount", 0),+ )++ for curve_data in data.get("Curves", []):+ curve = MotionCurve(+ target=curve_data.get("Target", ""),+ id=curve_data.get("Id", ""),+ )+ segments_raw = curve_data.get("Segments", [])++ # Parse segments: first value is time, then groups of points+ i = 0+ while i < len(segments_raw):+ if i == 0:+ # First segment: [time, value]+ curve.segments.append(MotionSegment(points=segments_raw[i:i + 2]))+ i += 2+ else:+ # Subsequent: type indicator + points+ seg_type = segments_raw[i]+ if seg_type == 0:+ # Linear: [0, time, value]+ curve.segments.append(MotionSegment(points=segments_raw[i + 1:i + 3]))+ i += 3+ elif seg_type == 1:+ # Bezier: [1, time, cx1, cy1, cx2, cy2, value]+ curve.segments.append(MotionSegment(points=segments_raw[i + 1:i + 7]))+ i += 7+ elif seg_type == 2:+ # Stepped: [2, time, value]+ curve.segments.append(MotionSegment(points=segments_raw[i + 1:i + 3]))+ i += 3+ elif seg_type == 3:+ # Inverse stepped: [3, time, value]+ curve.segments.append(MotionSegment(points=segments_raw[i + 1:i + 3]))+ i += 3+ else:+ # Unknown, skip+ i += 1++ info.curves.append(curve)++ return infodiff --git a/live2d/agent-harness/cli_anything/live2d/core/packager.py b/live2d/agent-harness/cli_anything/live2d/core/packager.pynew file mode 100644index 000000000..77907c7c5--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/core/packager.py@@ -0,0 +1,135 @@+"""Package a Live2D model into a zip archive."""++import zipfile+from pathlib import Path+from dataclasses import dataclass++from .parser import ModelInfo+++@dataclass+class PackageResult:+ output_path: Path+ files_count: int = 0+ total_size: int = 0+ missing_files: list[str] = None++ def __post_init__(self):+ if self.missing_files is None:+ self.missing_files = []++ def to_dict(self) -> dict:+ return {+ "output": str(self.output_path),+ "files_count": self.files_count,+ "total_size": self.total_size,+ "total_size_display": self._size_display(),+ "missing_files": self.missing_files,+ }++ def _size_display(self) -> str:+ s = self.total_size+ if s < 1024:+ return f"{s}B"+ elif s < 1024 * 1024:+ return f"{s / 1024:.1f}KB"+ else:+ return f"{s / (1024*1024):.1f}MB"+++def package_model(info: ModelInfo, output_path: Path, include_motions: bool = True,+ include_expressions: bool = True) -> PackageResult:+ """Package a model and all its dependencies into a zip."""+ model_dir = info.path.parent+ result = PackageResult(output_path=output_path)++ # Collect all files to include+ files = set()++ # Model file itself+ files.add(info.path)++ # Moc3+ if info.moc3:+ moc3_path = model_dir / info.moc3+ if moc3_path.exists():+ files.add(moc3_path)+ else:+ result.missing_files.append(info.moc3)++ # Textures+ for tex in info.textures:+ tex_path = model_dir / tex+ if tex_path.exists():+ files.add(tex_path)+ else:+ result.missing_files.append(tex)++ # Physics+ if info.physics:+ phys_path = model_dir / info.physics+ if phys_path.exists():+ files.add(phys_path)+ else:+ result.missing_files.append(info.physics)++ # Pose+ if info.pose:+ pose_path = model_dir / info.pose+ if pose_path.exists():+ files.add(pose_path)+ else:+ result.missing_files.append(info.pose)++ # UserData+ if info.userdata:+ ud_path = model_dir / info.userdata+ if ud_path.exists():+ files.add(ud_path)+ else:+ result.missing_files.append(info.userdata)++ # DisplayInfo+ if info.display_info:+ di_path = model_dir / info.display_info+ if di_path.exists():+ files.add(di_path)+ else:+ result.missing_files.append(info.display_info)++ # Motions+ if include_motions:+ for group, motions in info.motions.items():+ for m in motions:+ m_path = model_dir / m.file+ if m_path.exists():+ files.add(m_path)+ else:+ result.missing_files.append(m.file)+ # Include Sound files referenced in motions+ sound = m.extra.get("Sound") if hasattr(m, 'extra') else None+ if sound:+ s_path = model_dir / sound+ if s_path.exists():+ files.add(s_path)+ else:+ result.missing_files.append(sound)++ # Expressions+ if include_expressions:+ for expr in info.expressions:+ e_path = model_dir / expr.file+ if e_path.exists():+ files.add(e_path)+ else:+ result.missing_files.append(expr.file)++ # Create zip+ with zipfile.ZipFile(output_path, "w", zipfile.ZIP_DEFLATED) as zf:+ for f in sorted(files):+ arcname = f.relative_to(model_dir)+ zf.write(f, arcname)+ result.files_count += 1+ result.total_size += f.stat().st_size++ return resultdiff --git a/live2d/agent-harness/cli_anything/live2d/core/parser.py b/live2d/agent-harness/cli_anything/live2d/core/parser.pynew file mode 100644index 000000000..b8925689d--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/core/parser.py@@ -0,0 +1,180 @@+"""Parse Live2D Cubism model3.json files."""++import json+import os+import tempfile+from pathlib import Path+from dataclasses import dataclass, field+from typing import Optional+++@dataclass+class MotionRef:+ file: str+ fade_in: float = 0.0+ fade_out: float = 0.0+ extra: dict = field(default_factory=dict) # preserve unknown fields (Sound, MetaInfo, etc.)+++@dataclass+class ExpressionRef:+ name: str+ file: str+++@dataclass+class ModelInfo:+ path: Path+ version: str = ""+ moc3: str = ""+ textures: list[str] = field(default_factory=list)+ physics: str = ""+ pose: str = ""+ userdata: str = ""+ display_info: str = ""+ expressions: list[ExpressionRef] = field(default_factory=list)+ motions: dict[str, list[MotionRef]] = field(default_factory=dict)+ groups: list[dict] = field(default_factory=list)++ @property+ def motion_count(self) -> int:+ return sum(len(v) for v in self.motions.values())++ @property+ def motion_group_count(self) -> int:+ return len(self.motions)++ @property+ def texture_count(self) -> int:+ return len(self.textures)++ @property+ def expression_count(self) -> int:+ return len(self.expressions)++ def to_dict(self) -> dict:+ return {+ "model_file": str(self.path),+ "version": self.version,+ "moc3": self.moc3,+ "textures": self.textures,+ "texture_count": self.texture_count,+ "motions": {+ g: [{"file": m.file, "fade_in": m.fade_in, "fade_out": m.fade_out} for m in ms]+ for g, ms in self.motions.items()+ },+ "motion_count": self.motion_count,+ "motion_groups": self.motion_group_count,+ "expressions": [{"name": e.name, "file": e.file} for e in self.expressions],+ "expression_count": self.expression_count,+ "physics": self.physics,+ "pose": self.pose,+ "userdata": self.userdata,+ "groups": self.groups,+ }+++def load_model(path: Path) -> ModelInfo:+ """Load and parse a .model3.json file into a ModelInfo."""+ if not path.exists():+ raise FileNotFoundError(f"Model file not found: {path}")+ if not path.suffix == ".json":+ raise ValueError(f"Expected .model3.json, got: {path.suffix}")++ with open(path, "r", encoding="utf-8") as f:+ data = json.load(f)++ refs = data.get("FileReferences", {})+ info = ModelInfo(+ path=path,+ version=data.get("Version", ""),+ moc3=refs.get("Moc", ""),+ textures=refs.get("Textures", []),+ physics=refs.get("Physics", ""),+ pose=refs.get("Pose", ""),+ userdata=refs.get("UserData", ""),+ display_info=refs.get("DisplayInfo", ""),+ )++ # Expressions+ for expr in refs.get("Expressions", []):+ info.expressions.append(ExpressionRef(+ name=expr.get("Name", ""),+ file=expr.get("File", ""),+ ))++ # Motions+ for group_name, motions in refs.get("Motions", {}).items():+ info.motions[group_name] = []+ for m in motions:+ extra = {k: v for k, v in m.items() if k not in ("File", "FadeInTime", "FadeOutTime")}+ info.motions[group_name].append(MotionRef(+ file=m.get("File", ""),+ fade_in=m.get("FadeInTime", 0),+ fade_out=m.get("FadeOutTime", 0),+ extra=extra,+ ))++ # Groups+ info.groups = data.get("Groups", [])++ return info+++def save_model(info: ModelInfo, path: Path | None = None) -> Path:+ """Write a ModelInfo back to a .model3.json file."""+ target = path or info.path+ if not target.exists():+ raise FileNotFoundError(f"Model file not found: {target}")++ with open(target, "r", encoding="utf-8") as f:+ data = json.load(f)++ refs = data.setdefault("FileReferences", {})++ refs["Moc"] = info.moc3+ refs["Textures"] = info.textures+ refs["Physics"] = info.physics+ refs["Pose"] = info.pose+ refs["UserData"] = info.userdata+ refs["DisplayInfo"] = info.display_info++ # Expressions+ refs["Expressions"] = [+ {"Name": e.name, "File": e.file} for e in info.expressions+ ]++ # Motions+ motions_out = {}+ for group_name, motion_list in info.motions.items():+ entries = []+ for m in motion_list:+ entry = {"File": m.file, "FadeInTime": m.fade_in, "FadeOutTime": m.fade_out}+ entry.update(m.extra) # preserve Sound, MetaInfo, etc.+ entries.append(entry)+ motions_out[group_name] = entries+ refs["Motions"] = motions_out++ # Groups+ if info.groups:+ data["Groups"] = info.groups++ fd, tmp_name = tempfile.mkstemp(+ prefix=f".{target.name}.",+ suffix=".tmp",+ dir=target.parent,+ )+ tmp_path = Path(tmp_name)+ try:+ os.chmod(tmp_path, target.stat().st_mode)+ with os.fdopen(fd, "w", encoding="utf-8") as f:+ json.dump(data, f, indent=2, ensure_ascii=False)+ f.write("\n")+ f.flush()+ os.fsync(f.fileno())+ os.replace(tmp_path, target)+ except Exception:+ tmp_path.unlink(missing_ok=True)+ raise++ return targetdiff --git a/live2d/agent-harness/cli_anything/live2d/core/physics_parser.py b/live2d/agent-harness/cli_anything/live2d/core/physics_parser.pynew file mode 100644index 000000000..b3c9ae5bc--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/core/physics_parser.py@@ -0,0 +1,143 @@+"""Parse Live2D .physics3.json files."""++import json+from pathlib import Path+from dataclasses import dataclass, field+++@dataclass+class PhysicsInput:+ target: str # "Parameter"+ id: str # e.g. "ParamAngleX"+ type: str # "X", "Y", "Angle"+ reflect: bool = False+++@dataclass+class PhysicsOutput:+ target: str # "Parameter"+ id: str # e.g. "ParamHairFrontX"+ type: str # "X", "Y", "Angle"+ reflect: bool = False+ scale: float = 1.0+ weight: float = 1.0+++@dataclass+class PhysicsVertex:+ position: dict = field(default_factory=dict) # {x, y}+ mobility: float = 0.0+ delay: float = 0.0+ acceleration: float = 0.0+ radius: float = 0.0+++@dataclass+class PhysicsSetting:+ id: str = ""+ input: list[PhysicsInput] = field(default_factory=list)+ output: list[PhysicsOutput] = field(default_factory=list)+ vertices: list[PhysicsVertex] = field(default_factory=list)+ normalization: dict = field(default_factory=dict)++ @property+ def input_params(self) -> list[str]:+ return [i.id for i in self.input]++ @property+ def output_params(self) -> list[str]:+ return [o.id for o in self.output]++ def to_dict(self) -> dict:+ return {+ "id": self.id,+ "input_count": len(self.input),+ "output_count": len(self.output),+ "vertex_count": len(self.vertices),+ "input_params": self.input_params,+ "output_params": self.output_params,+ "normalization": self.normalization,+ }+++@dataclass+class PhysicsInfo:+ path: Path+ version: int = 0+ settings: list[PhysicsSetting] = field(default_factory=list)++ @property+ def setting_count(self) -> int:+ return len(self.settings)++ @property+ def all_input_params(self) -> list[str]:+ params = set()+ for s in self.settings:+ params.update(s.input_params)+ return sorted(params)++ @property+ def all_output_params(self) -> list[str]:+ params = set()+ for s in self.settings:+ params.update(s.output_params)+ return sorted(params)++ def to_dict(self) -> dict:+ return {+ "file": str(self.path),+ "version": self.version,+ "setting_count": self.setting_count,+ "settings": [s.to_dict() for s in self.settings],+ "all_input_params": self.all_input_params,+ "all_output_params": self.all_output_params,+ }+++def load_physics(path: Path) -> PhysicsInfo:+ """Load and parse a .physics3.json file."""+ if not path.exists():+ raise FileNotFoundError(f"Physics file not found: {path}")++ with open(path, "r", encoding="utf-8") as f:+ data = json.load(f)++ info = PhysicsInfo(path=path, version=data.get("Version", 0))++ for setting_data in data.get("PhysicsSettings", []):+ setting = PhysicsSetting(+ id=setting_data.get("Id", ""),+ normalization=setting_data.get("Normalization", {}),+ )++ for inp in setting_data.get("Input", []):+ setting.input.append(PhysicsInput(+ target=inp.get("Target", ""),+ id=inp.get("Id", ""),+ type=inp.get("Type", ""),+ reflect=inp.get("Reflect", False),+ ))++ for out in setting_data.get("Output", []):+ setting.output.append(PhysicsOutput(+ target=out.get("Target", ""),+ id=out.get("Id", ""),+ type=out.get("Type", ""),+ reflect=out.get("Reflect", False),+ scale=out.get("Scale", 1.0),+ weight=out.get("Weight", 1.0),+ ))++ for vert in setting_data.get("Vertices", setting_data.get("Vertex", [])):+ setting.vertices.append(PhysicsVertex(+ position=vert.get("Position", {}),+ mobility=vert.get("Mobility", 0),+ delay=vert.get("Delay", 0),+ acceleration=vert.get("Acceleration", 0),+ radius=vert.get("Radius", 0),+ ))++ info.settings.append(setting)++ return infodiff --git a/live2d/agent-harness/cli_anything/live2d/core/scanner.py b/live2d/agent-harness/cli_anything/live2d/core/scanner.pynew file mode 100644index 000000000..45314cd0a--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/core/scanner.py@@ -0,0 +1,35 @@+"""Scan directories for Live2D models."""++from pathlib import Path+from typing import Optional++from .parser import ModelInfo, load_model+++def scan_directory(directory: Path, recursive: bool = True) -> list[ModelInfo]:+ """Find and parse all .model3.json files in a directory."""+ if not directory.exists():+ raise FileNotFoundError(f"Directory not found: {directory}")+ if not directory.is_dir():+ raise NotADirectoryError(f"Not a directory: {directory}")++ pattern = "**/*.model3.json" if recursive else "*.model3.json"+ model_files = sorted(directory.glob(pattern))++ models = []+ errors = []+ for mf in model_files:+ try:+ models.append(load_model(mf))+ except Exception as e:+ errors.append({"file": str(mf), "error": str(e)})++ return models+++def find_model_files(directory: Path, recursive: bool = True) -> list[Path]:+ """Find all .model3.json paths without parsing."""+ if not directory.exists():+ return []+ pattern = "**/*.model3.json" if recursive else "*.model3.json"+ return sorted(directory.glob(pattern))diff --git a/live2d/agent-harness/cli_anything/live2d/core/snapshot.py b/live2d/agent-harness/cli_anything/live2d/core/snapshot.pynew file mode 100644index 000000000..1963161b9--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/core/snapshot.py@@ -0,0 +1,151 @@+"""Generate HTML preview of a Live2D model."""++from pathlib import Path+import json+import base64+from datetime import datetime++from cli_anything.live2d.core.parser import ModelInfo+++def _texture_to_data_uri(tex_path: Path) -> str:+ """Convert a texture file to a base64 data URI for embedding."""+ if not tex_path.exists():+ return ""+ data = tex_path.read_bytes()+ b64 = base64.b64encode(data).decode()+ suffix = tex_path.suffix.lower()+ mime = {"png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "webp": "image/webp"}.get(suffix.lstrip("."), "image/png")+ return f"data:{mime};base64,{b64}"+++def generate_html(info: ModelInfo, embed_textures: bool = False) -> str:+ """Generate an HTML preview page for a Live2D model."""+ model_dir = info.path.parent+ textures = []+ for tex in info.textures:+ tex_path = model_dir / tex+ if embed_textures:+ src = _texture_to_data_uri(tex_path)+ else:+ src = str(tex_path.relative_to(model_dir)) if tex_path.exists() else ""+ textures.append({"path": tex, "src": src, "exists": tex_path.exists()})++ motions_html = ""+ for group, motions in info.motions.items():+ rows = ""+ for i, m in enumerate(motions):+ motion_path = model_dir / m.file+ exists = motion_path.exists()+ status = "✅" if exists else "❌"+ rows += f"<tr><td>{i}</td><td>{m.file}</td><td>{m.fade_in}s</td><td>{m.fade_out}s</td><td>{status}</td></tr>\n"+ motions_html += f"""+ <h3>[{group}] ({len(motions)} motions)</h3>+ <table>+ <tr><th>#</th><th>File</th><th>Fade In</th><th>Fade Out</th><th>Status</th></tr>+ {rows}+ </table>"""++ expr_html = ""+ if info.expressions:+ rows = ""+ for e in info.expressions:+ expr_path = model_dir / e.file+ exists = expr_path.exists()+ status = "✅" if exists else "❌"+ rows += f"<tr><td>{e.name}</td><td>{e.file}</td><td>{status}</td></tr>\n"+ expr_html = f"""+ <h3>Expressions ({len(info.expressions)})</h3>+ <table>+ <tr><th>Name</th><th>File</th><th>Status</th></tr>+ {rows}+ </table>"""++ tex_html = ""+ for t in textures:+ if t["exists"]:+ tex_html += f"""+ <div class="tex-card">+ <img src="{t['src']}" alt="{t['path']}" />+ <p>{t['path']}</p>+ </div>"""+ else:+ tex_html += f"""+ <div class="tex-card missing">+ <p>❌ {t['path']}</p>+ </div>"""++ html = f"""<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="UTF-8"/>+<meta name="viewport" content="width=device-width, initial-scale=1.0"/>+<title>Live2D Preview — {info.path.stem}</title>+<style>+ * {{ margin: 0; padding: 0; box-sizing: border-box; }}+ body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #1a1a2e; color: #eee; padding: 24px; }}+ h1 {{ font-size: 24px; margin-bottom: 8px; color: #e94560; }}+ .meta {{ color: #888; margin-bottom: 24px; font-size: 14px; }}+ .stats {{ display: flex; gap: 16px; margin-bottom: 24px; flex-wrap: wrap; }}+ .stat {{ background: #16213e; padding: 16px 24px; border-radius: 12px; text-align: center; min-width: 100px; }}+ .stat .num {{ font-size: 28px; font-weight: bold; color: #e94560; }}+ .stat .label {{ font-size: 12px; color: #888; margin-top: 4px; }}+ h2 {{ font-size: 18px; margin: 24px 0 12px; color: #0f3460; }}+ h2 {{ color: #e94560; }}+ h3 {{ font-size: 14px; margin: 12px 0 8px; color: #aaa; }}+ table {{ width: 100%; border-collapse: collapse; margin-bottom: 16px; font-size: 13px; }}+ th {{ background: #16213e; padding: 8px 12px; text-align: left; font-weight: 600; }}+ td {{ padding: 8px 12px; border-bottom: 1px solid #2a2a4a; }}+ tr:hover {{ background: #16213e; }}+ .tex-grid {{ display: flex; gap: 12px; flex-wrap: wrap; }}+ .tex-card {{ background: #16213e; border-radius: 8px; padding: 12px; text-align: center; }}+ .tex-card img {{ max-width: 200px; max-height: 200px; border-radius: 4px; }}+ .tex-card p {{ font-size: 12px; color: #888; margin-top: 8px; word-break: break-all; }}+ .tex-card.missing {{ border: 1px dashed #e94560; }}+ .badge {{ display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 12px; }}+ .badge.ok {{ background: #1b4332; color: #95d5b2; }}+ .badge.missing {{ background: #3d0000; color: #ff6b6b; }}+ footer {{ margin-top: 40px; padding-top: 16px; border-top: 1px solid #2a2a4a; color: #555; font-size: 12px; }}+</style>+</head>+<body>+ <h1>🎭 {info.path.stem}</h1>+ <div class="meta">+ {info.path.name} · Version {info.version or 'N/A'} · Generated {datetime.now().strftime('%Y-%m-%d %H:%M')}+ </div>++ <div class="stats">+ <div class="stat"><div class="num">{info.texture_count}</div><div class="label">Textures</div></div>+ <div class="stat"><div class="num">{info.motion_count}</div><div class="label">Motions</div></div>+ <div class="stat"><div class="num">{info.expression_count}</div><div class="label">Expressions</div></div>+ <div class="stat"><div class="num">{info.motion_group_count}</div><div class="label">Groups</div></div>+ </div>++ <div class="meta">+ Moc3: <span class="badge {'ok' if info.moc3 else 'missing'}">{info.moc3 or 'none'}</span>+ Physics: <span class="badge {'ok' if info.physics else 'missing'}">{info.physics or 'none'}</span>+ Pose: <span class="badge {'ok' if info.pose else 'missing'}">{info.pose or 'none'}</span>+ </div>++ <h2>🖼️ Textures</h2>+ <div class="tex-grid">{tex_html}</div>++ <h2>🎬 Motions</h2>+ {motions_html}++ <h2>😊 Expressions</h2>+ {expr_html if expr_html else '<p style="color:#888">No expressions defined.</p>'}++ <footer>+ Generated by cli-anything-live2d · {info.path}+ </footer>+</body>+</html>"""+ return html+++def write_snapshot(info: ModelInfo, out_path: Path, embed_textures: bool = False) -> Path:+ """Write HTML snapshot to file."""+ html = generate_html(info, embed_textures=embed_textures)+ out_path.write_text(html, encoding="utf-8")+ return out_pathdiff --git a/live2d/agent-harness/cli_anything/live2d/core/template.py b/live2d/agent-harness/cli_anything/live2d/core/template.pynew file mode 100644index 000000000..3ab77a8d9--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/core/template.py@@ -0,0 +1,97 @@+"""Generate a Live2D model template/skeleton."""++import json+from pathlib import Path+++def generate_template(name: str, output_dir: Path) -> Path:+ """Generate a minimal Live2D model skeleton.++ Creates:+ - <name>.model3.json (main descriptor)+ - <name>.moc3 (empty placeholder)+ - textures/ (empty dir)+ - motions/ (empty dir)+ - expressions/ (empty dir)+ - <name>.physics3.json (minimal physics)++ Returns the path to the model3.json file.+ """+ output_dir.mkdir(parents=True, exist_ok=True)++ # Model3.json+ model3 = {+ "Version": 3,+ "FileReferences": {+ "Moc": f"{name}.moc3",+ "Textures": [f"textures/texture_00.png"],+ "Physics": f"{name}.physics3.json",+ "Pose": "",+ "UserData": "",+ "Expressions": [],+ "Motions": {+ "Idle": [+ {+ "File": "motions/idle_01.motion3.json",+ "FadeInTime": 0.5,+ "FadeOutTime": 0.5,+ }+ ]+ },+ },+ "Groups": [+ {+ "Target": "Parameter",+ "Name": "EyeBlink",+ "Ids": "ParamEyeLOpen,ParamEyeROpen",+ },+ {+ "Target": "Parameter",+ "Name": "LipSync",+ "Ids": "ParamMouthOpenY",+ },+ ],+ }++ model3_path = output_dir / f"{name}.model3.json"+ model3_path.write_text(json.dumps(model3, indent=2, ensure_ascii=False), encoding="utf-8")++ # Minimal physics+ physics = {+ "Version": 3,+ "PhysicsSettings": [],+ }+ phys_path = output_dir / f"{name}.physics3.json"+ phys_path.write_text(json.dumps(physics, indent=2), encoding="utf-8")++ # Empty motion+ motion = {+ "Version": 3,+ "Meta": {+ "Duration": 2.0,+ "Fps": 30.0,+ "Loop": True,+ "AreBeziersRestricted": False,+ "CurveCount": 0,+ "TotalSegmentCount": 0,+ "TotalPointCount": 0,+ "UserDataCount": 0,+ "TotalUserDataSize": 0,+ },+ "Curves": [],+ }+ motions_dir = output_dir / "motions"+ motions_dir.mkdir(exist_ok=True)+ (motions_dir / "idle_01.motion3.json").write_text(+ json.dumps(motion, indent=2), encoding="utf-8"+ )++ # Empty directories+ (output_dir / "textures").mkdir(exist_ok=True)+ (output_dir / "expressions").mkdir(exist_ok=True)++ # Placeholder moc3 (empty file with just the header)+ moc3_path = output_dir / f"{name}.moc3"+ moc3_path.write_bytes(b"MOC3\x03\x00\x00\x00")++ return model3_pathdiff --git a/live2d/agent-harness/cli_anything/live2d/core/texture_info.py b/live2d/agent-harness/cli_anything/live2d/core/texture_info.pynew file mode 100644index 000000000..763e253ed--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/core/texture_info.py@@ -0,0 +1,115 @@+"""Get texture image dimensions and metadata."""++from pathlib import Path+from dataclasses import dataclass+++@dataclass+class TextureInfo:+ path: Path+ width: int = 0+ height: int = 0+ size_bytes: int = 0+ format: str = ""++ @property+ def megapixels(self) -> float:+ return (self.width * self.height) / 1_000_000++ @property+ def size_display(self) -> str:+ s = self.size_bytes+ if s < 1024:+ return f"{s}B"+ elif s < 1024 * 1024:+ return f"{s / 1024:.1f}KB"+ else:+ return f"{s / (1024*1024):.1f}MB"++ def to_dict(self) -> dict:+ return {+ "file": str(self.path),+ "width": self.width,+ "height": self.height,+ "size_bytes": self.size_bytes,+ "size_display": self.size_display,+ "format": self.format,+ "megapixels": round(self.megapixels, 2),+ }+++def get_texture_info(path: Path) -> TextureInfo:+ """Get texture dimensions and metadata."""+ info = TextureInfo(path=path)++ if not path.exists():+ return info++ info.size_bytes = path.stat().st_size+ info.format = path.suffix.lower().lstrip(".")++ # Try PIL for dimensions+ try:+ from PIL import Image+ with Image.open(path) as img:+ info.width, info.height = img.size+ except ImportError:+ # Fallback: read PNG/JPEG headers directly+ _read_dimensions_fallback(path, info)+ except Exception:+ # Pillow found the file but can't identify it (corrupt/placeholder)+ _read_dimensions_fallback(path, info)++ return info+++def _read_dimensions_fallback(path: Path, info: TextureInfo):+ """Read image dimensions from file headers without PIL."""+ try:+ with open(path, "rb") as f:+ header = f.read(32)++ # PNG+ if header[:8] == b'\x89PNG\r\n\x1a\n':+ info.width = int.from_bytes(header[16:20], 'big')+ info.height = int.from_bytes(header[20:24], 'big')+ info.format = "png"++ # JPEG+ elif header[:2] == b'\xff\xd8':+ f.seek(0)+ data = f.read()+ i = 2+ while i < len(data) - 1:+ if data[i] == 0xFF:+ marker = data[i + 1]+ if marker in (0xC0, 0xC1, 0xC2):+ info.height = int.from_bytes(data[i + 5:i + 7], 'big')+ info.width = int.from_bytes(data[i + 7:i + 9], 'big')+ info.format = "jpeg"+ break+ elif marker == 0xD9:+ break+ else:+ length = int.from_bytes(data[i + 2:i + 4], 'big')+ i += 2 + length+ else:+ i += 1++ # WebP+ elif header[:4] == b'RIFF' and header[8:12] == b'WEBP':+ if header[12:16] == b'VP8 ':+ f.seek(26)+ dims = f.read(4)+ info.width = int.from_bytes(dims[:2], 'little') & 0x3FFF+ info.height = int.from_bytes(dims[2:4], 'little') & 0x3FFF+ info.format = "webp"+ elif header[12:16] == b'VP8L':+ f.seek(25)+ bits = int.from_bytes(f.read(4), 'little')+ info.width = (bits & 0x3FFF) + 1+ info.height = ((bits >> 14) & 0x3FFF) + 1+ info.format = "webp"++ except Exception:+ passdiff --git a/live2d/agent-harness/cli_anything/live2d/core/validator.py b/live2d/agent-harness/cli_anything/live2d/core/validator.pynew file mode 100644index 000000000..508b9675d--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/core/validator.py@@ -0,0 +1,107 @@+"""Validate Live2D model file integrity."""++from pathlib import Path+from dataclasses import dataclass, field+from typing import Optional++from .parser import ModelInfo+from .moc3_parser import load_moc3+++DEFAULT_MIN_MOC3_SIZE = 1024+++@dataclass+class ValidationResult:+ model_path: Path+ checked: int = 0+ errors: list[str] = field(default_factory=list)+ warnings: list[str] = field(default_factory=list)++ @property+ def ok(self) -> bool:+ return len(self.errors) == 0++ def to_dict(self) -> dict:+ return {+ "model": str(self.model_path),+ "ok": self.ok,+ "checked": self.checked,+ "errors": self.errors,+ "warnings": self.warnings,+ }+++def validate_model(+ info: ModelInfo,+ strict: bool = False,+ min_moc3_size: int = DEFAULT_MIN_MOC3_SIZE,+) -> ValidationResult:+ """Check that all referenced files exist.++ Strict mode adds production-export checks so template placeholders do not+ accidentally pass as usable Live2D runtime assets.+ """+ result = ValidationResult(model_path=info.path)+ model_dir = info.path.parent++ def check(rel_path: str, label: str) -> Optional[Path]:+ if not rel_path:+ return None+ result.checked += 1+ full = model_dir / rel_path+ if not full.exists():+ result.errors.append(f"Missing {label}: {rel_path}")+ return None+ return full++ # Moc3+ moc3_path = check(info.moc3, "Moc3")+ if moc3_path and strict:+ moc3 = load_moc3(moc3_path)+ if not moc3.valid:+ result.errors.append(f"Invalid Moc3 header: {info.moc3}")+ elif moc3.file_size < min_moc3_size:+ result.errors.append(+ f"Moc3 too small: {info.moc3} ({moc3.file_size}B, minimum {min_moc3_size}B)"+ )++ # Textures+ for tex in info.textures:+ tex_path = check(tex, "Texture")+ if strict and tex_path and tex_path.stat().st_size == 0:+ result.errors.append(f"Empty Texture: {tex}")++ # Physics / Pose / UserData+ check(info.physics, "Physics")+ check(info.pose, "Pose")+ check(info.userdata, "UserData")+ check(info.display_info, "DisplayInfo")++ # Expressions+ for expr in info.expressions:+ check(expr.file, f"Expression[{expr.name}]")++ # Motions+ for group, motions in info.motions.items():+ for m in motions:+ check(m.file, f"Motion[{group}]")++ # Warnings+ if not info.moc3:+ if strict:+ result.errors.append("No Moc3 file specified")+ else:+ result.warnings.append("No Moc3 file specified")+ if not info.textures:+ if strict:+ result.errors.append("No textures specified")+ else:+ result.warnings.append("No textures specified")++ return result+++def validate_all(infos: list[ModelInfo], strict: bool = False) -> list[ValidationResult]:+ """Validate multiple models."""+ return [validate_model(info, strict=strict) for info in infos]diff --git a/live2d/agent-harness/cli_anything/live2d/core/yoyo_pipeline.py b/live2d/agent-harness/cli_anything/live2d/core/yoyo_pipeline.pynew file mode 100644index 000000000..2bb506358--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/core/yoyo_pipeline.py@@ -0,0 +1,72 @@+"""Yoyo-specific Live2D export checks."""++from dataclasses import dataclass, field+from pathlib import Path++from .parser import ModelInfo, load_model+from .validator import ValidationResult, validate_model+++DEFAULT_REQUIRED_MOTION_GROUPS = ("idle",)+++@dataclass+class YoyoExportReport:+ model: ModelInfo+ validation: ValidationResult+ required_motion_groups: tuple[str, ...] = DEFAULT_REQUIRED_MOTION_GROUPS+ errors: list[str] = field(default_factory=list)+ warnings: list[str] = field(default_factory=list)++ @property+ def ok(self) -> bool:+ return not self.errors++ @property+ def summary(self) -> dict:+ return {+ "model_file": str(self.model.path),+ "moc3": self.model.moc3,+ "texture_count": self.model.texture_count,+ "motion_count": self.model.motion_count,+ "motion_groups": sorted(self.model.motions.keys()),+ "expression_count": self.model.expression_count,+ }++ def to_dict(self) -> dict:+ return {+ "ok": self.ok,+ "summary": self.summary,+ "required_motion_groups": list(self.required_motion_groups),+ "errors": self.errors,+ "warnings": self.warnings,+ "validation": self.validation.to_dict(),+ }+++def check_yoyo_export(+ model_path: Path,+ required_motion_groups: tuple[str, ...] = DEFAULT_REQUIRED_MOTION_GROUPS,+) -> YoyoExportReport:+ """Validate a Live2D export against the minimum Yoyo desktop-pet contract."""+ info = load_model(model_path)+ validation = validate_model(info, strict=True)+ errors = list(validation.errors)+ warnings = list(validation.warnings)++ available_groups = {name.strip().lower() for name in info.motions}+ for group in required_motion_groups:+ normalized = group.strip().lower()+ if normalized and normalized not in available_groups:+ errors.append(f"Missing required motion group: {normalized}")++ if info.expression_count == 0:+ warnings.append("No expressions found; Yoyo can run, but interactions will feel flat")++ return YoyoExportReport(+ model=info,+ validation=validation,+ required_motion_groups=required_motion_groups,+ errors=errors,+ warnings=warnings,+ )diff --git a/live2d/agent-harness/cli_anything/live2d/live2d_cli.py b/live2d/agent-harness/cli_anything/live2d/live2d_cli.pynew file mode 100644index 000000000..4fc9e33af--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/live2d_cli.py@@ -0,0 +1,2047 @@+#!/usr/bin/env python3+"""Live2D Cubism CLI — inspect, validate, and manage Live2D models.++Usage:+ cli-anything-live2d inspect model.model3.json+ cli-anything-live2d validate model.model3.json+ cli-anything-live2d motions model.model3.json+ cli-anything-live2d motion-info motions/idle.motion3.json+ cli-anything-live2d expressions model.model3.json+ cli-anything-live2d expr-info expressions/happy.exp3.json+ cli-anything-live2d textures model.model3.json+ cli-anything-live2d physics model.model3.json+ cli-anything-live2d moc3 model.moc3+ cli-anything-live2d deps model.model3.json+ cli-anything-live2d compare modelA.model3.json modelB.model3.json+ cli-anything-live2d pack model.model3.json -o output.zip+ cli-anything-live2d yoyo-check model.model3.json+ cli-anything-live2d init my-character+ cli-anything-live2d scan ./models/+ cli-anything-live2d export model.model3.json --format json+ cli-anything-live2d params model.model3.json+"""++import json+import os+import sys+from pathlib import Path+from typing import Optional++import click++from cli_anything.live2d.core.parser import load_model, save_model, ModelInfo, MotionRef, ExpressionRef+from cli_anything.live2d.core.backup import auto_backup, snapshot, list_backups, restore+from cli_anything.live2d.core.linter import lint_model+from cli_anything.live2d.core.differ import diff_models+from cli_anything.live2d.core.snapshot import write_snapshot+from cli_anything.live2d.core.validator import validate_model, validate_all+from cli_anything.live2d.core.scanner import scan_directory+from cli_anything.live2d.core.motion_parser import load_motion+from cli_anything.live2d.core.expression_parser import load_expression+from cli_anything.live2d.core.texture_info import get_texture_info+from cli_anything.live2d.core.physics_parser import load_physics+from cli_anything.live2d.core.moc3_parser import load_moc3+from cli_anything.live2d.core.comparer import compare_models+from cli_anything.live2d.core.dependency import build_dependency_graph+from cli_anything.live2d.core.packager import package_model+from cli_anything.live2d.core.template import generate_template+from cli_anything.live2d.core.yoyo_pipeline import check_yoyo_export++# Global state+_json_output = False+++def output(data, message: str = ""):+ """Print output in human or JSON format."""+ if _json_output:+ click.echo(json.dumps(data, indent=2, ensure_ascii=False, default=str))+ else:+ if message:+ click.echo(message)+ if isinstance(data, dict):+ _print_dict(data)+ elif isinstance(data, list):+ _print_list(data)+ else:+ click.echo(str(data))+++def _print_dict(d: dict, indent: int = 0):+ prefix = " " * indent+ for k, v in d.items():+ if isinstance(v, dict):+ click.echo(f"{prefix}{k}:")+ _print_dict(v, indent + 1)+ elif isinstance(v, list):+ click.echo(f"{prefix}{k}:")+ _print_list(v, indent + 1)+ else:+ click.echo(f"{prefix}{k}: {v}")+++def _print_list(items: list, indent: int = 0):+ prefix = " " * indent+ for i, item in enumerate(items):+ if isinstance(item, dict):+ click.echo(f"{prefix}[{i}]")+ _print_dict(item, indent + 1)+ else:+ click.echo(f"{prefix}- {item}")+++def handle_error(func):+ """Decorator for consistent error handling."""+ import functools+ @functools.wraps(func)+ def wrapper(*args, **kwargs):+ try:+ return func(*args, **kwargs)+ except FileNotFoundError as e:+ if _json_output:+ click.echo(json.dumps({"error": str(e), "type": "file_not_found"}))+ else:+ click.echo(f"Error: {e}", err=True)+ sys.exit(1)+ except (ValueError, IndexError) as e:+ if _json_output:+ click.echo(json.dumps({"error": str(e), "type": type(e).__name__}))+ else:+ click.echo(f"Error: {e}", err=True)+ sys.exit(1)+ return wrapper+++# ── Main CLI ────────────────────────────────────────────────────+[email protected]("--json", "use_json", is_flag=True, help="Output as JSON")[email protected]_option(version="0.3.0", prog_name="cli-anything-live2d")+def cli(use_json: bool):+ """Live2D Cubism CLI — inspect, validate, and manage Live2D models."""+ global _json_output+ _json_output = use_json+++def main():+ cli()+++# ── inspect ─────────────────────────────────────────────────────+[email protected]("model_path", type=click.Path(exists=True))+@handle_error+def inspect(model_path: str):+ """Inspect a Live2D model (.model3.json)."""+ info = load_model(Path(model_path))++ data = {+ "model_file": str(info.path),+ "version": info.version,+ "moc3": info.moc3,+ "textures": info.texture_count,+ "motions_total": info.motion_count,+ "motion_groups": info.motion_group_count,+ "expressions": info.expression_count,+ "physics": bool(info.physics),+ "pose": bool(info.pose),+ "userdata": bool(info.userdata),+ }++ if _json_output:+ output(data)+ return++ click.echo(f"\n 🎭 Live2D Model Inspector\n")+ click.echo(f" File: {info.path.name}")+ click.echo(f" Version: {info.version or 'N/A'}")+ click.echo(f" Moc3: {info.moc3}")+ click.echo(f" Textures: {info.texture_count}")+ click.echo(f" Motions: {info.motion_count} ({info.motion_group_count} groups)")+ click.echo(f" Expressions: {info.expression_count}")+ click.echo(f" Physics: {'✅' if info.physics else '❌'}")+ click.echo(f" Pose: {'✅' if info.pose else '❌'}")+ click.echo(f" UserData: {'✅' if info.userdata else '❌'}")+ click.echo()+++# ── validate ────────────────────────────────────────────────────+[email protected]("model_path", type=click.Path(exists=True))[email protected]("--verbose", "-v", is_flag=True, help="Show all checks")[email protected]("--strict", is_flag=True, help="Reject placeholder or incomplete production exports")[email protected]("--min-moc3-size", default=1024, show_default=True, help="Minimum .moc3 size in strict mode")+@handle_error+def validate(model_path: str, verbose: bool, strict: bool, min_moc3_size: int):+ """Validate a Live2D model — check all referenced files exist."""+ info = load_model(Path(model_path))+ result = validate_model(info, strict=strict, min_moc3_size=min_moc3_size)++ if _json_output:+ output(result.to_dict())+ if not result.ok:+ sys.exit(1)+ return++ click.echo(f"\n 🔍 Validation: {info.path.name}\n")+ if strict:+ click.echo(f" Mode: strict")+ click.echo(f" Files checked: {result.checked}")++ if result.errors:+ click.echo(f" Errors: {len(result.errors)}\n")+ for e in result.errors:+ click.echo(f" ❌ {e}")+ sys.exit(1)+ else:+ click.echo(f" ✅ All files present!")++ if result.warnings:+ for w in result.warnings:+ click.echo(f" ⚠️ {w}")+ click.echo()+++# ── motions ─────────────────────────────────────────────────────+[email protected]("model_path", type=click.Path(exists=True))[email protected]("--group", "-g", help="Filter by motion group")+@handle_error+def motions(model_path: str, group: Optional[str]):+ """List all motions in a Live2D model."""+ info = load_model(Path(model_path))++ if _json_output:+ data = {}+ for g, ms in info.motions.items():+ if group and g != group:+ continue+ data[g] = [{"file": m.file, "fade_in": m.fade_in, "fade_out": m.fade_out} for m in ms]+ output(data)+ return++ click.echo(f"\n 🎬 Motions: {info.path.name}\n")+ for group_name, items in info.motions.items():+ if group and group != group_name:+ continue+ click.echo(f" [{group_name}] ({len(items)} motions)")+ for i, m in enumerate(items):+ click.echo(f" {i}. {m.file} (fade: {m.fade_in}s / {m.fade_out}s)")+ click.echo()+++# ── motion-info ─────────────────────────────────────────────────+[email protected](name="motion-info")[email protected]("motion_path", type=click.Path(exists=True))+@handle_error+def motion_info_cmd(motion_path: str):+ """Detailed analysis of a .motion3.json file."""+ info = load_motion(Path(motion_path))++ if _json_output:+ output(info.to_dict())+ return++ click.echo(f"\n 🎬 Motion Analysis: {info.path.name}\n")+ click.echo(f" Version: {info.version}")+ click.echo(f" Duration: {info.duration}s")+ click.echo(f" FPS: {info.fps}")+ click.echo(f" Loop: {'Yes' if info.loop else 'No'}")+ click.echo(f" Curves: {info.curve_count}")+ click.echo(f" Segments: {info.total_segment_count}")+ click.echo(f" Points: {info.total_point_count}")+ click.echo()++ if info.parameter_curves:+ click.echo(f" Parameters ({len(info.parameter_curves)}):")+ for c in info.parameter_curves:+ click.echo(f" - {c.id} ({c.keyframe_count} keyframes)")+ click.echo()++ if info.part_curves:+ click.echo(f" Parts ({len(info.part_curves)}):")+ for c in info.part_curves:+ click.echo(f" - {c.id} ({c.keyframe_count} keyframes)")+ click.echo()+++# ── expressions ─────────────────────────────────────────────────+[email protected]("model_path", type=click.Path(exists=True))+@handle_error+def expressions(model_path: str):+ """List all expressions in a Live2D model."""+ info = load_model(Path(model_path))++ if _json_output:+ output([{"name": e.name, "file": e.file} for e in info.expressions])+ return++ click.echo(f"\n 😊 Expressions: {info.path.name}\n")+ if not info.expressions:+ click.echo(" (none)")+ return+ for i, expr in enumerate(info.expressions):+ click.echo(f" {i}. {expr.name} → {expr.file}")+ click.echo()+++# ── expr-info ───────────────────────────────────────────────────+[email protected](name="expr-info")[email protected]("expression_path", type=click.Path(exists=True))+@handle_error+def expr_info_cmd(expression_path: str):+ """Detailed analysis of a .exp3.json file."""+ info = load_expression(Path(expression_path))++ if _json_output:+ output(info.to_dict())+ return++ click.echo(f"\n 😊 Expression Analysis: {info.path.name}\n")+ click.echo(f" Version: {info.version}")+ click.echo(f" Fade In: {info.fade_in}s")+ click.echo(f" Fade Out: {info.fade_out}s")+ click.echo(f" Params: {info.param_count}\n")++ if info.params:+ click.echo(f" {'Parameter':<30} {'Value':>8}")+ click.echo(f" {'─' * 30} {'─' * 8}")+ for p in info.params:+ click.echo(f" {p.id:<30} {p.value:>8.2f}")+ click.echo()+++# ── textures ────────────────────────────────────────────────────+[email protected]("model_path", type=click.Path(exists=True))+@handle_error+def textures(model_path: str):+ """List all textures with dimensions and sizes."""+ info = load_model(Path(model_path))+ model_dir = info.path.parent++ if _json_output:+ data = []+ for tex in info.textures:+ data.append(get_texture_info(model_dir / tex).to_dict())+ output(data)+ return++ click.echo(f"\n 🖼️ Textures: {info.path.name}\n")+ for i, tex in enumerate(info.textures):+ tinfo = get_texture_info(model_dir / tex)+ if tinfo.width > 0:+ click.echo(f" ✅ {i}. {tex}")+ click.echo(f" {tinfo.width}×{tinfo.height} {tinfo.size_display} ({tinfo.format})")+ else:+ click.echo(f" ❌ {i}. {tex} (MISSING)")+ click.echo()+++# ── physics ─────────────────────────────────────────────────────+[email protected]("physics_path", type=click.Path(exists=True))+@handle_error+def physics(physics_path: str):+ """Show physics simulation configuration."""+ info = load_physics(Path(physics_path))++ if _json_output:+ output(info.to_dict())+ return++ click.echo(f"\n ⚡ Physics: {info.path.name}\n")+ click.echo(f" Version: {info.version}")+ click.echo(f" Settings: {info.setting_count}\n")++ for s in info.settings:+ click.echo(f" [{s.id}]")+ click.echo(f" Inputs: {', '.join(s.input_params)}")+ click.echo(f" Outputs: {', '.join(s.output_params)}")+ click.echo(f" Vertices: {len(s.vertices)}")+ if s.normalization:+ click.echo(f" Normalization:")+ for k, v in s.normalization.items():+ click.echo(f" {k}: min={v.get('Minimum')}, default={v.get('Default')}, max={v.get('Maximum')}")+ click.echo()++ if info.all_input_params:+ click.echo(f" All input params: {', '.join(info.all_input_params)}")+ if info.all_output_params:+ click.echo(f" All output params: {', '.join(info.all_output_params)}")+ click.echo()+++# ── moc3 ────────────────────────────────────────────────────────+[email protected]("moc3_path", type=click.Path(exists=True))+@handle_error+def moc3(moc3_path: str):+ """Show .moc3 binary file info."""+ info = load_moc3(Path(moc3_path))++ if _json_output:+ output(info.to_dict())+ return++ click.echo(f"\n 🔧 Moc3 Info: {info.path.name}\n")+ click.echo(f" Valid: {'✅' if info.valid else '❌'}")+ click.echo(f" Version: {info.version}")+ click.echo(f" Size: {info._size_display()}")+ click.echo()+++# ── params ──────────────────────────────────────────────────────+[email protected]("model_path", type=click.Path(exists=True))+@handle_error+def params(model_path: str):+ """Show model parameter groups (from model3.json)."""+ info = load_model(Path(model_path))++ if _json_output:+ output(info.groups)+ return++ click.echo(f"\n ⚙️ Parameters: {info.path.name}\n")+ if info.groups:+ for g in info.groups:+ target = g.get("Target", "")+ name = g.get("Name", "")+ ids = g.get("Ids", "")+ if isinstance(ids, list):+ ids = ", ".join(ids)+ click.echo(f" Group: {name} Target: {target} Ids: {ids}")+ else:+ click.echo(" (no parameter groups defined in model3.json)")+ click.echo()+++# ── deps ────────────────────────────────────────────────────────+[email protected]("model_path", type=click.Path(exists=True))+@handle_error+def deps(model_path: str):+ """Show dependency graph: which motions/expressions use which parameters."""+ info = load_model(Path(model_path))+ graph = build_dependency_graph(info)++ if _json_output:+ output(graph.to_dict())+ return++ click.echo(f"\n 🔗 Dependency Graph: {info.path.name}\n")+ click.echo(f" Parameters: {graph.param_count}")+ if graph.parse_errors:+ click.echo(f" Parse errors: {len(graph.parse_errors)}")+ click.echo()++ for pid, usage in sorted(graph.params.items(), key=lambda x: -x[1].total_references):+ click.echo(f" {pid} (refs: {usage.total_references})")+ if usage.motions:+ for m in usage.motions[:3]:+ click.echo(f" 📹 {m}")+ if len(usage.motions) > 3:+ click.echo(f" ... +{len(usage.motions) - 3} more")+ if usage.expressions:+ for e in usage.expressions:+ click.echo(f" 😊 {e}")+ click.echo()++ if graph.parse_errors:+ click.echo(f" ⚠️ Parse errors:")+ for err in graph.parse_errors:+ click.echo(f" {err['file']}: {err['error']}")+ click.echo()+++# ── compare ─────────────────────────────────────────────────────+[email protected]("model_a", type=click.Path(exists=True))[email protected]("model_b", type=click.Path(exists=True))+@handle_error+def compare(model_a: str, model_b: str):+ """Compare two Live2D models."""+ info_a = load_model(Path(model_a))+ info_b = load_model(Path(model_b))+ diff = compare_models(info_a, info_b)++ if _json_output:+ output(diff.to_dict())+ return++ click.echo(f"\n 🔀 Model Comparison\n")+ click.echo(f" A: {info_a.path.name}")+ click.echo(f" B: {info_b.path.name}\n")++ if not diff.has_changes:+ click.echo(" ✅ Models are identical!")+ click.echo()+ return++ click.echo(f" Added: {len(diff.added)}")+ click.echo(f" Removed: {len(diff.removed)}")+ click.echo(f" Changed: {len(diff.changed)}")+ click.echo()++ if diff.added:+ click.echo(" ➕ Added:")+ for item in diff.added:+ click.echo(f" [{item.category}] {item.name}")+ click.echo()++ if diff.removed:+ click.echo(" ➖ Removed:")+ for item in diff.removed:+ click.echo(f" [{item.category}] {item.name}")+ click.echo()++ if diff.changed:+ click.echo(" 🔄 Changed:")+ for item in diff.changed:+ click.echo(f" [{item.category}] {item.name}: {item.detail}")+ click.echo()+++# ── pack ────────────────────────────────────────────────────────+[email protected]("model_path", type=click.Path(exists=True))[email protected]("--out", "-o", type=click.Path(), default=None, help="Output zip path")[email protected]("--no-motions", is_flag=True, help="Exclude motions")[email protected]("--no-expressions", is_flag=True, help="Exclude expressions")+@handle_error+def pack(model_path: str, out: Optional[str], no_motions: bool, no_expressions: bool):+ """Package a model and all dependencies into a zip."""+ info = load_model(Path(model_path))++ if out is None:+ out = str(info.path.with_suffix(".zip"))++ result = package_model(+ info,+ Path(out),+ include_motions=not no_motions,+ include_expressions=not no_expressions,+ )++ if _json_output:+ output(result.to_dict())+ return++ click.echo(f"\n 📦 Package: {result.output_path.name}\n")+ click.echo(f" Files: {result.files_count}")+ click.echo(f" Size: {result._size_display()}")++ if result.missing_files:+ click.echo(f"\n ⚠️ Missing ({len(result.missing_files)}):")+ for f in result.missing_files:+ click.echo(f" - {f}")+ click.echo()+++# ── init ────────────────────────────────────────────────────────+[email protected](name="yoyo-check")[email protected]("model_path", type=click.Path(exists=True))+ "--require-motion",+ multiple=True,+ default=("idle",),+ show_default=True,+ help="Motion group required by the Yoyo desktop-pet runtime",+)+@handle_error+def yoyo_check(model_path: str, require_motion: tuple[str, ...]):+ """Check whether a Live2D export is ready for the Yoyo desktop pet."""+ report = check_yoyo_export(Path(model_path), required_motion_groups=require_motion)++ if _json_output:+ output(report.to_dict())+ if not report.ok:+ sys.exit(1)+ return++ click.echo(f"\n 🧪 Yoyo Live2D export check\n")+ click.echo(f" Model: {report.summary['model_file']}")+ click.echo(f" Moc3: {report.summary['moc3']}")+ click.echo(f" Textures: {report.summary['texture_count']}")+ click.echo(f" Motions: {report.summary['motion_count']} ({', '.join(report.summary['motion_groups']) or 'none'})")+ click.echo(f" Expressions: {report.summary['expression_count']}")++ if report.errors:+ click.echo(f"\n Errors: {len(report.errors)}")+ for error in report.errors:+ click.echo(f" ❌ {error}")+ sys.exit(1)++ if report.warnings:+ click.echo(f"\n Warnings: {len(report.warnings)}")+ for warning in report.warnings:+ click.echo(f" ⚠️ {warning}")++ click.echo(f"\n ✅ Ready for Yoyo desktop-pet integration\n")++[email protected]("name")[email protected]("--dir", "-d", type=click.Path(), default=".", help="Output directory")+@handle_error+def init(name: str, dir: str):+ """Generate a Live2D model template/skeleton."""+ output_dir = Path(dir) / name+ model_path = generate_template(name, output_dir)++ if _json_output:+ output({+ "name": name,+ "directory": str(output_dir),+ "model_file": str(model_path),+ "files": [str(f.relative_to(output_dir)) for f in sorted(output_dir.rglob("*")) if f.is_file()],+ })+ return++ click.echo(f"\n 🆕 Template: {name}\n")+ click.echo(f" Directory: {output_dir}")+ click.echo(f" Files:")+ for f in sorted(output_dir.rglob("*")):+ if f.is_file():+ click.echo(f" {f.relative_to(output_dir)}")+ click.echo()+ click.echo(f" Edit {model_path.name} to start building your model!")+ click.echo()+++# ── scan ────────────────────────────────────────────────────────+[email protected]("directory", type=click.Path(exists=True))[email protected]("--validate", "-v", "do_validate", is_flag=True, help="Also validate each model")+@handle_error+def scan(directory: str, do_validate: bool):+ """Scan a directory for all Live2D models."""+ d = Path(directory)+ models = scan_directory(d)++ if _json_output:+ data = [m.to_dict() for m in models]+ if do_validate:+ results = validate_all(models)+ for i, r in enumerate(results):+ data[i]["validation"] = r.to_dict()+ output(data)+ return++ click.echo(f"\n 🔎 Scanning: {d}\n")+ if not models:+ click.echo(" No .model3.json files found.")+ return++ click.echo(f" Found {len(models)} model(s):\n")+ for m in models:+ rel = m.path.relative_to(d)+ click.echo(f" 🎭 {rel}")+ click.echo(f" Textures: {m.texture_count} Motions: {m.motion_count} Expressions: {m.expression_count}")++ if do_validate:+ r = validate_model(m)+ if r.errors:+ click.echo(f" ⚠️ {len(r.errors)} missing files")+ else:+ click.echo(f" ✅ All files present")+ click.echo()+++# ── export ──────────────────────────────────────────────────────+[email protected](name="export")[email protected]("model_path", type=click.Path(exists=True))[email protected]("--format", "fmt", type=click.Choice(["json", "csv"]), default="json")[email protected]("--out", "-o", type=click.Path(), help="Output file path")+@handle_error+def export_cmd(model_path: str, fmt: str, out: Optional[str]):+ """Export model summary as JSON or CSV."""+ info = load_model(Path(model_path))++ if fmt == "json":+ text = json.dumps(info.to_dict(), indent=2, ensure_ascii=False)+ elif fmt == "csv":+ lines = ["type,group,name,file"]+ for tex in info.textures:+ lines.append(f"texture,,,{tex}")+ for expr in info.expressions:+ lines.append(f"expression,,{expr.name},{expr.file}")+ for group, motions in info.motions.items():+ for m in motions:+ fname = Path(m.file).stem+ lines.append(f"motion,{group},{fname},{m.file}")+ text = "\n".join(lines)++ if out:+ Path(out).write_text(text, encoding="utf-8")+ click.echo(f" ✅ Exported to {out}")+ else:+ click.echo(text)+++# ── edit-motion ────────────────────────────────────────────────+[email protected](name="edit-motion")[email protected]("model_path", type=click.Path(exists=True))[email protected]("--group", "-g", required=True, help="Motion group name")[email protected]("--index", "-i", type=int, required=True, help="Motion index in group (0-based)")[email protected]("--fade-in", type=float, help="New fade-in time (seconds)")[email protected]("--fade-out", type=float, help="New fade-out time (seconds)")[email protected]("--file", "new_file", help="Replace motion file path")+@handle_error+def edit_motion(model_path: str, group: str, index: int, fade_in: Optional[float], fade_out: Optional[float], new_file: Optional[str]):+ """Edit a motion's fade times or file path."""+ p = Path(model_path)+ auto_backup(p)+ info = load_model(p)++ if group not in info.motions:+ raise ValueError(f"Group '{group}' not found. Available: {list(info.motions.keys())}")++ motions = info.motions[group]+ if index < 0 or index >= len(motions):+ raise ValueError(f"Index {index} out of range. Group '{group}' has {len(motions)} motions (0-{len(motions)-1})")++ motion = motions[index]+ changes = []+ if fade_in is not None:+ motion.fade_in = fade_in+ changes.append(f"fade_in={fade_in}")+ if fade_out is not None:+ motion.fade_out = fade_out+ changes.append(f"fade_out={fade_out}")+ if new_file is not None:+ motion.file = new_file+ changes.append(f"file={new_file}")++ if not changes:+ click.echo(" Nothing to change. Use --fade-in, --fade-out, or --file.")+ return++ save_model(info)+ click.echo(f" ✅ [{group}][{index}] {motion.file}")+ for c in changes:+ click.echo(f" {c}")+ click.echo()+++# ── add-motion ─────────────────────────────────────────────────+[email protected](name="add-motion")[email protected]("model_path", type=click.Path(exists=True))[email protected]("--group", "-g", required=True, help="Motion group name")[email protected]("--file", "motion_file", required=True, help="Motion file path")[email protected]("--fade-in", type=float, default=0.5, show_default=True)[email protected]("--fade-out", type=float, default=0.5, show_default=True)+@handle_error+def add_motion(model_path: str, group: str, motion_file: str, fade_in: float, fade_out: float):+ """Add a motion to a group (creates group if needed)."""+ p = Path(model_path)+ auto_backup(p)+ info = load_model(p)++ if group not in info.motions:+ info.motions[group] = []++ info.motions[group].append(MotionRef(file=motion_file, fade_in=fade_in, fade_out=fade_out))+ save_model(info)+ click.echo(f" ✅ Added to [{group}] (now {len(info.motions[group])} motions)")+ click.echo(f" {motion_file} (fade: {fade_in}s / {fade_out}s)")+ click.echo()+++# ── rm-motion ──────────────────────────────────────────────────+[email protected](name="rm-motion")[email protected]("model_path", type=click.Path(exists=True))[email protected]("--group", "-g", required=True, help="Motion group name")[email protected]("--index", "-i", type=int, required=True, help="Motion index to remove")[email protected]_option(prompt="Are you sure?")+@handle_error+def rm_motion(model_path: str, group: str, index: int):+ """Remove a motion from a group."""+ p = Path(model_path)+ auto_backup(p)+ info = load_model(p)++ if group not in info.motions:+ raise ValueError(f"Group '{group}' not found.")++ motions = info.motions[group]+ if index < 0 or index >= len(motions):+ raise ValueError(f"Index {index} out of range (0-{len(motions)-1})")++ removed = motions.pop(index)+ if not motions:+ del info.motions[group]++ save_model(info)+ click.echo(f" ✅ Removed [{group}][{index}]: {removed.file}")+ click.echo()+++# ── add-expr ───────────────────────────────────────────────────+[email protected](name="add-expr")[email protected]("model_path", type=click.Path(exists=True))[email protected]("--name", "-n", required=True, help="Expression name")[email protected]("--file", "-f", required=True, help="Expression file path (.exp3.json)")+@handle_error+def add_expr(model_path: str, name: str, file: str):+ """Add an expression to the model."""+ p = Path(model_path)+ auto_backup(p)+ info = load_model(p)++ for e in info.expressions:+ if e.name == name:+ raise ValueError(f"Expression '{name}' already exists (→ {e.file})")++ info.expressions.append(ExpressionRef(name=name, file=file))+ save_model(info)+ click.echo(f" ✅ Added expression: {name} → {file}")+ click.echo()+++# ── rm-expr ────────────────────────────────────────────────────+[email protected](name="rm-expr")[email protected]("model_path", type=click.Path(exists=True))[email protected]("--name", "-n", required=True, help="Expression name to remove")[email protected]_option(prompt="Are you sure?")+@handle_error+def rm_expr(model_path: str, name: str):+ """Remove an expression from the model."""+ p = Path(model_path)+ auto_backup(p)+ info = load_model(p)++ found = None+ for e in info.expressions:+ if e.name == name:+ found = e+ break++ if not found:+ raise ValueError(f"Expression '{name}' not found.")++ info.expressions.remove(found)+ save_model(info)+ click.echo(f" ✅ Removed expression: {name} (was → {found.file})")+ click.echo()+++# ── edit-texture ───────────────────────────────────────────────+[email protected](name="edit-texture")[email protected]("model_path", type=click.Path(exists=True))[email protected]("--index", "-i", type=int, required=True, help="Texture index (0-based)")[email protected]("--path", "new_path", required=True, help="New texture path")+@handle_error+def edit_texture(model_path: str, index: int, new_path: str):+ """Replace a texture file path."""+ p = Path(model_path)+ auto_backup(p)+ info = load_model(p)++ if index < 0 or index >= len(info.textures):+ raise ValueError(f"Index {index} out of range. Model has {len(info.textures)} textures (0-{len(info.textures)-1})")++ old = info.textures[index]+ info.textures[index] = new_path+ save_model(info)+ click.echo(f" ✅ Texture [{index}]: {old} → {new_path}")+ click.echo()+++# ── edit-model ─────────────────────────────────────────────────+[email protected](name="edit-model")[email protected]("model_path", type=click.Path(exists=True))[email protected]("--moc3", help="Replace moc3 file path")[email protected]("--physics", help="Replace physics file path")[email protected]("--pose", help="Replace pose file path")[email protected]("--userdata", help="Replace userdata file path")+@handle_error+def edit_model(model_path: str, moc3: Optional[str], physics: Optional[str], pose: Optional[str], userdata: Optional[str]):+ """Edit model-level file references (moc3, physics, pose, userdata)."""+ p = Path(model_path)+ auto_backup(p)+ info = load_model(p)++ changes = []+ if moc3 is not None:+ info.moc3 = moc3+ changes.append(f"moc3={moc3}")+ if physics is not None:+ info.physics = physics+ changes.append(f"physics={physics}")+ if pose is not None:+ info.pose = pose+ changes.append(f"pose={pose}")+ if userdata is not None:+ info.userdata = userdata+ changes.append(f"userdata={userdata}")++ if not changes:+ click.echo(" Nothing to change. Use --moc3, --physics, --pose, or --userdata.")+ return++ save_model(info)+ click.echo(f" ✅ Updated {info.path.name}")+ for c in changes:+ click.echo(f" {c}")+ click.echo()+++# ── undo ───────────────────────────────────────────────────────+[email protected]("model_path", type=click.Path(exists=True))[email protected]("--list", "do_list", is_flag=True, help="List available backups")[email protected]("--backup", "backup_name", default=None, help="Specific backup file to restore")+@handle_error+def undo(model_path: str, do_list: bool, backup_name: Optional[str]):+ """Undo last edit by restoring from auto-backup."""+ p = Path(model_path)++ if do_list:+ backups = list_backups(p)+ if not backups:+ click.echo(" No backups found.")+ return+ click.echo(f"\n 📋 Backups for {p.name}\n")+ for b in backups:+ click.echo(f" {b['file']} ({b['size']} bytes)")+ click.echo()+ return++ src = restore(p, backup_name)+ click.echo(f" ✅ Restored from: {src.name}")+ click.echo()+++# ── batch ──────────────────────────────────────────────────────+[email protected]("directory", type=click.Path(exists=True))[email protected]("--set-fade-in", type=float, help="Set fade_in for all motions")[email protected]("--set-fade-out", type=float, help="Set fade_out for all motions")[email protected]("--add-motion-group", help="Add motion group name")[email protected]("--add-motion-file", help="Motion file path for --add-motion-group")[email protected]("--add-expr-name", help="Add expression name")[email protected]("--add-expr-file", help="Expression file path")[email protected]("--set-moc3", help="Set moc3 path for all models")[email protected]("--dry-run", is_flag=True, help="Show what would change without saving")+@handle_error+def batch(directory: str, set_fade_in: Optional[float], set_fade_out: Optional[float],+ add_motion_group: Optional[str], add_motion_file: Optional[str],+ add_expr_name: Optional[str], add_expr_file: Optional[str],+ set_moc3: Optional[str], dry_run: bool):+ """Batch-edit multiple models in a directory."""+ from cli_anything.live2d.core.scanner import scan_directory+ d = Path(directory)+ models = scan_directory(d)++ if not models:+ click.echo(" No models found.")+ return++ actions = []+ if set_fade_in is not None:+ actions.append(f"fade_in={set_fade_in}")+ if set_fade_out is not None:+ actions.append(f"fade_out={set_fade_out}")+ if add_motion_group and add_motion_file:+ actions.append(f"add motion [{add_motion_group}] → {add_motion_file}")+ if add_expr_name and add_expr_file:+ actions.append(f"add expression {add_expr_name} → {add_expr_file}")+ if set_moc3:+ actions.append(f"moc3={set_moc3}")++ if not actions:+ click.echo(" Nothing to do. Use --set-fade-in, --set-fade-out, --add-motion-*, --add-expr-*, --set-moc3.")+ return++ click.echo(f"\n 🔧 Batch: {len(models)} model(s)\n")+ for a in actions:+ click.echo(f" {a}")+ click.echo()++ for m in models:+ info = load_model(m.path)+ changed = False++ if not dry_run:+ auto_backup(m.path)++ if set_fade_in is not None:+ for group in info.motions.values():+ for mot in group:+ mot.fade_in = set_fade_in+ changed = True++ if set_fade_out is not None:+ for group in info.motions.values():+ for mot in group:+ mot.fade_out = set_fade_out+ changed = True++ if add_motion_group and add_motion_file:+ if add_motion_group not in info.motions:+ info.motions[add_motion_group] = []+ info.motions[add_motion_group].append(MotionRef(file=add_motion_file))+ changed = True++ if add_expr_name and add_expr_file:+ existing_names = {e.name for e in info.expressions}+ if add_expr_name not in existing_names:+ info.expressions.append(ExpressionRef(name=add_expr_name, file=add_expr_file))+ changed = True++ if set_moc3:+ info.moc3 = set_moc3+ changed = True++ status = "would change" if dry_run else ("✅ updated" if changed else "no change")+ click.echo(f" {m.path.relative_to(d)} → {status}")++ if changed and not dry_run:+ save_model(info)++ click.echo()+++# ── lint ───────────────────────────────────────────────────────+[email protected]("model_path", type=click.Path(exists=True))[email protected]("--level", type=click.Choice(["error", "warning", "info"]), default="warning", help="Min level to show")+@handle_error+def lint(model_path: str, level: str):+ """Lint a model for best practices (naming, textures, structure)."""+ report = lint_model(Path(model_path))++ if _json_output:+ output(report.to_dict())+ if not report.ok:+ sys.exit(1)+ return++ level_order = {"error": 0, "warning": 1, "info": 2}+ min_level = level_order.get(level, 1)++ filtered = [i for i in report.issues if level_order.get(i.level, 0) <= min_level]++ click.echo(f"\n 🔎 Lint: {report.model_path.name}\n")+ if not filtered:+ click.echo(" ✅ No issues found!")+ else:+ icons = {"error": "❌", "warning": "⚠️", "info": "ℹ️"}+ for i in filtered:+ icon = icons.get(i.level, "?")+ click.echo(f" {icon} [{i.category}] {i.message}")+ if i.fix_hint:+ click.echo(f" 💡 {i.fix_hint}")+ click.echo(f"\n Summary: {len(report.errors)} errors, {len(report.warnings)} warnings, {len(report.infos)} info")++ click.echo()+ if not report.ok:+ sys.exit(1)+++# ── diff (enhanced) ────────────────────────────────────────────+[email protected](name="diff")[email protected]("model_a", type=click.Path(exists=True))[email protected]("model_b", type=click.Path(exists=True))+@handle_error+def diff_cmd(model_a: str, model_b: str):+ """Detailed diff between two models (field, motion, expression, texture level)."""+ info_a = load_model(Path(model_a))+ info_b = load_model(Path(model_b))+ d = diff_models(info_a, info_b)++ if _json_output:+ output(d.to_dict())+ return++ click.echo(f"\n 🔀 Diff: {info_a.path.name} vs {info_b.path.name}\n")+ if not d.has_changes:+ click.echo(" ✅ No differences!")+ click.echo()+ return++ icons = {"texture": "🖼️", "motion": "🎬", "expression": "😊", "field": "📝", "param": "⚙️"}+ for item in d.items:+ icon = icons.get(item.category, "•")+ click.echo(f" {icon} [{item.category}] {item.name}")+ click.echo(f" {item.detail}")++ click.echo(f"\n Total: {len(d.items)} difference(s)")+ click.echo()+++# ── param-edit ─────────────────────────────────────────────────+[email protected](name="param-edit")[email protected]("expression_path", type=click.Path(exists=True))[email protected]("--param-id", "-p", required=True, help="Parameter ID (e.g. ParamEyeLOpen)")[email protected]("--value", "-v", type=float, required=True, help="New value")[email protected]("--fade-in", type=float, help="Override fade-in for this param")[email protected]("--fade-out", type=float, help="Override fade-out for this param")+@handle_error+def param_edit(expression_path: str, param_id: str, value: float, fade_in: Optional[float], fade_out: Optional[float]):+ """Edit a parameter value inside an expression file (.exp3.json)."""+ p = Path(expression_path)+ if not p.exists():+ raise FileNotFoundError(f"Expression file not found: {p}")++ with open(p, "r", encoding="utf-8") as f:+ data = json.load(f)++ params = data.get("Parameters", [])+ found = False+ for param in params:+ if param.get("Id") == param_id:+ param["Value"] = value+ if fade_in is not None:+ param["FadeInTime"] = fade_in+ if fade_out is not None:+ param["FadeOutTime"] = fade_out+ found = True+ break++ if not found:+ # Add new param+ new_param = {"Id": param_id, "Value": value}+ if fade_in is not None:+ new_param["FadeInTime"] = fade_in+ if fade_out is not None:+ new_param["FadeOutTime"] = fade_out+ params.append(new_param)+ data["Parameters"] = params+ click.echo(f" ✅ Added {param_id}={value}")+ else:+ click.echo(f" ✅ Updated {param_id}={value}")++ with open(p, "w", encoding="utf-8") as f:+ json.dump(data, f, indent=2, ensure_ascii=False)++ click.echo()+++# ── snapshot ───────────────────────────────────────────────────+[email protected]("model_path", type=click.Path(exists=True))[email protected]("--out", "-o", type=click.Path(), default=None, help="Output HTML path")[email protected]("--embed", is_flag=True, help="Embed textures as base64 (self-contained)")+@handle_error+def snapshot_cmd(model_path: str, out: Optional[str], embed: bool):+ """Generate an HTML preview of the model."""+ info = load_model(Path(model_path))++ if out is None:+ name = info.path.name.replace(".model3.json", "").replace(".json", "")+ out = str(info.path.parent / f"{name}.html")++ result = write_snapshot(info, Path(out), embed_textures=embed)+ click.echo(f" ✅ Preview: {result}")+ click.echo()+++# ── watch ──────────────────────────────────────────────────────+[email protected]("directory", type=click.Path(exists=True))[email protected]("--interval", type=float, default=2.0, show_default=True, help="Check interval in seconds")+@handle_error+def watch(directory: str, interval: float):+ """Watch directory for changes and auto-validate Live2D models."""+ import time+ from cli_anything.live2d.core.scanner import scan_directory++ d = Path(directory)+ click.echo(f"\n 👁️ Watching: {d}")+ click.echo(f" Interval: {interval}s (Ctrl+C to stop)\n")++ last_mtimes: dict[str, float] = {}++ try:+ while True:+ models = scan_directory(d)+ current_files = {}++ for m in models:+ # Collect all related files+ related = [m.path]+ model_dir = m.path.parent+ for tex in m.textures:+ related.append(model_dir / tex)+ for motions in m.motions.values():+ for mot in motions:+ related.append(model_dir / mot.file)+ for expr in m.expressions:+ related.append(model_dir / expr.file)++ for f in related:+ if f.exists():+ key = str(f)+ mtime = f.stat().st_mtime+ current_files[key] = mtime++ if key in last_mtimes and mtime != last_mtimes[key]:+ click.echo(f" 🔄 Changed: {f.relative_to(d)} ({time.strftime('%H:%M:%S')})")+ # Auto-validate the parent model+ result = validate_model(m)+ if result.errors:+ for e in result.errors:+ click.echo(f" ❌ {e}")+ else:+ click.echo(f" ✅ Valid")++ last_mtimes = current_files+ time.sleep(interval)++ except KeyboardInterrupt:+ click.echo("\n Stopped watching.")+++# ── atlas ──────────────────────────────────────────────────────+[email protected]("model_path", type=click.Path(exists=True))[email protected]("--merge", is_flag=True, help="Suggest texture merge (analyze sizes)")[email protected]("--split", is_flag=True, help="Suggest texture split (oversized textures)")[email protected]("--max-size", type=int, default=2048, show_default=True, help="Max texture dimension")+@handle_error+def atlas(model_path: str, merge: bool, split: bool, max_size: int):+ """Analyze and manage texture atlases."""+ info = load_model(Path(model_path))+ model_dir = info.path.parent++ click.echo(f"\n 🗺️ Texture Atlas: {info.path.name}\n")++ textures_info = []+ for i, tex in enumerate(info.textures):+ tinfo = get_texture_info(model_dir / tex)+ textures_info.append((i, tex, tinfo))+ exists = "✅" if tinfo.width > 0 else "❌"+ size_str = f"{tinfo.width}×{tinfo.height}" if tinfo.width > 0 else "MISSING"+ click.echo(f" {exists} [{i}] {tex} {size_str} {tinfo.size_display}")++ if merge:+ click.echo(f"\n 📦 Merge suggestions:")+ small = [(i, tex, t) for i, tex, t in textures_info if t.width > 0 and t.width <= 512 and t.height <= 512]+ if len(small) >= 2:+ click.echo(f" {len(small)} small textures could be merged into a single atlas")+ for i, tex, t in small:+ click.echo(f" [{i}] {tex} ({t.width}×{t.height})")+ else:+ click.echo(f" No small textures to merge.")++ if split:+ click.echo(f"\n ✂️ Split suggestions:")+ oversized = [(i, tex, t) for i, tex, t in textures_info if t.width > max_size or t.height > max_size]+ if oversized:+ for i, tex, t in oversized:+ click.echo(f" [{i}] {tex} ({t.width}×{t.height}) exceeds {max_size}px")+ else:+ click.echo(f" All textures within {max_size}px limit.")++ click.echo()+++# ── migrate ────────────────────────────────────────────────────+[email protected]("model_path", type=click.Path(exists=True))[email protected]("--target-version", type=int, default=3, show_default=True, help="Target model version")[email protected]("--dry-run", is_flag=True, help="Show changes without saving")+@handle_error+def migrate(model_path: str, target_version: int, dry_run: bool):+ """Migrate a model to a newer format version."""+ p = Path(model_path)+ info = load_model(p)++ click.echo(f"\n 🔄 Migrate: {info.path.name}\n")+ click.echo(f" Current version: {info.version}")+ click.echo(f" Target version: {target_version}")++ current = int(info.version) if info.version else 0+ if current >= target_version:+ click.echo(f"\n ✅ Already at version {current}, no migration needed.")+ click.echo()+ return++ changes = []++ # Read raw JSON for structural changes+ with open(p, "r", encoding="utf-8") as f:+ data = json.load(f)++ refs = data.get("FileReferences", {})++ # Version 1 → 2: ensure Motions dict exists+ if current < 2 and "Motions" not in refs:+ refs["Motions"] = {}+ changes.append("Added Motions structure")++ # Version 2 → 3: ensure Groups array exists+ if current < 3 and "Groups" not in data:+ data["Groups"] = []+ changes.append("Added Groups array")++ data["Version"] = target_version+ changes.append(f"Version {current} → {target_version}")++ if not changes:+ click.echo(" No structural changes needed.")+ else:+ for c in changes:+ click.echo(f" • {c}")++ if dry_run:+ click.echo(f"\n (dry run — not saved)")+ else:+ if not dry_run:+ auto_backup(p)+ with open(p, "w", encoding="utf-8") as f:+ json.dump(data, f, indent=2, ensure_ascii=False)+ click.echo(f"\n ✅ Saved.")++ click.echo()+++# ── find-replace ───────────────────────────────────────────────+[email protected](name="find-replace")[email protected]("model_path", type=click.Path(exists=True))[email protected]("--find", "-f", required=True, help="Text to find in file paths")[email protected]("--replace", "-r", required=True, help="Replacement text")[email protected]("--dry-run", is_flag=True, help="Show changes without saving")+@handle_error+def find_replace(model_path: str, find: str, replace: str, dry_run: bool):+ """Batch rename file references (textures, motions, expressions)."""+ p = Path(model_path)+ info = load_model(p)+ changes = []++ # Textures+ for i, tex in enumerate(info.textures):+ if find in tex:+ new_tex = tex.replace(find, replace)+ changes.append(f"texture [{i}]: {tex} → {new_tex}")+ if not dry_run:+ info.textures[i] = new_tex++ # Motions+ for group, motions in info.motions.items():+ for i, m in enumerate(motions):+ if find in m.file:+ new_file = m.file.replace(find, replace)+ changes.append(f"motion [{group}][{i}]: {m.file} → {new_file}")+ if not dry_run:+ m.file = new_file++ # Expressions+ for expr in info.expressions:+ if find in expr.file:+ new_file = expr.file.replace(find, replace)+ changes.append(f"expression {expr.name}: {expr.file} → {new_file}")+ if not dry_run:+ expr.file = new_file+ if find in expr.name:+ new_name = expr.name.replace(find, replace)+ changes.append(f"expression name: {expr.name} → {new_name}")+ if not dry_run:+ expr.name = new_name++ # Top-level+ for field_name in ("moc3", "physics", "pose", "userdata"):+ val = getattr(info, field_name)+ if val and find in val:+ new_val = val.replace(find, replace)+ changes.append(f"{field_name}: {val} → {new_val}")+ if not dry_run:+ setattr(info, field_name, new_val)++ if not changes:+ click.echo(f" No occurrences of '{find}' found.")+ return++ click.echo(f"\n 🔍 Find & Replace: '{find}' → '{replace}'\n")+ for c in changes:+ click.echo(f" {'📝' if not dry_run else '👀'} {c}")++ if not dry_run:+ auto_backup(p)+ save_model(info)+ click.echo(f"\n ✅ Saved ({len(changes)} change(s))")+ else:+ click.echo(f"\n (dry run — {len(changes)} change(s) would be made)")+ click.echo()+++# ── orphan ─────────────────────────────────────────────────────+[email protected]("model_path", type=click.Path(exists=True))+@handle_error+def orphan(model_path: str):+ """Find files in the model directory that aren't referenced by the model."""+ info = load_model(Path(model_path))+ model_dir = info.path.parent++ # Collect all referenced files+ referenced = set()+ referenced.add(info.moc3)+ referenced.add(info.physics)+ referenced.add(info.pose)+ referenced.add(info.userdata)+ referenced.add(info.display_info)+ referenced.update(info.textures)+ for motions in info.motions.values():+ for m in motions:+ referenced.add(m.file)+ for e in info.expressions:+ referenced.add(e.file)+ # Remove empty strings+ referenced.discard("")++ # Scan all files in model directory+ all_files = set()+ for f in model_dir.rglob("*"):+ if f.is_file() and f.name != info.path.name:+ rel = str(f.relative_to(model_dir))+ # Skip backup dirs and hidden files+ if ".live2d-backups" in rel or rel.startswith("."):+ continue+ all_files.add(rel)++ orphans = sorted(all_files - referenced)++ if _json_output:+ output({"model": str(info.path), "referenced": len(referenced), "total_files": len(all_files), "orphans": orphans})+ return++ click.echo(f"\n 👻 Orphan Files: {info.path.name}\n")+ click.echo(f" Referenced: {len(referenced)} files")+ click.echo(f" Total: {len(all_files)} files")+ click.echo()++ if not orphans:+ click.echo(" ✅ No orphan files!")+ else:+ click.echo(f" {len(orphans)} orphan file(s):\n")+ for o in orphans:+ click.echo(f" 🗑️ {o}")+ click.echo()+++# ── restore-file ───────────────────────────────────────────────+[email protected](name="restore-file")[email protected]("model_path", type=click.Path(exists=True))[email protected]("--file", "target_file", required=True, help="File to restore (relative path from model dir)")[email protected]("--backup", "backup_name", default=None, help="Specific backup to restore from")+@handle_error+def restore_file(model_path: str, target_file: str, backup_name: Optional[str]):+ """Restore a specific file from backup."""+ from cli_anything.live2d.core.backup import _backup_dir_for+ p = Path(model_path)+ bdir = _backup_dir_for(p)++ if not bdir.exists():+ raise FileNotFoundError(f"No backups found for {p.name}")++ # Find the backup+ if backup_name:+ backup_path = bdir / backup_name+ else:+ backups = sorted(bdir.glob("*.model3.json"), reverse=True)+ if not backups:+ raise FileNotFoundError("No backups found")+ backup_path = backups[0]++ if not backup_path.exists():+ raise FileNotFoundError(f"Backup not found: {backup_path}")++ # The backup is the model JSON itself+ model_dir = p.parent+ if target_file == p.name:+ # Restoring the model file itself+ import shutil+ shutil.copy2(backup_path, p)+ click.echo(f" ✅ Restored {p.name} from {backup_path.name}")+ else:+ click.echo(f" ℹ️ Backups only store the .model3.json file.")+ click.echo(f" To restore other files, use your version control (git).")+ click.echo()+++# ── backup-clean ───────────────────────────────────────────────+[email protected](name="backup-clean")[email protected]("model_path", type=click.Path(exists=True))[email protected]("--keep", "-k", type=int, default=10, show_default=True, help="Number of recent backups to keep")[email protected]("--dry-run", is_flag=True, help="Show what would be deleted")+@handle_error+def backup_clean(model_path: str, keep: int, dry_run: bool):+ """Clean old backups, keep only the N most recent."""+ from cli_anything.live2d.core.backup import _backup_dir_for+ p = Path(model_path)+ bdir = _backup_dir_for(p)++ if not bdir.exists():+ click.echo(" No backups found.")+ return++ backups = sorted(bdir.glob("*.model3.json"), reverse=True)+ to_delete = backups[keep:]++ if _json_output:+ deleted = []+ if not dry_run:+ for f in to_delete:+ f.unlink()+ deleted.append(f.name)+ output({+ "total": len(backups),+ "keep": keep,+ "delete": len(to_delete),+ "deleted": deleted,+ "dry_run": dry_run,+ "files": [f.name for f in to_delete],+ })+ return++ click.echo(f"\n 🧹 Backup Cleanup\n")+ click.echo(f" Total backups: {len(backups)}")+ click.echo(f" Keeping: {min(keep, len(backups))}")+ click.echo(f" Deleting: {len(to_delete)}")+ click.echo()++ for f in to_delete:+ if dry_run:+ click.echo(f" 👀 would delete: {f.name}")+ else:+ f.unlink()+ click.echo(f" 🗑️ deleted: {f.name}")++ if not dry_run and to_delete:+ click.echo(f"\n ✅ Cleaned {len(to_delete)} backup(s)")+ elif not to_delete:+ click.echo(" Nothing to clean.")+ click.echo()+++# ── manifest ───────────────────────────────────────────────────+[email protected]("model_path", type=click.Path(exists=True))[email protected]("--out", "-o", type=click.Path(), help="Output file path")+@handle_error+def manifest(model_path: str, out: Optional[str]):+ """Generate a manifest of all model files with checksums and sizes."""+ import hashlib+ info = load_model(Path(model_path))+ model_dir = info.path.parent++ files = []++ # Model file itself+ files.append(_manifest_entry(info.path, model_dir))++ # Moc3+ if info.moc3:+ p = model_dir / info.moc3+ if p.exists():+ files.append(_manifest_entry(p, model_dir))++ # Textures+ for tex in info.textures:+ p = model_dir / tex+ if p.exists():+ files.append(_manifest_entry(p, model_dir))++ # Motions+ for motions in info.motions.values():+ for m in motions:+ p = model_dir / m.file+ if p.exists():+ files.append(_manifest_entry(p, model_dir))++ # Expressions+ for e in info.expressions:+ p = model_dir / e.file+ if p.exists():+ files.append(_manifest_entry(p, model_dir))++ # Physics, pose, userdata+ for ref in (info.physics, info.pose, info.userdata, info.display_info):+ if ref:+ p = model_dir / ref+ if p.exists():+ files.append(_manifest_entry(p, model_dir))++ total_size = sum(f["size"] for f in files)++ if _json_output:+ output({"model": str(info.path), "files": len(files), "total_size": total_size, "entries": files})+ return++ click.echo(f"\n 📋 Manifest: {info.path.name}\n")+ click.echo(f" {'File':<45} {'Size':>10} SHA256 (short)")+ click.echo(f" {'─' * 45} {'─' * 10} {'─' * 16}")+ for f in files:+ size_str = _format_size(f["size"])+ click.echo(f" {f['path']:<45} {size_str:>10} {f['sha256'][:12]}")+ click.echo(f"\n Total: {len(files)} files, {_format_size(total_size)}")+ click.echo()++ if out:+ import json as _json+ Path(out).write_text(_json.dumps({"files": files, "total": len(files), "total_size": total_size}, indent=2))+ click.echo(f" ✅ Written to {out}")+ click.echo()+++def _manifest_entry(path: Path, base: Path) -> dict:+ import hashlib+ data = path.read_bytes()+ return {+ "path": str(path.relative_to(base)),+ "size": len(data),+ "sha256": hashlib.sha256(data).hexdigest(),+ }+++def _format_size(n: int) -> str:+ if n < 1024:+ return f"{n}B"+ elif n < 1024 * 1024:+ return f"{n / 1024:.1f}KB"+ else:+ return f"{n / (1024*1024):.1f}MB"+++# ── stats ──────────────────────────────────────────────────────+[email protected]("directory", type=click.Path(exists=True))+@handle_error+def stats(directory: str):+ """Project overview: model count, motions, expressions, textures, disk usage."""+ from cli_anything.live2d.core.scanner import scan_directory+ d = Path(directory)+ models = scan_directory(d)++ total_motions = 0+ total_expressions = 0+ total_textures = 0+ total_groups = set()+ total_size = 0++ for m in models:+ info = load_model(m.path)+ total_motions += info.motion_count+ total_expressions += info.expression_count+ total_textures += info.texture_count+ total_groups.update(info.motions.keys())+ total_size += info.path.stat().st_size+ model_dir = info.path.parent+ for tex in info.textures:+ p = model_dir / tex+ if p.exists():+ total_size += p.stat().st_size+ for motions in info.motions.values():+ for mot in motions:+ p = model_dir / mot.file+ if p.exists():+ total_size += p.stat().st_size+ for e in info.expressions:+ p = model_dir / e.file+ if p.exists():+ total_size += p.stat().st_size++ if _json_output:+ output({+ "directory": str(d),+ "models": len(models),+ "motions": total_motions,+ "expressions": total_expressions,+ "textures": total_textures,+ "groups": sorted(total_groups),+ "total_size": total_size,+ })+ return++ click.echo(f"\n 📊 Project Stats: {d}\n")+ click.echo(f" Models: {len(models)}")+ click.echo(f" Motions: {total_motions}")+ click.echo(f" Expressions: {total_expressions}")+ click.echo(f" Textures: {total_textures}")+ click.echo(f" Groups: {len(total_groups)} ({', '.join(sorted(total_groups))})")+ click.echo(f" Disk: {_format_size(total_size)}")+ click.echo()+++# ── gen-motion ─────────────────────────────────────────────────+[email protected](name="gen-motion")[email protected]("name")[email protected]("--duration", "-d", type=float, default=2.0, show_default=True, help="Duration in seconds")[email protected]("--fps", type=float, default=30, show_default=True, help="Frames per second")[email protected]("--loop", "do_loop", is_flag=True, default=True, help="Loop animation")[email protected]("--out", "-o", type=click.Path(), default=None, help="Output path")+@handle_error+def gen_motion(name: str, duration: float, fps: float, do_loop: bool, out: Optional[str]):+ """Generate a skeleton .motion3.json file."""+ if out is None:+ out = f"{name}.motion3.json"++ data = {+ "Version": 1,+ "Meta": {+ "Duration": duration,+ "Fps": fps,+ "Loop": do_loop,+ "CurveCount": 0,+ "TotalSegmentCount": 0,+ "TotalPointCount": 0,+ },+ "Curves": [],+ }++ Path(out).write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")+ click.echo(f" ✅ Generated: {out}")+ click.echo(f" Duration: {duration}s FPS: {fps} Loop: {do_loop}")+ click.echo()+++# ── gen-expr ───────────────────────────────────────────────────+[email protected](name="gen-expr")[email protected]("name")[email protected]("--fade-in", type=float, default=0.5, show_default=True)[email protected]("--fade-out", type=float, default=0.5, show_default=True)[email protected]("--out", "-o", type=click.Path(), default=None, help="Output path")+@handle_error+def gen_expr(name: str, fade_in: float, fade_out: float, out: Optional[str]):+ """Generate a skeleton .exp3.json file."""+ if out is None:+ out = f"{name}.exp3.json"++ data = {+ "Version": 1,+ "FadeInTime": fade_in,+ "FadeOutTime": fade_out,+ "Parameters": [],+ }++ Path(out).write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")+ click.echo(f" ✅ Generated: {out}")+ click.echo(f" Fade: {fade_in}s / {fade_out}s")+ click.echo(f" Edit with: cli-anything-live2d param-edit {out} -p ParamId -v 1.0")+ click.echo()+++# ── rename-group ───────────────────────────────────────────────+[email protected](name="rename-group")[email protected]("model_path", type=click.Path(exists=True))[email protected]("--old", required=True, help="Current group name")[email protected]("--new", "new_name", required=True, help="New group name")+@handle_error+def rename_group(model_path: str, old: str, new_name: str):+ """Rename a motion group."""+ p = Path(model_path)+ auto_backup(p)+ info = load_model(p)++ if old not in info.motions:+ raise ValueError(f"Group '{old}' not found. Available: {list(info.motions.keys())}")+ if new_name in info.motions:+ raise ValueError(f"Group '{new_name}' already exists.")++ info.motions[new_name] = info.motions.pop(old)+ save_model(info)+ click.echo(f" ✅ Renamed group: {old} → {new_name} ({len(info.motions[new_name])} motions)")+ click.echo()+++# ── param-list ─────────────────────────────────────────────────+[email protected](name="param-list")[email protected]("model_path", type=click.Path(exists=True))+@handle_error+def param_list(model_path: str):+ """List all unique parameters used across motions and expressions."""+ info = load_model(Path(model_path))+ model_dir = info.path.parent++ params: dict[str, dict] = {} # id -> {motions: [], expressions: []}++ # Scan motions+ for group, motions in info.motions.items():+ for m in motions:+ mp = model_dir / m.file+ if not mp.exists():+ continue+ try:+ from cli_anything.live2d.core.motion_parser import load_motion+ minfo = load_motion(mp)+ for c in minfo.parameter_curves:+ if c.id not in params:+ params[c.id] = {"motions": [], "expressions": []}+ params[c.id]["motions"].append(f"[{group}] {Path(m.file).stem}")+ except Exception:+ pass++ # Scan expressions+ for expr in info.expressions:+ ep = model_dir / expr.file+ if not ep.exists():+ continue+ try:+ from cli_anything.live2d.core.expression_parser import load_expression+ einfo = load_expression(ep)+ for p in einfo.params:+ if p.id not in params:+ params[p.id] = {"motions": [], "expressions": []}+ params[p.id]["expressions"].append(expr.name)+ except Exception:+ pass++ if _json_output:+ output({"model": str(info.path), "parameter_count": len(params), "parameters": params})+ return++ click.echo(f"\n ⚙️ Parameter Usage: {info.path.name}\n")+ if not params:+ click.echo(" (no parameters found in motions/expressions)")+ click.echo()+ return++ for pid in sorted(params):+ usage = params[pid]+ total = len(usage["motions"]) + len(usage["expressions"])+ click.echo(f" {pid} ({total} reference(s))")+ for m in usage["motions"][:3]:+ click.echo(f" 📹 {m}")+ if len(usage["motions"]) > 3:+ click.echo(f" ... +{len(usage['motions']) - 3} more motions")+ for e in usage["expressions"]:+ click.echo(f" 😊 {e}")+ click.echo()+++# ── flatten ────────────────────────────────────────────────────+[email protected]("model_path", type=click.Path(exists=True))[email protected]("--out-dir", "-o", required=True, help="Output directory for flattened model")[email protected]("--dry-run", is_flag=True, help="Show what would be copied")+@handle_error+def flatten(model_path: str, out_dir: str, dry_run: bool):+ """Flatten model directory structure (all files in one dir) for deployment."""+ import shutil+ info = load_model(Path(model_path))+ model_dir = info.path.parent+ out = Path(out_dir)++ # Collect all files+ files = []+ files.append((info.path, info.path.name))+ if info.moc3:+ files.append((model_dir / info.moc3, Path(info.moc3).name))+ for tex in info.textures:+ files.append((model_dir / tex, Path(tex).name))+ for motions in info.motions.values():+ for m in motions:+ files.append((model_dir / m.file, Path(m.file).name))+ sound = m.extra.get("Sound")+ if isinstance(sound, str) and sound:+ files.append((model_dir / sound, Path(sound).name))+ for e in info.expressions:+ files.append((model_dir / e.file, Path(e.file).name))+ for ref in (info.physics, info.pose, info.userdata, info.display_info):+ if ref:+ p = model_dir / ref+ if p.exists():+ files.append((p, Path(ref).name))++ # Deduplicate and detect collisions+ seen = {} # name -> original source path+ unique_files = []+ collisions = []+ for src, name in files:+ if not src.exists():+ continue+ if name in seen:+ if seen[name] != src:+ collisions.append((name, seen[name], src))+ else:+ seen[name] = src+ unique_files.append((src, name))++ if collisions:+ click.echo(f"\n ❌ Basename collisions detected:\n")+ for name, a, b in collisions:+ click.echo(f" {name}:")+ click.echo(f" {a.relative_to(model_dir)}")+ click.echo(f" {b.relative_to(model_dir)}")+ click.echo(f"\n Cannot flatten — rename files to avoid collisions first.")+ click.echo()+ sys.exit(1)++ click.echo(f"\n 📦 Flatten: {info.path.name} → {out}\n")++ if dry_run:+ for src, name in unique_files:+ click.echo(f" 👀 {src.relative_to(model_dir)} → {name}")+ click.echo(f"\n (dry run — {len(unique_files)} files would be copied)")+ click.echo()+ return++ out.mkdir(parents=True, exist_ok=True)+ for src, name in unique_files:+ shutil.copy2(src, out / name)+ click.echo(f" ✅ {name}")++ # Update model JSON to use flat paths+ flat_info = load_model(info.path)+ flat_info.moc3 = Path(flat_info.moc3).name if flat_info.moc3 else ""+ flat_info.textures = [Path(t).name for t in flat_info.textures]+ flat_info.physics = Path(flat_info.physics).name if flat_info.physics else ""+ flat_info.pose = Path(flat_info.pose).name if flat_info.pose else ""+ flat_info.userdata = Path(flat_info.userdata).name if flat_info.userdata else ""+ flat_info.display_info = Path(flat_info.display_info).name if flat_info.display_info else ""+ for motions in flat_info.motions.values():+ for m in motions:+ m.file = Path(m.file).name+ sound = m.extra.get("Sound")+ if isinstance(sound, str) and sound:+ m.extra["Sound"] = Path(sound).name+ for e in flat_info.expressions:+ e.file = Path(e.file).name++ flat_info.path = out / info.path.name+ save_model(flat_info)++ if _json_output:+ output({"files": len(unique_files), "out_dir": str(out), "entries": [n for _, n in unique_files]})+ else:+ click.echo(f"\n ✅ Flattened {len(unique_files)} files to {out}")+ click.echo()+++# ── runtime-check ──────────────────────────────────────────────+[email protected](name="runtime-check")[email protected]("model_path", type=click.Path(exists=True))[email protected]("--target", type=click.Choice(["cubism-viewer", "web-sdk", "yoyo", "all"]), default="all", show_default=True)+@handle_error+def runtime_check(model_path: str, target: str):+ """Check model compatibility with specific Live2D runtimes."""+ info = load_model(Path(model_path))+ model_dir = info.path.parent+ issues = []++ # Common checks+ if not info.moc3:+ issues.append(("error", "common", "No moc3 file referenced"))+ else:+ moc3_path = model_dir / info.moc3+ if not moc3_path.exists():+ issues.append(("error", "common", f"Moc3 file not found: {info.moc3}"))+ else:+ size = moc3_path.stat().st_size+ if size < 1024:+ issues.append(("error", "common", f"Moc3 file too small ({size} bytes)"))++ if not info.textures:+ issues.append(("error", "common", "No textures defined"))+ else:+ for i, tex in enumerate(info.textures):+ tp = model_dir / tex+ if not tp.exists():+ issues.append(("error", "common", f"Texture [{i}] missing: {tex}"))+ else:+ from cli_anything.live2d.core.texture_info import get_texture_info+ tinfo = get_texture_info(tp)+ if tinfo.width > 4096 or tinfo.height > 4096:+ issues.append(("warning", "common", f"Texture [{i}] very large ({tinfo.width}×{tinfo.height})"))++ if not info.motions:+ issues.append(("warning", "common", "No motions defined"))++ # Web SDK checks+ if target in ("web-sdk", "all"):+ if not info.physics:+ issues.append(("warning", "web-sdk", "No physics file (recommended for web)"))+ for group, motions in info.motions.items():+ for i, m in enumerate(motions):+ if m.fade_in > 1.0 or m.fade_out > 1.0:+ issues.append(("info", "web-sdk", f"[{group}][{i}] has long fade times ({m.fade_in}/{m.fade_out}s) — may feel sluggish on web"))++ # Cubism Viewer checks+ if target in ("cubism-viewer", "all"):+ if not info.expressions:+ issues.append(("info", "cubism-viewer", "No expressions (Cubism Viewer supports them well)"))+ if "Idle" not in info.motions and "idle" not in info.motions:+ issues.append(("warning", "cubism-viewer", "No Idle motion group (expected by most viewers)"))++ # Yoyo checks+ if target in ("yoyo", "all"):+ # Normalize: accept both "Idle" and "idle"+ yoyo_idle = info.motions.get("Idle") or info.motions.get("idle")+ if not yoyo_idle:+ issues.append(("error", "yoyo", "No Idle group (required for Yoyo)"))+ else:+ if not any(m.fade_in <= 0.5 for m in yoyo_idle):+ issues.append(("warning", "yoyo", "Idle motions should have fast fade-in (≤0.5s)"))++ if _json_output:+ output({"model": str(info.path), "target": target, "issues": [{"level": l, "scope": s, "msg": m} for l, s, m in issues]})+ if any(l == "error" for l, _, _ in issues):+ sys.exit(1)+ return++ click.echo(f"\n 🔧 Runtime Check: {info.path.name} (target: {target})\n")+ if not issues:+ click.echo(" ✅ No issues found!")+ else:+ icons = {"error": "❌", "warning": "⚠️", "info": "ℹ️"}+ for level, scope, msg in issues:+ click.echo(f" {icons[level]} [{scope}] {msg}")++ errors = sum(1 for l, _, _ in issues if l == "error")+ warns = sum(1 for l, _, _ in issues if l == "warning")+ click.echo(f"\n {errors} error(s), {warns} warning(s)")+ if errors:+ sys.exit(1)+ click.echo()+++if __name__ == "__main__":+ main()diff --git a/live2d/agent-harness/cli_anything/live2d/skills/SKILL.md b/live2d/agent-harness/cli_anything/live2d/skills/SKILL.mdnew file mode 100644index 000000000..ad9d27771--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/skills/SKILL.md@@ -0,0 +1,105 @@+---+name: cli-anything-live2d+description: "Inspect, validate, edit, lint, diff, batch-manage, and deploy Live2D Cubism models (.model3.json) from the command line."+metadata: { "cli-anything": { "category": "graphics", "requires": null } }+---++# cli-anything-live2d++Full-featured CLI for Live2D Cubism models. 42 commands covering inspection,+editing, linting, diffing, batch operations, asset management, generation,+and deployment — all without the Live2D Editor.++## Commands (42 total)++### Read (18)++| Command | Purpose |+|---------|---------|+| `inspect <model>` | Model overview (version, counts, features) |+| `validate <model>` | Check all referenced files exist |+| `motions <model>` | List motions with fade times |+| `motion-info <file>` | Detailed motion analysis |+| `expressions <model>` | List expression presets |+| `expr-info <file>` | Detailed expression analysis |+| `textures <model>` | List textures with dimensions and sizes |+| `physics <file>` | Physics simulation config |+| `moc3 <file>` | Moc3 binary info |+| `params <model>` | Parameter groups |+| `param-list <model>` | All params across motions/expressions |+| `deps <model>` | Dependency graph |+| `compare <a> <b>` | Quick comparison |+| `diff <a> <b>` | Detailed diff |+| `scan <dir>` | Find all models in directory |+| `export <model>` | Export as JSON/CSV |+| `stats <dir>` | Project overview |+| `manifest <model>` | File inventory with SHA256 checksums |++### Edit (10, all auto-backup)++| Command | Purpose |+|---------|---------|+| `edit-motion` | Edit motion fade times or file path |+| `add-motion` | Add motion to group |+| `rm-motion` | Remove motion |+| `add-expr` | Add expression |+| `rm-expr` | Remove expression |+| `edit-texture` | Replace texture path |+| `edit-model` | Edit moc3/physics/pose/userdata |+| `param-edit` | Edit parameter value in .exp3.json |+| `rename-group` | Rename a motion group |+| `find-replace` | Batch rename file references |++### Generation (3)++| Command | Purpose |+|---------|---------|+| `init` | Generate full model template |+| `gen-motion` | Generate skeleton .motion3.json |+| `gen-expr` | Generate skeleton .exp3.json |++### Analysis (4)++| Command | Purpose |+|---------|---------|+| `lint` | Best practice checks |+| `runtime-check` | Cubism Viewer / Web SDK / Yoyo compatibility |+| `atlas` | Texture atlas analysis |+| `orphan` | Find unreferenced files |++### Workflow (7)++| Command | Purpose |+|---------|---------|+| `undo` | Restore from auto-backup |+| `backup-clean` | Rotate old backups |+| `restore-file` | Restore specific file from backup |+| `batch` | Batch-edit multiple models |+| `snapshot` | Generate HTML preview |+| `watch` | Auto-validate on file changes |+| `flatten` | Flatten directory for deployment |++### Other (3)++| Command | Purpose |+|---------|---------|+| `migrate` | Model format version upgrade |+| `pack` | Package model + deps into zip |+| `yoyo-check` | Yoyo desktop-pet readiness |++All read commands support `--json`. Edit commands auto-backup.++## Examples++```bash+cli-anything-live2d inspect model.model3.json+cli-anything-live2d lint model.model3.json --level info+cli-anything-live2d edit-motion model.model3.json -g Idle -i 0 --fade-in 0.3+cli-anything-live2d find-replace model.model3.json -f "old_tex" -f "new_tex"+cli-anything-live2d orphan model.model3.json+cli-anything-live2d runtime-check model.model3.json --target web-sdk+cli-anything-live2d flatten model.model3.json --out-dir ./deploy/+cli-anything-live2d batch ./models/ --set-fade-in 0.3 --dry-run+cli-anything-live2d snapshot model.model3.json --embed+cli-anything-live2d stats ./project/+```diff --git a/live2d/agent-harness/cli_anything/live2d/tests/__init__.py b/live2d/agent-harness/cli_anything/live2d/tests/__init__.pynew file mode 100644index 000000000..4d4e8ec1e--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/tests/__init__.py@@ -0,0 +1 @@+"""Tests for cli-anything-live2d."""diff --git a/live2d/agent-harness/cli_anything/live2d/tests/test_core.py b/live2d/agent-harness/cli_anything/live2d/tests/test_core.pynew file mode 100644index 000000000..5f0548e76--- /dev/null+++ b/live2d/agent-harness/cli_anything/live2d/tests/test_core.py@@ -0,0 +1,181 @@+"""Unit tests for Live2D CLI core modules (no backend needed)."""++import json+import pytest+from pathlib import Path+from unittest.mock import patch++from cli_anything.live2d.core.parser import load_model, ModelInfo, MotionRef, ExpressionRef+from cli_anything.live2d.core.validator import validate_model, ValidationResult+from cli_anything.live2d.core.scanner import scan_directory, find_model_files+++# ── Fixtures ────────────────────────────────────────────────────++SAMPLE_MODEL3 = {+ "Version": 3,+ "FileReferences": {+ "Moc": "model.moc3",+ "Textures": ["textures/texture_00.png", "textures/texture_01.png"],+ "Physics": "model.physics3.json",+ "Pose": "model.pose3.json",+ "UserData": "model userdata3.json",+ "Expressions": [+ {"Name": "happy", "File": "expressions/happy.exp3.json"},+ {"Name": "angry", "File": "expressions/angry.exp3.json"},+ ],+ "Motions": {+ "idle": [+ {"File": "motions/idle_01.motion3.json", "FadeInTime": 0.5, "FadeOutTime": 0.5},+ {"File": "motions/idle_02.motion3.json", "FadeInTime": 0.5, "FadeOutTime": 0.5},+ ],+ "tap_body": [+ {"File": "motions/tap_body.motion3.json", "FadeInTime": 0.2, "FadeOutTime": 0.2},+ ],+ },+ },+ "Groups": [+ {"Target": "Parameter", "Name": "EyeBlink", "Ids": "ParamEyeLOpen,ParamEyeROpen"},+ ],+}+++def sample_model3_file(tmp_path):+ """Create a temporary .model3.json file."""+ model_file = tmp_path / "test_model.model3.json"+ model_file.write_text(json.dumps(SAMPLE_MODEL3), encoding="utf-8")+ return model_file+++def sample_model_with_files(tmp_path):+ """Create a temporary model with all referenced files."""+ model_dir = tmp_path / "character"+ model_dir.mkdir()++ # Model file+ model_file = model_dir / "test_model.model3.json"+ model_file.write_text(json.dumps(SAMPLE_MODEL3), encoding="utf-8")++ # Create referenced files+ (model_dir / "model.moc3").touch()+ (model_dir / "textures").mkdir()+ (model_dir / "textures" / "texture_00.png").touch()+ (model_dir / "textures" / "texture_01.png").touch()+ (model_dir / "model.physics3.json").touch()+ (model_dir / "model.pose3.json").touch()+ (model_dir / "model userdata3.json").touch()+ (model_dir / "expressions").mkdir()+ (model_dir / "expressions" / "happy.exp3.json").touch()+ (model_dir / "expressions" / "angry.exp3.json").touch()+ (model_dir / "motions").mkdir()+ (model_dir / "motions" / "idle_01.motion3.json").touch()+ (model_dir / "motions" / "idle_02.motion3.json").touch()+ (model_dir / "motions" / "tap_body.motion3.json").touch()++ return model_file+++# ── Parser Tests ────────────────────────────────────────────────++class TestParser:+ def test_load_model(self, sample_model3_file):+ info = load_model(sample_model3_file)+ assert isinstance(info, ModelInfo)+ assert info.version == 3+ assert info.moc3 == "model.moc3"+ assert info.texture_count == 2+ assert info.motion_count == 3+ assert info.motion_group_count == 2+ assert info.expression_count == 2+ assert info.physics == "model.physics3.json"+ assert info.pose == "model.pose3.json"++ def test_motions_parsed(self, sample_model3_file):+ info = load_model(sample_model3_file)+ assert "idle" in info.motions+ assert "tap_body" in info.motions+ assert len(info.motions["idle"]) == 2+ assert info.motions["idle"][0].fade_in == 0.5++ def test_expressions_parsed(self, sample_model3_file):+ info = load_model(sample_model3_file)+ names = [e.name for e in info.expressions]+ assert "happy" in names+ assert "angry" in names++ def test_groups_parsed(self, sample_model3_file):+ info = load_model(sample_model3_file)+ assert len(info.groups) == 1+ assert info.groups[0]["Name"] == "EyeBlink"++ def test_to_dict(self, sample_model3_file):+ info = load_model(sample_model3_file)+ d = info.to_dict()+ assert isinstance(d, dict)+ assert d["texture_count"] == 2+ assert d["motion_count"] == 3++ def test_file_not_found(self, tmp_path):+ with pytest.raises(FileNotFoundError):+ load_model(tmp_path / "nonexistent.model3.json")++ def test_bad_extension(self, tmp_path):+ f = tmp_path / "test.txt"+ f.write_text("{}")+ with pytest.raises(ValueError):+ load_model(f)+++# ── Validator Tests ─────────────────────────────────────────────++class TestValidator:+ def test_valid_model(self, sample_model_with_files):+ info = load_model(sample_model_with_files)+ result = validate_model(info)+ assert result.ok+ assert result.checked > 0+ assert len(result.errors) == 0++ def test_missing_files(self, sample_model3_file):+ """Model references files that don't exist -> errors."""+ info = load_model(sample_model3_file)+ result = validate_model(info)+ assert not result.ok+ assert len(result.errors) > 0+ assert any("Moc3" in e for e in result.errors)++ def test_result_to_dict(self, sample_model3_file):+ info = load_model(sample_model3_file)+ result = validate_model(info)+ d = result.to_dict()+ assert isinstance(d, dict)+ assert "ok" in d+ assert "errors" in d+++# ── Scanner Tests ───────────────────────────────────────────────++class TestScanner:+ def test_scan_finds_models(self, sample_model_with_files):+ model_dir = sample_model_with_files.parent+ models = scan_directory(model_dir)+ assert len(models) == 1+ assert models[0].moc3 == "model.moc3"++ def test_scan_empty_dir(self, tmp_path):+ empty = tmp_path / "empty"+ empty.mkdir()+ models = scan_directory(empty)+ assert len(models) == 0++ def test_scan_not_found(self, tmp_path):+ with pytest.raises(FileNotFoundError):+ scan_directory(tmp_path / "nonexistent")++ def test_find_model_files(self, sample_model_with_files):+ model_dir = sample_model_with_files.parent+ files = find_model_files(model_dir)+ assert len(files) == 1+ assert files[0].suffix == ".json"diff --git a/live2d/agent-harness/setup.py b/live2d/agent-harness/setup.pynew file mode 100644index 000000000..7605588b2--- /dev/null+++ b/live2d/agent-harness/setup.py@@ -0,0 +1,86 @@+#!/usr/bin/env python3+"""Setup script for cli-anything-live2d.++Install (dev mode):+ pip install -e .++Build:+ python -m build++Publish:+ twine upload dist/*+"""++from pathlib import Path+from setuptools import setup, find_namespace_packages++ROOT = Path(__file__).parent+README = ROOT / "cli_anything/live2d/README.md"++long_description = README.read_text(encoding="utf-8") if README.exists() else ""++setup(+ name="cli-anything-live2d",+ version="0.3.0",+ description="CLI harness for Live2D Cubism — inspect, validate, and manage .model3.json models",+ long_description=long_description,+ long_description_content_type="text/markdown",++ author="cli-anything contributors",+ author_email="",+ url="https://github.com/HKUDS/CLI-Anything",++ project_urls={+ "Source": "https://github.com/HKUDS/CLI-Anything",+ "Tracker": "https://github.com/HKUDS/CLI-Anything/issues",+ },++ license="MIT",++ packages=find_namespace_packages(include=("cli_anything.*",)),++ python_requires=">=3.10",++ install_requires=[+ "click>=8.1",+ ],++ extras_require={+ "dev": [+ "pytest>=7",+ "pytest-cov>=4",+ ],+ },++ entry_points={+ "console_scripts": [+ "cli-anything-live2d=cli_anything.live2d.live2d_cli:main",+ ],+ },+ package_data={+ "cli_anything.live2d": ["skills/*.md"],+ },+ include_package_data=True,+ zip_safe=False,++ keywords=[+ "cli",+ "live2d",+ "cubism",+ "model",+ "animation",+ "vtuber",+ ],++ classifiers=[+ "Development Status :: 3 - Alpha",+ "Intended Audience :: Developers",+ "Topic :: Multimedia :: Graphics",+ "Topic :: Software Development :: Libraries :: Python Modules",+ "License :: OSI Approved :: MIT License",+ "Programming Language :: Python :: 3",+ "Programming Language :: Python :: 3.10",+ "Programming Language :: Python :: 3.11",+ "Programming Language :: Python :: 3.12",+ ],+)diff --git a/live2d/agent-harness/tests/__init__.py b/live2d/agent-harness/tests/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/live2d/agent-harness/tests/test_new_features.py b/live2d/agent-harness/tests/test_new_features.pynew file mode 100644index 000000000..1e2a54065--- /dev/null+++ b/live2d/agent-harness/tests/test_new_features.py@@ -0,0 +1,621 @@+"""Tests for new features added in v0.3.0: edit, backup, lint, diff, snapshot, batch, param-edit, atlas, migrate, undo."""++import json+import pytest+from pathlib import Path++from click.testing import CliRunner++from cli_anything.live2d.core import parser as parser_module+from cli_anything.live2d.core.parser import load_model, save_model, MotionRef, ExpressionRef+from cli_anything.live2d.core.backup import snapshot, list_backups, restore, auto_backup, _backup_dir_for+from cli_anything.live2d.core.linter import lint_model, LintReport+from cli_anything.live2d.core.differ import diff_models+from cli_anything.live2d.core.snapshot import write_snapshot, generate_html+from cli_anything.live2d.live2d_cli import cli+++# ── Fixtures ────────────────────────────────────────────────────++SAMPLE_MODEL3 = {+ "Version": 3,+ "FileReferences": {+ "Moc": "model.moc3",+ "Textures": ["textures/texture_00.png"],+ "Physics": "model.physics3.json",+ "Expressions": [+ {"Name": "happy", "File": "expressions/happy.exp3.json"},+ ],+ "Motions": {+ "Idle": [+ {"File": "motions/idle_01.motion3.json", "FadeInTime": 0.5, "FadeOutTime": 0.5},+ {"File": "motions/idle_02.motion3.json", "FadeInTime": 0.5, "FadeOutTime": 0.5},+ ],+ "TapBody": [+ {"File": "motions/tap_body.motion3.json", "FadeInTime": 0.2, "FadeOutTime": 0.2},+ ],+ },+ },+ "Groups": [],+}++SAMPLE_EXPRESSION = {+ "Version": 1,+ "FadeInTime": 0.5,+ "FadeOutTime": 0.5,+ "Parameters": [+ {"Id": "ParamEyeLOpen", "Value": 0.0},+ {"Id": "ParamEyeROpen", "Value": 0.0},+ ],+}+++def model_dir(tmp_path):+ """Create a model directory with all files present."""+ d = tmp_path / "character"+ d.mkdir()++ (d / "model.model3.json").write_text(json.dumps(SAMPLE_MODEL3), encoding="utf-8")+ (d / "model.moc3").write_bytes(b"MOC3" + b"\x00" * 2000)+ (d / "model.physics3.json").write_text("{}", encoding="utf-8")+ (d / "textures").mkdir()+ (d / "textures" / "texture_00.png").write_bytes(b"\x89PNG" + b"\x00" * 100)+ (d / "expressions").mkdir()+ (d / "expressions" / "happy.exp3.json").write_text(json.dumps(SAMPLE_EXPRESSION), encoding="utf-8")+ (d / "motions").mkdir()+ (d / "motions" / "idle_01.motion3.json").write_text(json.dumps({+ "Version": 1, "Meta": {"Duration": 2.0, "Fps": 30, "Loop": True, "CurveCount": 1,+ "TotalSegmentCount": 2, "TotalPointCount": 4},+ "Curves": [{"Target": "Parameter", "Id": "ParamAngleX", "Segments": [0, 0, 0, 1, 1, 1]}]+ }), encoding="utf-8")+ (d / "motions" / "idle_02.motion3.json").write_text(json.dumps({+ "Version": 1, "Meta": {"Duration": 3.0, "Fps": 30, "Loop": True, "CurveCount": 0,+ "TotalSegmentCount": 0, "TotalPointCount": 0},+ "Curves": []+ }), encoding="utf-8")+ (d / "motions" / "tap_body.motion3.json").write_text(json.dumps({+ "Version": 1, "Meta": {"Duration": 1.0, "Fps": 30, "Loop": False, "CurveCount": 0,+ "TotalSegmentCount": 0, "TotalPointCount": 0},+ "Curves": []+ }), encoding="utf-8")++ return d+++def model_path(model_dir):+ return model_dir / "model.model3.json"+++# ── Backup Tests ────────────────────────────────────────────────++class TestBackup:+ def test_snapshot_creates_backup(self, model_path):+ bp = snapshot(model_path)+ assert bp.exists()+ assert bp.suffix == ".json"+ # backup dir uses model file stem (model.model3)+ assert "model" in bp.parent.name++ def test_list_backups(self, model_path):+ snapshot(model_path)+ backups = list_backups(model_path)+ assert len(backups) >= 1+ assert "file" in backups[0]++ def test_restore_latest(self, model_path):+ # Modify, backup, modify again, restore+ info = load_model(model_path)+ info.moc3 = "changed.moc3"+ save_model(info)++ snapshot(model_path) # backup the changed version++ info.moc3 = "changed_again.moc3"+ save_model(info)++ src = restore(model_path)+ restored = load_model(model_path)+ assert restored.moc3 == "changed.moc3"++ def test_auto_backup_dedup(self, model_path):+ """Auto-backup should skip unchanged content."""+ b1 = auto_backup(model_path)+ b2 = auto_backup(model_path)+ assert b1 is not None+ assert b2 is None++ def test_auto_backup_keeps_rapid_changed_states(self, model_path):+ """Rapid edits should still get separate undo points when content changed."""+ b1 = auto_backup(model_path)++ info = load_model(model_path)+ info.moc3 = "changed.moc3"+ save_model(info)++ b2 = auto_backup(model_path)+ assert b1 is not None+ assert b2 is not None+ assert b2 != b1+ assert len(list_backups(model_path)) == 2+ assert load_model(b2).moc3 == "changed.moc3"++ def test_backup_clean_json_deletes_without_dry_run(self, model_path):+ bdir = _backup_dir_for(model_path)+ bdir.mkdir(parents=True)+ for name in (+ "20240101_000000_000000.model3.json",+ "20240102_000000_000000.model3.json",+ "20240103_000000_000000.model3.json",+ ):+ (bdir / name).write_text(model_path.read_text(encoding="utf-8"), encoding="utf-8")++ result = CliRunner().invoke(cli, ["--json", "backup-clean", str(model_path), "--keep", "1"])++ assert result.exit_code == 0, result.output+ data = json.loads(result.output)+ assert data["delete"] == 2+ assert data["deleted"] == [+ "20240102_000000_000000.model3.json",+ "20240101_000000_000000.model3.json",+ ]+ assert sorted(p.name for p in bdir.glob("*.model3.json")) == [+ "20240103_000000_000000.model3.json",+ ]++ def test_list_empty(self, tmp_path):+ f = tmp_path / "m.model3.json"+ f.write_text("{}")+ assert list_backups(f) == []+++# ── Edit + Save Tests ──────────────────────────────────────────++class TestEditAndSave:+ def test_edit_motion_fade(self, model_path):+ info = load_model(model_path)+ info.motions["Idle"][0].fade_in = 1.0+ info.motions["Idle"][0].fade_out = 2.0+ save_model(info)++ reloaded = load_model(model_path)+ assert reloaded.motions["Idle"][0].fade_in == 1.0+ assert reloaded.motions["Idle"][0].fade_out == 2.0++ def test_add_motion(self, model_path):+ info = load_model(model_path)+ info.motions["NewGroup"] = [MotionRef(file="motions/new.motion3.json", fade_in=0.1, fade_out=0.1)]+ save_model(info)++ reloaded = load_model(model_path)+ assert "NewGroup" in reloaded.motions+ assert len(reloaded.motions["NewGroup"]) == 1++ def test_rm_motion(self, model_path):+ info = load_model(model_path)+ info.motions["Idle"].pop(0)+ save_model(info)++ reloaded = load_model(model_path)+ assert len(reloaded.motions["Idle"]) == 1++ def test_add_expression(self, model_path):+ info = load_model(model_path)+ info.expressions.append(ExpressionRef(name="wink", file="expressions/wink.exp3.json"))+ save_model(info)++ reloaded = load_model(model_path)+ names = [e.name for e in reloaded.expressions]+ assert "wink" in names++ def test_rm_expression(self, model_path):+ info = load_model(model_path)+ info.expressions = [e for e in info.expressions if e.name != "happy"]+ save_model(info)++ reloaded = load_model(model_path)+ assert reloaded.expression_count == 0++ def test_edit_texture(self, model_path):+ info = load_model(model_path)+ info.textures[0] = "textures/new_tex.png"+ save_model(info)++ reloaded = load_model(model_path)+ assert reloaded.textures[0] == "textures/new_tex.png"++ def test_edit_model_fields(self, model_path):+ info = load_model(model_path)+ info.moc3 = "new_model.moc3"+ info.physics = "new_physics.json"+ save_model(info)++ reloaded = load_model(model_path)+ assert reloaded.moc3 == "new_model.moc3"+ assert reloaded.physics == "new_physics.json"++ def test_save_model_preserves_original_when_write_fails(self, model_path, monkeypatch):+ original = model_path.read_text(encoding="utf-8")+ info = load_model(model_path)+ info.moc3 = "should_not_persist.moc3"++ def fail_dump(*args, **kwargs):+ raise RuntimeError("simulated write failure")++ monkeypatch.setattr(parser_module.json, "dump", fail_dump)++ with pytest.raises(RuntimeError):+ save_model(info)++ assert model_path.read_text(encoding="utf-8") == original+ assert list(model_path.parent.glob(f".{model_path.name}.*.tmp")) == []+++# ── Lint Tests ──────────────────────────────────────────────────++class TestLint:+ def test_lint_clean_model(self, model_path):+ report = lint_model(model_path)+ # Should have no errors for a well-formed model+ assert report.ok++ def test_lint_missing_texture(self, model_dir, model_path):+ (model_dir / "textures" / "texture_00.png").unlink()+ report = lint_model(model_path)+ assert not report.ok+ assert any("Texture" in i.message and "not found" in i.message for i in report.issues)++ def test_lint_missing_motion(self, model_dir, model_path):+ (model_dir / "motions" / "idle_01.motion3.json").unlink()+ report = lint_model(model_path)+ assert not report.ok+ assert any("Motion" in i.message and "not found" in i.message for i in report.issues)++ def test_lint_report_to_dict(self, model_path):+ report = lint_model(model_path)+ d = report.to_dict()+ assert isinstance(d, dict)+ assert "ok" in d+ assert "issues" in d++ def test_lint_negative_fade(self, model_path):+ info = load_model(model_path)+ info.motions["Idle"][0].fade_in = -1.0+ save_model(info)+ report = lint_model(model_path)+ assert any("Negative" in i.message for i in report.issues)+++# ── Diff Tests ──────────────────────────────────────────────────++class TestDiff:+ def test_diff_identical(self, model_path):+ a = load_model(model_path)+ b = load_model(model_path)+ d = diff_models(a, b)+ assert not d.has_changes++ def test_diff_moc3_change(self, model_path, tmp_path):+ import shutil+ other = tmp_path / "other"+ shutil.copytree(model_path.parent, other)+ other_model = other / "model.model3.json"++ info_b = load_model(other_model)+ info_b.moc3 = "different.moc3"+ save_model(info_b)++ a = load_model(model_path)+ b = load_model(other_model)+ d = diff_models(a, b)+ assert d.has_changes+ assert any(i.category == "field" and i.name == "moc3" for i in d.items)++ def test_diff_motion_fade(self, model_path, tmp_path):+ import shutil+ other = tmp_path / "other"+ shutil.copytree(model_path.parent, other)+ other_model = other / "model.model3.json"++ info_b = load_model(other_model)+ info_b.motions["Idle"][0].fade_in = 99.0+ save_model(info_b)++ a = load_model(model_path)+ b = load_model(other_model)+ d = diff_models(a, b)+ assert d.has_changes+ assert any(i.category == "motion" and "fade_in" in i.detail for i in d.items)++ def test_diff_expression_added(self, model_path, tmp_path):+ import shutil+ other = tmp_path / "other"+ shutil.copytree(model_path.parent, other)+ other_model = other / "model.model3.json"++ info_b = load_model(other_model)+ info_b.expressions.append(ExpressionRef(name="wink", file="expressions/wink.exp3.json"))+ save_model(info_b)++ a = load_model(model_path)+ b = load_model(other_model)+ d = diff_models(a, b)+ assert any(i.category == "expression" and i.name == "wink" for i in d.items)++ def test_diff_to_dict(self, model_path):+ a = load_model(model_path)+ b = load_model(model_path)+ d = diff_models(a, b)+ assert isinstance(d.to_dict(), dict)+++# ── Snapshot Tests ──────────────────────────────────────────────++class TestSnapshot:+ def test_generate_html(self, model_path):+ info = load_model(model_path)+ html = generate_html(info)+ assert "<html" in html+ assert "test_model" in html or "model" in html.lower()+ assert "Idle" in html+ assert "happy" in html++ def test_write_snapshot(self, model_path, tmp_path):+ info = load_model(model_path)+ out = tmp_path / "preview.html"+ result = write_snapshot(info, out)+ assert result.exists()+ content = result.read_text()+ assert "<html" in content+++# ── Param Edit Tests ────────────────────────────────────────────++class TestParamEdit:+ def test_edit_existing_param(self, model_dir):+ expr_path = model_dir / "expressions" / "happy.exp3.json"+ with open(expr_path, "r") as f:+ data = json.load(f)++ for p in data["Parameters"]:+ if p["Id"] == "ParamEyeLOpen":+ p["Value"] = 1.0+ break++ with open(expr_path, "w") as f:+ json.dump(data, f, indent=2)++ with open(expr_path, "r") as f:+ reloaded = json.load(f)++ eye_param = next(p for p in reloaded["Parameters"] if p["Id"] == "ParamEyeLOpen")+ assert eye_param["Value"] == 1.0++ def test_add_new_param(self, model_dir):+ expr_path = model_dir / "expressions" / "happy.exp3.json"+ with open(expr_path, "r") as f:+ data = json.load(f)++ data["Parameters"].append({"Id": "ParamMouthOpenY", "Value": 0.5})++ with open(expr_path, "w") as f:+ json.dump(data, f, indent=2)++ with open(expr_path, "r") as f:+ reloaded = json.load(f)++ assert len(reloaded["Parameters"]) == 3+ mouth = next(p for p in reloaded["Parameters"] if p["Id"] == "ParamMouthOpenY")+ assert mouth["Value"] == 0.5+++# ── Migrate Tests ───────────────────────────────────────────────++class TestMigrate:+ def test_migrate_v1_to_v3(self, model_dir):+ model_path = model_dir / "model.model3.json"+ with open(model_path, "r") as f:+ data = json.load(f)++ data["Version"] = 1+ del data["Groups"]++ with open(model_path, "w") as f:+ json.dump(data, f, indent=2)++ with open(model_path, "r") as f:+ data = json.load(f)+ data["Version"] = 3+ data["Groups"] = []+ with open(model_path, "w") as f:+ json.dump(data, f, indent=2)++ info = load_model(model_path)+ assert info.version == 3++ def test_already_at_target(self, model_path):+ info = load_model(model_path)+ assert info.version == 3 # already v3+++# ── Atlas Tests ─────────────────────────────────────────────────++class TestAtlas:+ def test_atlas_reads_textures(self, model_path):+ info = load_model(model_path)+ assert len(info.textures) == 1+ assert info.textures[0] == "textures/texture_00.png"+++# ── Find-Replace Tests ─────────────────────────────────────────++class TestFindReplace:+ def test_replace_texture_path(self, model_path):+ info = load_model(model_path)+ info.textures[0] = info.textures[0].replace("textures/", "tex/")+ save_model(info)+ reloaded = load_model(model_path)+ assert reloaded.textures[0] == "tex/texture_00.png"++ def test_replace_motion_file(self, model_path):+ info = load_model(model_path)+ for m in info.motions["Idle"]:+ m.file = m.file.replace("idle_", "idle_v2_")+ save_model(info)+ reloaded = load_model(model_path)+ assert "idle_v2_" in reloaded.motions["Idle"][0].file+++# ── Orphan Tests ───────────────────────────────────────────────++class TestOrphan:+ def test_no_orphans(self, model_path):+ info = load_model(model_path)+ model_dir = info.path.parent+ # All existing files should be referenced+ referenced = set()+ referenced.add(info.moc3)+ referenced.update(info.textures)+ for ms in info.motions.values():+ for m in ms:+ referenced.add(m.file)+ for e in info.expressions:+ referenced.add(e.file)+ referenced.discard("")+ assert len(referenced) > 0++ def test_detects_orphan(self, model_dir, model_path):+ # Create an orphan file+ (model_dir / "unused.png").write_bytes(b"fake")+ info = load_model(model_path)+ referenced = set(info.textures)+ assert "unused.png" not in referenced+++# ── Gen-Motion Tests ───────────────────────────────────────────++class TestGenMotion:+ def test_gen_motion_creates_file(self, tmp_path):+ out = tmp_path / "test.motion3.json"+ data = {+ "Version": 1,+ "Meta": {"Duration": 2.0, "Fps": 30, "Loop": True, "CurveCount": 0, "TotalSegmentCount": 0, "TotalPointCount": 0},+ "Curves": [],+ }+ out.write_text(json.dumps(data, indent=2), encoding="utf-8")+ assert out.exists()+ loaded = json.loads(out.read_text())+ assert loaded["Meta"]["Duration"] == 2.0+++# ── Gen-Expr Tests ─────────────────────────────────────────────++class TestGenExpr:+ def test_gen_expr_creates_file(self, tmp_path):+ out = tmp_path / "test.exp3.json"+ data = {"Version": 1, "FadeInTime": 0.5, "FadeOutTime": 0.5, "Parameters": []}+ out.write_text(json.dumps(data, indent=2), encoding="utf-8")+ assert out.exists()+ loaded = json.loads(out.read_text())+ assert loaded["Parameters"] == []+++# ── Rename-Group Tests ────────────────────────────────────────++class TestRenameGroup:+ def test_rename_group(self, model_path):+ info = load_model(model_path)+ assert "Idle" in info.motions+ motions_copy = info.motions.pop("Idle")+ info.motions["idle_v2"] = motions_copy+ save_model(info)+ reloaded = load_model(model_path)+ assert "Idle" not in reloaded.motions+ assert "idle_v2" in reloaded.motions+ assert len(reloaded.motions["idle_v2"]) == 2+++# ── Manifest Tests ─────────────────────────────────────────────++class TestManifest:+ def test_manifest_collects_files(self, model_path):+ import hashlib+ info = load_model(model_path)+ model_dir = info.path.parent+ files = []+ for tex in info.textures:+ p = model_dir / tex+ if p.exists():+ data = p.read_bytes()+ files.append({"path": tex, "size": len(data), "sha256": hashlib.sha256(data).hexdigest()})+ assert len(files) >= 1+ assert "sha256" in files[0]+++# ── Param-List Tests ───────────────────────────────────────────++class TestParamList:+ def test_param_list_finds_params(self, model_path):+ from cli_anything.live2d.core.motion_parser import load_motion+ info = load_model(model_path)+ model_dir = info.path.parent+ params = set()+ for ms in info.motions.values():+ for m in ms:+ mp = model_dir / m.file+ if mp.exists():+ try:+ minfo = load_motion(mp)+ for c in minfo.parameter_curves:+ params.add(c.id)+ except Exception:+ pass+ # Our fixture has ParamAngleX in idle_01+ assert "ParamAngleX" in params+++# ── Flatten Tests ──────────────────────────────────────────────++class TestFlatten:+ def test_flatten_copies_files(self, model_path, tmp_path):+ import shutil+ out = tmp_path / "flat"+ out.mkdir()+ info = load_model(model_path)+ model_dir = info.path.parent+ # Simulate flatten: copy model file and update paths+ shutil.copy2(model_path, out / model_path.name)+ for tex in info.textures:+ src = model_dir / tex+ if src.exists():+ shutil.copy2(src, out / Path(tex).name)+ assert (out / model_path.name).exists()++ def test_flatten_copies_and_rewrites_motion_sound(self, model_dir, model_path, tmp_path):+ data = json.loads(model_path.read_text(encoding="utf-8"))+ data["FileReferences"]["Motions"]["Idle"][0]["Sound"] = "sounds/idle.wav"+ model_path.write_text(json.dumps(data), encoding="utf-8")+ (model_dir / "sounds").mkdir()+ (model_dir / "sounds" / "idle.wav").write_bytes(b"RIFFtest")++ out = tmp_path / "flat"+ result = CliRunner().invoke(cli, ["flatten", str(model_path), "--out-dir", str(out)])++ assert result.exit_code == 0, result.output+ assert (out / "idle.wav").exists()+ flat_info = load_model(out / model_path.name)+ assert flat_info.motions["Idle"][0].file == "idle_01.motion3.json"+ assert flat_info.motions["Idle"][0].extra["Sound"] == "idle.wav"+++# ── Runtime-Check Tests ───────────────────────────────────────++class TestRuntimeCheck:+ def test_runtime_check_clean_model(self, model_path):+ info = load_model(model_path)+ # Should have moc3 and textures+ assert info.moc3+ assert len(info.textures) > 0+ # Should have Idle group+ assert "Idle" in info.motionsdiff --git a/live2d/agent-harness/tests/test_validator.py b/live2d/agent-harness/tests/test_validator.pynew file mode 100644index 000000000..733d22279--- /dev/null+++ b/live2d/agent-harness/tests/test_validator.py@@ -0,0 +1,41 @@+import json+import tempfile+import unittest+from pathlib import Path++from cli_anything.live2d.core.parser import load_model+from cli_anything.live2d.core.validator import validate_model+++class ValidatorStrictModeTest(unittest.TestCase):+ def test_strict_validation_rejects_placeholder_moc3(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ (root / "textures").mkdir()+ (root / "textures" / "texture_00.png").write_bytes(b"fake-png")+ (root / "yoyo.moc3").write_bytes(b"MOC3\x03\x00\x00\x00")+ (root / "yoyo.model3.json").write_text(+ json.dumps(+ {+ "Version": 3,+ "FileReferences": {+ "Moc": "yoyo.moc3",+ "Textures": ["textures/texture_00.png"],+ },+ }+ ),+ encoding="utf-8",+ )++ info = load_model(root / "yoyo.model3.json")+ result = validate_model(info, strict=True)++ self.assertFalse(result.ok)+ self.assertTrue(+ any("Moc3 too small" in error for error in result.errors),+ result.errors,+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/live2d/agent-harness/tests/test_yoyo_pipeline.py b/live2d/agent-harness/tests/test_yoyo_pipeline.pynew file mode 100644index 000000000..1da021dfd--- /dev/null+++ b/live2d/agent-harness/tests/test_yoyo_pipeline.py@@ -0,0 +1,64 @@+import json+import tempfile+import unittest+from pathlib import Path++from cli_anything.live2d.core.yoyo_pipeline import check_yoyo_export+++def write_model(root: Path, motions: dict):+ (root / "textures").mkdir()+ (root / "textures" / "texture_00.png").write_bytes(b"fake-png")+ (root / "yoyo.moc3").write_bytes(b"MOC3\x03\x00\x00\x00" + (b"\0" * 2048))+ (root / "yoyo.model3.json").write_text(+ json.dumps(+ {+ "Version": 3,+ "FileReferences": {+ "Moc": "yoyo.moc3",+ "Textures": ["textures/texture_00.png"],+ "Motions": motions,+ },+ }+ ),+ encoding="utf-8",+ )+++class YoyoPipelineTest(unittest.TestCase):+ def test_check_requires_idle_motion_group(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ write_model(root, motions={"Tap": [{"File": "motions/tap.motion3.json"}]})+ (root / "motions").mkdir()+ (root / "motions" / "tap.motion3.json").write_text(+ json.dumps({"Version": 3, "Meta": {"Duration": 1.0}, "Curves": []}),+ encoding="utf-8",+ )++ report = check_yoyo_export(root / "yoyo.model3.json")++ self.assertFalse(report.ok)+ self.assertTrue(+ any("Missing required motion group: idle" in error for error in report.errors),+ report.errors,+ )++ def test_check_accepts_strict_model_with_idle_motion(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ write_model(root, motions={"Idle": [{"File": "motions/idle.motion3.json"}]})+ (root / "motions").mkdir()+ (root / "motions" / "idle.motion3.json").write_text(+ json.dumps({"Version": 3, "Meta": {"Duration": 1.0}, "Curves": []}),+ encoding="utf-8",+ )++ report = check_yoyo_export(root / "yoyo.model3.json")++ self.assertTrue(report.ok, report.errors)+ self.assertEqual(report.summary["motion_count"], 1)+++if __name__ == "__main__":+ unittest.main()diff --git a/registry.json b/registry.jsonindex 76da9a180..971230650 100644--- a/registry.json+++ b/registry.json@@ -1343,6 +1343,25 @@}]},+ {+ "name": "live2d",+ "display_name": "Live2D Cubism",+ "version": "0.3.0",+ "description": "Inspect, validate, edit, lint, diff, batch-manage, and deploy Live2D Cubism models (.model3.json, .moc3, .motion3.json, .exp3.json) from the command line — 42 commands covering the full model lifecycle",+ "requires": "Python 3.10+",+ "homepage": "https://www.live2d.com",+ "source_url": null,+ "install_cmd": "pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=live2d/agent-harness",+ "entry_point": "cli-anything-live2d",+ "skill_md": "skills/cli-anything-live2d/SKILL.md",+ "category": "graphics",+ "contributors": [+ {+ "name": "zyzly0705",+ "url": "https://github.com/zyzly0705"+ }+ ]+ },{"name": "tigris","display_name": "Tigris",@@ -1363,4 +1382,4 @@]}]-}\ No newline at end of file+}diff --git a/skills/cli-anything-live2d/SKILL.md b/skills/cli-anything-live2d/SKILL.mdnew file mode 100644index 000000000..741c147cf--- /dev/null+++ b/skills/cli-anything-live2d/SKILL.md@@ -0,0 +1,105 @@+---+name: "cli-anything-live2d"+description: "Inspect, validate, edit, lint, diff, batch-manage, and deploy Live2D Cubism models (.model3.json) from the command line."+metadata: { "cli-anything": { "category": "graphics", "requires": null } }+---++# cli-anything-live2d++Full-featured CLI for Live2D Cubism models. 42 commands covering inspection,+editing, linting, diffing, batch operations, asset management, generation,+and deployment — all without the Live2D Editor.++## Commands (42 total)++### Read (18)++| Command | Purpose |+|---------|---------|+| `inspect <model>` | Model overview (version, counts, features) |+| `validate <model>` | Check all referenced files exist |+| `motions <model>` | List motions with fade times |+| `motion-info <file>` | Detailed motion analysis |+| `expressions <model>` | List expression presets |+| `expr-info <file>` | Detailed expression analysis |+| `textures <model>` | List textures with dimensions and sizes |+| `physics <file>` | Physics simulation config |+| `moc3 <file>` | Moc3 binary info |+| `params <model>` | Parameter groups |+| `param-list <model>` | All params across motions/expressions |+| `deps <model>` | Dependency graph |+| `compare <a> <b>` | Quick comparison |+| `diff <a> <b>` | Detailed diff |+| `scan <dir>` | Find all models in directory |+| `export <model>` | Export as JSON/CSV |+| `stats <dir>` | Project overview |+| `manifest <model>` | File inventory with SHA256 checksums |++### Edit (10, all auto-backup)++| Command | Purpose |+|---------|---------|+| `edit-motion` | Edit motion fade times or file path |+| `add-motion` | Add motion to group |+| `rm-motion` | Remove motion |+| `add-expr` | Add expression |+| `rm-expr` | Remove expression |+| `edit-texture` | Replace texture path |+| `edit-model` | Edit moc3/physics/pose/userdata |+| `param-edit` | Edit parameter value in .exp3.json |+| `rename-group` | Rename a motion group |+| `find-replace` | Batch rename file references |++### Generation (3)++| Command | Purpose |+|---------|---------|+| `init` | Generate full model template |+| `gen-motion` | Generate skeleton .motion3.json |+| `gen-expr` | Generate skeleton .exp3.json |++### Analysis (4)++| Command | Purpose |+|---------|---------|+| `lint` | Best practice checks |+| `runtime-check` | Cubism Viewer / Web SDK / Yoyo compatibility |+| `atlas` | Texture atlas analysis |+| `orphan` | Find unreferenced files |++### Workflow (7)++| Command | Purpose |+|---------|---------|+| `undo` | Restore from auto-backup |+| `backup-clean` | Rotate old backups |+| `restore-file` | Restore specific file from backup |+| `batch` | Batch-edit multiple models |+| `snapshot` | Generate HTML preview |+| `watch` | Auto-validate on file changes |+| `flatten` | Flatten directory for deployment |++### Other (3)++| Command | Purpose |+|---------|---------|+| `migrate` | Model format version upgrade |+| `pack` | Package model + deps into zip |+| `yoyo-check` | Yoyo desktop-pet readiness |++All read commands support `--json`. Edit commands auto-backup.++## Examples++```bash+cli-anything-live2d inspect model.model3.json+cli-anything-live2d lint model.model3.json --level info+cli-anything-live2d edit-motion model.model3.json -g Idle -i 0 --fade-in 0.3+cli-anything-live2d find-replace model.model3.json -f "old_tex" -f "new_tex"+cli-anything-live2d orphan model.model3.json+cli-anything-live2d runtime-check model.model3.json --target web-sdk+cli-anything-live2d flatten model.model3.json --out-dir ./deploy/+cli-anything-live2d batch ./models/ --set-fade-in 0.3 --dry-run+cli-anything-live2d snapshot model.model3.json --embed+cli-anything-live2d stats ./project/+```