lycheedev 1.0.0

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 (60) hide show
  1. package/bin/lycheedev.js +257 -0
  2. package/package.json +42 -0
  3. package/src/addon.js +87 -0
  4. package/src/config.js +64 -0
  5. package/src/doctor.js +100 -0
  6. package/src/install.js +131 -0
  7. package/src/paths.js +93 -0
  8. package/src/python.js +107 -0
  9. package/src/skill.js +48 -0
  10. package/src/wow.js +110 -0
  11. package/vendor/addon/Core/Bootstrap.lua +131 -0
  12. package/vendor/addon/Core/Clients/Mainline.lua +9 -0
  13. package/vendor/addon/Core/Clients/Mists.lua +9 -0
  14. package/vendor/addon/Core/Clients/Titan.lua +9 -0
  15. package/vendor/addon/Core/Compatibility.lua +43 -0
  16. package/vendor/addon/Core/Database.lua +859 -0
  17. package/vendor/addon/Core/Inspector.lua +647 -0
  18. package/vendor/addon/Core/Locale.lua +307 -0
  19. package/vendor/addon/Core/Locale_enUS.lua +318 -0
  20. package/vendor/addon/Core/Safety.lua +42 -0
  21. package/vendor/addon/Core/Serializer.lua +324 -0
  22. package/vendor/addon/Libs/AutomationQR.lua +1176 -0
  23. package/vendor/addon/Lychee Dev_Mainline.toc +43 -0
  24. package/vendor/addon/Lychee Dev_Mists.toc +43 -0
  25. package/vendor/addon/Lychee Dev_Wrath.toc +43 -0
  26. package/vendor/addon/Media/GitHub.png +0 -0
  27. package/vendor/addon/Media/Logo.png +0 -0
  28. package/vendor/addon/Modules/Automation/Controller.lua +757 -0
  29. package/vendor/addon/Modules/Automation/Report.lua +409 -0
  30. package/vendor/addon/Modules/Automation/auto/auto.lua +12 -0
  31. package/vendor/addon/Modules/Diagnostics.lua +238 -0
  32. package/vendor/addon/Modules/Events/Catalog.lua +184 -0
  33. package/vendor/addon/Modules/Events/CatalogData_Mainline.lua +1788 -0
  34. package/vendor/addon/Modules/Events/CatalogData_Mists.lua +1489 -0
  35. package/vendor/addon/Modules/Events/CatalogData_Titan.lua +1492 -0
  36. package/vendor/addon/Modules/Events/Monitor.lua +181 -0
  37. package/vendor/addon/Modules/FunctionTrace.lua +85 -0
  38. package/vendor/addon/Modules/ObjectInspector.lua +329 -0
  39. package/vendor/addon/UI/AutomationOverlay.lua +183 -0
  40. package/vendor/addon/UI/Export.lua +140 -0
  41. package/vendor/addon/UI/Features.lua +890 -0
  42. package/vendor/addon/UI/MainWindow.lua +1145 -0
  43. package/vendor/addon/UI/Pages/About.lua +223 -0
  44. package/vendor/addon/UI/Pages/Automation.lua +417 -0
  45. package/vendor/addon/UI/Pages/Diagnostics.lua +289 -0
  46. package/vendor/addon/UI/Pages/ExportRecords.lua +387 -0
  47. package/vendor/addon/UI/Pages/Object.lua +573 -0
  48. package/vendor/addon/UI/Pages/Trace.lua +165 -0
  49. package/vendor/skill/SKILL.md +94 -0
  50. package/vendor/skill/agents/openai.yaml +4 -0
  51. package/vendor/skill/references/automation.md +327 -0
  52. package/vendor/skill/references/runtime-investigations.md +97 -0
  53. package/vendor/skill/scripts/automation/__init__.py +1 -0
  54. package/vendor/skill/scripts/automation/registry.py +516 -0
  55. package/vendor/skill/scripts/automation/saved_variables.py +438 -0
  56. package/vendor/skill/scripts/automation/session.py +207 -0
  57. package/vendor/skill/scripts/automation/windows.py +573 -0
  58. package/vendor/skill/scripts/automation.py +865 -0
  59. package/vendor/skill/scripts/requirements.txt +13 -0
  60. package/vendor/skill/scripts/selftest_offline.py +981 -0
@@ -0,0 +1,865 @@
1
+ #!/usr/bin/env python3
2
+ """Lychee Dev automation CLI: task delivery, notices, reload and receipt.
3
+
4
+ Subcommand groups (design section 9):
5
+
6
+ - ``task`` update the installed auto.lua registry (upsert/remove/list)
7
+ - ``profile`` bind one WoW client installation, addon dir and SV path
8
+ - ``sv`` find account-level SavedVariables candidates; read a Ticket
9
+ - ``capture`` poll the game window and decode the completion notice QR
10
+ - ``send`` deliver one slash command through focus/clipboard/Enter
11
+ - ``run`` task flow: run command, notice, output reload, SavedVariables
12
+ read and artifact save (the input-side reload that loads the
13
+ new task block is a separate, operator-visible step)
14
+ - ``bugs`` bug snapshot flow: run command, notice, output reload, read
15
+ - ``status`` summarize the host session log
16
+ - ``recover`` print recent host log events and the suggested next step
17
+
18
+ Exit codes: 0 success; 1 invalid usage or a missing binding/profile; 2 task
19
+ registry failure; 3 SavedVariables read or verification failure; 4 window
20
+ identity, command input, or missing optional capture dependency failure; 5 no
21
+ notice decoded before the timeout. Expected failures print one explicit
22
+ ``error: ...`` line instead of a traceback.
23
+
24
+ Live-window features (capture/send/run/bugs) require optional packages
25
+ (windows-capture, numpy, zxing-cpp) and real-game verification; they fail with
26
+ explicit messages instead of guessing. Host data lives under the session data
27
+ directory, never inside the skill sources or the addon ZIP.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import argparse
33
+ import hashlib
34
+ import json
35
+ import os
36
+ import secrets
37
+ import sys
38
+ import time
39
+ import traceback
40
+
41
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
42
+
43
+ from automation import registry, saved_variables as svlib # noqa: E402
44
+ from automation import session as session_mod # noqa: E402
45
+ from automation.registry import RegistryError # noqa: E402
46
+ from automation.saved_variables import SavedVariablesError # noqa: E402
47
+
48
+ NOTICE_MAX_BYTES = 512
49
+ BUG_TASK_ID = "bug"
50
+ CLIENT_FOLDERS = {"retail": "_retail_", "classic": "_classic_", "titan": "_classic_arena"}
51
+ DEFAULT_TIMEOUT = 120.0
52
+ DEFAULT_INTERVAL = 0.1
53
+ SV_READ_RETRIES = 3
54
+ SV_READ_RETRY_DELAY = 0.5
55
+ EXIT_USAGE = 1
56
+ EXIT_REGISTRY = 2
57
+ EXIT_SV_READ = 3
58
+ EXIT_INPUT = 4
59
+ EXIT_NOTICE_TIMEOUT = 5
60
+
61
+
62
+ class CliError(Exception):
63
+ """An expected CLI failure: message on stderr, explicit non-zero exit."""
64
+
65
+ def __init__(self, message: str, code: int = EXIT_USAGE):
66
+ super().__init__(message)
67
+ self.code = code
68
+
69
+
70
+ def resolve_install_dir(args, *, required: bool = True) -> str | None:
71
+ if getattr(args, "install_dir", None):
72
+ return args.install_dir
73
+ if getattr(args, "profile", None):
74
+ session = session_mod.Session(data_dir=args.data_dir,
75
+ installation=args.installation)
76
+ return load_profile(session, args.profile)["addon_dir"]
77
+ if required:
78
+ raise CliError("either --install-dir or --profile is required")
79
+ return None
80
+
81
+
82
+ # --- task ---------------------------------------------------------------------
83
+
84
+ def new_request_id() -> str:
85
+ stamp = time.strftime("%Y%m%d-%H%M%S", time.gmtime())
86
+ return f"req-{stamp}-{secrets.token_hex(3)}"
87
+
88
+
89
+ def cmd_task(args) -> int:
90
+ install_dir = resolve_install_dir(args)
91
+ task_path = os.path.join(install_dir, "Modules", "Automation", "auto", "auto.lua")
92
+ reg = registry.TaskRegistry(task_path)
93
+
94
+ if args.task_command == "list":
95
+ definitions = reg.read()
96
+ for task_id, definition in definitions.items():
97
+ print(f"{task_id}\t{definition['requestId']}\t{definition['revision']}"
98
+ f"\t{definition['sourceBytes']}B")
99
+ return 0
100
+
101
+ if args.task_command == "remove":
102
+ if not args.id:
103
+ raise CliError("task remove requires --id")
104
+ removed = reg.remove(args.id, expect_revision=args.expect_revision)
105
+ print(f"removed {args.id}" if removed else f"{args.id} not present")
106
+ return 0
107
+
108
+ if not args.id:
109
+ raise CliError("task upsert requires --id")
110
+ if not args.source_file:
111
+ raise CliError("task upsert requires --source-file")
112
+ try:
113
+ with open(args.source_file, "rb") as handle:
114
+ raw = handle.read()
115
+ except FileNotFoundError:
116
+ raise CliError(f"source file not found: {args.source_file}")
117
+ except OSError as error:
118
+ raise CliError(f"could not read source file: {error}")
119
+ try:
120
+ # The generated Lua shell stays ASCII; the writer escapes non-ASCII
121
+ # source bytes as \ddd, so the source itself only has to be UTF-8.
122
+ source = raw.decode("utf-8")
123
+ except UnicodeDecodeError as error:
124
+ raise CliError(f"source file is not valid UTF-8: {error}") from error
125
+
126
+ request_id = args.request_id or new_request_id()
127
+ definition = reg.upsert(
128
+ args.id,
129
+ request_id=request_id,
130
+ revision=args.revision or new_request_id(),
131
+ source=source,
132
+ created_at=args.created_at or int(time.time()),
133
+ expires_at=args.expires_at or 0,
134
+ expected_interface=args.expected_interface,
135
+ output_limit=args.output_limit,
136
+ expect_revision=args.expect_revision,
137
+ )
138
+ print(json.dumps({
139
+ "taskId": definition["taskId"],
140
+ "requestId": definition["requestId"],
141
+ "revision": definition["revision"],
142
+ "sourceBytes": definition["sourceBytes"],
143
+ "fileHash": definition["fileHash"],
144
+ }, sort_keys=True))
145
+ return 0
146
+
147
+
148
+ # --- profile ------------------------------------------------------------------
149
+
150
+ def load_profile(session: session_mod.Session, name: str) -> dict:
151
+ profile = session.load_json("profiles.json").get(name)
152
+ if not profile:
153
+ raise CliError(f"profile {name!r} is not configured; use 'profile set' first")
154
+ return profile
155
+
156
+
157
+ def save_profile(session: session_mod.Session, name: str, profile: dict) -> None:
158
+ profiles = session.load_json("profiles.json")
159
+ profiles[name] = profile
160
+ session.save_json("profiles.json", profiles)
161
+
162
+
163
+ def cmd_profile(args) -> int:
164
+ session = session_mod.Session(data_dir=args.data_dir,
165
+ installation=args.installation)
166
+ if args.profile_command == "show":
167
+ print(json.dumps(load_profile(session, args.name), sort_keys=True, indent=2))
168
+ return 0
169
+ for flag in ("client", "wow_root", "addon_dir"):
170
+ if not getattr(args, flag):
171
+ raise CliError(f"profile set requires --{flag.replace('_', '-')}")
172
+ if not os.path.isdir(args.addon_dir):
173
+ raise CliError(f"addon directory not found: {args.addon_dir}")
174
+ if not os.path.isdir(args.wow_root):
175
+ raise CliError(f"WoW root directory not found: {args.wow_root}")
176
+ profile = {
177
+ "client": args.client,
178
+ "clientFolder": CLIENT_FOLDERS[args.client],
179
+ "wow_root": os.path.abspath(args.wow_root),
180
+ "addon_dir": os.path.abspath(args.addon_dir),
181
+ "sv_path": os.path.abspath(args.sv_path) if args.sv_path else None,
182
+ }
183
+ save_profile(session, args.name, profile)
184
+ session.log_event("profile_set", name=args.name, client=args.client)
185
+ print(f"profile {args.name} saved")
186
+ return 0
187
+
188
+
189
+ # --- saved variables ----------------------------------------------------------
190
+
191
+ def resolve_client_root(profile: dict) -> str:
192
+ """Resolve the client folder (`_retail_`, ...) under the configured WoW root.
193
+
194
+ A profile may point either at the WoW root that contains ``_retail_`` or at
195
+ the client folder itself; the account tree decides which one is right.
196
+ """
197
+
198
+ root = os.path.abspath(profile.get("wow_root") or "")
199
+ folder = profile.get("clientFolder") or CLIENT_FOLDERS.get(profile.get("client"))
200
+ candidates = []
201
+ if folder:
202
+ candidates.append(os.path.join(root, folder))
203
+ candidates.append(root)
204
+ for candidate in candidates:
205
+ if os.path.isdir(os.path.join(candidate, "WTF", "Account")):
206
+ return candidate
207
+ raise CliError(
208
+ f"account root not found for client {profile.get('client')!r}; checked "
209
+ + ", ".join(candidates))
210
+
211
+
212
+ def retry_read(loader, *, attempts: int, delay: float, on_retry=None,
213
+ sleep=time.sleep):
214
+ """Bounded retry for a torn, replaced or temporarily unreadable SV file.
215
+
216
+ Returns ``(value, error, attempts_used)``. The loader is called at most
217
+ ``attempts`` times; when every attempt fails the last error is returned.
218
+ """
219
+
220
+ last_error: Exception | None = None
221
+ used = 0
222
+ for attempt in range(1, max(1, attempts) + 1):
223
+ used = attempt
224
+ try:
225
+ return loader(), None, used
226
+ except (SavedVariablesError, UnicodeDecodeError, OSError, ValueError) as error:
227
+ last_error = error
228
+ if on_retry is not None:
229
+ on_retry(attempt, error)
230
+ if attempt < max(1, attempts):
231
+ sleep(delay)
232
+ return None, last_error, used
233
+
234
+
235
+ def _load_ticket(sv_path: str, args) -> tuple[dict, str, dict]:
236
+ database = svlib.load_database(sv_path)
237
+ record = svlib.get_record(database, args.ticket)
238
+ failures = svlib.verify_evidence(
239
+ record,
240
+ ticket=args.ticket,
241
+ created_at=args.created_at,
242
+ task_id=args.task,
243
+ execution_id=args.request_id,
244
+ revision=args.revision,
245
+ )
246
+ if failures:
247
+ raise SavedVariablesError("; ".join(failures))
248
+ content = record["payload"]["content"]
249
+ report = svlib.parse_inner_report(
250
+ content,
251
+ task_id=args.task,
252
+ execution_id=args.request_id,
253
+ revision=args.revision,
254
+ request_type=getattr(args, "request_type", None),
255
+ metadata=record.get("metadata"),
256
+ )
257
+ return record, content, report
258
+
259
+
260
+ def cmd_sv(args) -> int:
261
+ session = session_mod.Session(data_dir=args.data_dir,
262
+ installation=args.installation)
263
+
264
+ if args.sv_command == "find":
265
+ if not args.profile:
266
+ raise CliError("sv find requires --profile")
267
+ profile = load_profile(session, args.profile)
268
+ account_root = os.path.join(resolve_client_root(profile), "WTF", "Account")
269
+ found = []
270
+ for entry in sorted(os.listdir(account_root)):
271
+ candidate = os.path.join(account_root, entry, "SavedVariables",
272
+ "Lychee Dev.lua")
273
+ if entry != "SavedVariables" and os.path.isfile(candidate):
274
+ found.append(candidate)
275
+ for candidate in found:
276
+ print(candidate)
277
+ if not found:
278
+ print(f"no account-level 'Lychee Dev.lua' found under {account_root}",
279
+ file=sys.stderr)
280
+ return EXIT_USAGE
281
+ return 0
282
+
283
+ if not args.ticket:
284
+ raise CliError("sv read requires --ticket")
285
+ sv_path = args.sv
286
+ if not sv_path and args.profile:
287
+ sv_path = (load_profile(session, args.profile) or {}).get("sv_path")
288
+ if not sv_path:
289
+ raise CliError("saved variables file not found; bind it via "
290
+ "'profile set --sv-path'")
291
+ if os.path.basename(sv_path) != "Lychee Dev.lua" or sv_path.endswith(".bak"):
292
+ raise CliError("refusing to read anything but the live 'Lychee Dev.lua' file")
293
+ if not os.path.isfile(sv_path):
294
+ raise CliError(f"saved variables file not found: {sv_path}")
295
+
296
+ session.log_event("sv_read_started", ticket=args.ticket, path=sv_path)
297
+ before = session.file_snapshot(sv_path)
298
+ attempts = max(1, int(args.retries) + 1)
299
+ result, error, used = retry_read(
300
+ lambda: _load_ticket(sv_path, args),
301
+ attempts=attempts,
302
+ delay=args.retry_delay,
303
+ on_retry=lambda attempt, failure: session.log_event(
304
+ "sv_read_retry", ticket=args.ticket, attempt=attempt,
305
+ reason=str(failure)),
306
+ )
307
+ if result is None:
308
+ session.log_event("sv_read_failed", ticket=args.ticket, reason=str(error))
309
+ print(f"saved variables read failed after {used} attempt(s): {error}",
310
+ file=sys.stderr)
311
+ return EXIT_SV_READ
312
+ record, content, report = result
313
+ after = session.file_snapshot(sv_path)
314
+
315
+ content_bytes = content.encode("utf-8")
316
+ sha256 = hashlib.sha256(content_bytes).hexdigest()
317
+ paths = {
318
+ "evidence": session.save_artifact(
319
+ args.ticket, "evidence.json",
320
+ json.dumps(record, ensure_ascii=False, indent=2, sort_keys=True)),
321
+ "report": session.save_artifact(
322
+ args.ticket, "report.json",
323
+ json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True)),
324
+ "content": session.save_artifact(args.ticket, "content.json", content),
325
+ }
326
+ session.log_event(
327
+ "received",
328
+ ticket=args.ticket,
329
+ requestId=args.request_id,
330
+ taskId=args.task,
331
+ revision=args.revision,
332
+ status=report.get("status"),
333
+ complete=report.get("complete"),
334
+ byteCount=len(content_bytes),
335
+ sha256=sha256,
336
+ attempts=used,
337
+ fileChanged=(before != after),
338
+ artifacts=paths,
339
+ )
340
+ print(json.dumps({
341
+ "ticket": args.ticket,
342
+ "status": report.get("status"),
343
+ "complete": report.get("complete"),
344
+ "byteCount": len(content_bytes),
345
+ "sha256": sha256,
346
+ "attempts": used,
347
+ "artifacts": paths,
348
+ }, sort_keys=True, indent=2))
349
+ return 0
350
+
351
+
352
+ # --- window input and capture --------------------------------------------------
353
+
354
+ def _window_module():
355
+ try:
356
+ from automation import windows
357
+ return windows
358
+ except Exception as error: # pragma: no cover - non-Windows hosts
359
+ raise CliError(f"window control requires Windows: {error}")
360
+
361
+
362
+ def _deliver(session: session_mod.Session, windows, args, text: str) -> None:
363
+ """Log the intent, then send exactly one command (design section 6.2)."""
364
+
365
+ mode = getattr(args, "mode", "foreground")
366
+ session.log_event("command_sent", hwnd=args.hwnd, text=text, mode=mode)
367
+ try:
368
+ windows.send_command(args.hwnd, text, pid=getattr(args, "pid", None),
369
+ exe_path=getattr(args, "exe_path", None),
370
+ mode=mode)
371
+ except (windows.WindowIdentityError, windows.InputError) as error:
372
+ session.log_event("command_failed", hwnd=args.hwnd, text=text,
373
+ mode=mode, reason=str(error))
374
+ raise CliError(f"command delivery failed: {error}", code=EXIT_INPUT)
375
+
376
+
377
+ def cmd_send(args) -> int:
378
+ """Deliver one command through the host log and the reload dedup."""
379
+
380
+ windows = _window_module()
381
+ session = session_mod.Session(data_dir=args.data_dir,
382
+ installation=args.installation)
383
+ if args.text == "/reload" and args.request_id and args.ticket:
384
+ if not session.mark_reload_requested(args.request_id, args.ticket):
385
+ raise CliError(
386
+ f"reload for {args.ticket} was already requested; check the saved "
387
+ "variables file before repeating it")
388
+ _deliver(session, windows, args, args.text)
389
+ print("sent")
390
+ return 0
391
+
392
+
393
+ def ack_command(ticket: str, outcome: str) -> str:
394
+ """Build the in-game command that reports a ticket's read outcome.
395
+
396
+ The plugin cannot see whether the host read a result, so the host says so
397
+ through the same chat-command channel it already uses for run/bug.
398
+ """
399
+
400
+ if outcome not in ("received", "failed"):
401
+ raise CliError("ack status must be 'received' or 'failed'")
402
+ return f"/dev auto ack {ticket} {outcome}"
403
+
404
+
405
+ def cmd_ack(args) -> int:
406
+ """Tell the running game that a ticket was read (or failed to be read)."""
407
+
408
+ windows = _window_module()
409
+ session = session_mod.Session(data_dir=args.data_dir,
410
+ installation=args.installation)
411
+ text = ack_command(args.ticket, args.status)
412
+ _deliver(session, windows, args, text)
413
+ session.log_event("ticket_ack_sent", ticket=args.ticket, status=args.status)
414
+ print(f"ack sent: {args.ticket} {args.status}")
415
+ return 0
416
+
417
+
418
+ def validate_notice(json_text: str) -> dict:
419
+ if not isinstance(json_text, str) or not json_text:
420
+ raise SavedVariablesError("notice payload is empty")
421
+ if len(json_text.encode("utf-8")) > NOTICE_MAX_BYTES:
422
+ raise SavedVariablesError("notice payload exceeds 512 bytes")
423
+ try:
424
+ notice = json.loads(json_text)
425
+ except ValueError as error:
426
+ raise SavedVariablesError(f"notice is not valid JSON: {error}") from error
427
+ if not isinstance(notice, dict) or notice.get("v") != 1:
428
+ raise SavedVariablesError("unsupported notice protocol version")
429
+ limits = {"ticket": 64, "task": 64, "run": 128}
430
+ for key, limit in limits.items():
431
+ value = notice.get(key)
432
+ if not isinstance(value, str) or not value:
433
+ raise SavedVariablesError(f"notice field {key} is missing")
434
+ if len(value) > limit:
435
+ raise SavedVariablesError(f"notice field {key} exceeds {limit} chars")
436
+ if not svlib.TICKET_PATTERN.match(notice["ticket"]):
437
+ raise SavedVariablesError("notice ticket has an invalid format")
438
+ if not registry.TASK_ID_PATTERN.match(notice["task"]):
439
+ raise SavedVariablesError("notice task id has an invalid format")
440
+ if not registry.REQUEST_ID_PATTERN.match(notice["run"]):
441
+ raise SavedVariablesError("notice run id has an invalid format")
442
+ if not isinstance(notice.get("ts"), int) or isinstance(notice["ts"], bool) \
443
+ or notice["ts"] <= 0:
444
+ raise SavedVariablesError("notice ts is missing or invalid")
445
+ return notice
446
+
447
+
448
+ def notice_identity_problems(notice: dict, *, expected_task: str | None,
449
+ expected_run: str | None) -> list[str]:
450
+ """Compare a decoded notice against the request this run actually delivered.
451
+
452
+ A static QR left on screen from an older run must never be accepted, so the
453
+ task and request identity are cross-checked before any reload (design
454
+ section 6.2).
455
+ """
456
+
457
+ problems = []
458
+ if expected_task is not None and notice["task"] != expected_task:
459
+ problems.append(f"notice task {notice['task']!r} != expected {expected_task!r}")
460
+ if expected_run is not None and notice["run"] != expected_run:
461
+ problems.append(f"notice run {notice['run']!r} != expected {expected_run!r}")
462
+ return problems
463
+
464
+
465
+ def poll_notice(windows, session: session_mod.Session, args, *,
466
+ expected_task: str | None = None,
467
+ expected_run: str | None = None) -> dict | None:
468
+ """Keep one WGC session open and poll until a matching notice or the deadline.
469
+
470
+ The session outlives a single frame because a task can run far longer than
471
+ one capture interval. Stale notices (older task or request identity) are
472
+ logged and ignored; only the exact expected notice is returned.
473
+ """
474
+
475
+ interval = getattr(args, "interval", None) or DEFAULT_INTERVAL
476
+ deadline = time.monotonic() + args.timeout
477
+ with windows.open_notice_capture(args.hwnd, pid=getattr(args, "pid", None),
478
+ exe_path=getattr(args, "exe_path", None),
479
+ interval=interval) as capture:
480
+ while time.monotonic() < deadline:
481
+ if capture.window_closed:
482
+ session.log_event("notice_capture_closed", hwnd=args.hwnd)
483
+ return None
484
+ roi = capture.latest_roi()
485
+ if roi is not None:
486
+ for payload in windows.decode_qr(roi):
487
+ try:
488
+ notice = validate_notice(payload)
489
+ except (SavedVariablesError, ValueError) as error:
490
+ session.log_event("notice_rejected", reason=str(error))
491
+ continue
492
+ problems = notice_identity_problems(
493
+ notice, expected_task=expected_task,
494
+ expected_run=expected_run)
495
+ if problems:
496
+ session.log_event("notice_identity_mismatch",
497
+ ticket=notice["ticket"],
498
+ task=notice["task"],
499
+ requestId=notice["run"],
500
+ reason="; ".join(problems))
501
+ continue
502
+ session.log_event(
503
+ "notice_seen", ticket=notice["ticket"], task=notice["task"],
504
+ requestId=notice["run"], ts=notice["ts"])
505
+ return notice
506
+ time.sleep(interval)
507
+ return None
508
+
509
+
510
+ def cmd_capture(args) -> int:
511
+ windows = _window_module()
512
+ session = session_mod.Session(data_dir=args.data_dir,
513
+ installation=args.installation)
514
+ notice = poll_notice(windows, session, args)
515
+ if notice is None:
516
+ print("no completion notice decoded before the timeout (or the capture "
517
+ "session closed)", file=sys.stderr)
518
+ return EXIT_NOTICE_TIMEOUT
519
+ print(json.dumps(notice, sort_keys=True))
520
+ return 0
521
+
522
+
523
+ # --- orchestrated flows ---------------------------------------------------------
524
+
525
+ def _notice_to_sv(session: session_mod.Session, windows, notice: dict, args,
526
+ *, revision: str | None, request_type: str) -> int:
527
+ """Validate a notice, request one reload, wait, then read the ticket."""
528
+
529
+ task = notice["task"]
530
+ request_id = notice["run"]
531
+ ticket = notice["ticket"]
532
+ if not session.mark_reload_requested(request_id, ticket, task=task):
533
+ raise CliError(
534
+ f"reload for {ticket} was already requested; check the saved "
535
+ "variables file before repeating the reload")
536
+ baseline = session.file_snapshot(args.sv)
537
+ _deliver(session, windows, args, "/reload")
538
+ if not session.wait_for_saved_variables(args.sv, timeout=args.timeout,
539
+ baseline=baseline):
540
+ session.log_event("sv_write_timeout", ticket=ticket)
541
+ raise CliError("the game did not rewrite its saved variables in time",
542
+ code=EXIT_NOTICE_TIMEOUT)
543
+ read_args = argparse.Namespace(
544
+ sv_command="read", data_dir=args.data_dir, installation=args.installation,
545
+ profile=None, sv=args.sv, ticket=ticket, task=task, request_id=request_id,
546
+ revision=revision, created_at=notice["ts"], request_type=request_type,
547
+ retries=SV_READ_RETRIES, retry_delay=SV_READ_RETRY_DELAY,
548
+ all_installations=False,
549
+ )
550
+ code = cmd_sv(read_args)
551
+ if code != 0:
552
+ raise CliError(f"saved variables read failed for {ticket}", code=code)
553
+ return 0
554
+
555
+
556
+ def _installed_definition(install_dir: str, task_id: str) -> dict:
557
+ task_path = os.path.join(install_dir, "Modules", "Automation", "auto", "auto.lua")
558
+ definition = registry.TaskRegistry(task_path).read().get(task_id)
559
+ if definition is None:
560
+ raise CliError(f"task {task_id!r} is not present in {task_path}")
561
+ return definition
562
+
563
+
564
+ def cmd_run(args) -> int:
565
+ windows = _window_module()
566
+ session = session_mod.Session(data_dir=args.data_dir,
567
+ installation=args.installation)
568
+ install_dir = resolve_install_dir(args, required=False)
569
+ expected_request_id = args.request_id
570
+ revision = args.revision
571
+ if install_dir:
572
+ definition = _installed_definition(install_dir, args.task)
573
+ if args.request_id is not None and args.request_id != definition["requestId"]:
574
+ raise CliError(
575
+ f"--request-id {args.request_id!r} does not match the loaded block "
576
+ f"requestId {definition['requestId']!r}")
577
+ expected_request_id = args.request_id or definition["requestId"]
578
+ revision = args.revision or definition["revision"]
579
+
580
+ session.log_event("run_started", task=args.task,
581
+ requestId=expected_request_id, revision=revision)
582
+ _deliver(session, windows, args, f"/dev auto run {args.task}")
583
+ notice = poll_notice(windows, session, args, expected_task=args.task,
584
+ expected_run=expected_request_id)
585
+ if notice is None:
586
+ session.log_event("run_unresolved", task=args.task,
587
+ requestId=expected_request_id)
588
+ raise CliError("no completion notice decoded before the timeout (or the "
589
+ "capture session closed); the run stays unresolved in the "
590
+ "host log", code=EXIT_NOTICE_TIMEOUT)
591
+ return _notice_to_sv(session, windows, notice, args, revision=revision,
592
+ request_type="task")
593
+
594
+
595
+ def cmd_bugs(args) -> int:
596
+ windows = _window_module()
597
+ if not 1 <= args.count <= 100:
598
+ raise CliError("--count must be an integer between 1 and 100")
599
+ session = session_mod.Session(data_dir=args.data_dir,
600
+ installation=args.installation)
601
+ session.log_event("bugs_started", count=args.count)
602
+ _deliver(session, windows, args, f"/dev auto bug {args.count}")
603
+ notice = poll_notice(windows, session, args, expected_task=BUG_TASK_ID,
604
+ expected_run=args.request_id)
605
+ if notice is None:
606
+ session.log_event("bugs_unresolved", count=args.count)
607
+ raise CliError("no completion notice decoded before the timeout (or the "
608
+ "capture session closed); the run stays unresolved in the "
609
+ "host log", code=EXIT_NOTICE_TIMEOUT)
610
+ return _notice_to_sv(session, windows, notice, args, revision=args.revision,
611
+ request_type="bug")
612
+
613
+
614
+ # --- session --------------------------------------------------------------------
615
+
616
+ def _tail(records: list[dict], limit: int) -> list[dict]:
617
+ if limit <= 0:
618
+ return records
619
+ return records[-limit:]
620
+
621
+
622
+ def _log_scope(args) -> str | None:
623
+ if getattr(args, "all_installations", False):
624
+ return session_mod.ALL_INSTALLATIONS
625
+ return None
626
+
627
+
628
+ def cmd_status(args) -> int:
629
+ session = session_mod.Session(data_dir=args.data_dir,
630
+ installation=args.installation)
631
+ events = _tail(session.read_events(args.event, installation=_log_scope(args)),
632
+ args.limit)
633
+ for record in events:
634
+ print(json.dumps(record, ensure_ascii=False, sort_keys=True))
635
+ if not events:
636
+ print(f"no matching host log events in installation "
637
+ f"{session.installation!r}")
638
+ return 0
639
+
640
+
641
+ def cmd_recover(args) -> int:
642
+ session = session_mod.Session(data_dir=args.data_dir,
643
+ installation=args.installation)
644
+ scope = _log_scope(args)
645
+ events = _tail(session.read_events(installation=scope), args.limit)
646
+ for record in events:
647
+ print(json.dumps(record, ensure_ascii=False, sort_keys=True))
648
+ reloads = {r.get("ticket") for r in
649
+ session.read_events("reload_requested", installation=scope)}
650
+ received = {r.get("ticket") for r in
651
+ session.read_events("received", installation=scope)}
652
+ pending = sorted(t for t in reloads if t not in received)
653
+ for ticket in pending:
654
+ print(f"UNRESOLVED: reload requested for {ticket} but not received yet; "
655
+ "inspect the saved variables file manually before any retry")
656
+ if not pending:
657
+ print(f"no unresolved reload requests in installation "
658
+ f"{session.installation!r}")
659
+ return 0
660
+
661
+
662
+ # --- parser ----------------------------------------------------------------------
663
+
664
+ def build_parser() -> argparse.ArgumentParser:
665
+ parser = argparse.ArgumentParser(prog="automation.py",
666
+ description=__doc__)
667
+ parser.add_argument("--data-dir", default=session_mod.default_data_dir(),
668
+ help="host data directory (log, artifacts, profiles)")
669
+ parser.add_argument("--installation", default="default",
670
+ help="installation name used as the dedup/log scope "
671
+ "(default: default)")
672
+ sub = parser.add_subparsers(dest="command", required=True)
673
+
674
+ task = sub.add_parser("task", help="update the installed auto.lua registry")
675
+ task.add_argument("task_command", choices=["upsert", "remove", "list"])
676
+ task.add_argument("--install-dir", help="installed addon directory (contains "
677
+ "Modules/Automation/auto/auto.lua)")
678
+ task.add_argument("--profile", help="profile name to take --install-dir from")
679
+ task.add_argument("--id", help="task id ([A-Za-z0-9_-]{1,64})")
680
+ task.add_argument("--source-file", help="UTF-8 Lua source file for the task")
681
+ task.add_argument("--request-id", help="request id for this execution "
682
+ "(default: generated)")
683
+ task.add_argument("--revision", help="source revision (default: generated)")
684
+ task.add_argument("--expect-revision",
685
+ help="replace only when the stored revision matches")
686
+ task.add_argument("--created-at", type=int, help="creation timestamp (epoch)")
687
+ task.add_argument("--expires-at", type=int, default=0,
688
+ help="expiry timestamp (epoch, 0 = never)")
689
+ task.add_argument("--expected-interface", type=int,
690
+ help="expected client Interface version")
691
+ task.add_argument("--output-limit", type=int,
692
+ help="captured stdout limit in bytes")
693
+ task.set_defaults(func=cmd_task)
694
+
695
+ profile = sub.add_parser("profile", help="bind one client installation")
696
+ profile.add_argument("profile_command", choices=["set", "show"])
697
+ profile.add_argument("--name", required=True, help="profile name")
698
+ profile.add_argument("--client", choices=sorted(CLIENT_FOLDERS),
699
+ help="client type: retail, classic or titan")
700
+ profile.add_argument("--wow-root", help="WoW root that contains the client folder")
701
+ profile.add_argument("--addon-dir", help="installed addon directory")
702
+ profile.add_argument("--sv-path", help="exact 'Lychee Dev.lua' path to read")
703
+ profile.set_defaults(func=cmd_profile)
704
+
705
+ sv = sub.add_parser("sv", help="find or read SavedVariables")
706
+ sv.add_argument("sv_command", choices=["find", "read"])
707
+ sv.add_argument("--profile", help="profile name (install dir and SV path)")
708
+ sv.add_argument("--sv", help="exact 'Lychee Dev.lua' path")
709
+ sv.add_argument("--ticket", help="exact Ticket to read (required for read)")
710
+ sv.add_argument("--task", help="expected task id")
711
+ sv.add_argument("--request-id", help="expected execution/request id")
712
+ sv.add_argument("--revision", help="expected source revision")
713
+ sv.add_argument("--created-at", type=int, help="expected record createdAt")
714
+ sv.add_argument("--request-type", choices=["task", "bug"],
715
+ help="expected inner report request type")
716
+ sv.add_argument("--retries", type=int, default=SV_READ_RETRIES,
717
+ help="additional read attempts for a torn or replaced file "
718
+ f"(default: {SV_READ_RETRIES})")
719
+ sv.add_argument("--retry-delay", type=float, default=SV_READ_RETRY_DELAY,
720
+ help="seconds between read attempts "
721
+ f"(default: {SV_READ_RETRY_DELAY})")
722
+ sv.set_defaults(func=cmd_sv)
723
+
724
+ window = argparse.ArgumentParser(add_help=False)
725
+ window.add_argument("--hwnd", type=lambda value: int(value, 0), required=True,
726
+ help="target window handle (decimal or 0x...)")
727
+ window.add_argument("--pid", type=int, help="expected process id")
728
+ window.add_argument("--exe-path", help="expected executable path")
729
+ window.add_argument(
730
+ "--mode", choices=("foreground", "messages"), default="foreground",
731
+ help="input strategy: 'foreground' focuses the window and uses "
732
+ "SendInput; 'messages' posts keys straight to the window and needs "
733
+ "no foreground but requires the chat box to be open already "
734
+ "(default: foreground)")
735
+
736
+ polling = argparse.ArgumentParser(add_help=False)
737
+ polling.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT,
738
+ help="seconds to keep polling for the notice "
739
+ f"(default: {DEFAULT_TIMEOUT})")
740
+ polling.add_argument("--interval", type=float, default=DEFAULT_INTERVAL,
741
+ help="seconds between notice polls "
742
+ f"(default: {DEFAULT_INTERVAL})")
743
+
744
+ send = sub.add_parser("send", parents=[window],
745
+ help="deliver one slash command")
746
+ send.add_argument("--text", required=True, help="exact slash command to send")
747
+ send.add_argument("--request-id",
748
+ help="request id used to dedup a '/reload' command")
749
+ send.add_argument("--ticket", help="ticket used to dedup a '/reload' command")
750
+ send.set_defaults(func=cmd_send)
751
+
752
+ ack = sub.add_parser("ack", parents=[window],
753
+ help="report a ticket's read outcome to the running game")
754
+ ack.add_argument("--ticket", required=True, help="exact ticket that was read")
755
+ ack.add_argument("--status", required=True, choices=("received", "failed"),
756
+ help="'received' when the report was read, 'failed' otherwise")
757
+ ack.set_defaults(func=cmd_ack)
758
+
759
+ capture = sub.add_parser("capture", parents=[window, polling],
760
+ help="poll the window and decode the notice QR")
761
+ capture.set_defaults(func=cmd_capture)
762
+
763
+ run = sub.add_parser("run", parents=[window, polling],
764
+ help="deliver and resolve one task run")
765
+ run.add_argument("--task", required=True, help="task id to run")
766
+ run.add_argument("--sv", required=True, help="'Lychee Dev.lua' path to read")
767
+ run.add_argument("--install-dir",
768
+ help="installed addon directory used to resolve the expected "
769
+ "request id and revision")
770
+ run.add_argument("--profile", help="profile name for --install-dir")
771
+ run.add_argument("--request-id", help="expected request id (default: the "
772
+ "loaded block's requestId)")
773
+ run.add_argument("--revision", help="expected source revision (default: the "
774
+ "loaded block's revision)")
775
+ run.set_defaults(func=cmd_run)
776
+
777
+ bugs = sub.add_parser("bugs", parents=[window, polling],
778
+ help="snapshot recent errors and resolve the run")
779
+ bugs.add_argument("--count", type=int, required=True,
780
+ help="error records to snapshot (1-100)")
781
+ bugs.add_argument("--sv", required=True, help="'Lychee Dev.lua' path to read")
782
+ bugs.add_argument("--request-id", help="expected request id, when known")
783
+ bugs.add_argument("--revision", help="expected source revision, when known")
784
+ bugs.set_defaults(func=cmd_bugs)
785
+
786
+ status = sub.add_parser("status", help="print host log events")
787
+ status.add_argument("--event", help="only this event name")
788
+ status.add_argument("--limit", type=int, default=20,
789
+ help="most recent records to print (0 = all, default: 20)")
790
+ status.add_argument("--all-installations", action="store_true",
791
+ help="include every installation scope, not just this one")
792
+ status.set_defaults(func=cmd_status)
793
+
794
+ recover = sub.add_parser("recover", help="show unresolved reload intents")
795
+ recover.add_argument("--limit", type=int, default=50,
796
+ help="most recent records to print (0 = all, default: 50)")
797
+ recover.add_argument("--all-installations", action="store_true",
798
+ help="include every installation scope, not just this one")
799
+ recover.set_defaults(func=cmd_recover)
800
+
801
+ return parser
802
+
803
+
804
+ def _expected_error_types() -> tuple:
805
+ errors = [RegistryError, SavedVariablesError, UnicodeDecodeError,
806
+ json.JSONDecodeError, OSError]
807
+ try:
808
+ from automation import windows
809
+ except Exception: # pragma: no cover - non-Windows hosts
810
+ return tuple(errors)
811
+ errors.extend([windows.WindowIdentityError, windows.InputError,
812
+ windows.CaptureDependencyError])
813
+ return tuple(errors)
814
+
815
+
816
+ def _window_error_types() -> tuple:
817
+ """Errors that mean the game window, its identity, or the capture
818
+ dependency failed. They map to the documented window/input exit code.
819
+
820
+ The result must never be an empty tuple: ``except`` with no exception
821
+ types falls back to catching BaseException, and an exception group is
822
+ rejected outright by ``except``. Non-Windows hosts return a harmless
823
+ unused placeholder so the handler simply never fires.
824
+ """
825
+
826
+ try:
827
+ from automation import windows
828
+ except Exception: # pragma: no cover - non-Windows hosts
829
+ return (RuntimeError,)
830
+ return (windows.WindowIdentityError, windows.InputError,
831
+ windows.CaptureDependencyError)
832
+
833
+
834
+ def main(argv=None) -> int:
835
+ parser = build_parser()
836
+ args = parser.parse_args(argv)
837
+ try:
838
+ return args.func(args)
839
+ except CliError as error:
840
+ print(f"error: {error}", file=sys.stderr)
841
+ return error.code
842
+ except RegistryError as error:
843
+ print(f"error: task registry failed: {error}", file=sys.stderr)
844
+ return EXIT_REGISTRY
845
+ except SavedVariablesError as error:
846
+ print(f"error: saved variables failed: {error}", file=sys.stderr)
847
+ return EXIT_SV_READ
848
+ except _window_error_types() as error:
849
+ print(f"error: {error}", file=sys.stderr)
850
+ return EXIT_INPUT
851
+ except _expected_error_types() as error:
852
+ print(f"error: {error}", file=sys.stderr)
853
+ return EXIT_USAGE
854
+ except KeyboardInterrupt:
855
+ print("error: interrupted", file=sys.stderr)
856
+ return EXIT_USAGE
857
+ except Exception as error: # unexpected: keep the traceback, stay non-zero
858
+ print(f"unexpected failure: {type(error).__name__}: {error}",
859
+ file=sys.stderr)
860
+ traceback.print_exc()
861
+ return EXIT_USAGE
862
+
863
+
864
+ if __name__ == "__main__":
865
+ sys.exit(main())