A LeRobot-inspired data, capture, training, and safe execution pipeline for PC & game agents.
leGamer replaces robot joints and cameras with computer actions and streams — screen video, raw keyboard/mouse input, plus independently optional system audio, player microphone, player webcam, and timestamped player plan/speech transcripts — using the same core efficiency philosophy as LeRobot:
- Video-Compressed Datasets (MP4 + Parquet + Raw Sidecar): Store screen streams as short-GOP H.264 MP4 video shards instead of gigabytes of loose PNGs or uncompressed arrays, paired with Parquet tick tables and append-only raw input logs so 20Hz/60Hz training tables can be recompiled without losing sub-tick clicks or double-taps.
- Unified
record → replay → train → evalContract: One CPU-serializable observation/action/receipt contract shared across offline recording, deterministic replay, dataset windowing (delta_timestamps), and live closed-loop evaluation. - Profile-Separated Action Space: Clean separation between UI cursor pixel deltas (
ui_client_px) and 3D/FPS raw mouse counts (game_raw_counts), unified with relative(dx, dy)chunks and 4-state (keep / down / up / click) channels. - Two-Process Low-RAM Runtime: A lightweight,
torch-free CPU I/O Owner (capture, raw input, recording, safety STOP/takeover, execution) separated from the GPU Policy Process — designed from day one for consumer hardware (e.g., 16GB RAM / 6GB VRAM). - Model-Agnostic Core: Core package has zero dependency on any specific neural architecture. Plug in models such as H-nets or your own policy via thin adapters.
┌─────────────────────────────────────────────────────────────┐
│ CPU I/O Owner (torch-free) │
│ • Screen + Raw Input (core) │
│ • Optional streams: system audio / player mic / webcam │
│ • Optional text intent stream: live/offline STT & plans │
│ • ObservationAssembler (strict causality: avail <= decision)│
│ • Priority STOP / user takeover / intent lease / executor │
│ • Async segment writer (H.264 MP4 + Parquet + raw JSONL) │
└──────────────────────────┬──────────────────────────────────┘
│ shared-memory uint8 slots + small control msgs
┌──────────────────────────▼──────────────────────────────────┐
│ GPU Policy Process (optional: H-nets, ACT, Diffusion, ...) │
│ • Windowed uint8 frames + proprioception -> ActionProposal │
│ • Owns model weights, hidden state, and training loop │
└─────────────────────────────────────────────────────────────┘
dataset_root/
├── meta/
│ ├── info.json # schema, codec, profiles, enabled optional streams
│ ├── tasks.parquet # task_id, goal_text
│ ├── episodes/*.parquet # episode bounds, split, shard/time/row offsets
│ └── stats.json # train-split-only normalization stats
├── videos/
│ ├── screen/*.mp4 # [core] short-GOP H.264 shards (IDR shard starts)
│ └── webcam/*.mp4 # [optional] player webcam (same timebase, own index)
├── frames/
│ ├── screen/*.parquet # frame_id, PTS/timebase, capture_ns, available_ns
│ └── webcam/*.parquet # [optional] webcam frame index & drop/validity flags
├── signals/*.parquet # compiled tick state/action, validity, loss masks
├── raw/
│ ├── events/*.jsonl # [core] append-only raw keyboard/mouse stream
│ └── audio/ # [optional, each independently toggleable]
│ ├── system/*.flac # computer/game audio (stereo)
│ ├── mic/*.flac # player voice audio (mono)
│ └── index.parquet # per-source sample/time anchors & discontinuities
├── intents/
│ ├── text_events/*.parquet # [optional] append-only STT/typed revisions (as-of causal)
│ └── plan_events/*.parquet # [optional] plan lifecycle (create / revise / cancel)
├── derived/
│ └── face_rig/*.parquet # [optional] gaze & VTuber expression/pose (can run without saving raw webcam)
└── annotations/
├── outcomes/*.parquet # evaluator-only oracle/success labels (never fed to policy)
└── plan_action_links/*.parquet # post-hoc 1:N / N:M plan-to-execution links
Verified scope: Core contracts, capture/tray UI, custom HiT vision, multi-game BC/RL/dialogue trainers, 5Hz/20Hz chunk runner, Lumine 2 import/distillation, and NAS staging are implemented and pass 338 CPU tests (5 GPU-only tests skipped in CPU runs). Unverified scope: live-game Windows hook/microphone hardware capture, RTX 2060 (6GB) 150M training/5Hz latency benchmarks, real NAS network throughput, and real-game policy skill gains remain to be measured.
- Core Contract, Replay & Causal Windows (Steps 1–2): Action codec (
ui_client_px/game_raw_counts), short-GOP H.264 MP4 + Parquet + raw JSONLschema 0.4, deterministic replay, causalLeGamerWindowDataset, andHNetBCPolicyadapter. - Windows Capture, Sandboxed Execution & Tray App (Steps 3–5, 10B, 10D): Monitor/window capture, opt-in sandbox executor, PyQt5 tray app with default-ON supervised keyboard/mouse capture, opt-in mic WAV sidecars,
Ctrl+Alt+F9/F10quality marks, and ROM-safe Unicode/manual game folder naming (docs/GAME_NAMING.md). - Custom HiT Vision, Multi-Game Blending & Mini VPT (Steps 9B–9D): 100% from-scratch 768px aspect-fit
hit_learnedvision bridge,MixedGameDataset(equal/sqrt/proportionalweighting + ~95% idle filtering), internet video ingestion, standalone HiT vision pretraining, and shared-HiT inverse dynamics pseudo-labeling. - Specialist Teachers, Quality Feedback, Auto-Grader ReST & BC→RL (Steps 9E–9I): Per-game discrete teacher distillation, 3-channel quality feedback (loopback mod bridge / hotkeys / post-hoc grader), pure-NumPy ROI state detector + offline
EmbeddingGemma 2auto-grader, 6GB-safe sequential ReST loop, and BC-initialized RL fine-tuning (awr/ppo_clip). - Joint Action+Dialogue & 5Hz/20Hz Chunk Execution (Steps 10A, 10C): Shared-brain action AR + natural-language dialogue AR (
lm_headLoRA +SpeakGateHead) andChunkExecutionController(5Hz brain chunk prediction, 20Hz virtual execution, goal/scene/conflict interrupts with guaranteed key release). - Lumine 2 Import, NAS Staging & Remote Teacher Distillation (Steps 11–12B): Streaming
LumineResearch/Lumine2-dataTAR importer (docs/LUMINE2_IMPORT.md), NAS cold archive → bounded localE:segment staging (docs/NAS_STAGING.md), and license-gated remote Lumine 2 (9B) distillation (relabel/dagger/bootstrap, docs/LUMINE2_DISTILL.md).
See DESIGN.md for the full technical design and docs/BACKLOG.md for v0.2+ backlog ideas.
Apache License 2.0 — see LICENSE.
The core contracts and codec do not import torch. NumPy UI and dataset support are optional extras; no screen capture, microphone, GPU or OS input is started.
python -m pip install -e ".[dataset,dev]"
# Set LEGAMER_FFMPEG to a verified FFmpeg executable with libx264/libx264rgb.
$env:LEGAMER_FFMPEG = '<absolute path to ffmpeg.exe>'
$env:PYTEST_DISABLE_PLUGIN_AUTOLOAD = '1'
python -m pytest -q -p no:cacheproviderfrom tempfile import TemporaryDirectory
from legamer.envs.synthetic_ui import SyntheticUIEnv, OracleRelativePolicy
from legamer.dataset import EpisodeRecorder, ReplayEnv
env = SyntheticUIEnv()
env.reset(seed=7, split='eval', task_type='drag')
with TemporaryDirectory() as root:
with EpisodeRecorder(root, env) as writer:
score = OracleRelativePolicy(overshoot_recovery=True).run(
env, on_events=writer.record_events)
episode_id = writer.finalize()
check = ReplayEnv(root, episode_id).validate()
assert score['success'] and check['effects_equal']Step 1 defaults to CPU compressed H.264 (video_profile='h264_yuv420p',
libx264, CRF20, fast, GOP10, B0). EpisodeRecorder(..., crf=...) changes the
compressed CRF. Use video_profile='lossless_rgb' for exact pixel regression
(libx264rgb, CRF0). Dataset metadata pins profile, pixel format, effective CRF
and GOP; one dataset root uses one configuration. Old pre-profile Step1 datasets
are rejected explicitly, not silently reinterpreted.
Both profiles verify frame count/shape and MP4/decoded-frame checksums. Lossless
requires exact raw-pixel parity; compressed frames require per-frame PSNR >=30dB
against the raw reference. ReplayEnv.validate() returns frames_valid for
profile validation and frames_equal for actual pixel equality; lossy validity
must not be described as exact equality. State, effects and observation metadata
remain exact. This gate is an RGB quality check, not an OCR/click accuracy test.
MP4 PTS is a storage-frame index; capture/availability ns in the Parquet index is
the physical timeline. Synthetic post-effect frames use a +1ns phase to avoid
feeding a consequence into its own decision tick.
Only meta/episodes/<id>.parquet publishes a completed episode. Assets and
checksums are written before that commit marker. .pending/ and orphan assets
are not replayable episodes. A killed writer leaves .writer.lock; reconcile
its process and staged data before manually removing that lock. Never remove a
live writer's lock. This is process-crash visibility, not a power-loss guarantee.
Successful finalization removes the raw RGB spool and its empty episode staging
directory; failed episodes preserve
staging for diagnosis. Optional streams default OFF; no empty media/text files
are generated. Recording is bounded to 2400 frames by default.
Codec/virtual-executor code was ported from H-nets as the leGamer implementation. H-nets consumers have not switched in this task (that repository is read-only). The remaining migration is a separate atomic consumer switch to thin imports; until then, H-nets' legacy codec must not be treated as a synchronized second implementation. This Step 1 provides virtual replay, not the live handover daemon.
legamer.dataset.window stays torch-free. LeGamerWindowDataset(root, split='train', horizon=4) uses the same ObservationAssembler as live inference.
It returns uint8 [4,3,256,256] frames, frame IDs, frame_pad_mask, and
frame_age_ns (capture staleness relative to each requested slot). Missing
pre-episode slots are zero/PAD with age -1 and ID None; repeated older frames
carry padding flags. No future frame fills an earlier slot. Action targets use
future 20Hz ticks, with terminal and raw compiler ambiguity masks.
Statistics can only be computed on a train reader. Decode caching is a bounded, per-reader uint8 LRU; this first version sequentially decodes an episode on a miss. Short synthetic episodes fit the cache. Long-video random seek throughput and multi-worker total RAM are not validated. The first pilot uses no DataLoader worker pool and keeps CPU storage separate from GPU tensors.
The optional adapter loads torch/H-nets only on explicit import. Install
H-nets separately or set LEGAMER_HNETS_SOURCE to its source root. Missing model
dependencies raise an error; no replacement model is selected. Tests that import
all core modules exclude this one opt-in module and separately verify the model
boundary in a fresh subprocess.
$env:LEGAMER_HNETS_SOURCE = '<H-nets source root>'
$env:LEGAMER_FFMPEG = '<FFmpeg executable>'
$env:PYTEST_DISABLE_PLUGIN_AUTOLOAD = '1'
python -m pytest -q -p no:cacheprovider
# GPU pilot: use a fresh output directory and a read-only official checkpoint.
python scripts/run_bc_pilot.py --out '<new pilot output>' --checkpoint '<base.pt>' --hnets '<H-nets root>'HNetBCPolicy freezes the FP32 LM, trains the small VisionHiT/action/bridge/fusion
modules, and uses caller-controlled CUDA FP16 autocast. Each decision replays a
bounded four-frame tape through MultimodalSession in both training and live
inference; it does not retain unbounded cross-decision KV. UI-only action profile
conversion at the H-nets boundary is explicit. The pilot records 80 optimizer
attempts, including AMP skips, and reports held-out loss separately from virtual
closed-loop success/false clicks/holds, inference latency and peak VRAM. Virtual
20Hz time is not a claim that wall-clock inference meets a 50ms deadline.
Install the optional capture dependencies and provide a working CPU FFmpeg executable through LEGAMER_FFMPEG.
python scripts/record_window.py --list-windows
python scripts/record_window.py --hwnd 0x123456 --output-dir E:\datasets\sandbox-session --duration 30 --segment-frames 120Pick your local sandbox HWND explicitly, or use --title-contains (exactly one match required). The target must remain visible, non-minimized and foreground. Focus loss or client geometry changes discard the current observation and split continuity. Capture failures stop that observation; there is no desktop/screen fallback. PrintWindow can block or return black content in unsupported GPU-rendered applications.
Default recording is screen only: no keyboard/mouse hooks, audio, microphone or webcam. The optional InputObserver interface accepts explicitly supplied, HWND/PID/epoch-bound physical observations; it has no native global-hook implementation in v0.1. Capture segments have source_kind=window_capture, physical client geometry and cursor validity. All action loss masks are false (SOURCE_MISSING state), so screen-only frames never become expert KEEP labels.
Whole-monitor capture (capture/monitor.py, the Step 5 tray default): MonitorBackend copies one monitor with GDI BitBlt from the screen DC (per-monitor-v2 DPI, physical pixels, negative virtual-screen coordinates allowed) and reuses the same segment/FFmpeg/commit path. There is no focus gating: the whole monitor is recorded whatever is in front, including the tray menu and the record-key prompt when they are open there. Windows marked WDA_EXCLUDEFROMCAPTURE (the leGamer overlays and capture border) are left out by Windows. Monitor segments keep source_kind=window_capture (the kind ReplayEnv and the window reader accept for captured screens); capture_json has capture_target="monitor" and the monitor rect instead of hwnd/pid. A monitor rect change drops the observation and splits continuity, as a window geometry change does. Measured on a 1920x1080 monitor: about 18 fps inside the 20 fps loop. Exclusive-fullscreen and some flip-model games bypass the GDI copy and come out black: a frame whose every pixel is at or below 8/255 is dropped (capture_failed_black) and the tray tooltip shows 검은 화면만 잡힘 until the next recording; switch such games to windowed or borderless mode. A genuinely all-black scene (a black loading screen filling the monitor) is dropped the same way.
Segments reuse the Step1 H.264 yuv420p CRF20/GOP10/bf0 and fixed 30dB PSNR gate. Session QPC nanoseconds are authoritative; MP4 PTS indexes stored frames, not real-time cadence. sessions/*.jsonl records drops and continuity. Completed meta/episodes markers expose only fully verified assets; .pending and a stale .writer.lock after a killed process require explicit operator reconciliation. Do not automatically delete pending media or steal a writer lock. ReplayEnv.validate() checks capture media integrity, without claiming synthetic dynamics replay.
Default mode performs no OS input and does not create a native target:
python scripts/eval_sandbox_exec.py --ledger E:\datasets\legamer-dry-run.jsonlThe following live command is for explicit, user-supervised evaluation only after independent review. It opens its own Tk sandbox; it cannot target an arbitrary external HWND. BOTH flags and a click on the sandbox's Arm button are required:
python scripts/eval_sandbox_exec.py --allow-os-input --confirm-sandbox --ledger E:\datasets\legamer-live.jsonlEsc, Ctrl+C or closing the sandbox requests STOP. Physical input yields control. The native monitor installs keyboard/mouse low-level hooks only while explicitly armed; own injected events are tagged, physical events only signal takeover, and keystroke text is not recorded. The demo uses one immutable 3-second host lease and permits LMB only. game_raw_counts, TEXT_COMMIT and policy Escape injection are unsupported. Native driver calls recheck HWND/PID, foreground, geometry, channel support and client bounds. Mouse clicks/wheel require observed acknowledgement of a commanded move.
VirtualExecutor is the sole step compiler. Receipts distinguish proposed/accepted/actual dispatched calls/observed effect; absent observations remain null. Rejected and dry-run proposals have no executed records. driver_kind=fake means simulation, not OS success. Cancellation records dropped suffixes; release calls remain attributed to the proposal which owned that channel. Disk flush and effect callbacks run outside the execution safety lock. Host receipt errors stop further dispatch.
Native limits: SendInput is global. Strict foreground gating also applies to cleanup; if focus/UIPI/driver failure prevents an owned key-up, pending_cleanup remains nonempty and the CLI exits 2. Refocus the own sandbox before closing/retrying host cleanup. Never declare those holds released. Process hard-kill, OS/API failure, a focus switch racing the OS dispatch, or a failed native hook are not covered by a same-process guarantee. No native input or live hook installation was exercised in pytest; that separate supervised validation and independent review remain pending. Do not use this version on important applications.
Tests set LEGAMER_TEST_NO_OS_INPUT=1, prohibiting real native input/hook startup even in child processes. Structural tests use explicit API stubs. capture/ stays read-only and unchanged.
python scripts/legamer_tray.py --demo-hud
python scripts/legamer_tray.py --output-dir E:\datasets\legamer_uiThe first command is an animated preview: it creates no recording or native input
resources. The normal command stays in the tray; nothing opens at startup. Only one
tray can run: a second launch prints "already running" and exits with code 3
(--demo-hud is exempt).
The icon is a red circle while recording and a blue square while idle or paused
(amber square on error). Left- or right-click it for a plain system menu. One entry
toggles: it reads 녹화 when not recording and 정지 (save and stop) while recording or
paused; 재개 appears only after an emergency stop. The capture target defaults to the
left-most monitor's full screen (대상: 왼쪽 모니터 전체); the 대상 submenu switches to a
window (focus-gated, as in Step 3) or back to the monitor, and its title shows the
current target. While the mouse is over the tray icon or the menu is open, a 3 px blue
border (no fill) outlines the capture area; it hides 0.5 s after both end. Hover is read
from the icon geometry, so when the icon sits in the taskbar overflow flyout (^) only
the open menu shows the border. The border is protected like the overlays below; if
protection fails it is not shown and the tooltip says so. Border coordinates assume Qt
runs unscaled (no QT_SCALE_FACTOR / Qt high-DPI scaling), so Qt pixels equal physical pixels.
Ctrl+Shift+F9 records/resumes, F10 saves/stops, F11 discards
only the current uncommitted segment, and F12 pauses immediately. These four include
Ctrl+Shift; unavailable global shortcuts are reported in the tray tooltip.
One keyboard key also toggles recording: Pause by default, changeable with the tray
entry 녹화 키 정하기 · (press the new key in the small prompt, Esc cancels). A press
records when idle and saves while recording or paused. It is registered with
RegisterHotKey without modifiers, so Windows gives it only to leGamer and no other app sees it.
Keys that cannot work alone are refused with one line: Shift/Ctrl/Alt, letters, digits,
Enter, Space, Tab, Esc, the Windows key and F9-F12. If another app already owns the key,
the tray tooltip and the menu line say so. It is saved as a virtual-key code in
recording_prefs.json (record_key).
The mouse side button can toggle recording the same way (옆 버튼으로 녹화 ▸ 위 = X2,
아래 = X1, 끔 = default): a press records when idle and saves while recording or paused, once
per press with a 400 ms lockout. It is polled, not hooked, so the click also reaches the
app in front (a browser or the Claude app goes back/forward). That is why it is off by
default; a choice saved in an existing prefs file is kept.
Previously committed segments survive discard. With a window target, clicking the tray
pauses the focus-gated recorder; returning to the target starts a new segment. Closing from
종료 saves the remaining segment before exiting.
Two overlays appear only while recording (hidden at idle, after save/discard, on
emergency stop and on error; the demo starts recording so it still shows them), both without a background card: a
bottom-center subtitle strip (outlined text, nothing drawn when there is no live
text) and a bottom-right input cluster (left-hand block Esc–5 / Tab–T / Caps–G /
Shift–V / Ctrl Alt Space, mouse L/R/wheel/X1/X2, fading motion arrow, recording
dot). Idle keys are faint outlines and held keys glow; other keys (F-keys,
arrows, Enter, ...) flash as small text. The cluster fades after 2 s without
input. Size variants A/B/C: InputOverlay(..., variant='A') (default A, user pick 2026-12-02). The
input cluster is a read-only polling preview, not recorded expert input
labels. Wheel notches cannot be polled, so the wheel flash has no live source yet.
TrayApp.feed_subtitle(TextEvent, now_ns) provides a live-STT display slot with
revision/retraction handling; no ASR engine is started.
The tray menu's "기록할 항목" submenus pick system audio (off/on), mic
(off / text only / audio+text) and webcam (off / face rig only / video+face rig).
Preferences are saved to %LOCALAPPDATA%\legamer\recording_prefs.json.
Non-off microphone modes now record WAV sidecars on the next recording start;
STT remains a separate post-processing step. System audio and webcam remain
unconnected preferences. Normal tray recording captures supervised physical
keyboard/mouse input by default; --no-input-capture selects screen-only.
See docs/TRAY_RECORDER.md for boundaries and verification. The demo never writes recording preferences.
Qt dependencies are optional (ui
extra) and isolated under ui/.
On Windows, each overlay verifies WDA_EXCLUDEFROMCAPTURE and click-through/no-focus
styles before display. If protection fails, it stays hidden and reports the
failure in the tray tooltip; restart to retry. Windows display affinity is not
an absolute guarantee for every third-party capture implementation. Native
protection and global-shortcut behavior still need an interactive Windows smoke
check. Automated UI tests use offscreen widgets and stub Win32 APIs.
For a safe exported preview:
$env:QT_QPA_PLATFORM='offscreen'
$env:LEGAMER_TEST_NO_OS_INPUT='1'
python scripts/legamer_tray.py --demo-hud --export-preview E:\preview.png --quit-after 1The export paints a mock game scene under the real overlay widgets; add
--preview-empty-subtitle to check that the subtitle strip vanishes.