lycheedev 1.2.0 → 2.0.1

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.
Files changed (118) hide show
  1. package/LICENSE +49 -0
  2. package/README.md +45 -0
  3. package/THIRD_PARTY_NOTICES +812 -0
  4. package/bin/lycheedev.mjs +56 -0
  5. package/native/windows-amd64/lycheedev.exe +0 -0
  6. package/package.json +12 -33
  7. package/payload/addon/Bridge/CaptureWriter.lua +154 -0
  8. package/payload/addon/Bridge/Definitions.lua +3 -0
  9. package/payload/addon/Bridge/Identity.lua +127 -0
  10. package/{vendor/addon/Libs/AutomationQR.lua → payload/addon/Bridge/MatrixSymbol.lua} +23 -30
  11. package/payload/addon/Bridge/ProbeQueue.lua +136 -0
  12. package/payload/addon/Bridge/ProbeRunner.lua +128 -0
  13. package/payload/addon/Bridge/ReceiptView.lua +160 -0
  14. package/payload/addon/Bridge/Reentry.lua +192 -0
  15. package/payload/addon/Bridge/ReportStore.lua +153 -0
  16. package/payload/addon/Bridge/Session.lua +163 -0
  17. package/payload/addon/Clients/Evergreen.lua +2 -0
  18. package/payload/addon/Clients/Live.lua +2 -0
  19. package/payload/addon/Clients/Pandaria.lua +2 -0
  20. package/payload/addon/Clients/Titan.lua +2 -0
  21. package/payload/addon/Core/Compat.lua +59 -0
  22. package/payload/addon/Core/Controls.lua +168 -0
  23. package/{vendor/addon/Core/Bootstrap.lua → payload/addon/Core/Execute.lua} +12 -23
  24. package/{vendor → payload}/addon/Core/Inspector.lua +19 -235
  25. package/{vendor → payload}/addon/Core/Locale.lua +128 -93
  26. package/{vendor → payload}/addon/Core/Locale_enUS.lua +128 -95
  27. package/payload/addon/Core/Persistence.lua +58 -0
  28. package/payload/addon/Core/Platform.lua +58 -0
  29. package/payload/addon/Core/Runtime.lua +25 -0
  30. package/payload/addon/Core/Safety.lua +56 -0
  31. package/{vendor → payload}/addon/Core/Serializer.lua +18 -6
  32. package/payload/addon/Core/Stores.lua +611 -0
  33. package/payload/addon/Lychee Dev_Forever.toc +52 -0
  34. package/payload/addon/Lychee Dev_Mainline.toc +52 -0
  35. package/payload/addon/Lychee Dev_Mists.toc +52 -0
  36. package/payload/addon/Lychee Dev_Wrath.toc +52 -0
  37. package/payload/addon/Modules/AutomationView.lua +393 -0
  38. package/{vendor → payload}/addon/Modules/Diagnostics.lua +92 -36
  39. package/{vendor → payload}/addon/Modules/Events/Catalog.lua +9 -0
  40. package/{vendor → payload}/addon/Modules/Events/Monitor.lua +45 -5
  41. package/payload/addon/Modules/FunctionTrace.lua +150 -0
  42. package/{vendor → payload}/addon/Modules/ObjectInspector.lua +105 -31
  43. package/{vendor → payload}/addon/UI/Export.lua +64 -34
  44. package/{vendor → payload}/addon/UI/Pages/About.lua +26 -14
  45. package/payload/addon/UI/Pages/Automation.lua +446 -0
  46. package/payload/addon/UI/Pages/Diagnostics.lua +402 -0
  47. package/{vendor/addon/UI/Features.lua → payload/addon/UI/Pages/Events.lua} +192 -302
  48. package/{vendor → payload}/addon/UI/Pages/ExportRecords.lua +213 -132
  49. package/{vendor → payload}/addon/UI/Pages/Object.lua +229 -121
  50. package/payload/addon/UI/Pages/Run.lua +423 -0
  51. package/payload/addon/UI/Pages/Trace.lua +314 -0
  52. package/payload/addon/UI/TreeView.lua +246 -0
  53. package/{vendor/addon/UI/MainWindow.lua → payload/addon/UI/Widgets.lua} +89 -529
  54. package/payload/addon/UI/Window.lua +425 -0
  55. package/payload/skill/SKILL.md +87 -0
  56. package/payload/skill/agents/openai.yaml +7 -0
  57. package/payload/skill/references/addon-validation.md +42 -0
  58. package/payload/skill/references/asset-export.md +109 -0
  59. package/payload/skill/references/commands.md +169 -0
  60. package/payload/skill/references/data-investigation.md +242 -0
  61. package/payload/skill/references/error-diagnosis.md +41 -0
  62. package/payload/skill/references/installation.md +18 -0
  63. package/payload/skill/references/live-investigation.md +129 -0
  64. package/payload/skill/references/source-research.md +82 -0
  65. package/payload/skill/scripts/lycheedev.mjs +59 -0
  66. package/release.json +346 -0
  67. package/bin/lycheedev.js +0 -746
  68. package/src/addon.js +0 -95
  69. package/src/config.js +0 -68
  70. package/src/doctor.js +0 -126
  71. package/src/install.js +0 -145
  72. package/src/paths.js +0 -93
  73. package/src/py/instances.py +0 -165
  74. package/src/python.js +0 -111
  75. package/src/skill.js +0 -48
  76. package/src/wow.js +0 -541
  77. package/vendor/addon/Core/Clients/Forever.lua +0 -9
  78. package/vendor/addon/Core/Clients/Mainline.lua +0 -9
  79. package/vendor/addon/Core/Clients/Mists.lua +0 -9
  80. package/vendor/addon/Core/Clients/Titan.lua +0 -9
  81. package/vendor/addon/Core/Compatibility.lua +0 -43
  82. package/vendor/addon/Core/Database.lua +0 -859
  83. package/vendor/addon/Core/Safety.lua +0 -42
  84. package/vendor/addon/Lychee Dev_Forever.toc +0 -44
  85. package/vendor/addon/Lychee Dev_Mainline.toc +0 -44
  86. package/vendor/addon/Lychee Dev_Mists.toc +0 -44
  87. package/vendor/addon/Lychee Dev_Wrath.toc +0 -44
  88. package/vendor/addon/Modules/Automation/Controller.lua +0 -896
  89. package/vendor/addon/Modules/Automation/Reload.lua +0 -101
  90. package/vendor/addon/Modules/Automation/Report.lua +0 -409
  91. package/vendor/addon/Modules/Automation/auto/auto.lua +0 -12
  92. package/vendor/addon/Modules/FunctionTrace.lua +0 -85
  93. package/vendor/addon/UI/AutomationOverlay.lua +0 -253
  94. package/vendor/addon/UI/Pages/Automation.lua +0 -417
  95. package/vendor/addon/UI/Pages/Diagnostics.lua +0 -289
  96. package/vendor/addon/UI/Pages/Trace.lua +0 -165
  97. package/vendor/skill/SKILL.md +0 -44
  98. package/vendor/skill/agents/openai.yaml +0 -4
  99. package/vendor/skill/references/automation.md +0 -130
  100. package/vendor/skill/references/clients.md +0 -51
  101. package/vendor/skill/references/runtime-investigations.md +0 -104
  102. package/vendor/skill/scripts/automation/__init__.py +0 -1
  103. package/vendor/skill/scripts/automation/registry.py +0 -516
  104. package/vendor/skill/scripts/automation/reload.py +0 -121
  105. package/vendor/skill/scripts/automation/saved_variables.py +0 -438
  106. package/vendor/skill/scripts/automation/session.py +0 -207
  107. package/vendor/skill/scripts/automation/windows.py +0 -792
  108. package/vendor/skill/scripts/automation.py +0 -1067
  109. package/vendor/skill/scripts/requirements.txt +0 -13
  110. package/vendor/skill/scripts/selftest_offline.py +0 -1061
  111. package/vendor/skill/scripts/test_input_safety.py +0 -132
  112. package/vendor/skill/scripts/test_reload.py +0 -120
  113. /package/{vendor → payload}/addon/Media/GitHub.png +0 -0
  114. /package/{vendor → payload}/addon/Media/Logo.png +0 -0
  115. /package/{vendor → payload}/addon/Modules/Events/CatalogData_Forever.lua +0 -0
  116. /package/{vendor → payload}/addon/Modules/Events/CatalogData_Mainline.lua +0 -0
  117. /package/{vendor → payload}/addon/Modules/Events/CatalogData_Mists.lua +0 -0
  118. /package/{vendor → payload}/addon/Modules/Events/CatalogData_Titan.lua +0 -0
@@ -1,516 +0,0 @@
1
- """Task block registry for the Lychee Dev automation task file.
2
-
3
- The task file (``Modules/Automation/auto/auto.lua``) only ever contains Lua
4
- data: an empty ``ns.AutomationTaskDefinitions`` table plus optional task blocks
5
- between generated markers. This module owns reading and updating that file:
6
-
7
- - the whole installation directory is protected by an OS-level exclusive lock
8
- file so concurrent writers cannot interleave,
9
- - updates replace exactly one block and keep every other block and its order,
10
- - generated Lua stays Lua 5.1 compatible and pure ASCII (quotes, backslashes,
11
- newlines, non-ASCII bytes and marker text are escaped),
12
- - writes go through a temp file in the same directory followed by an atomic
13
- replace, so a crash leaves either the complete old or the complete new file,
14
- - the new file's SHA-256 is recorded for every successful write,
15
- - content outside the task blocks is preserved verbatim; only the block region
16
- is regenerated,
17
- - the installed path is resolved through symlinks/junctions before any read or
18
- write, so two names for one directory cannot disagree,
19
- - the parser only accepts the data syntax this module generates; it never
20
- executes Lua.
21
- """
22
-
23
- from __future__ import annotations
24
-
25
- import hashlib
26
- import os
27
- import re
28
- import tempfile
29
- import zlib
30
- from contextlib import contextmanager
31
-
32
- try: # Windows-only; the registry stays importable on other hosts for tests.
33
- import msvcrt
34
- except ImportError: # pragma: no cover - exercised only off-Windows
35
- msvcrt = None
36
-
37
- try:
38
- import fcntl
39
- except ImportError: # pragma: no cover
40
- fcntl = None
41
-
42
- TASK_ID_PATTERN = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
43
- REQUEST_ID_PATTERN = re.compile(r"^[A-Za-z0-9_.-]{1,128}$")
44
-
45
- REGISTRY_SCHEMA_VERSION = 1
46
- REGISTRY_KINDS = ("lua", "bug_snapshot")
47
-
48
- MAX_BLOCKS = 16
49
- MAX_REGISTRY_BYTES = 1024 * 1024
50
- MAX_SOURCE_BYTES = 256 * 1024
51
-
52
- BEGIN_MARKER = "-- BEGIN LYCHEE DEV TASK "
53
- END_MARKER = "-- END LYCHEE DEV TASK "
54
-
55
- REGISTRY_HEADER = """local ADDON_NAME, ns = ...
56
-
57
- -- Automation task registry. This file contains generated data only; loading it
58
- -- must never execute task source. Task blocks are written between the
59
- -- BEGIN/END markers by the Lychee Dev skill tooling and are removed before
60
- -- release packaging ships an empty registry.
61
-
62
- ns.AutomationTaskDefinitions = ns.AutomationTaskDefinitions or {}
63
-
64
- -- Task blocks use exactly this marker shape (task id may not contain the
65
- -- marker text): "-- BEGIN LYCHEE DEV TASK <task-id>" ... "-- END LYCHEE DEV TASK <task-id>".
66
- -- The skill tooling inserts and replaces them; releases ship this file empty.
67
- """
68
-
69
-
70
- class RegistryError(Exception):
71
- """Raised for every expected registry failure; the old file stays intact."""
72
-
73
-
74
- def validate_task_id(task_id: str) -> str:
75
- if not isinstance(task_id, str) or not TASK_ID_PATTERN.match(task_id):
76
- raise RegistryError(f"invalid task id: {task_id!r}")
77
- return task_id
78
-
79
-
80
- def validate_request_id(request_id: str) -> str:
81
- if not isinstance(request_id, str) or not REQUEST_ID_PATTERN.match(request_id):
82
- raise RegistryError(f"invalid request id: {request_id!r}")
83
- return request_id
84
-
85
-
86
- def escape_lua_string(text: str) -> str:
87
- """Encode text as one Lua 5.1 double-quoted literal, ASCII only."""
88
-
89
- out = ['"']
90
- for byte in text.encode("utf-8"):
91
- char = chr(byte)
92
- if char == '"':
93
- out.append('\\"')
94
- elif char == "\\":
95
- out.append("\\\\")
96
- elif char == "\n":
97
- out.append("\\n")
98
- elif char == "\r":
99
- out.append("\\r")
100
- elif char == "\t":
101
- out.append("\\t")
102
- elif 0x20 <= byte <= 0x7E:
103
- out.append(char)
104
- else:
105
- out.append(f"\\{byte:03d}")
106
- out.append('"')
107
- return "".join(out)
108
-
109
-
110
- def unescape_lua_string(literal: str) -> str:
111
- """Decode a Lua 5.1 double-quoted literal (without the quotes) to text."""
112
-
113
- if not literal.startswith('"') or not literal.endswith('"') or len(literal) < 2:
114
- raise RegistryError("expected a double-quoted Lua string literal")
115
- body = literal[1:-1]
116
- out = bytearray()
117
- index = 0
118
- while index < len(body):
119
- char = body[index]
120
- if char != "\\":
121
- byte_value = ord(char)
122
- if byte_value > 0x7E:
123
- raise RegistryError("non-ASCII byte in string literal")
124
- out.append(byte_value)
125
- index += 1
126
- continue
127
- index += 1
128
- if index >= len(body):
129
- raise RegistryError("dangling escape in string literal")
130
- escape = body[index]
131
- simple = {'"': '"', "\\": "\\", "n": "\n", "r": "\r", "t": "\t", "a": "\a",
132
- "b": "\b", "f": "\f", "v": "\v"}
133
- if escape in simple:
134
- out.extend(simple[escape].encode("utf-8"))
135
- index += 1
136
- elif escape in "0123456789":
137
- # Lua 5.1 \ddd takes one to three decimal digits and must fit a byte.
138
- match = re.match(r"[0-9]{1,3}", body[index:])
139
- digits = match.group(0)
140
- value = int(digits)
141
- if value > 255:
142
- raise RegistryError(f"decimal escape too large: \\{digits}")
143
- out.append(value)
144
- index += len(digits)
145
- else:
146
- raise RegistryError(f"unsupported escape: \\{escape}")
147
- return out.decode("utf-8")
148
-
149
-
150
- def adler32_hex(text: str) -> str:
151
- return format(zlib.adler32(text.encode("utf-8")) & 0xFFFFFFFF, "08x")
152
-
153
-
154
- def build_block(
155
- task_id: str,
156
- *,
157
- request_id: str,
158
- revision: str,
159
- source: str,
160
- created_at: int,
161
- expires_at: int = 0,
162
- expected_interface: int | None = None,
163
- output_limit: int | None = None,
164
- ) -> list[str]:
165
- validate_task_id(task_id)
166
- validate_request_id(request_id)
167
- if not isinstance(revision, str) or not 1 <= len(revision) <= 128:
168
- raise RegistryError("revision must be a non-empty string of at most 128 chars")
169
- source_bytes = source.encode("utf-8")
170
- if not source_bytes:
171
- raise RegistryError("task source must not be empty")
172
- if len(source_bytes) > MAX_SOURCE_BYTES:
173
- raise RegistryError(
174
- f"task source exceeds the {MAX_SOURCE_BYTES} byte limit: {len(source_bytes)}")
175
-
176
- lines = [
177
- f"{BEGIN_MARKER}{task_id}",
178
- f'ns.AutomationTaskDefinitions["{task_id}"] = {{',
179
- " schema = 1,",
180
- f" requestId = {escape_lua_string(request_id)},",
181
- f" revision = {escape_lua_string(revision)},",
182
- ' kind = "lua",',
183
- f" createdAt = {int(created_at)},",
184
- f" expiresAt = {int(expires_at or 0)},",
185
- f" sourceBytes = {len(source_bytes)},",
186
- f' sourceChecksum = "{adler32_hex(source)}",',
187
- ]
188
- if expected_interface:
189
- lines.append(f" expectedClient = {{ interface = {int(expected_interface)} }},")
190
- if output_limit:
191
- lines.append(f" outputLimit = {int(output_limit)},")
192
- lines.append(f" source = {escape_lua_string(source)},")
193
- lines.append("}")
194
- lines.append(f"{END_MARKER}{task_id}")
195
- return lines
196
-
197
-
198
- class _Block:
199
- __slots__ = ("task_id", "lines")
200
-
201
- def __init__(self, task_id: str, lines: list[str]):
202
- self.task_id = task_id
203
- self.lines = lines
204
-
205
-
206
- FIELD_PATTERN = re.compile(r"^\s*(\w+) = (.+?),\s*$")
207
-
208
-
209
- def _parse_field(block: _Block, field: str):
210
- """Extract one field value from a generated block (data syntax only)."""
211
-
212
- for line in block.lines:
213
- match = FIELD_PATTERN.match(line)
214
- if match and match.group(1) == field:
215
- return match.group(2)
216
- return None
217
-
218
-
219
- def _decode_block(block: _Block) -> dict:
220
- task_id = block.task_id
221
- if block.lines[0] != f"{BEGIN_MARKER}{task_id}" or block.lines[-1] != f"{END_MARKER}{task_id}":
222
- raise RegistryError(f"damaged markers in block {task_id}")
223
- header = block.lines[1]
224
- if header != f'ns.AutomationTaskDefinitions["{task_id}"] = {{':
225
- raise RegistryError(f"unexpected block header in {task_id}")
226
- if block.lines[-2] != "}":
227
- raise RegistryError(f"unexpected block footer in {task_id}")
228
- for index, line in enumerate(block.lines[2:-2], start=2):
229
- if not FIELD_PATTERN.match(line):
230
- raise RegistryError(
231
- f"block {task_id} has an unexpected line {index + 1}: {line!r}")
232
-
233
- definition: dict = {"taskId": task_id}
234
- schema_raw = _parse_field(block, "schema")
235
- if schema_raw is None or not schema_raw.strip().isdigit():
236
- raise RegistryError(f"block {task_id} has a bad schema")
237
- schema = int(schema_raw)
238
- if schema != REGISTRY_SCHEMA_VERSION:
239
- raise RegistryError(
240
- f"block {task_id} uses unsupported schema {schema} "
241
- f"(supported: {REGISTRY_SCHEMA_VERSION})")
242
- definition["schema"] = schema
243
- kind_raw = _parse_field(block, "kind")
244
- if kind_raw is None:
245
- raise RegistryError(f"block {task_id} is missing kind")
246
- kind = unescape_lua_string(kind_raw) if kind_raw.startswith('"') else kind_raw
247
- if kind not in REGISTRY_KINDS:
248
- raise RegistryError(f"block {task_id} uses unsupported kind {kind!r}")
249
- definition["kind"] = kind
250
- for name in ("requestId", "revision"):
251
- raw = _parse_field(block, name)
252
- if raw is None:
253
- raise RegistryError(f"block {task_id} is missing {name}")
254
- definition[name] = unescape_lua_string(raw)
255
- for name in ("createdAt", "expiresAt", "sourceBytes"):
256
- raw = _parse_field(block, name)
257
- if raw is None or not raw.lstrip("-").isdigit():
258
- raise RegistryError(f"block {task_id} has a bad {name}")
259
- definition[name] = int(raw)
260
- checksum = _parse_field(block, "sourceChecksum")
261
- if checksum is None or not re.match(r'^"[0-9a-f]{8}"$', checksum):
262
- raise RegistryError(f"block {task_id} has a bad sourceChecksum")
263
- definition["sourceChecksum"] = checksum.strip('"')
264
- output_limit = _parse_field(block, "outputLimit")
265
- if output_limit is not None:
266
- definition["outputLimit"] = int(output_limit)
267
- expected = _parse_field(block, "expectedClient")
268
- if expected is not None:
269
- match = re.match(r"^\{ interface = (\d+) \}$", expected)
270
- if not match:
271
- raise RegistryError(f"block {task_id} has a bad expectedClient")
272
- definition["expectedClient"] = {"interface": int(match.group(1))}
273
- source_raw = _parse_field(block, "source")
274
- if source_raw is None:
275
- raise RegistryError(f"block {task_id} has no source")
276
- source = unescape_lua_string(source_raw)
277
- encoded = source.encode("utf-8")
278
- if len(encoded) != definition["sourceBytes"]:
279
- raise RegistryError(f"block {task_id} sourceBytes mismatch")
280
- if adler32_hex(source) != definition["sourceChecksum"]:
281
- raise RegistryError(f"block {task_id} sourceChecksum mismatch")
282
- definition["source"] = source
283
- return definition
284
-
285
-
286
- def parse_blocks(text: str) -> tuple[dict[str, dict], list[_Block]]:
287
- """Parse the registry into decoded definitions plus ordered raw blocks."""
288
-
289
- blocks: list[_Block] = []
290
- current: _Block | None = None
291
- for line in text.splitlines():
292
- if line.startswith(BEGIN_MARKER):
293
- if current is not None:
294
- raise RegistryError("nested BEGIN marker inside a task block")
295
- task_id = line[len(BEGIN_MARKER):].strip()
296
- validate_task_id(task_id)
297
- current = _Block(task_id, [line])
298
- elif line.startswith(END_MARKER):
299
- if current is None:
300
- raise RegistryError("END marker without a matching BEGIN marker")
301
- task_id = line[len(END_MARKER):].strip()
302
- if task_id != current.task_id:
303
- raise RegistryError("END marker task id does not match its BEGIN marker")
304
- current.lines.append(line)
305
- blocks.append(current)
306
- current = None
307
- elif current is not None:
308
- if line.startswith(BEGIN_MARKER[:5]) and line.startswith("-- BEGIN"):
309
- raise RegistryError("corrupted marker inside a task block")
310
- current.lines.append(line)
311
- if current is not None:
312
- raise RegistryError("unterminated task block")
313
- if not blocks and "ns.AutomationTaskDefinitions" not in text:
314
- raise RegistryError("file does not look like a Lychee Dev task registry")
315
-
316
- seen: dict[str, dict] = {}
317
- for block in blocks:
318
- if block.task_id in seen:
319
- raise RegistryError(f"duplicate task block: {block.task_id}")
320
- seen[block.task_id] = _decode_block(block)
321
- return seen, blocks
322
-
323
-
324
- @contextmanager
325
- def _directory_lock(directory: str):
326
- """Hold an exclusive lock file inside the installation directory."""
327
-
328
- lock_path = os.path.join(directory, "auto.lua.lock")
329
- lock = open(lock_path, "a+b")
330
- try:
331
- if msvcrt is not None:
332
- msvcrt.locking(lock.fileno(), msvcrt.LK_LOCK, 1)
333
- elif fcntl is not None:
334
- fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
335
- yield
336
- finally:
337
- try:
338
- if msvcrt is not None:
339
- lock.seek(0)
340
- msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
341
- elif fcntl is not None:
342
- fcntl.flock(lock.fileno(), fcntl.LOCK_UN)
343
- finally:
344
- lock.close()
345
-
346
-
347
- def resolve_registry_path(path: str) -> str:
348
- """Resolve symlinks and directory junctions before any read or write.
349
-
350
- Two paths that name the same file must lock, read and replace the same
351
- file; ``realpath`` follows Windows junctions and symlinks so a shared
352
- installation reached through a link cannot split the revision check.
353
- """
354
-
355
- return os.path.realpath(os.path.abspath(path))
356
-
357
-
358
- def split_regions(text: str) -> tuple[str, str]:
359
- """Return the verbatim text before the first block and after the last one.
360
-
361
- The block region is the only part this module regenerates; anything a human
362
- or another tool placed outside the markers stays byte-for-byte. The blank
363
- separator lines right after the last END marker belong to the region so
364
- repeated writes do not grow the file.
365
- """
366
-
367
- lines = text.splitlines(keepends=True)
368
- first = None
369
- last = None
370
- for index, line in enumerate(lines):
371
- if first is None and line.startswith(BEGIN_MARKER):
372
- first = index
373
- elif line.startswith(END_MARKER):
374
- last = index
375
- if first is None or last is None or last < first:
376
- return text, ""
377
- tail = last + 1
378
- while tail < len(lines) and lines[tail].strip() == "":
379
- tail += 1
380
- return "".join(lines[:first]), "".join(lines[tail:])
381
-
382
-
383
- def _atomic_write(path: str, data: bytes) -> None:
384
- directory = os.path.dirname(os.path.abspath(path))
385
- handle = tempfile.NamedTemporaryFile(
386
- "wb", dir=directory, delete=False, prefix=".auto-", suffix=".tmp")
387
- try:
388
- with handle:
389
- handle.write(data)
390
- handle.flush()
391
- os.fsync(handle.fileno())
392
- os.replace(handle.name, path)
393
- except BaseException:
394
- try:
395
- os.unlink(handle.name)
396
- except OSError:
397
- pass
398
- raise
399
-
400
-
401
- class TaskRegistry:
402
- """Reader/writer for one installed auto.lua task registry."""
403
-
404
- def __init__(self, path: str):
405
- self.path = resolve_registry_path(path)
406
- self.last_write_hash: str | None = None
407
-
408
- def _read_text(self) -> str:
409
- if not os.path.exists(self.path):
410
- return REGISTRY_HEADER
411
- with open(self.path, "r", encoding="utf-8") as handle:
412
- return handle.read()
413
-
414
- def read(self) -> dict[str, dict]:
415
- text = self._read_text()
416
- definitions, _ = parse_blocks(text)
417
- return definitions
418
-
419
- def _write(self, blocks: list[_Block], template: str | None = None) -> tuple[str, str]:
420
- """Write the block region, preserving everything outside it.
421
-
422
- Returns the written text and the SHA-256 of the exact bytes on disk.
423
- """
424
-
425
- if template is None:
426
- template = self._read_text()
427
- prefix, suffix = split_regions(template)
428
- if prefix and not prefix.endswith("\n"):
429
- prefix += "\n"
430
- if blocks and prefix and not prefix.endswith("\n\n"):
431
- prefix += "\n"
432
- parts = [prefix]
433
- for block in blocks:
434
- for line in block.lines:
435
- parts.append(line + "\n")
436
- parts.append("\n")
437
- parts.append(suffix)
438
- text = "".join(parts)
439
- encoded = text.encode("utf-8")
440
- if len(encoded) > MAX_REGISTRY_BYTES:
441
- raise RegistryError(
442
- f"registry exceeds the {MAX_REGISTRY_BYTES} byte limit: {len(encoded)}")
443
- if "\r" in text or any(ord(char) > 127 for char in text):
444
- raise RegistryError("registry must stay ASCII with LF endings")
445
- digest = hashlib.sha256(encoded).hexdigest()
446
- _atomic_write(self.path, encoded)
447
- self.last_write_hash = digest
448
- return text, digest
449
-
450
- def upsert(
451
- self,
452
- task_id: str,
453
- *,
454
- request_id: str,
455
- revision: str,
456
- source: str,
457
- created_at: int,
458
- expires_at: int = 0,
459
- expected_interface: int | None = None,
460
- output_limit: int | None = None,
461
- expect_revision: str | None = None,
462
- ) -> dict:
463
- validate_task_id(task_id)
464
- directory = os.path.dirname(self.path) or "."
465
- os.makedirs(directory, exist_ok=True)
466
- with _directory_lock(directory):
467
- text = self._read_text()
468
- definitions, blocks = parse_blocks(text)
469
- if task_id in definitions and expect_revision is not None:
470
- if definitions[task_id]["revision"] != expect_revision:
471
- raise RegistryError(
472
- f"revision conflict for {task_id}: expected {expect_revision!r}, "
473
- f"found {definitions[task_id]['revision']!r}")
474
- new_lines = build_block(
475
- task_id,
476
- request_id=request_id,
477
- revision=revision,
478
- source=source,
479
- created_at=created_at,
480
- expires_at=expires_at,
481
- expected_interface=expected_interface,
482
- output_limit=output_limit,
483
- )
484
- replaced = False
485
- for index, block in enumerate(blocks):
486
- if block.task_id == task_id:
487
- blocks[index] = _Block(task_id, new_lines)
488
- replaced = True
489
- break
490
- if not replaced:
491
- if len(blocks) >= MAX_BLOCKS:
492
- raise RegistryError(f"registry already holds {MAX_BLOCKS} task blocks")
493
- blocks.append(_Block(task_id, new_lines))
494
- written, file_hash = self._write(blocks, template=text)
495
- parsed, _ = parse_blocks(written)
496
- definition = dict(parsed[task_id])
497
- definition["fileHash"] = file_hash
498
- return definition
499
-
500
- def remove(self, task_id: str, *, expect_revision: str | None = None) -> bool:
501
- validate_task_id(task_id)
502
- directory = os.path.dirname(self.path) or "."
503
- if not os.path.exists(self.path):
504
- return False
505
- with _directory_lock(directory):
506
- text = self._read_text()
507
- definitions, blocks = parse_blocks(text)
508
- if task_id not in definitions:
509
- return False
510
- if expect_revision is not None and definitions[task_id]["revision"] != expect_revision:
511
- raise RegistryError(
512
- f"revision conflict for {task_id}: expected {expect_revision!r}, "
513
- f"found {definitions[task_id]['revision']!r}")
514
- remaining = [block for block in blocks if block.task_id != task_id]
515
- self._write(remaining, template=text)
516
- return True
@@ -1,121 +0,0 @@
1
- """Nonce-bound reload readiness; images remain on the host, not in model input."""
2
- from __future__ import annotations
3
-
4
- import json
5
- import os
6
- import re
7
- import struct
8
- import time
9
- import zlib
10
-
11
- NONCE = re.compile(r"[A-Za-z0-9.-]{1,64}\Z")
12
-
13
-
14
- class ReloadError(Exception):
15
- pass
16
-
17
-
18
- def marker(payload, nonce):
19
- if not isinstance(payload, str) or len(payload.encode("utf-8")) > 512:
20
- return None
21
- try:
22
- value = json.loads(payload)
23
- except (ValueError, TypeError):
24
- return None
25
- if not isinstance(value, dict) or value.get("v") != 1:
26
- return None
27
- if value.get("kind") != "reload" or value.get("run") != nonce or value.get("status") != "ready":
28
- return None
29
- if type(value.get("ts")) is not int or value["ts"] <= 0:
30
- return None
31
- if not all(isinstance(value.get(k), str) and 0 < len(value[k]) <= 64 for k in ("client", "build")):
32
- return None
33
- return value
34
-
35
-
36
- def save_timeout_image(session, nonce, roi):
37
- if roi is None:
38
- return None
39
- # WGC's bounded ROI is BGR(A); write RGB PNG with the stdlib, no new dependency.
40
- height, width = roi.shape[:2]
41
- raw = b"".join(b"\0" + roi[y, :, :3][:, ::-1].tobytes() for y in range(height))
42
- def chunk(kind, data):
43
- return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xffffffff)
44
- png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
45
- png += chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
46
- directory = session.state_path(os.path.join("reload", nonce))
47
- os.makedirs(directory, exist_ok=True)
48
- path = os.path.join(directory, "timeout.png")
49
- with open(path, "wb") as handle:
50
- handle.write(png)
51
- return path
52
-
53
-
54
- def wait_ready(windows, session, args, nonce):
55
- deadline = time.monotonic() + args.timeout
56
- interval = getattr(args, "interval", None) or .1
57
- last_roi = None
58
- with windows.open_notice_capture(args.hwnd, pid=args.pid, exe_path=args.exe_path, interval=interval) as capture:
59
- while time.monotonic() < deadline:
60
- if capture.window_closed:
61
- break
62
- roi = capture.latest_roi()
63
- if roi is not None:
64
- last_roi = roi
65
- for payload in windows.decode_qr(roi):
66
- ready = marker(payload, nonce)
67
- if ready:
68
- return ready
69
- time.sleep(interval)
70
- path = save_timeout_image(session, nonce, last_roi)
71
- session.log_event("reload_ready_timeout", nonce=nonce, screenshot=path)
72
- raise ReloadError(f"reload readiness unresolved for {nonce}; resume this nonce without reloading; screenshot={path}")
73
-
74
-
75
- def wait_cleared(windows, args, nonce):
76
- deadline = time.monotonic() + min(args.timeout, 5)
77
- interval = getattr(args, "interval", None) or .1
78
- absent = 0
79
- with windows.open_notice_capture(args.hwnd, pid=args.pid, exe_path=args.exe_path, interval=interval) as capture:
80
- while time.monotonic() < deadline:
81
- if capture.window_closed:
82
- return False
83
- roi = capture.latest_roi()
84
- if roi is not None:
85
- visible = any(marker(payload, nonce) for payload in windows.decode_qr(roi))
86
- absent = 0 if visible else absent + 1
87
- if absent >= 2:
88
- return True
89
- time.sleep(interval)
90
- return False
91
-
92
-
93
- def execute(windows, session, args, deliver, nonce, *, ticket=None, resume=False):
94
- if not NONCE.fullmatch(nonce):
95
- raise ReloadError("invalid reload nonce")
96
- history = [e for e in session.read_events() if e.get("nonce") == nonce]
97
- previous = next((e for e in history if e["event"] == "reload_handshake_requested"), None)
98
- if resume:
99
- if not previous or any(previous.get(k) != getattr(args, attr, None)
100
- for k, attr in (("hwnd", "hwnd"), ("pid", "pid"), ("exePath", "exe_path"))):
101
- raise ReloadError("reload resume requires the original nonce and window binding")
102
- if any(e["event"] == "reload_ready_cleared" for e in history):
103
- return {"status": "already_completed", "nonce": nonce}
104
- else:
105
- if previous:
106
- raise ReloadError("reload nonce was already submitted; use --resume, do not reload again")
107
- session.log_event("reload_handshake_requested", nonce=nonce, ticket=ticket,
108
- hwnd=args.hwnd, pid=args.pid, exePath=args.exe_path)
109
- deliver(session, windows, args, f"/dev auto reload {nonce}" + (f" {ticket}" if ticket else ""))
110
- started = time.monotonic()
111
- confirmed = next((e for e in history if e["event"] == "reload_ready_confirmed"), None)
112
- ready = confirmed.get("ready") if confirmed else wait_ready(windows, session, args, nonce)
113
- if not confirmed:
114
- session.log_event("reload_ready_confirmed", nonce=nonce, ready=ready)
115
- deliver(session, windows, args, f"/dev auto unidentify {nonce}")
116
- if not wait_cleared(windows, args, nonce):
117
- session.log_event("reload_ready_cleanup_unresolved", nonce=nonce)
118
- raise ReloadError(f"reload ready, but marker cleanup unresolved; resume {nonce}")
119
- session.log_event("reload_ready_cleared", nonce=nonce)
120
- return {"status": "reload_ready", "nonce": nonce, "elapsedSeconds": round(time.monotonic() - started, 2),
121
- "client": ready["client"], "build": ready["build"], "markerCleared": True}