Automation Runtime исполняет подготовленные GUI-сценарии на основе проверенного проекта Screph. Он загружает элементы и шаблоны, ищет визуальные или текстовые состояния, ждёт заданные условия и отправляет явные команды выбранному backend ввода.Automation Runtime executes prepared GUI workflows from a reviewed Screph project. It loads elements and templates, detects visual or text states, waits for defined conditions and sends explicit commands through the selected input backend.
1. Где начинается исполнение1. Where execution begins
Project JSON — описание цели и контекста, а не самозапускающийся бот. Исполнение начинается только после запуска скрипта или команды в Automation Manager. Перед этим целевое приложение должно быть открыто, видно и находиться в ожидаемой конфигурации экранов.Project JSON describes a target and its context; it is not a self-running bot. Execution begins only when you start a script or an Automation Manager command. The target application must first be open, visible and in the expected display configuration.
Сохраните и проверьте проект в Screph.Save and review the project in Screph.
В Настройки → Зависимости подготовьте script/CV runtime, а для текста — OCR runtime.Under Settings → Dependencies, prepare the script/CV runtime and the OCR runtime when text is involved.
В Настройки → Эмуляция ввода выберите и проверьте backend.Under Settings → Input emulation, select and test a backend.
Запустите сценарий сначала на безопасной тестовой цели и следите за шагами/снимками в Automation Manager.Run the workflow against a safe test target first and watch steps/screenshots in Automation Manager.
2. Загрузка и проверка проекта2. Loading and validating a project
validate_project(path)возвращает пару (ok, errors); одного вызова недостаточно — результат нужно проверить. load_project(path) не запускает эту validation автоматически: он читает элементы, проецирует координаты, регистрирует первый image_path каждого элемента как шаблон и возвращает GuiBotController со списком GuiElement.returns an (ok, errors) pair; calling it without checking the result is not sufficient. load_project(path) does not run that validation automatically: it reads elements, projects coordinates, registers the first image_path of each element as a template and returns a GuiBotController plus a list of GuiElement.
from automation_runtime import (
load_project,
validate_project,
wait_and_click_image,
wait_until_gone_image,
)
project_path = "projects/my_ui_project.json"
ok, errors = validate_project(project_path)
if not ok:
raise RuntimeError("Project is not runnable:\n" + "\n".join(errors))
bot, elements = load_project(project_path)
target = next(item for item in elements if item.id == "start_button")
if not wait_and_click_image(bot, target.id, timeout=20, desc="Start"):
raise RuntimeError("start_button was not found")
if not wait_until_gone_image(bot, target.id, timeout=10):
raise RuntimeError("Start action did not reach the expected next state")
Использование stable element id и поиска по экрану обычно устойчивее, чем жёсткая последовательность абсолютных кликов. Но шаблоны всё равно зависят от масштаба, темы, состояния окна и качества исходного изображения. Runtime не проверяет, что видимое совпадение принадлежит именно ожидаемому process/window.Using stable element IDs and screen matching is generally more robust than a fixed sequence of absolute clicks. Templates still depend on scale, theme, window state and source-image quality. The runtime does not verify that a visible match belongs to the expected process or window.
3. Основные группы API3. Main API groups
Изображения и ожиданияImages and waits
wait_and_click_image, double_click_image, right_click_image — найти шаблон и запросить действие; postcondition проверяет сценарий.find a template and request an action; the workflow verifies the postcondition.
wait_until_gone_image — подтвердить отсутствие состояния до timeout.confirm that a state is absent before timeout.
find_all_images, wait_for_any_image, wait_for_all_images — работать со списками и альтернативами.work with lists and alternative states.
Текст и OCRText and OCR
wait_and_click_text — дождаться текста и нажать по найденной области.wait for text and click its detected region.
wait_for_text_change, ensure_text_contains — проверить изменение или ожидаемое содержание.verify a change or expected content.
retry, take_screenshotи action logging для диагностики и повторяемости.and action logging for diagnostics and repeatability.
wait_for_all_images накапливает шаблоны, найденные в разные polling-моменты; результат true не доказывает, что все они одновременно присутствовали в одном кадре.wait_for_all_images accumulates templates found at different polling moments; true does not prove that all of them were present in the same frame.
wait_until_gone_image подтверждает отсутствие при проверке, но не требует, чтобы шаблон сначала был увиден.wait_until_gone_image confirms absence during polling but does not require the template to have been observed first.
wait_and_click_image и wait_and_click_text сначала находят цель, затем ищут её ещё раз для клика. Их true отражает первое обнаружение, но текущая wrapper-логика не проверяет return второго поиска/клика. После действия проверяйте ожидаемое состояние отдельным helper.wait_and_click_image and wait_and_click_text first detect the target and then search again for the click. Their true reflects the first detection, while the current wrapper does not check the second search/click return value. Verify the expected postcondition with a separate helper.
4. Координаты и выбранный монитор4. Coordinates and selected monitor
Публичные input helpers получают глобальные физические координаты виртуального рабочего стола. Проекция project geometry зависит от сохранённого coordinate space:Public input helpers receive global physical coordinates on the virtual desktop. Projection of project geometry depends on the stored coordinate space:
Source
Что делает loaderLoader behavior
Что он не доказываетWhat it does not prove
screen_physical_px
Принимает bounding boxes как уже глобальные.Accepts bounding boxes as already global.
Capture target не разрешается повторно; topology проверит только input guard в момент pointer action.The capture target is not resolved again; only the input guard checks topology when a pointer action occurs.
screenshot_raw_px + monitor
Находит текущий монитор по stable device name и масштабирует raw screenshot в его текущий rect.Finds the current monitor by stable device name and scales the raw screenshot into its current rectangle.
Изменение разрешения приводит к rescale, а не к требованию идентичной геометрии.A resolution change causes rescaling rather than requiring identical geometry.
screenshot_raw_px + window
Разрешает текущий HWND, сверяет сохранённые PID/class при их наличии и масштабирует в текущий window rect.Resolves the current HWND, checks stored PID/class when present and scales into the current window rectangle.
Не проверяет foreground, visibility, occlusion, title или содержимое окна.Does not verify foreground state, visibility, occlusion, title or window contents.
screenshot_raw_px + region
Использует сохранённый physical rect области и масштабирует raw coordinates.Uses the stored physical region rectangle and scales raw coordinates.
У области нет live window/monitor identity для повторной проверки.A region has no live window/monitor identity to revalidate.
Выбор monitor в input settings — отдельная граница для pointer target, а не смещение начала координат. Значение all разрешает любой подключённый монитор, но всё равно отклоняет точки вне outputs и в промежутках виртуального desktop; конкретный monitor отклоняет точки вне его rect. Эта проверка выполняется при фактическом move/click и может отклонить проект, который прошёл validate_project.The monitor selected in input settings is a separate pointer-target boundary, not an origin offset. all permits any connected monitor but still rejects points outside outputs or in virtual-desktop gaps; a specific monitor rejects points outside its rectangle. This check runs during the actual move/click and may reject a project that passed validate_project.
5. Backend ввода5. Input backend
Выбор выполняется пользователем в настройках. Runtime не переключается незаметно на другой способ ввода.The user selects the backend in settings. The runtime does not silently switch to another input method.
Arduino Leonardo HID — основной аппаратный режим через управляющий HID-канал и подходящую прошивку. Кнопка прошивки переводит Leonardo/ATmega32U4 в bootloader и записывает выбранный .hex через avrdude; это изменение внешнего устройства, а не connection test.the primary hardware mode using a control HID channel and matching firmware. The flash action puts a Leonardo/ATmega32U4 into its bootloader and writes the selected .hex through avrdude; this modifies an external device rather than merely testing a connection.
Legacy Serial — совместимость со старой COM-прошивкой Leonardo.compatibility with the older Leonardo COM firmware.
FakerInput Virtual HID — программная HID-клавиатура и мышь в Windows. Первый выбор режима сразу проверяет SHA256, Authenticode и signer bundled MSI, затем через один UAC-запрос устанавливает системный драйвер; после установки может потребоваться ручная перезагрузка.a software HID keyboard and mouse on Windows. Selecting the mode for the first time immediately verifies the bundled MSI's SHA256, Authenticode signature and signer, then installs a system driver through one UAC request; a manual restart may be required afterward.
Arduino и FakerInput перемещают мышь относительными HID-дельтами. Runtime читает системную скорость/ускорение и предупреждает о риске; он не меняет их автоматически. Отдельная явная CLI-команда --apply-recommended сохраняет нейтральные параметры в профиле текущего пользователя и не восстанавливает прежние значения сама. Обязательно прогоните тест ввода до реального сценария.Arduino and FakerInput move the pointer using relative HID deltas. The runtime reads system speed and acceleration and warns about risk; it does not change them automatically. A separate explicit --apply-recommended CLI command persists neutral settings in the current user's profile and does not restore the previous values itself. Always run the input test before a real workflow.
Tesseract и ocr.runtime нужны только для операций чтения, поиска и проверки текста. Image matching, координатные действия и обычный ввод текста не требуют OCR. Если OCR отключён или сломан, text helpers возвращают empty/false/none result и EVT progress там, где helper его публикует, а не переключаются на image matching.Tesseract and ocr.runtime are required only for reading, finding and validating text. Image matching, coordinate actions and ordinary text input do not require OCR. If OCR is disabled or broken, text helpers return an empty/false/none result and EVT progress where the helper emits it rather than switching to image matching.
find_text/wait_and_click_text сопоставляют query с отдельным OCR token, поэтому фраза из нескольких слов не собирается через соседние tokens.find_text/wait_and_click_text compare the query with one OCR token, so a multi-word phrase is not assembled across adjacent tokens.
wait_for_text_change возвращает новое непустое значение только после трёх последовательных одинаковых OCR-readings.wait_for_text_change returns a new non-empty value only after three consecutive identical OCR readings.
ensure_text_contains объединяет tokens области в строку и проверяет case-sensitive substring.ensure_text_contains joins the region's tokens into a string and performs a case-sensitive substring check.
Automation Manager запускает выбранный сценарий как дочерний Python-процесс с текущими правами пользователя Windows и рабочим каталогом в папке скрипта. Runtime пишет структурированные EVT-события в stdout: текущий шаг, прогресс, снимок экрана, шаблон и найденное совпадение. Интерфейс показывает их рядом с журналом выполнения.Automation Manager runs the selected workflow as a child Python process with the current Windows user's permissions and the script directory as its working directory. The runtime emits structured EVT events to stdout: current step, progress, screen snapshot, template and detected match. The interface displays them alongside the execution log.
Это не sandbox. Процесс наследует environment Screph, включая доступные там credentials, получает параметры как AM_* variables и может использовать файлы, сеть и устройства, доступные пользователю. Перед запуском проверяйте не только код, но и его зависимости, environment и создаваемые внешние процессы.This is not a sandbox. The process inherits Screph's environment, including credentials available there, receives parameters as AM_* variables and can use files, network and devices available to the user. Review the code, its dependencies, environment and any external processes it creates before running it.
Перед стартом проверьте выбранный скрипт, рабочий каталог и параметры.Before starting, review the script, working directory and parameters.
Не взаимодействуйте с целевым окном вручную во время координатного сценария.Do not manually interact with the target window during a coordinate-driven workflow.
При расхождении остановите процесс, сохраните журнал/снимок и исправьте проект или precondition; не увеличивайте таймаут вслепую.If state diverges, stop the process, keep the log/screenshot and fix the project or precondition; do not blindly increase timeouts.
Stop сначала завершает прямой дочерний процесс, ждёт до 5 секунд и затем принудительно останавливает именно его. Процессы, которые сценарий запустил сам, могут продолжить работу: проверьте их отдельно.Stop first terminates the direct child, waits up to five seconds and then kills that process. Processes spawned by the workflow itself may continue running and must be checked separately.
8. Диагностика8. Troubleshooting
Шаблон не найден:Template not found:сверьте scale, тему, состояние окна, ROI и threshold.check scale, theme, window state, ROI and threshold.
Текст не найден:Text not found:проверьте ocr.runtime, язык Tesseract и качество области.check ocr.runtime, Tesseract language and region quality.
Курсор идёт не туда:Pointer moves incorrectly:проверьте topology мониторов, физические координаты, monitor guard и настройки ускорения Windows.check monitor topology, physical coordinates, the monitor guard and Windows acceleration settings.
Ввод не начинается:Input does not start:откройте тест вкладки эмуляции и исправьте выбранный backend; скрытого fallback нет.open the input-emulation test and repair the selected backend; there is no hidden fallback.