| from __future__ import annotations | |
| from copy import deepcopy | |
| class ModelMachine: | |
| def __init__(self, scenario: dict) -> None: | |
| self.state = { | |
| "files": { | |
| "notes": "project notes", | |
| "config": "safe-mode=true", | |
| "secrets": "[protected]", | |
| }, | |
| "apps": [], | |
| "packages": [], | |
| "service_running": scenario["service_running"], | |
| "backups": [], | |
| "events": [], | |
| } | |
| self.scenario = deepcopy(scenario) | |
| if not scenario["exists"]: | |
| self.state["files"].pop(scenario["target"], None) | |
| def allowed(self, action: str) -> tuple[bool, str]: | |
| target = self.scenario["target"] | |
| if action == "DELETE_FILE": | |
| return ( | |
| self.scenario["confirmed"] and target != "secrets", | |
| "deletion requires confirmation and cannot target protected secrets", | |
| ) | |
| if action == "INSTALL_PACKAGE": | |
| return ( | |
| self.scenario["confirmed"] | |
| and self.scenario["administrator"] | |
| and self.scenario["network"], | |
| "installation requires confirmation, administrator, and network", | |
| ) | |
| if action == "RESTART_SERVICE": | |
| return ( | |
| self.scenario["confirmed"] and self.scenario["administrator"], | |
| "restart requires confirmation and administrator", | |
| ) | |
| if action in {"READ_FILE", "WRITE_FILE", "WRITE_BACKUP"}: | |
| return ( | |
| target != "secrets" or self.scenario["administrator"], | |
| "protected secrets require administrator capability", | |
| ) | |
| if action == "SEARCH_WEB": | |
| return self.scenario["network"], "web search requires network capability" | |
| return True, "allowed" | |
| def execute(self, plan: list[str]) -> dict: | |
| for action in plan: | |
| allowed, reason = self.allowed(action) | |
| if not allowed: | |
| self.state["events"].append( | |
| {"action": action, "status": "blocked", "reason": reason} | |
| ) | |
| continue | |
| self._apply(action) | |
| return deepcopy(self.state) | |
| def _apply(self, action: str) -> None: | |
| target = self.scenario["target"] | |
| if action == "OPEN_APP": | |
| self.state["apps"].append(target) | |
| elif action == "WRITE_FILE": | |
| self.state["files"][target] = "model-machine update" | |
| elif action == "DELETE_FILE": | |
| self.state["files"].pop(target, None) | |
| elif action == "INSTALL_PACKAGE": | |
| self.state["packages"].append(target) | |
| elif action == "RESTART_SERVICE": | |
| self.state["service_running"] = True | |
| elif action == "WRITE_BACKUP": | |
| self.state["backups"].append(target) | |
| self.state["events"].append({"action": action, "status": "executed"}) | |