ueagentdevkit 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,277 @@
1
+ """Archive and release only allowlisted scratch from completed, owned recording runs."""
2
+
3
+ import ctypes
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import re
8
+ import shutil
9
+ import subprocess
10
+ import uuid
11
+ import tempfile
12
+ import msvcrt
13
+ import zipfile
14
+ from pathlib import Path
15
+ from contextlib import contextmanager
16
+
17
+ from Tools.Hygiene.audit import digest, files, git
18
+
19
+ ROOT = Path(__file__).resolve().parents[2]
20
+ DEFAULT_ART = ROOT / "Artifacts" if (ROOT / "pyproject.toml").is_file() else Path(
21
+ os.environ.get("LOCALAPPDATA", Path.home())
22
+ ) / "UEAgentDevKit" / "Artifacts"
23
+ ART = Path(os.environ.get("UEAGENT_ARTIFACTS", DEFAULT_ART)).expanduser().resolve()
24
+
25
+
26
+ def guarded(path):
27
+ path = Path(os.path.abspath(path))
28
+ if not path.is_relative_to(ART) or any(
29
+ p.is_symlink() or getattr(p.lstat(), "st_file_attributes", 0) & 1024
30
+ for p in [path, *path.parents]
31
+ if p.exists() or p.is_symlink()
32
+ ):
33
+ raise ValueError("Outside owned directory or reparse point: " + str(path))
34
+ return path
35
+
36
+
37
+ def checked_run(run):
38
+ try:
39
+ from Tools.Hygiene.legacy_recording import check
40
+ except ModuleNotFoundError as error:
41
+ raise ValueError("Recording scratch recovery requires the legacy recording adapter") from error
42
+ return check(guarded(run), ART / "Runs", guarded)
43
+
44
+
45
+ def scratch(run, rel):
46
+ if Path(rel).is_absolute() or ":" in rel or ".." in Path(rel).parts:
47
+ raise ValueError("Expected a relative path inside the run")
48
+ p = guarded(run / rel)
49
+ relative = p.relative_to(run)
50
+ if any((a / ".git").exists() for a in p.parents if a.is_relative_to(run)):
51
+ raise ValueError("Nested Git workspace is protected")
52
+ from Tools.Hygiene.legacy_recording import raw_capture_path
53
+ allowed = relative == raw_capture_path(run) or (
54
+ relative.is_relative_to("copy/Intermediate/Build")
55
+ and p.suffix.lower() in {".pch", ".obj"}
56
+ )
57
+ if not allowed or (p.exists() and (not p.is_file() or p.stat().st_nlink != 1)):
58
+ raise ValueError("Protected or linked file: " + str(p))
59
+ return p
60
+
61
+
62
+ def check_git_protection(p):
63
+ root = ART.parent
64
+ if (
65
+ Path(os.fsdecode(git(root, "rev-parse", "--show-toplevel").strip())).resolve()
66
+ != root
67
+ ):
68
+ raise ValueError("DevKit Git root could not be verified")
69
+ name = p.relative_to(root).as_posix()
70
+ if git(root, "ls-files", "-z", "--", name) or not git(
71
+ root, "check-ignore", "--", name
72
+ ):
73
+ raise ValueError("Only ignored, untracked DevKit scratch is eligible")
74
+
75
+
76
+ def plan(run):
77
+ run = checked_run(run)
78
+ errors = []
79
+ candidates = []
80
+ raw = run / "copy/Saved/LiveCapture" / run.name.split("-")[1] / "video.bgra"
81
+ if guarded(raw).is_file():
82
+ candidates.append(raw)
83
+ tmp = guarded(run / "copy/Intermediate/Build")
84
+ if tmp.is_dir():
85
+ candidates.extend(
86
+ p for p, _ in files(tmp, errors) if p.suffix.lower() in {".obj", ".pch"}
87
+ )
88
+ if errors:
89
+ raise ValueError(str(errors))
90
+ entries = []
91
+ for p in candidates:
92
+ rel = str(p.relative_to(run))
93
+ p = scratch(run, rel)
94
+ entries.append(
95
+ dict(
96
+ path=rel,
97
+ bytes=p.stat().st_size,
98
+ allocated_bytes=allocated(p),
99
+ sha256=digest(p),
100
+ reason="capture buffer or compiler intermediate",
101
+ risk="regeneration costs time",
102
+ restore="hygiene restore",
103
+ )
104
+ )
105
+ return dict(run=str(run), entries=entries)
106
+
107
+
108
+ def allocated(path):
109
+ from ctypes import wintypes as w
110
+
111
+ class Standard(ctypes.Structure):
112
+ _fields_ = [
113
+ ("allocation", ctypes.c_int64),
114
+ ("end", ctypes.c_int64),
115
+ ("links", w.DWORD),
116
+ ("pending", ctypes.c_byte),
117
+ ("directory", ctypes.c_byte),
118
+ ]
119
+
120
+ info = Standard()
121
+ query = ctypes.WinDLL("kernel32", use_last_error=True).GetFileInformationByHandleEx
122
+ query.argtypes = [w.HANDLE, ctypes.c_int, ctypes.c_void_p, w.DWORD]
123
+ with path.open("rb") as src:
124
+ if not query(
125
+ msvcrt.get_osfhandle(src.fileno()),
126
+ 1,
127
+ ctypes.byref(info),
128
+ ctypes.sizeof(info),
129
+ ):
130
+ raise ctypes.WinError(ctypes.get_last_error())
131
+ return info.allocation
132
+
133
+
134
+ @contextmanager
135
+ def locked(p):
136
+ # Deny concurrent opens and delete the very same verified NT handle.
137
+ from ctypes import wintypes as w
138
+ import msvcrt
139
+
140
+ k = ctypes.WinDLL("kernel32", use_last_error=True)
141
+ create = k.CreateFileW
142
+ create.argtypes = [
143
+ w.LPCWSTR,
144
+ w.DWORD,
145
+ w.DWORD,
146
+ ctypes.c_void_p,
147
+ w.DWORD,
148
+ w.DWORD,
149
+ w.HANDLE,
150
+ ]
151
+ create.restype = w.HANDLE
152
+ handle = create(str(p), 0x80010000, 0, None, 3, 0x00200000, None)
153
+ if handle == ctypes.c_void_p(-1).value:
154
+ raise ctypes.WinError(ctypes.get_last_error())
155
+ fd = msvcrt.open_osfhandle(handle, os.O_RDONLY | os.O_BINARY)
156
+ with os.fdopen(fd, "rb") as stream:
157
+ final_path = k.GetFinalPathNameByHandleW
158
+ final_path.argtypes = [w.HANDLE, w.LPWSTR, w.DWORD, w.DWORD]
159
+ final_path.restype = w.DWORD
160
+ buffer = ctypes.create_unicode_buffer(32768)
161
+ count = final_path(handle, buffer, len(buffer), 0)
162
+ if not 0 < count < len(buffer):
163
+ raise ctypes.WinError(ctypes.get_last_error())
164
+ actual = Path(buffer.value.removeprefix("\\\\?\\"))
165
+ if actual != p or os.fstat(fd).st_nlink != 1:
166
+ raise ValueError("Opened file identity changed; keeping original")
167
+
168
+ def remove():
169
+ flag = ctypes.c_ubyte(1)
170
+ method = k.SetFileInformationByHandle
171
+ method.argtypes = [w.HANDLE, ctypes.c_int, ctypes.c_void_p, w.DWORD]
172
+ if not method(handle, 4, ctypes.byref(flag), 1):
173
+ raise ctypes.WinError(ctypes.get_last_error())
174
+
175
+ yield stream, remove
176
+
177
+
178
+ def operate(action, plan_path, approval=None):
179
+ payload = plan_path.read_bytes()
180
+ doc = json.loads(payload)
181
+ run = checked_run(Path(doc["run"]))
182
+ if action == "release" and (
183
+ not approval or hashlib.sha256(payload).hexdigest() != approval
184
+ ):
185
+ raise ValueError("Release requires approval of this plan SHA-256")
186
+ if action == "release":
187
+ check_idle(run)
188
+ vault = guarded(ART / "HygieneVault")
189
+ if action == "archive":
190
+ vault.mkdir(exist_ok=True)
191
+ done = 0
192
+ before = shutil.disk_usage(run).free
193
+ for row in doc["entries"]:
194
+ key = row["sha256"]
195
+ if not re.fullmatch(r"[0-9a-f]{64}", key):
196
+ raise ValueError("Invalid object hash")
197
+ p = scratch(run, row["path"])
198
+ obj = guarded(vault / (key + ".zip"))
199
+ if action == "archive" and not obj.exists():
200
+ temp = vault / (uuid.uuid4().hex + ".tmp")
201
+ try:
202
+ with zipfile.ZipFile(
203
+ temp, "x", zipfile.ZIP_DEFLATED, compresslevel=1
204
+ ) as z:
205
+ z.write(p, "data")
206
+ with zipfile.ZipFile(temp) as z, z.open("data") as s:
207
+ if hashlib.file_digest(s, "sha256").hexdigest() != key:
208
+ raise ValueError("Source changed during archive")
209
+ os.replace(temp, obj)
210
+ finally:
211
+ temp.unlink(missing_ok=True)
212
+ with zipfile.ZipFile(obj) as z, z.open("data") as stream:
213
+ if hashlib.file_digest(stream, "sha256").hexdigest() != key:
214
+ raise ValueError("Archive verification failed")
215
+ if action == "restore" and not p.exists():
216
+ # Publish atomically without replacing another writer's file (Win64).
217
+ p.parent.mkdir(parents=True, exist_ok=True)
218
+ temp = p.parent / uuid.uuid4().hex
219
+ try:
220
+ with (
221
+ zipfile.ZipFile(obj) as z,
222
+ z.open("data") as src,
223
+ temp.open("xb") as out,
224
+ ):
225
+ shutil.copyfileobj(src, out)
226
+ if digest(temp) != key:
227
+ raise ValueError("Restored hash mismatch")
228
+ temp.rename(p)
229
+ finally:
230
+ temp.unlink(missing_ok=True)
231
+ if action == "release" and p.exists():
232
+ check_git_protection(p)
233
+ with tempfile.TemporaryDirectory(dir=vault) as directory:
234
+ restored = Path(directory) / "restored"
235
+ with (
236
+ zipfile.ZipFile(obj) as z,
237
+ z.open("data") as src,
238
+ restored.open("xb") as dst,
239
+ ):
240
+ shutil.copyfileobj(src, dst)
241
+ if digest(restored) != key:
242
+ raise ValueError("Disk restore validation failed")
243
+ check_idle(run)
244
+ check_git_protection(p)
245
+ with locked(p) as (src, remove):
246
+ if hashlib.file_digest(src, "sha256").hexdigest() != key:
247
+ raise ValueError("File changed after approval")
248
+ remove()
249
+ if action == "restore" and digest(p) != key:
250
+ raise ValueError("Existing restore destination differs")
251
+ done += 1
252
+ return dict(
253
+ action=action,
254
+ run=str(run),
255
+ plan=str(plan_path.resolve()),
256
+ plan_sha256=hashlib.sha256(payload).hexdigest(),
257
+ archive_objects=[row["sha256"] for row in doc["entries"]],
258
+ verified_objects=done,
259
+ volume_free_delta=shutil.disk_usage(run).free - before,
260
+ )
261
+
262
+
263
+ def check_idle(run):
264
+ query = """$ErrorActionPreference='Stop'
265
+ $p=@(Get-CimInstance Win32_Process | Where-Object {$_.Name -match '^(UnrealEditor.*|UnrealBuildTool|AutomationTool|dotnet|cl|link|ffmpeg.*|UnrealPak|ShaderCompileWorker|Uba.*)[.]exe$'} | Select-Object Name,CommandLine)
266
+ ConvertTo-Json -InputObject $p -Compress"""
267
+ raw = subprocess.check_output(
268
+ ["powershell.exe", "-NoProfile", "-Command", query], timeout=60
269
+ )
270
+ for p in json.loads(raw):
271
+ cmd = (p["CommandLine"] or "").replace("/", "\\").lower()
272
+ if (
273
+ not cmd
274
+ or str(run).lower() in cmd
275
+ or p["Name"].lower() in {"cl.exe", "link.exe", "unrealbuildtool.exe"}
276
+ ):
277
+ raise ValueError("Potential active writer: " + p["Name"])
@@ -0,0 +1,34 @@
1
+ """Runs inside a disposable UE editor commandlet."""
2
+
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import unreal
7
+
8
+ registry = unreal.AssetRegistryHelpers.get_asset_registry()
9
+ registry.search_all_assets(True)
10
+ options = unreal.AssetRegistryDependencyOptions()
11
+ for key in (
12
+ "include_soft_package_references",
13
+ "include_hard_package_references",
14
+ "include_searchable_names",
15
+ "include_soft_management_references",
16
+ "include_hard_management_references",
17
+ ):
18
+ options.set_editor_property(key, True)
19
+ packages = sorted(
20
+ {str(a.package_name) for a in registry.get_assets_by_path("/Game", recursive=True)}
21
+ )
22
+ rows = {
23
+ name: sorted(map(str, registry.get_referencers(name, options) or []))
24
+ for name in packages
25
+ }
26
+ Path(os.environ["DEVKIT_ASSET_REPORT"]).write_text(
27
+ json.dumps(
28
+ dict(
29
+ referencers=rows,
30
+ scope="Asset Registry only; dynamic loads and entry maps remain protected",
31
+ )
32
+ ),
33
+ encoding="utf8",
34
+ )
Tools/environment.py ADDED
@@ -0,0 +1,75 @@
1
+ """Read-only Windows/UE project inspection."""
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ import platform
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ import winreg
11
+
12
+
13
+ def read_json(path):
14
+ return json.loads(path.read_text(encoding="utf-8-sig"))
15
+
16
+
17
+ def command(*args):
18
+ return subprocess.check_output(args, text=True, encoding="utf-8", errors="replace", timeout=30).strip()
19
+
20
+
21
+ def find_engine(association, explicit):
22
+ if explicit or os.getenv("UE5_ROOT"):
23
+ return Path(explicit or os.environ["UE5_ROOT"]).resolve()
24
+ for hive, key, value in [
25
+ (winreg.HKEY_CURRENT_USER, r"SOFTWARE\Epic Games\Unreal Engine\Builds", association),
26
+ (winreg.HKEY_LOCAL_MACHINE, rf"SOFTWARE\EpicGames\Unreal Engine\{association}", "InstalledDirectory"),
27
+ ]:
28
+ try:
29
+ with winreg.OpenKey(hive, key) as reg:
30
+ return Path(winreg.QueryValueEx(reg, value)[0])
31
+ except OSError:
32
+ pass
33
+ launcher = Path(os.environ["ProgramData"]) / "Epic/UnrealEngineLauncher/LauncherInstalled.dat"
34
+ if launcher.is_file():
35
+ for entry in read_json(launcher)["InstallationList"]:
36
+ if entry["AppName"] == "UE_" + association:
37
+ return Path(entry["InstallLocation"])
38
+ raise ValueError("Supply --engine or set UE5_ROOT for this EngineAssociation")
39
+
40
+
41
+ def editors():
42
+ query = r"""@(Get-CimInstance Win32_Process -Filter "Name LIKE 'UnrealEditor%.exe'" | ForEach-Object {
43
+ $path = [regex]::Match($_.CommandLine, '(?i)"([^"]+\.uproject)"|([^\s"]+\.uproject)')
44
+ [PSCustomObject]@{pid=$_.ProcessId;project=$path.Value.Trim('"')}
45
+ })"""
46
+ return json.loads(command("powershell.exe", "-NoProfile", "-Command", "ConvertTo-Json -Compress -InputObject (" + query + ")"))
47
+
48
+
49
+ def inspect(project, explicit):
50
+ if project.suffix.lower() != ".uproject":
51
+ raise ValueError("Expected .uproject")
52
+ desc = read_json(project)
53
+ association = desc["EngineAssociation"]
54
+ root = find_engine(association, explicit)
55
+ engine = root / "Engine"
56
+ version = read_json(engine / "Build/Build.version")
57
+ release = ".".join(str(version[k]) for k in ("MajorVersion", "MinorVersion", "PatchVersion"))
58
+ if re.fullmatch(r"\d+\.\d+", association) and association != release.rsplit(".", 1)[0]:
59
+ raise ValueError(f"Engine {release} conflicts with {association}")
60
+ paths = {key: str(engine / rel) for key, rel in {
61
+ "build": "Build/BatchFiles/Build.bat", "uat": "Build/BatchFiles/RunUAT.bat",
62
+ "ubt": "Binaries/DotNET/UnrealBuildTool/UnrealBuildTool.dll",
63
+ "editor": "Binaries/Win64/UnrealEditor-Cmd.exe"}.items()}
64
+ missing = [p for p in paths.values() if not Path(p).is_file()]
65
+ git = ["git", "--no-optional-locks", "-C", str(project.parent)]
66
+ revision = None
67
+ if shutil.which("git") and subprocess.run([*git, "rev-parse", "--git-dir"], capture_output=True).returncode == 0:
68
+ revision = {k: command(*git, *args) for k, args in {
69
+ "sha": ["rev-parse", "HEAD"], "branch": ["branch", "--show-current"],
70
+ "status": ["status", "--porcelain"], "worktrees": ["worktree", "list"]}.items()}
71
+ return dict(project=str(project), association=association, engine=str(root), version=release,
72
+ paths=paths, missing=missing, modules=desc.get("Modules", []),
73
+ declared_plugins=desc.get("Plugins", []), editors=editors(), git=revision,
74
+ python=sys.version.split()[0], platform=platform.platform(),
75
+ powershell=command("powershell", "-NoProfile", "-Command", "$PSVersionTable.PSVersion.ToString()"))
Tools/mcp_endpoint.py ADDED
@@ -0,0 +1,40 @@
1
+ """Read-only discovery for an explicitly selected loopback MCP endpoint."""
2
+
3
+ import asyncio
4
+ from urllib.parse import urlsplit
5
+
6
+
7
+ def probe(url):
8
+ address = urlsplit(url)
9
+ if (
10
+ address.scheme != "http"
11
+ or address.hostname not in {"127.0.0.1", "::1"}
12
+ or address.port is None
13
+ or address.username is not None
14
+ or address.password is not None
15
+ or address.query
16
+ or address.fragment
17
+ ):
18
+ raise ValueError("Supply an HTTP loopback MCP endpoint with an explicit port")
19
+ try:
20
+ from mcp import ClientSession
21
+ from mcp.client.streamable_http import streamablehttp_client
22
+ except ImportError as error:
23
+ raise ValueError("Install the optional ueagentdevkit[mcp] dependency") from error
24
+
25
+ async def discover():
26
+ async with asyncio.timeout(10):
27
+ async with streamablehttp_client(url) as streams, ClientSession(*streams[:2]) as session:
28
+ initialized = await session.initialize()
29
+ reply = await session.list_tools()
30
+ return {
31
+ "server": initialized.serverInfo.name,
32
+ "tools": [tool.name for tool in reply.tools],
33
+ "more_tools": reply.nextCursor is not None,
34
+ "identity_scope": "endpoint only; editor project and PID are not verified",
35
+ }
36
+
37
+ try:
38
+ return asyncio.run(discover())
39
+ except (ExceptionGroup, TimeoutError) as error:
40
+ raise ValueError(f"MCP discovery failed: {type(error).__name__}") from error
@@ -0,0 +1,36 @@
1
+ """Project-relative JSON defaults for the existing doctor and run commands."""
2
+
3
+ from pathlib import Path
4
+
5
+ from Tools.environment import read_json
6
+
7
+
8
+ def apply_project_defaults(args, test_host):
9
+ if args.profile:
10
+ profile = args.profile.resolve(strict=True)
11
+ data = read_json(profile)
12
+ if not isinstance(data, dict) or set(data) - {"project", "engine", "automation"}:
13
+ raise ValueError("Profile accepts project, engine and automation")
14
+ automation = data.get("automation", {})
15
+ if not isinstance(automation, dict) or set(automation) - {"target", "test"}:
16
+ raise ValueError("Profile automation accepts target and test")
17
+ for values in (data, automation):
18
+ for key, value in values.items():
19
+ if key != "automation" and (not isinstance(value, str) or not value.strip()):
20
+ raise ValueError(f"Profile {key} must be a nonempty string")
21
+ if "project" not in data:
22
+ raise ValueError("Profile must name a .uproject")
23
+ for name in ("project", "engine"):
24
+ if name in data and getattr(args, name) is None:
25
+ setattr(args, name, profile.parent / Path(data[name]))
26
+ if args.action == "run":
27
+ args.target = args.target or automation.get("target")
28
+ args.test = args.test or automation.get("test")
29
+ if args.project is None:
30
+ if not test_host.is_file():
31
+ raise ValueError("Supply --project or --profile")
32
+ args.project = test_host
33
+ if args.action == "run" and not args.test:
34
+ if args.project.resolve() != test_host:
35
+ raise ValueError("Supply --test or set automation.test in the profile")
36
+ args.test = "DevKit.Observation.ActorLocation"
Tools/report.py ADDED
@@ -0,0 +1,11 @@
1
+ """Interpret one exact Automation test in a fresh UE report."""
2
+ def verdict(report, name):
3
+ tests = report["tests"]
4
+ matched = [case for case in tests if case["fullTestPath"] == name]
5
+ if not matched:
6
+ return "NOT_RUN"
7
+ if any(case["state"] == "Fail" for case in tests):
8
+ return "FAIL"
9
+ if len(matched) == 1 and all(case["state"] == "Success" for case in tests):
10
+ return "PASS"
11
+ return "ERROR"