Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /MarkinHaus_ToolBoxV2 /toolboxv2 /utils /clis /manifest_cli.py
"""
Manifest CLI - Command line interface for tb-manifest.yaml management
Commands:
tb manifest show - Display current manifest
tb manifest validate - Validate manifest syntax and semantics
tb manifest apply - Generate sub-configs from manifest
tb manifest init - Create default manifest interactively
tb manifest status - Show service status vs manifest
tb manifest sync - Sync running services with manifest
"""
import argparse
import sys
from pathlib import Path
from typing import Optional
from .cli_printing import (
print_box_header,
print_box_footer,
print_status,
print_separator,
print_code_block,
c_print,
)
def create_parser() -> argparse.ArgumentParser:
"""Create argument parser for manifest CLI."""
parser = argparse.ArgumentParser(
prog="tb manifest",
description="๐ ToolBoxV2 Manifest Configuration Manager",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Manifest Commands โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
โ โ
โ tb manifest show Show current manifest content โ
โ tb manifest validate Validate manifest syntax and semantics โ
โ tb manifest apply Generate sub-configs from manifest โ
โ tb manifest init Create default manifest interactively โ
โ tb manifest status Show service status vs manifest โ
โ tb manifest sync Sync running services with manifest โ
โ โ
โ Feature Management: โ
โ tb manifest list List all features and their status โ
โ tb manifest enable <feature> Enable a feature (auto-installs deps) โ
โ tb manifest disable <feature> Disable a feature โ
โ tb manifest files <feature> Show files belonging to a feature โ
โ โ
โ Pack/Unpack: โ
โ tb manifest pack <feature> Pack feature into ZIP archive โ
โ tb manifest unpack <path> Unpack feature from ZIP archive โ
โ tb manifest packed List available packed features โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
"""
)
subparsers = parser.add_subparsers(dest="command", help="Manifest commands")
# show
p_show = subparsers.add_parser("show", help="Display current manifest")
p_show.add_argument("--json", action="store_true", help="Output as JSON")
p_show.add_argument("--section", type=str, help="Show specific section (app, database, workers, etc.)")
# validate
p_validate = subparsers.add_parser("validate", help="Validate manifest")
p_validate.add_argument("--strict", action="store_true", help="Strict validation mode")
# apply
p_apply = subparsers.add_parser("apply", help="Generate sub-configs from manifest")
p_apply.add_argument("--dry-run", action="store_true", help="Show what would be generated")
p_apply.add_argument("--force", action="store_true", help="Overwrite existing files")
p_apply.add_argument("--env", action="store_true", help="Also suggest missing env vars")
# init
p_init = subparsers.add_parser("init", help="Create default manifest")
p_init.add_argument("--force", action="store_true", help="Overwrite existing manifest")
p_init.add_argument("--env", type=str, choices=["development", "production", "staging"],
default="development", help="Initial environment")
# status
subparsers.add_parser("status", help="Show service status vs manifest")
# sync
p_sync = subparsers.add_parser("sync", help="Sync running services with manifest")
p_sync.add_argument("--dry-run", action="store_true", help="Show what would be done")
p_sync.add_argument("--restart", action="store_true", help="Restart all manifest services")
# Feature management commands
p_list = subparsers.add_parser("list", help="List all features and their status")
p_enable = subparsers.add_parser("enable", help="Enable a feature (auto-installs dependencies)")
p_enable.add_argument("feature", nargs="?", help="Feature name to enable")
p_disable = subparsers.add_parser("disable", help="Disable a feature")
p_disable.add_argument("feature", nargs="?", help="Feature name to disable")
p_files = subparsers.add_parser("files", help="Show files belonging to a feature")
p_files.add_argument("feature", nargs="?", help="Feature name to show files for")
# Pack/Unpack commands
p_pack = subparsers.add_parser("pack", help="Pack feature into ZIP archive")
p_pack.add_argument("feature", help="Feature name to pack")
p_pack.add_argument("--output", "-o", type=str, help="Output directory (default: ./features_sto/)")
p_unpack = subparsers.add_parser("unpack", help="Unpack feature from ZIP archive")
p_unpack.add_argument("path", help="Path to ZIP file")
p_unpack.add_argument("--target", "-t", type=str, help="Target features directory")
p_packed = subparsers.add_parser("packed", help="List available packed features")
p_packed.add_argument("--dir", type=str, help="Directory to search (default: ./features_sto/)")
# set
p_set = subparsers.add_parser("set", help="Set manifest value (also syncs .env)")
p_set.add_argument("key", help="Dotted key, e.g. database.mode")
p_set.add_argument("value", help="New value")
# get
p_get = subparsers.add_parser("get", help="Get manifest value")
p_get.add_argument("key", help="Dotted key, e.g. database.mode")
return parser
def cmd_show(args) -> int:
"""Show manifest content."""
from toolboxv2.utils.manifest import ManifestLoader
from toolboxv2 import tb_root_dir
loader = ManifestLoader(tb_root_dir)
if not loader.exists():
print_status("No tb-manifest.yaml found", "error")
print_status("Create one with: tb manifest init", "info")
return 1
try:
if args.json:
manifest = loader.load()
import json
if args.section:
section_data = getattr(manifest, args.section, None)
if section_data is None:
print_status(f"Unknown section: {args.section}", "error")
return 1
print(json.dumps(section_data.model_dump(), indent=2, default=str))
else:
print(json.dumps(manifest.model_dump(), indent=2, default=str))
else:
# Show raw YAML
with open(loader.manifest_path, "r", encoding="utf-8") as f:
content = f.read()
if args.section:
# Extract section from YAML
import yaml
data = yaml.safe_load(content)
if args.section not in data:
print_status(f"Unknown section: {args.section}", "error")
return 1
print_code_block(yaml.dump({args.section: data[args.section]}, default_flow_style=False), "yaml")
else:
print_box_header("tb-manifest.yaml", "๐")
print_code_block(content, "yaml", show_line_numbers=True)
print_box_footer()
return 0
except Exception as e:
print_status(f"Error reading manifest: {e}", "error")
return 1
def cmd_validate(args) -> int:
"""Validate manifest."""
from toolboxv2.utils.manifest import ManifestLoader
from toolboxv2 import tb_root_dir
loader = ManifestLoader(tb_root_dir)
print_box_header("Manifest Validation", "โ
")
if not loader.exists():
print_status("No tb-manifest.yaml found", "error")
print_box_footer()
return 1
try:
# Try to load (validates schema)
manifest = loader.load()
print_status("Schema validation: PASSED", "success")
# Semantic validation
is_valid, errors = loader.validate()
if is_valid:
print_status("Semantic validation: PASSED", "success")
else:
print_status("Semantic validation: FAILED", "error")
for err in errors:
print(f" โข {err}")
print_box_footer()
return 0 if is_valid else 1
except Exception as e:
print_status(f"Schema validation: FAILED", "error")
print(f" โข {e}")
print_box_footer()
return 1
def cmd_apply(args) -> int:
"""Apply manifest to generate sub-configs."""
from toolboxv2.utils.manifest import ManifestLoader, ConfigConverter
from toolboxv2 import tb_root_dir
loader = ManifestLoader(tb_root_dir)
print_box_header("Apply Manifest", "๐")
if not loader.exists():
print_status("No tb-manifest.yaml found", "error")
print_status("Create one with: tb manifest init", "info")
print_box_footer()
return 1
try:
manifest = loader.load()
converter = ConfigConverter(manifest, tb_root_dir)
if args.dry_run:
print_status("Dry run - no files will be written", "info")
print()
print("Would generate:")
print(f" โข {tb_root_dir / '.config.yaml'}")
print(f" โข {tb_root_dir / 'bin' / 'config.toml'}")
print(f" โข {tb_root_dir / '.info' / 'services.json'}")
if manifest.nginx.enabled:
print(f" โข {tb_root_dir / 'nginx.conf'}")
if args.env:
suggestions = converter._suggest_env_vars()
if suggestions:
print()
print_status("Missing environment variables:", "warning")
for var, default in suggestions.items():
print(f" โข {var}={default or '(needs value)'}")
else:
print_status("Generating configuration files...", "progress")
generated = converter.apply_all()
print()
print_status("Generated files:", "success")
for path in generated:
print(f" โ {path}")
if args.env:
suggestions = converter._suggest_env_vars()
if suggestions:
print()
print_status("Missing environment variables:", "warning")
for var, default in suggestions.items():
print(f" โข {var}={default or '(needs value)'}")
response = input("\n Add missing vars to .env? (y/N): ").strip().lower()
if response == 'y':
added = converter.append_missing_env_vars()
print_status(f"Added {len(added)} variables to .env", "success")
print_box_footer()
return 0
except Exception as e:
print_status(f"Apply failed: {e}", "error")
import traceback
traceback.print_exc()
print_box_footer()
return 1
def cmd_init(args) -> int:
"""Create default manifest."""
from toolboxv2.utils.manifest import ManifestLoader, TBManifest
from toolboxv2.utils.manifest.schema import Environment
from toolboxv2 import tb_root_dir
loader = ManifestLoader(tb_root_dir)
print_box_header("Initialize Manifest", "๐")
if loader.exists() and not args.force:
print_status("tb-manifest.yaml already exists", "warning")
print_status("Use --force to overwrite", "info")
print_box_footer()
return 1
try:
# Create manifest with specified environment
env_map = {
"development": Environment.DEVELOPMENT,
"production": Environment.PRODUCTION,
"staging": Environment.STAGING,
}
manifest = TBManifest(
app={"environment": env_map[args.env]}
)
loader.save(manifest)
print_status(f"Created: {loader.manifest_path}", "success")
print_status(f"Environment: {args.env}", "info")
print()
print(" Next steps:")
print(" 1. Edit tb-manifest.yaml to customize your config")
print(" 2. Run 'tb manifest validate' to check for errors")
print(" 3. Run 'tb manifest apply' to generate sub-configs")
print_box_footer()
return 0
except Exception as e:
print_status(f"Failed to create manifest: {e}", "error")
print_box_footer()
return 1
def cmd_status(args) -> int:
"""Show service status vs manifest."""
from toolboxv2.utils.manifest import ManifestServiceManager
manager = ManifestServiceManager()
manifest = manager.get_manifest()
print_box_header("Service Status", "๐")
if not manifest:
print_status("No tb-manifest.yaml found", "warning")
print_status("Showing legacy services.json status", "info")
print()
report = manager.get_status_report()
# Group by status
running = []
should_run = []
extra = []
stopped = []
for name, info in report.items():
status = info.get("status", "unknown")
if status == "running":
running.append((name, info))
elif status == "not_started":
should_run.append((name, info))
elif status == "running_extra":
extra.append((name, info))
else:
stopped.append((name, info))
if running:
print_status("Running (in manifest):", "success")
for name, info in running:
pid = info.get("pid", "?")
print(f" โ {name} (PID: {pid})")
if should_run:
print()
print_status("Should be running (not started):", "warning")
for name, info in should_run:
print(f" โ {name}")
if extra:
print()
print_status("Running (not in manifest):", "info")
for name, info in extra:
pid = info.get("pid", "?")
print(f" ? {name} (PID: {pid})")
print_box_footer()
return 0
def cmd_sync(args) -> int:
"""Sync running services with manifest."""
from toolboxv2.utils.manifest import ManifestServiceManager
manager = ManifestServiceManager()
print_box_header("Sync Services", "๐")
if not manager.get_manifest():
print_status("No tb-manifest.yaml found", "error")
print_box_footer()
return 1
if args.restart:
print_status("Restarting all manifest services...", "progress")
result = manager.restart_manifest_services()
else:
if args.dry_run:
print_status("Dry run - no services will be started", "info")
result = manager.sync_services(dry_run=args.dry_run)
print()
if result.already_running:
print_status("Already running:", "info")
for name in result.already_running:
print(f" โข {name}")
if result.started:
action = "Would start" if args.dry_run else "Started"
print_status(f"{action}:", "success")
for name in result.started:
print(f" โ {name}")
if result.commands_executed:
action = "Would execute" if args.dry_run else "Executed"
print_status(f"{action} commands:", "success")
for cmd in result.commands_executed:
print(f" $ {cmd}")
if result.failed:
print_status("Failed:", "error")
for name, error in result.failed.items():
print(f" โ {name}: {error}")
print_box_footer()
return 0 if not result.failed else 1
# =============================================================================
# Feature Management Commands
# =============================================================================
def _get_feature_manager():
"""Get or create FeatureManager instance."""
from toolboxv2.utils.system.feature_manager import FeatureManager
from toolboxv2 import tb_root_dir
features_dir = tb_root_dir / "features"
print(str(features_dir), features_dir.exists())
return FeatureManager(features_dir=str(features_dir.name))
def cmd_list(args) -> int:
"""List all features and their status."""
from rich.table import Table
from rich.console import Console
console = Console()
print_box_header("Feature Status", "๐ฆ")
try:
fm = _get_feature_manager()
if not fm.features:
print_status("No features found", "warning")
print_status("Features are loaded from toolboxv2/features/*/feature.yaml", "info")
print_box_footer()
return 1
table = Table(show_header=True, header_style="bold cyan")
table.add_column("Feature", style="bold")
table.add_column("Status")
table.add_column("Version")
table.add_column("Immutable")
table.add_column("Description")
for fname, fspec in fm.features.items():
status = "[green]ENABLED[/green]" if fspec.enabled else "[red]DISABLED[/red]"
immut = "[yellow]YES[/yellow]" if fspec.immutable else "[dim]NO[/dim]"
table.add_row(
fname,
status,
fspec.version,
immut,
fspec.description[:40] + "..." if len(fspec.description) > 40 else fspec.description
)
console.print(table)
print_box_footer()
return 0
except Exception as e:
print_status(f"Error listing features: {e}", "error")
print_box_footer()
return 1
def cmd_enable(args) -> int:
"""Enable a feature with auto-dependency installation."""
if not args.feature:
print_status("Feature name required", "error")
print_status("Usage: tb manifest enable <feature>", "info")
return 1
feature_name = args.feature.lower()
print_box_header(f"Enable Feature: {feature_name}", "โ
")
try:
fm = _get_feature_manager()
if feature_name not in fm.features:
print_status(f"Unknown feature: {feature_name}", "error")
print_status(f"Available: {', '.join(fm.features.keys())}", "info")
print_box_footer()
return 1
feature = fm.features[feature_name]
# Check requirements
if feature.requires:
print_status(f"Checking requirements: {', '.join(feature.requires)}", "progress")
for req in feature.requires:
if not fm.is_enabled(req):
print_status(f"Required feature '{req}' is not enabled", "error")
print_status(f"Run: tb manifest enable {req}", "info")
print_box_footer()
return 1
# Show dependencies that will be installed
if feature.dependencies:
print_status(f"Dependencies to install: {', '.join(feature.dependencies)}", "info")
success = fm.enable(feature_name)
if success:
print_status(f"Feature '{feature_name}' enabled", "success")
# Save to manifest
if fm.save_to_manifest(feature_name):
print_status("Updated tb-manifest.yaml", "success")
print_box_footer()
return 0
else:
print_status(f"Failed to enable '{feature_name}'", "error")
print_box_footer()
return 1
except Exception as e:
print_status(f"Error enabling feature: {e}", "error")
import traceback
traceback.print_exc()
print_box_footer()
return 1
def cmd_disable(args) -> int:
"""Disable a feature."""
if not args.feature:
print_status("Feature name required", "error")
print_status("Usage: tb manifest disable <feature>", "info")
return 1
feature_name = args.feature.lower()
print_box_header(f"Disable Feature: {feature_name}", "๐ซ")
try:
fm = _get_feature_manager()
if feature_name not in fm.features:
print_status(f"Unknown feature: {feature_name}", "error")
print_status(f"Available: {', '.join(fm.features.keys())}", "info")
print_box_footer()
return 1
feature = fm.features[feature_name]
# Warn for core
if feature_name == "core":
print_status("WARNING: Disabling 'core' is not recommended!", "warning")
confirm = input("Continue? (yes/no): ").strip().lower()
if confirm != "yes":
print_status("Aborted", "info")
print_box_footer()
return 0
# Warn for immutable
if feature.immutable:
print_status(f"WARNING: Feature '{feature_name}' is marked as immutable", "warning")
success = fm.disable(feature_name)
if success:
print_status(f"Feature '{feature_name}' disabled", "success")
# Save to manifest
if fm.save_to_manifest(feature_name):
print_status("Updated tb-manifest.yaml", "success")
print_box_footer()
return 0
else:
print_status(f"Failed to disable '{feature_name}'", "error")
print_box_footer()
return 1
except Exception as e:
print_status(f"Error disabling feature: {e}", "error")
print_box_footer()
return 1
def cmd_files(args) -> int:
"""Show files belonging to a feature."""
if not args.feature:
print_status("Feature name required", "error")
print_status("Usage: tb manifest files <feature>", "info")
return 1
feature_name = args.feature.lower()
print_box_header(f"Files for Feature: {feature_name}", "๐")
try:
fm = _get_feature_manager()
if feature_name not in fm.features:
print_status(f"Unknown feature: {feature_name}", "error")
print_status(f"Available: {', '.join(fm.features.keys())}", "info")
print_box_footer()
return 1
feature = fm.features[feature_name]
print_status(f"Description: {feature.description}", "info")
print_status(f"Version: {feature.version}", "info")
print()
if feature.files:
print_status("File patterns:", "success")
for fpattern in feature.files:
print(f" โข {fpattern}")
else:
print_status("No file patterns defined", "warning")
if feature.imports:
print()
print_status("Imports:", "info")
for imp in feature.imports:
print(f" โข {imp}")
if feature.dependencies:
print()
print_status("Dependencies:", "info")
for dep in feature.dependencies:
print(f" โข {dep}")
if feature.requires:
print()
print_status("Requires features:", "info")
for req in feature.requires:
status = "[green]โ[/green]" if fm.is_enabled(req) else "[red]โ[/red]"
print(f" โข {req} {status}")
print_box_footer()
return 0
except Exception as e:
print_status(f"Error showing files: {e}", "error")
print_box_footer()
return 1
# =============================================================================
# Pack/Unpack Commands
# =============================================================================
def cmd_pack(args) -> int:
"""Pack a feature into a ZIP archive."""
feature_name = args.feature.lower()
print_box_header(f"Pack Feature: {feature_name}", "๐ฆ")
try:
fm = _get_feature_manager()
if feature_name not in fm.features:
print_status(f"Unknown feature: {feature_name}", "error")
print_status(f"Available: {', '.join(fm.features.keys())}", "info")
print_box_footer()
return 1
feature = fm.features[feature_name]
print_status(f"Version: {feature.version}", "info")
print_status(f"Description: {feature.description}", "info")
# Show what will be packed
files = fm.get_files_for_feature(feature_name)
if files:
print()
print_status("Files to pack:", "progress")
for f in files:
print(f" โข {f}")
if feature.dependencies:
print()
print_status("Dependencies:", "info")
for dep in feature.dependencies:
print(f" โข {dep}")
print()
print_status("Packing...", "progress")
zip_path = fm.pack_feature(feature_name, output_path=args.output)
if zip_path:
print_status(f"Created: {zip_path}", "success")
# Show file size
from pathlib import Path
size_kb = Path(zip_path).stat().st_size // 1024
print_status(f"Size: {size_kb} KB", "info")
print_box_footer()
return 0
else:
print_status("Pack failed", "error")
print_box_footer()
return 1
except Exception as e:
print_status(f"Error packing feature: {e}", "error")
import traceback
traceback.print_exc()
print_box_footer()
return 1
def cmd_unpack(args) -> int:
"""Unpack a feature from a ZIP archive."""
from pathlib import Path
fm = _get_feature_manager()
zip_path = fm.resolve_packed_zip(args.path)
if zip_path is None:
print_box_header(f"Unpack Feature: {args.path}", "๐ฅ")
print_status(f"Nicht gefunden als Pfad, Dateiname oder Feature-Name: {args.path}", "error")
print_status("Verfรผgbare Pakete: tb manifest packed", "info")
print_box_footer()
return 1
print_box_header(f"Unpack Feature: {zip_path.name}", "๐ฅ")
if not zip_path.exists():
print_status(f"File not found: {zip_path}", "error")
print_box_footer()
return 1
try:
# Show package info
print_status(f"Archive: {zip_path}", "info")
size_kb = zip_path.stat().st_size // 1024
print_status(f"Size: {size_kb} KB", "info")
print()
print_status("Unpacking...", "progress")
feature_name = fm.unpack_feature(str(zip_path), target_dir=args.target)
if feature_name:
print_status(f"Feature unpacked: {feature_name}", "success")
# Show status
if feature_name in fm.features:
feature = fm.features[feature_name]
print()
print_status(f"Version: {feature.version}", "info")
print_status(f"Enabled: {feature.enabled}", "info")
if feature.dependencies:
print()
print_status("Dependencies (install with enable):", "info")
for dep in feature.dependencies:
print(f" โข {dep}")
print()
print_status(f"Enable with: tb manifest enable {feature_name}", "info")
print_box_footer()
return 0
else:
print_status("Unpack failed", "error")
print_box_footer()
return 1
except Exception as e:
print_status(f"Error unpacking feature: {e}", "error")
import traceback
traceback.print_exc()
print_box_footer()
return 1
def cmd_packed(args) -> int:
"""List available packed features."""
from rich.table import Table
from rich.console import Console
console = Console()
print_box_header("Packed Features", "๐ฆ")
try:
from toolboxv2 import tb_root_dir
fm = _get_feature_manager()
packages = fm.list_packed_features(search_dir=args.dir)
if not packages:
print_status("No packed features found", "warning")
search_dir = args.dir or "./features_sto/"
print_status(f"Search directory: {search_dir}", "info")
print_status("Pack a feature with: tb manifest pack <feature>", "info")
print_box_footer()
return 0
table = Table(show_header=True, header_style="bold cyan")
table.add_column("Feature", style="bold")
table.add_column("Version")
table.add_column("Size")
table.add_column("Packed At")
table.add_column("Path")
for pkg in packages:
if "error" in pkg:
table.add_row(
pkg.get("filename", "unknown"),
"[red]ERROR[/red]",
"-",
"-",
pkg.get("path", "")
)
else:
table.add_row(
pkg.get("feature_name", pkg.get("filename", "unknown")),
pkg.get("version", "unknown"),
f"{pkg.get('size_kb', '?')} KB",
str(pkg.get("packed_at", "-")) if pkg.get("packed_at") else "-",
pkg.get("path", "").replace(str(tb_root_dir), "")
)
console.print(table)
print()
print_status(f"Found {len(packages)} package(s)", "info")
print_status("Unpack with: tb manifest unpack <path>", "info")
print_box_footer()
return 0
except Exception as e:
print_status(f"Error listing packages: {e}", "error")
print_box_footer()
return 1
# =============================================================================
# Set / Get Commands
# =============================================================================
_MANIFEST_TO_ENV = {
"app.profile": "TB_PROFILE",
"app.profiling": "PROFILING",
"database.mode": "TB_DB_MODE",
"app.debug": "TB_DEBUG",
"app.log_level": "TOOLBOX_LOGGING_LEVEL",
"app.environment": "TB_ENVIRONMENT",
"auth.jwt.secret": "TB_JWT_SECRET",
"auth.session.cookie_secret": "TB_COOKIE_SECRET",
"database.minio.endpoint": "MINIO_ENDPOINT",
"database.minio.access_key": "MINIO_ACCESS_KEY",
"database.minio.secret_key": "MINIO_SECRET_KEY",
"database.redis.url": "DB_CONNECTION_URI",
"nginx.server_name": "TB_NGINX_SERVER_NAME",
"paths.data_dir": "TB_DATA_DIR",
"isaa.self_agent.max_iteration": "DEFAULT_MAX_ITERATIONS",
"isaa.self_agent.verbose_logging": "AGENT_VERBOSE",
"isaa.self_agent.coder_stream": "CODER_STREAM",
"isaa.self_agent.with_google_tools": "WITH_GOOGLE_TOOLS",
"isaa.self_agent.max_history": "DEFAULT_MAX_HISTORY_LENGTH",
"isaa.self_agent.fast_model": "FASTMODEL",
"isaa.self_agent.blitz_model": "BLITZMODEL",
"isaa.self_agent.complex_model": "COMPLEXMODEL",
"isaa.self_agent.summary_model": "SUMMARYMODEL",
"isaa.self_agent.image_model": "IMAGEMODEL",
"isaa.self_agent.audio_model": "AUDIOMODEL",
"isaa.self_agent.embedding_model": "DEFAULTMODELEMBEDDING",
}
def _coerce(value: str):
"""Auto-cast string to bool/int/float where sensible."""
if value.lower() in ("true", "false"):
return value.lower() == "true"
try:
return int(value)
except ValueError:
pass
try:
return float(value)
except ValueError:
pass
return value
def cmd_set(args) -> int:
"""Set a manifest key and optionally sync to .env."""
import yaml
from toolboxv2 import tb_root_dir
from toolboxv2.utils.manifest import ManifestLoader
loader = ManifestLoader(tb_root_dir)
if not loader.exists():
print_status("No tb-manifest.yaml found โ run 'tb manifest init' first", "error")
return 1
try:
with open(loader.manifest_path, encoding="utf-8") as f:
data = yaml.safe_load(f)
keys = args.key.split(".")
node = data
for k in keys[:-1]:
if k not in node or not isinstance(node[k], dict):
node[k] = {}
node = node[k]
old_val = node.get(keys[-1], "<unset>")
new_val = _coerce(args.value)
node[keys[-1]] = new_val
with open(loader.manifest_path, "w", encoding="utf-8") as f:
yaml.dump(data, f, default_flow_style=False, allow_unicode=True, sort_keys=False)
print_status(f"{args.key}: {old_val!r} โ {new_val!r}", "success")
# Sync to .env if mapping exists
env_key = _MANIFEST_TO_ENV.get(args.key)
if env_key:
env_path = tb_root_dir.parent / ".env"
lines, found = [], False
if env_path.exists():
for line in env_path.read_text(encoding="utf-8").splitlines():
if line.startswith(f"{env_key}="):
lines.append(f"{env_key}={args.value}")
found = True
else:
lines.append(line)
if not found:
lines.append(f"{env_key}={args.value}")
env_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
print_status(f".env: {env_key}={args.value}", "info")
return 0
except Exception as e:
print_status(f"Error: {e}", "error")
return 1
def cmd_get(args) -> int:
"""Get a manifest key value."""
import yaml
from toolboxv2 import tb_root_dir
from toolboxv2.utils.manifest import ManifestLoader
loader = ManifestLoader(tb_root_dir)
if not loader.exists():
print_status("No tb-manifest.yaml found", "error")
return 1
try:
with open(loader.manifest_path, encoding="utf-8") as f:
data = yaml.safe_load(f)
node = data
for k in args.key.split("."):
if not isinstance(node, dict) or k not in node:
print_status(f"Key not found: {args.key}", "error")
return 1
node = node[k]
print(f"{args.key} = {node!r}")
return 0
except Exception as e:
print_status(f"Error: {e}", "error")
return 1
# =============================================================================
# Main Entry Point
# =============================================================================
def cli_manifest_main():
"""Main entry point for manifest CLI."""
parser = create_parser()
args = parser.parse_args()
if not args.command:
parser.print_help()
return 0
commands = {
"show": cmd_show,
"validate": cmd_validate,
"apply": cmd_apply,
"init": cmd_init,
"status": cmd_status,
"sync": cmd_sync,
# Feature commands
"list": cmd_list,
"enable": cmd_enable,
"disable": cmd_disable,
"files": cmd_files,
# Pack/Unpack commands
"pack": cmd_pack,
"unpack": cmd_unpack,
"packed": cmd_packed,
"set": cmd_set,
"get": cmd_get,
}
handler = commands.get(args.command)
if handler:
return handler(args)
else:
parser.print_help()
return 1
if __name__ == "__main__":
sys.exit(cli_manifest_main())
"""
Manifest CLI - Command line interface for tb-manifest.yaml management
Commands:
tb manifest show - Display current manifest
tb manifest validate - Validate manifest syntax and semantics
tb manifest apply - Generate sub-configs from manifest
tb manifest init - Create default manifest interactively
tb manifest status - Show service status vs manifest
tb manifest sync - Sync running services with manifest
"""
import argparse
import sys
from pathlib import Path
from typing import Optional
from .cli_printing import (
print_box_header,
print_box_footer,
print_status,
print_separator,
print_code_block,
c_print,
)
def create_parser() -> argparse.ArgumentParser:
"""Create argument parser for manifest CLI."""
parser = argparse.ArgumentParser(
prog="tb manifest",
description="๐ ToolBoxV2 Manifest Configuration Manager",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Manifest Commands โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
โ โ
โ tb manifest show Show current manifest content โ
โ tb manifest validate Validate manifest syntax and semantics โ
โ tb manifest apply Generate sub-configs from manifest โ
โ tb manifest init Create default manifest interactively โ
โ tb manifest status Show service status vs manifest โ
โ tb manifest sync Sync running services with manifest โ
โ โ
โ Feature Management: โ
โ tb manifest list List all features and their status โ
โ tb manifest enable <feature> Enable a feature (auto-installs deps) โ
โ tb manifest disable <feature> Disable a feature โ
โ tb manifest files <feature> Show files belonging to a feature โ
โ โ
โ Pack/Unpack: โ
โ tb manifest pack <feature> Pack feature into ZIP archive โ
โ tb manifest unpack <path> Unpack feature from ZIP archive โ
โ tb manifest packed List available packed features โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
"""
)
subparsers = parser.add_subparsers(dest="command", help="Manifest commands")
# show
p_show = subparsers.add_parser("show", help="Display current manifest")
p_show.add_argument("--json", action="store_true", help="Output as JSON")
p_show.add_argument("--section", type=str, help="Show specific section (app, database, workers, etc.)")
# validate
p_validate = subparsers.add_parser("validate", help="Validate manifest")
p_validate.add_argument("--strict", action="store_true", help="Strict validation mode")
# apply
p_apply = subparsers.add_parser("apply", help="Generate sub-configs from manifest")
p_apply.add_argument("--dry-run", action="store_true", help="Show what would be generated")
p_apply.add_argument("--force", action="store_true", help="Overwrite existing files")
p_apply.add_argument("--env", action="store_true", help="Also suggest missing env vars")
# init
p_init = subparsers.add_parser("init", help="Create default manifest")
p_init.add_argument("--force", action="store_true", help="Overwrite existing manifest")
p_init.add_argument("--env", type=str, choices=["development", "production", "staging"],
default="development", help="Initial environment")
# status
subparsers.add_parser("status", help="Show service status vs manifest")
# sync
p_sync = subparsers.add_parser("sync", help="Sync running services with manifest")
p_sync.add_argument("--dry-run", action="store_true", help="Show what would be done")
p_sync.add_argument("--restart", action="store_true", help="Restart all manifest services")
# Feature management commands
p_list = subparsers.add_parser("list", help="List all features and their status")
p_enable = subparsers.add_parser("enable", help="Enable a feature (auto-installs dependencies)")
p_enable.add_argument("feature", nargs="?", help="Feature name to enable")
p_disable = subparsers.add_parser("disable", help="Disable a feature")
p_disable.add_argument("feature", nargs="?", help="Feature name to disable")
Xet Storage Details
- Size:
- 36.2 kB
- Xet hash:
- 1ba7099ad10338f8dcd13e6926b7649f12b6b2fcd9356b5bc52f9b642573aa2d
ยท
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.