#!/usr/bin/env python3
from __future__ import annotations
import argparse
import base64
import html
import json
import mimetypes
import os
import re
import shutil
import sys
import tempfile
import zipfile
from html.parser import HTMLParser
from pathlib import Path
from urllib.parse import urlparse
from design_registry import (
DEFAULT_DELIVERABLE_FOR_KIND,
DELIVERABLE_TYPES,
KINDS,
contract_by_id as _contract_by_id,
kind_contract as _kind_contract,
load_kind_contracts as _load_kind_contracts,
load_scenario_blueprints as _load_scenario_blueprints,
load_style_registry as _load_style_registry,
scenario_by_id as _scenario_by_id,
scenario_template_path as _scenario_template_path,
style_by_id as _style_by_id,
style_replacements as _style_replacements,
)
from local_runtime import run_server
from request_router import recommend_for_brief
AI_CAPABILITIES = {"none", "text", "vision", "image", "code"}
STARTERS = {
"tool": "tool",
"dashboard": "dashboard",
"guided": "guided",
"knowledge": "knowledge",
"game": "game",
"presentation": "presentation",
"motion": "motion",
}
TOKEN_PATTERN = re.compile(
r"__(?:TITLE|SUMMARY|KIND|DELIVERABLE|SCENARIO|STYLE_ID|STYLE_CSS|AI_CAPABILITIES)__|\b(?:TODO|FILL_ME)\b",
re.I,
)
SECRET_PATTERNS = [
re.compile(r"\bsk-[A-Za-z0-9_-]{16,}\b"),
re.compile(r"api[_-]?key\s*[:=]\s*['\"][^'\"]+['\"]", re.I),
re.compile(r"authorization\s*[:=]\s*['\"]bearer\s+[^'\"]+['\"]", re.I),
]
PRESENTATION_RATIOS = {
"21x9",
"16x9",
"16x10",
"4x3",
"3x2",
"1x1",
"4x5",
"9x16",
}
DEFAULT_PRESENTATION_LAYOUTS = [
"cover",
"section",
"statement",
"split",
"comparison",
"process",
"timeline",
"metrics",
"evidence",
"gallery",
"diagram",
"closing",
]
DEFAULT_BRAND = {
"name": "Unbranded",
"visualSystem": "custom",
"colors": {
"background": "#E8E8E3",
"surface": "#FFFDF8",
"text": "#18201C",
"muted": "#667068",
"primary": "#1D6552",
"secondary": "#C8D8D0",
"line": "#CFD4CC",
},
"fonts": {
"display": '"Songti SC", "Noto Serif CJK SC", Georgia, serif',
"body": '"PingFang SC", "Microsoft YaHei", system-ui, sans-serif',
"data": 'ui-monospace, "Cascadia Code", Consolas, monospace',
},
"layouts": DEFAULT_PRESENTATION_LAYOUTS,
}
class Inspector(HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.doctype_count = 0
self.tags: list[str] = []
self.end_tags: list[str] = []
self.attrs: list[tuple[str, dict[str, str]]] = []
self.title_depth = 0
self.title_parts: list[str] = []
def handle_decl(self, decl: str) -> None:
if decl.strip().lower() == "doctype html":
self.doctype_count += 1
def handle_starttag(
self, tag: str, attrs: list[tuple[str, str | None]]
) -> None:
tag = tag.lower()
values = {key.lower(): value or "" for key, value in attrs}
self.tags.append(tag)
self.attrs.append((tag, values))
if tag == "title":
self.title_depth += 1
def handle_endtag(self, tag: str) -> None:
tag = tag.lower()
self.end_tags.append(tag)
if tag == "title" and self.title_depth:
self.title_depth -= 1
def handle_data(self, data: str) -> None:
if self.title_depth:
self.title_parts.append(data)
def _read(path: Path) -> str:
return path.read_text(encoding="utf-8-sig")
def _write(path: Path, content: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content.replace("\r\n", "\n"), encoding="utf-8")
def _parse_capabilities(value: str) -> list[str]:
parts = [part.strip().lower() for part in value.split(",") if part.strip()]
if not parts:
return ["none"]
invalid = set(parts) - AI_CAPABILITIES
if invalid:
raise argparse.ArgumentTypeError(
f"Unknown AI capabilities: {', '.join(sorted(invalid))}"
)
if "none" in parts and len(parts) > 1:
raise argparse.ArgumentTypeError("none cannot be combined with other capabilities")
return list(dict.fromkeys(parts))
def _starter_for(kind: str, capabilities: list[str]) -> str:
if kind == "tool" and capabilities != ["none"]:
return "ai-tool"
return STARTERS[kind]
def _deliverable_for(kind: str, value: str | None) -> str:
deliverable = value or DEFAULT_DELIVERABLE_FOR_KIND[kind]
if deliverable not in DELIVERABLE_TYPES:
raise SystemExit(f"Unknown deliverable type: {deliverable}")
return deliverable
def _brand_pack_root() -> Path:
return Path(__file__).resolve().parents[1] / "assets" / "brand-packs"
def _resolve_brand_path(value: str) -> Path:
built_in = _brand_pack_root() / value
candidate = built_in if built_in.is_dir() else Path(value).expanduser().resolve()
if candidate.is_dir():
candidate = candidate / "brand.json"
if not candidate.is_file():
raise SystemExit(f"Could not find brand pack: {value}")
return candidate
def _css_value(value: object, label: str) -> str:
text = str(value).strip()
if not text or any(token in text for token in ("{", "}", ";", " tuple[dict[str, object], Path | None]:
if not value:
return json.loads(json.dumps(DEFAULT_BRAND)), None
path = _resolve_brand_path(value)
try:
profile = json.loads(_read(path))
except (json.JSONDecodeError, OSError) as exc:
raise SystemExit(f"Invalid brand profile {path}: {exc}") from exc
if not isinstance(profile, dict):
raise SystemExit("Brand profile must be a JSON object")
for key in ("name", "visualSystem", "colors", "fonts", "layouts"):
if key not in profile:
raise SystemExit(f"Brand profile is missing {key}")
colors = profile.get("colors")
fonts = profile.get("fonts")
layouts = profile.get("layouts")
if not isinstance(colors, dict) or not isinstance(fonts, dict):
raise SystemExit("Brand colors and fonts must be JSON objects")
if not isinstance(layouts, list) or not layouts:
raise SystemExit("Brand layouts must be a non-empty list")
required_colors = set(DEFAULT_BRAND["colors"])
required_fonts = set(DEFAULT_BRAND["fonts"])
if required_colors - set(colors):
raise SystemExit(
f"Brand colors are missing: {', '.join(sorted(required_colors - set(colors)))}"
)
if required_fonts - set(fonts):
raise SystemExit(
f"Brand fonts are missing: {', '.join(sorted(required_fonts - set(fonts)))}"
)
for key, color in colors.items():
if not re.fullmatch(r"#[0-9A-Fa-f]{6}", str(color)):
raise SystemExit(f"Brand color {key} must be #RRGGBB")
for key, font in fonts.items():
_css_value(font, f"fonts.{key}")
for layout in layouts:
if not re.fullmatch(r"[a-z][a-z0-9-]*", str(layout)):
raise SystemExit(f"Invalid brand layout name: {layout}")
return profile, path
def _brand_replacements(value: str | None) -> dict[str, str]:
profile, path = _load_brand(value)
colors = profile["colors"]
fonts = profile["fonts"]
assert isinstance(colors, dict) and isinstance(fonts, dict)
logo_markup = ""
logo = str(profile.get("logo", "")).strip()
if logo:
if path is None:
raise SystemExit("A logo requires a file-backed brand pack")
logo_path = (path.parent / logo).resolve()
if not logo_path.is_file() or not logo_path.is_relative_to(path.parent.resolve()):
raise SystemExit(f"Brand logo is missing or outside the brand pack: {logo}")
mime = mimetypes.guess_type(logo_path.name)[0] or "application/octet-stream"
encoded = base64.b64encode(logo_path.read_bytes()).decode("ascii")
data_uri = f"data:{mime};base64,{encoded}"
logo_markup = (
f''
)
custom_css = ""
css_file = str(profile.get("customCss", "")).strip()
if css_file:
if path is None:
raise SystemExit("customCss requires a file-backed brand pack")
css_path = (path.parent / css_file).resolve()
if not css_path.is_file() or not css_path.is_relative_to(path.parent.resolve()):
raise SystemExit(f"Brand CSS is missing or outside the brand pack: {css_file}")
custom_css = _read(css_path)
if " None:
scenario_id = getattr(args, "scenario", None)
scenario = _scenario_by_id(scenario_id) if scenario_id else None
requested_kind = getattr(args, "kind", None)
if not requested_kind and not scenario:
raise SystemExit("--kind is required unless --scenario is supplied")
kind = requested_kind or str(scenario["kind"])
if scenario and requested_kind and requested_kind != scenario["kind"]:
raise SystemExit(f"Scenario {scenario_id} requires --kind {scenario['kind']}")
requested_deliverable = getattr(args, "deliverable", None)
if scenario and requested_deliverable and requested_deliverable != scenario["deliverable"]:
raise SystemExit(
f"Scenario {scenario_id} requires --deliverable {scenario['deliverable']}"
)
requested_style = getattr(args, "style", None)
deliverable = _deliverable_for(
kind, str(scenario["deliverable"]) if scenario else requested_deliverable
)
style = requested_style or (str(scenario["defaultStyle"]) if scenario else None)
output = Path(args.out).expanduser().resolve()
if output.exists() and any(output.iterdir()):
raise SystemExit(f"Output directory is not empty: {output}")
output.mkdir(parents=True, exist_ok=True)
capabilities = _parse_capabilities(args.ai)
starter_name = _starter_for(kind, capabilities)
contract = (
_kind_contract(kind)
if not scenario
and starter_name == kind
and kind in {"tool", "dashboard", "guided", "knowledge", "game", "presentation"}
else None
)
source = (
_scenario_template_path(scenario)
if scenario
else Path(__file__).resolve().parents[1]
/ "assets"
/ "starters"
/ starter_name
/ "index.html"
)
if not source.is_file():
raise SystemExit(f"Missing starter: {source}")
content = _read(source)
replacements = {
"__TITLE__": html.escape(args.title, quote=True),
"__SUMMARY__": html.escape(args.summary, quote=True),
"__KIND__": kind,
"__DELIVERABLE__": deliverable,
"__SCENARIO__": scenario_id or "custom",
"__AI_CAPABILITIES__": ",".join(capabilities),
}
replacements.update(_style_replacements(style))
brand = getattr(args, "brand", None)
if brand and kind != "presentation":
raise SystemExit("Brand packs are currently supported for presentation scaffolds")
if brand and style:
raise SystemExit("Choose either --brand or --style; brand identity takes precedence")
if kind == "presentation":
replacements.update(_brand_replacements(brand))
for old, new in replacements.items():
content = content.replace(old, new)
if contract:
dials = contract["dials"]
assert isinstance(dials, dict)
body_attributes = (
f' data-kind-contract="{html.escape(str(contract["id"]), quote=True)}"'
f' data-design-variance="{dials["variance"]}"'
f' data-motion-intensity="{dials["motion"]}"'
f' data-visual-density="{dials["density"]}"'
)
content = re.sub(r"
)", f")",
f' None:
output = Path(args.out).expanduser().resolve()
html_path = output if output.suffix.lower() in {".html", ".htm"} else output / "styleboard.html"
if html_path.exists() and not args.force:
raise SystemExit(f"Output already exists: {html_path}. Use --force to replace it.")
if html_path.exists() and not html_path.is_file():
raise SystemExit(f"Styleboard output is not a file: {html_path}")
source = (
Path(__file__).resolve().parents[1]
/ "assets"
/ "presentation-styleboard"
/ "index.html"
)
if not source.is_file():
raise SystemExit(f"Missing presentation styleboard: {source}")
content = _read(source)
replacements = {
"__TITLE__": html.escape(args.title, quote=True),
"__SUMMARY__": html.escape(args.summary, quote=True),
}
for old, new in replacements.items():
content = content.replace(old, new)
_write(html_path, content)
print(f"Styleboard: {html_path}")
def list_brands(args: argparse.Namespace) -> None:
brands: dict[str, dict[str, object]] = {}
for path in sorted(_brand_pack_root().glob("*/brand.json")):
profile, _ = _load_brand(str(path))
brands[path.parent.name] = {
"name": profile["name"],
"visualSystem": profile["visualSystem"],
}
if args.json:
print(json.dumps(brands, ensure_ascii=False, indent=2))
return
for identifier, profile in brands.items():
print(f"{identifier:24} {profile['name']} ({profile['visualSystem']})")
def init_brand(args: argparse.Namespace) -> None:
source = _brand_pack_root() / args.from_pack
if not (source / "brand.json").is_file():
raise SystemExit(f"Unknown built-in brand pack: {args.from_pack}")
output = Path(args.out).expanduser().resolve()
if output.exists() and any(output.iterdir()):
raise SystemExit(f"Output directory is not empty: {output}")
output.mkdir(parents=True, exist_ok=True)
for path in source.iterdir():
if path.is_file():
shutil.copy2(path, output / path.name)
brand_path = output / "brand.json"
profile = json.loads(_read(brand_path))
profile["name"] = args.name
_write(brand_path, json.dumps(profile, ensure_ascii=False, indent=2) + "\n")
print(f"Brand pack: {output}")
def _external_reference(value: str) -> bool:
parsed = urlparse(value)
return parsed.scheme in {"http", "https"} or value.startswith("//")
def _local_reference_exists(html_path: Path, value: str) -> bool:
if not value or value.startswith(("#", "data:", "blob:", "mailto:", "tel:")):
return True
parsed = urlparse(value)
if parsed.scheme or value.startswith("/runtime/"):
return True
if value.startswith("/"):
return False
return (html_path.parent / parsed.path).resolve().exists()
def _tag_attribute(tag: str, name: str) -> str:
match = re.search(rf"\b{re.escape(name)}\s*=\s*(['\"])(.*?)\1", tag, re.I | re.S)
return match.group(2).strip() if match else ""
def _presentation_static_checks(
source: str, body_values: dict[str, str]
) -> tuple[list[str], list[str]]:
errors: list[str] = []
warnings: list[str] = []
slide_pattern = re.compile(
r"]*\bclass\s*=\s*(['\"])[^'\"]*\bslide\b[^'\"]*\1)[^>]*>[\s\S]*?",
re.I,
)
slides = list(slide_pattern.finditer(source))
slide_ids: list[str] = []
active_count = 0
allowed_brand_layouts = {
item.strip()
for item in body_values.get("data-brand-layouts", "").split(",")
if item.strip()
}
for number, match in enumerate(slides, start=1):
block = match.group(0)
tag = block[: block.find(">") + 1]
classes = _tag_attribute(tag, "class").split()
active_count += int("active" in classes)
layout = _tag_attribute(tag, "data-layout")
slide_id = _tag_attribute(tag, "data-slide-id")
if not layout:
errors.append(f"Slide {number} is missing data-layout")
elif not re.fullmatch(r"[a-z][a-z0-9-]*", layout):
warnings.append(
f"Slide {number} data-layout should be a descriptive kebab-case name"
)
elif allowed_brand_layouts and layout not in allowed_brand_layouts:
errors.append(
f"Slide {number} layout {layout} is not allowed by the active brand pack"
)
if not slide_id:
errors.append(f"Slide {number} is missing data-slide-id")
elif not re.fullmatch(r"[a-z0-9][a-z0-9-]*", slide_id):
errors.append(f"Slide {number} has an invalid data-slide-id: {slide_id}")
else:
slide_ids.append(slide_id)
if not re.search(r"]*>", block, re.I | re.S):
src = _tag_attribute(image_tag, "src")
if not src or src.startswith(("data:", "blob:")) or _external_reference(src):
continue
slot = _tag_attribute(image_tag, "data-image-slot")
if not slot:
warnings.append(
f"Slide {number} local image is missing data-image-slot"
)
continue
ratio = slot.rsplit("-", 1)[-1].lower()
if ratio not in PRESENTATION_RATIOS:
warnings.append(
f"Slide {number} image slot should end in a supported ratio such as hero-16x9"
)
duplicates = sorted({slide_id for slide_id in slide_ids if slide_ids.count(slide_id) > 1})
if duplicates:
errors.append(f"Duplicate data-slide-id values: {', '.join(duplicates)}")
if slides and active_count != 1:
errors.append("Presentation must have exactly one initially active slide")
stage_mode = body_values.get("data-stage-mode", "")
if stage_mode not in {"fixed", "responsive"}:
warnings.append("Declare data-stage-mode as fixed or responsive")
if not body_values.get("data-visual-system"):
warnings.append("Declare a subject-specific data-visual-system")
if not body_values.get("data-brand"):
warnings.append("Declare data-brand, using Unbranded when no brand pack applies")
if body_values.get("data-density") not in {"sparse", "balanced", "dense"}:
warnings.append("Declare data-density as sparse, balanced, or dense")
runtime_markers = {
"shareable slide hashes": r"location\.hash|hashchange|#slide-",
"wheel navigation": r"\bwheel\b",
"touch or pointer swipe navigation": r"touchstart|pointerdown",
}
for label, pattern in runtime_markers.items():
if not re.search(pattern, source, re.I):
warnings.append(f"Presentation is missing {label}")
if re.search(r"