Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /Mother-AI-OS_mother /mother /cli /init_cmd.py
| """Mother init command - portable instance generator. | |
| Creates deployment-ready configuration bundles with: | |
| - docker-compose.yml templates | |
| - .env.example files | |
| - Policy templates | |
| - Configuration export/import | |
| """ | |
| import json | |
| import shutil | |
| import tarfile | |
| import tempfile | |
| from dataclasses import dataclass, field | |
| from datetime import datetime | |
| from pathlib import Path | |
| class InitConfig: | |
| """Configuration for instance initialization.""" | |
| output_dir: Path = field(default_factory=lambda: Path(".")) | |
| include_docker: bool = True | |
| include_policy: bool = True | |
| include_env: bool = True | |
| DOCKER_COMPOSE_TEMPLATE = """# Mother AI OS - Docker Compose Configuration | |
| # Generated by: mother init | |
| # Date: {date} | |
| services: | |
| mother: | |
| image: mother-ai:latest | |
| build: | |
| context: . | |
| dockerfile: Dockerfile | |
| container_name: mother | |
| restart: unless-stopped | |
| ports: | |
| - "${{MOTHER_PORT:-8080}}:8080" | |
| environment: | |
| - MOTHER_HOST=0.0.0.0 | |
| - MOTHER_PORT=8080 | |
| - MOTHER_REQUIRE_AUTH=${{MOTHER_REQUIRE_AUTH:-true}} | |
| - MOTHER_SAFE_MODE=${{MOTHER_SAFE_MODE:-true}} | |
| - MOTHER_SANDBOX_MODE=${{MOTHER_SANDBOX_MODE:-true}} | |
| - MOTHER_AUDIT_ENABLED=${{MOTHER_AUDIT_ENABLED:-true}} | |
| - AI_PROVIDER=${{AI_PROVIDER:-anthropic}} | |
| - ANTHROPIC_API_KEY=${{ANTHROPIC_API_KEY:-}} | |
| - OPENAI_API_KEY=${{OPENAI_API_KEY:-}} | |
| volumes: | |
| - mother_data:/app/data | |
| - mother_logs:/app/logs | |
| - ./config:/app/config:ro | |
| - ./workspace:/app/workspace | |
| healthcheck: | |
| test: ["CMD", "curl", "-f", "http://localhost:8080/health"] | |
| interval: 30s | |
| timeout: 10s | |
| retries: 3 | |
| start_period: 10s | |
| networks: | |
| - mother_network | |
| volumes: | |
| mother_data: | |
| mother_logs: | |
| networks: | |
| mother_network: | |
| driver: bridge | |
| """ | |
| DOCKERFILE_TEMPLATE = """# Mother AI OS - Dockerfile | |
| # Generated by: mother init | |
| # Date: {date} | |
| FROM python:3.12-slim | |
| WORKDIR /app | |
| # Install system dependencies | |
| RUN apt-get update && apt-get install -y \\ | |
| curl \\ | |
| && rm -rf /var/lib/apt/lists/* | |
| # Install Mother | |
| RUN pip install --no-cache-dir mother-ai | |
| # Create directories | |
| RUN mkdir -p /app/data /app/logs /app/config /app/workspace | |
| # Set permissions | |
| RUN chmod 700 /app/data /app/config | |
| # Expose port | |
| EXPOSE 8080 | |
| # Health check | |
| HEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \\ | |
| CMD curl -f http://localhost:8080/health || exit 1 | |
| # Run | |
| CMD ["mother", "serve"] | |
| """ | |
| ENV_EXAMPLE_TEMPLATE = """# Mother AI OS - Environment Configuration | |
| # Generated by: mother init | |
| # Date: {date} | |
| # | |
| # Copy this file to .env and fill in the required values. | |
| # NEVER commit .env to version control! | |
| # ============================================================================= | |
| # REQUIRED: API Authentication | |
| # ============================================================================= | |
| # LLM Provider (anthropic, openai, zhipu, gemini) | |
| AI_PROVIDER=anthropic | |
| # Provider API Keys (set the one matching your AI_PROVIDER) | |
| ANTHROPIC_API_KEY= | |
| OPENAI_API_KEY= | |
| ZHIPU_API_KEY= | |
| GEMINI_API_KEY= | |
| # ============================================================================= | |
| # REQUIRED: Mother API Authentication | |
| # ============================================================================= | |
| # Enable authentication (MUST be true for production) | |
| MOTHER_REQUIRE_AUTH=true | |
| # Legacy single API key (optional, multi-key mode preferred) | |
| # MOTHER_API_KEY= | |
| # ============================================================================= | |
| # SECURITY SETTINGS (defaults are secure) | |
| # ============================================================================= | |
| # Safe mode - restricts high-risk capabilities | |
| MOTHER_SAFE_MODE=true | |
| # Sandbox mode - restricts file operations to workspace | |
| MOTHER_SANDBOX_MODE=true | |
| # Audit logging - records all capability executions | |
| MOTHER_AUDIT_ENABLED=true | |
| # ============================================================================= | |
| # NETWORK SETTINGS | |
| # ============================================================================= | |
| # API host (use 127.0.0.1 unless external access needed) | |
| MOTHER_HOST=127.0.0.1 | |
| # API port | |
| MOTHER_PORT=8080 | |
| # ============================================================================= | |
| # PATHS (optional, defaults are usually fine) | |
| # ============================================================================= | |
| # Config directory | |
| # MOTHER_CONFIG_DIR=~/.config/mother | |
| # Workspace directory for sandboxed file operations | |
| # MOTHER_WORKSPACE_DIR=./workspace | |
| # Audit log path | |
| # MOTHER_AUDIT_LOG_PATH=./logs/audit.jsonl | |
| # Custom policy file path | |
| # MOTHER_POLICY_PATH=./config/policy.yaml | |
| """ | |
| POLICY_TEMPLATE = """# Mother AI OS - Security Policy | |
| # Generated by: mother init | |
| # Date: {date} | |
| # | |
| # This policy controls what capabilities Mother can execute. | |
| # Customize this file to match your security requirements. | |
| version: "1.0" | |
| # Global settings | |
| settings: | |
| # Default action when no rule matches (allow/deny) | |
| default_action: deny | |
| # Enable audit logging for all actions | |
| audit_all: true | |
| # Maximum concurrent operations | |
| max_concurrent: 10 | |
| # Capability rules | |
| rules: | |
| # File system operations | |
| - pattern: "filesystem_read*" | |
| action: allow | |
| conditions: | |
| safe_mode: true | |
| - pattern: "filesystem_write*" | |
| action: allow | |
| conditions: | |
| safe_mode: true | |
| sandbox_mode: true | |
| - pattern: "filesystem_delete*" | |
| action: deny # Explicitly deny deletions by default | |
| # Web operations | |
| - pattern: "web_fetch*" | |
| action: allow | |
| rate_limit: 100/minute | |
| - pattern: "web_search*" | |
| action: allow | |
| rate_limit: 60/minute | |
| # Shell operations | |
| - pattern: "shell_execute*" | |
| action: deny # Deny shell by default | |
| # Email operations | |
| - pattern: "email_*" | |
| action: allow | |
| conditions: | |
| requires_approval: true | |
| # Task operations | |
| - pattern: "tasks_*" | |
| action: allow | |
| # Role-based overrides | |
| roles: | |
| admin: | |
| # Admins can do everything | |
| - pattern: "*" | |
| action: allow | |
| operator: | |
| # Operators can execute most operations | |
| - pattern: "shell_execute*" | |
| action: allow | |
| conditions: | |
| audit: true | |
| readonly: | |
| # Readonly users can only read | |
| - pattern: "*_write*" | |
| action: deny | |
| - pattern: "*_delete*" | |
| action: deny | |
| - pattern: "*_execute*" | |
| action: deny | |
| """ | |
| def generate_files(config: InitConfig) -> list[Path]: | |
| """Generate initialization files. | |
| Args: | |
| config: Initialization configuration | |
| Returns: | |
| List of generated file paths | |
| """ | |
| generated = [] | |
| now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
| config.output_dir.mkdir(parents=True, exist_ok=True) | |
| # Generate docker-compose.yml | |
| if config.include_docker: | |
| compose_path = config.output_dir / "docker-compose.yml" | |
| compose_path.write_text(DOCKER_COMPOSE_TEMPLATE.format(date=now)) | |
| generated.append(compose_path) | |
| # Generate Dockerfile | |
| dockerfile_path = config.output_dir / "Dockerfile" | |
| dockerfile_path.write_text(DOCKERFILE_TEMPLATE.format(date=now)) | |
| generated.append(dockerfile_path) | |
| # Generate .env.example | |
| if config.include_env: | |
| env_path = config.output_dir / ".env.example" | |
| env_path.write_text(ENV_EXAMPLE_TEMPLATE.format(date=now)) | |
| generated.append(env_path) | |
| # Generate policy template | |
| if config.include_policy: | |
| policy_dir = config.output_dir / "config" | |
| policy_dir.mkdir(parents=True, exist_ok=True) | |
| policy_path = policy_dir / "policy.yaml" | |
| policy_path.write_text(POLICY_TEMPLATE.format(date=now)) | |
| generated.append(policy_path) | |
| return generated | |
| def export_config(output_path: Path, include_keys: bool = False) -> dict: | |
| """Export current configuration to a bundle. | |
| Args: | |
| output_path: Path for the export archive | |
| include_keys: Whether to include API keys database | |
| Returns: | |
| Export metadata | |
| """ | |
| from ..config.settings import get_settings | |
| settings = get_settings() | |
| config_dir = Path(settings.config_dir) | |
| with tempfile.TemporaryDirectory() as tmpdir: | |
| export_dir = Path(tmpdir) / "mother-export" | |
| export_dir.mkdir() | |
| exported_files = [] | |
| # Export email accounts | |
| accounts_file = config_dir / "email_accounts.json" | |
| if accounts_file.exists(): | |
| shutil.copy(accounts_file, export_dir / "email_accounts.json") | |
| exported_files.append("email_accounts.json") | |
| # Export plugin config | |
| plugin_config = config_dir / "plugins.json" | |
| if plugin_config.exists(): | |
| shutil.copy(plugin_config, export_dir / "plugins.json") | |
| exported_files.append("plugins.json") | |
| # Export API keys database (if requested) | |
| if include_keys: | |
| keys_db = config_dir / "keys.db" | |
| if keys_db.exists(): | |
| shutil.copy(keys_db, export_dir / "keys.db") | |
| exported_files.append("keys.db") | |
| # Export policy file | |
| if settings.policy_path: | |
| policy_file = Path(settings.policy_path) | |
| if policy_file.exists(): | |
| shutil.copy(policy_file, export_dir / "policy.yaml") | |
| exported_files.append("policy.yaml") | |
| # Create metadata | |
| metadata = { | |
| "version": "1.0", | |
| "exported_at": datetime.now().isoformat(), | |
| "files": exported_files, | |
| "settings": { | |
| "safe_mode": settings.safe_mode, | |
| "sandbox_mode": settings.sandbox_mode, | |
| "require_auth": settings.require_auth, | |
| "audit_enabled": settings.audit_log_enabled, | |
| }, | |
| } | |
| metadata_path = export_dir / "manifest.json" | |
| metadata_path.write_text(json.dumps(metadata, indent=2)) | |
| # Create tarball | |
| with tarfile.open(output_path, "w:gz") as tar: | |
| tar.add(export_dir, arcname="mother-export") | |
| return metadata | |
| def import_config(archive_path: Path, force: bool = False) -> dict: | |
| """Import configuration from a bundle. | |
| Args: | |
| archive_path: Path to the import archive | |
| force: Overwrite existing files | |
| Returns: | |
| Import result | |
| """ | |
| from ..config.settings import get_settings | |
| settings = get_settings() | |
| config_dir = Path(settings.config_dir) | |
| config_dir.mkdir(parents=True, exist_ok=True) | |
| result = { | |
| "imported": [], | |
| "skipped": [], | |
| "errors": [], | |
| } | |
| with tempfile.TemporaryDirectory() as tmpdir: | |
| # Extract archive | |
| with tarfile.open(archive_path, "r:gz") as tar: | |
| tar.extractall(tmpdir, filter="data") | |
| export_dir = Path(tmpdir) / "mother-export" | |
| if not export_dir.exists(): | |
| raise ValueError("Invalid export archive: missing mother-export directory") | |
| # Read manifest | |
| manifest_path = export_dir / "manifest.json" | |
| if not manifest_path.exists(): | |
| raise ValueError("Invalid export archive: missing manifest.json") | |
| manifest = json.loads(manifest_path.read_text()) | |
| # Import each file | |
| for filename in manifest.get("files", []): | |
| src = export_dir / filename | |
| dst = config_dir / filename | |
| if not src.exists(): | |
| result["errors"].append(f"{filename}: not found in archive") | |
| continue | |
| if dst.exists() and not force: | |
| result["skipped"].append(f"{filename}: already exists (use --force)") | |
| continue | |
| try: | |
| shutil.copy(src, dst) | |
| result["imported"].append(filename) | |
| except Exception as e: | |
| result["errors"].append(f"{filename}: {e}") | |
| return result | |
| def cmd_init( | |
| output_dir: str = ".", | |
| no_docker: bool = False, | |
| no_policy: bool = False, | |
| no_env: bool = False, | |
| json_output: bool = False, | |
| ) -> int: | |
| """Run the init command. | |
| Args: | |
| output_dir: Output directory for generated files | |
| no_docker: Skip Docker files | |
| no_policy: Skip policy template | |
| no_env: Skip .env.example | |
| json_output: Output as JSON | |
| Returns: | |
| Exit code | |
| """ | |
| config = InitConfig( | |
| output_dir=Path(output_dir), | |
| include_docker=not no_docker, | |
| include_policy=not no_policy, | |
| include_env=not no_env, | |
| ) | |
| generated = generate_files(config) | |
| if json_output: | |
| result = { | |
| "output_dir": str(config.output_dir.absolute()), | |
| "files": [str(f.relative_to(config.output_dir)) for f in generated], | |
| } | |
| print(json.dumps(result, indent=2)) | |
| else: | |
| print(f"Initialized Mother in {config.output_dir.absolute()}") | |
| print() | |
| print("Generated files:") | |
| for f in generated: | |
| print(f" - {f.relative_to(config.output_dir)}") | |
| print() | |
| print("Next steps:") | |
| print(" 1. Copy .env.example to .env and configure") | |
| print(" 2. Review config/policy.yaml for security settings") | |
| print(" 3. Run 'mother keys init && mother keys add admin -r admin'") | |
| print(" 4. Run 'mother doctor' to verify configuration") | |
| return 0 | |
| def cmd_export( | |
| output: str = "mother-export.tar.gz", | |
| include_keys: bool = False, | |
| json_output: bool = False, | |
| ) -> int: | |
| """Export current configuration. | |
| Args: | |
| output: Output file path | |
| include_keys: Include API keys database | |
| json_output: Output as JSON | |
| Returns: | |
| Exit code | |
| """ | |
| output_path = Path(output) | |
| if output_path.exists(): | |
| if not json_output: | |
| response = input(f"File {output} already exists. Overwrite? [y/N] ") | |
| if response.lower() != "y": | |
| print("Aborted.") | |
| return 1 | |
| try: | |
| metadata = export_config(output_path, include_keys=include_keys) | |
| if json_output: | |
| print(json.dumps(metadata, indent=2)) | |
| else: | |
| print(f"Exported configuration to {output_path}") | |
| print(f"Files included: {', '.join(metadata['files'])}") | |
| if include_keys: | |
| print("Note: API keys database was included") | |
| except Exception as e: | |
| if json_output: | |
| print(json.dumps({"error": str(e)})) | |
| else: | |
| print(f"Error: {e}") | |
| return 1 | |
| return 0 | |
| def cmd_import( | |
| archive: str, | |
| force: bool = False, | |
| json_output: bool = False, | |
| ) -> int: | |
| """Import configuration from archive. | |
| Args: | |
| archive: Path to import archive | |
| force: Overwrite existing files | |
| json_output: Output as JSON | |
| Returns: | |
| Exit code | |
| """ | |
| archive_path = Path(archive) | |
| if not archive_path.exists(): | |
| if json_output: | |
| print(json.dumps({"error": "Archive not found"})) | |
| else: | |
| print(f"Error: Archive not found: {archive}") | |
| return 1 | |
| try: | |
| result = import_config(archive_path, force=force) | |
| if json_output: | |
| print(json.dumps(result, indent=2)) | |
| else: | |
| if result["imported"]: | |
| print("Imported:") | |
| for f in result["imported"]: | |
| print(f" - {f}") | |
| if result["skipped"]: | |
| print("Skipped:") | |
| for f in result["skipped"]: | |
| print(f" - {f}") | |
| if result["errors"]: | |
| print("Errors:") | |
| for e in result["errors"]: | |
| print(f" - {e}") | |
| except Exception as e: | |
| if json_output: | |
| print(json.dumps({"error": str(e)})) | |
| else: | |
| print(f"Error: {e}") | |
| return 1 | |
| return 0 | |
| # Exports | |
| __all__ = [ | |
| "InitConfig", | |
| "generate_files", | |
| "export_config", | |
| "import_config", | |
| "cmd_init", | |
| "cmd_export", | |
| "cmd_import", | |
| ] | |
Xet Storage Details
- Size:
- 15.9 kB
- Xet hash:
- a433cdd7558274136a765fa64a4065d81930bdf77ea2c9b11b9b2b49bf4b2394
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.