lycheedev 1.1.1 → 2.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 (115) 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 +129 -94
  26. package/{vendor → payload}/addon/Core/Locale_enUS.lua +129 -96
  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 -742
  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 -43
  85. package/vendor/addon/Lychee Dev_Mainline.toc +0 -43
  86. package/vendor/addon/Lychee Dev_Mists.toc +0 -43
  87. package/vendor/addon/Lychee Dev_Wrath.toc +0 -43
  88. package/vendor/addon/Modules/Automation/Controller.lua +0 -884
  89. package/vendor/addon/Modules/Automation/Report.lua +0 -409
  90. package/vendor/addon/Modules/Automation/auto/auto.lua +0 -12
  91. package/vendor/addon/Modules/FunctionTrace.lua +0 -85
  92. package/vendor/addon/UI/AutomationOverlay.lua +0 -253
  93. package/vendor/addon/UI/Pages/Automation.lua +0 -417
  94. package/vendor/addon/UI/Pages/Diagnostics.lua +0 -289
  95. package/vendor/addon/UI/Pages/Trace.lua +0 -165
  96. package/vendor/skill/SKILL.md +0 -42
  97. package/vendor/skill/agents/openai.yaml +0 -4
  98. package/vendor/skill/references/automation.md +0 -128
  99. package/vendor/skill/references/clients.md +0 -51
  100. package/vendor/skill/references/runtime-investigations.md +0 -104
  101. package/vendor/skill/scripts/automation/__init__.py +0 -1
  102. package/vendor/skill/scripts/automation/registry.py +0 -516
  103. package/vendor/skill/scripts/automation/saved_variables.py +0 -438
  104. package/vendor/skill/scripts/automation/session.py +0 -207
  105. package/vendor/skill/scripts/automation/windows.py +0 -792
  106. package/vendor/skill/scripts/automation.py +0 -1034
  107. package/vendor/skill/scripts/requirements.txt +0 -13
  108. package/vendor/skill/scripts/selftest_offline.py +0 -1061
  109. package/vendor/skill/scripts/test_input_safety.py +0 -132
  110. /package/{vendor → payload}/addon/Media/GitHub.png +0 -0
  111. /package/{vendor → payload}/addon/Media/Logo.png +0 -0
  112. /package/{vendor → payload}/addon/Modules/Events/CatalogData_Forever.lua +0 -0
  113. /package/{vendor → payload}/addon/Modules/Events/CatalogData_Mainline.lua +0 -0
  114. /package/{vendor → payload}/addon/Modules/Events/CatalogData_Mists.lua +0 -0
  115. /package/{vendor → payload}/addon/Modules/Events/CatalogData_Titan.lua +0 -0
@@ -1,1034 +0,0 @@
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 -> candidate install folders, in the order to try. A folder name is a
51
- # location rather than an identity: the launcher reuses a test folder for
52
- # whatever is on the test track, so WoW: Forever currently lives in
53
- # `_classic_beta_` while a dedicated `_forever_` folder is also accepted. The
54
- # right folder is decided by what exists under the WoW root, not by the name.
55
- CLIENT_FOLDERS = {
56
- "retail": ("_retail_",),
57
- "classic": ("_classic_",),
58
- "titan": ("_classic_titan_",),
59
- "forever": ("_classic_beta_", "_forever_"),
60
- }
61
- DEFAULT_TIMEOUT = 120.0
62
- DEFAULT_INTERVAL = 0.1
63
- SV_READ_RETRIES = 3
64
- SV_READ_RETRY_DELAY = 0.5
65
- EXIT_USAGE = 1
66
- EXIT_REGISTRY = 2
67
- EXIT_SV_READ = 3
68
- EXIT_INPUT = 4
69
- EXIT_NOTICE_TIMEOUT = 5
70
-
71
-
72
- class CliError(Exception):
73
- """An expected CLI failure: message on stderr, explicit non-zero exit."""
74
-
75
- def __init__(self, message: str, code: int = EXIT_USAGE):
76
- super().__init__(message)
77
- self.code = code
78
-
79
-
80
- def resolve_install_dir(args, *, required: bool = True) -> str | None:
81
- if getattr(args, "install_dir", None):
82
- return args.install_dir
83
- if getattr(args, "profile", None):
84
- session = session_mod.Session(data_dir=args.data_dir,
85
- installation=args.installation)
86
- return load_profile(session, args.profile)["addon_dir"]
87
- if required:
88
- raise CliError("either --install-dir or --profile is required")
89
- return None
90
-
91
-
92
- # --- task ---------------------------------------------------------------------
93
-
94
- def new_request_id() -> str:
95
- stamp = time.strftime("%Y%m%d-%H%M%S", time.gmtime())
96
- return f"req-{stamp}-{secrets.token_hex(3)}"
97
-
98
-
99
- def cmd_task(args) -> int:
100
- install_dir = resolve_install_dir(args)
101
- task_path = os.path.join(install_dir, "Modules", "Automation", "auto", "auto.lua")
102
- reg = registry.TaskRegistry(task_path)
103
-
104
- if args.task_command == "list":
105
- definitions = reg.read()
106
- for task_id, definition in definitions.items():
107
- print(f"{task_id}\t{definition['requestId']}\t{definition['revision']}"
108
- f"\t{definition['sourceBytes']}B")
109
- return 0
110
-
111
- if args.task_command == "remove":
112
- if not args.id:
113
- raise CliError("task remove requires --id")
114
- removed = reg.remove(args.id, expect_revision=args.expect_revision)
115
- print(f"removed {args.id}" if removed else f"{args.id} not present")
116
- return 0
117
-
118
- if not args.id:
119
- raise CliError("task upsert requires --id")
120
- if not args.source_file:
121
- raise CliError("task upsert requires --source-file")
122
- try:
123
- with open(args.source_file, "rb") as handle:
124
- raw = handle.read()
125
- except FileNotFoundError:
126
- raise CliError(f"source file not found: {args.source_file}")
127
- except OSError as error:
128
- raise CliError(f"could not read source file: {error}")
129
- try:
130
- # The generated Lua shell stays ASCII; the writer escapes non-ASCII
131
- # source bytes as \ddd, so the source itself only has to be UTF-8.
132
- source = raw.decode("utf-8")
133
- except UnicodeDecodeError as error:
134
- raise CliError(f"source file is not valid UTF-8: {error}") from error
135
-
136
- request_id = args.request_id or new_request_id()
137
- definition = reg.upsert(
138
- args.id,
139
- request_id=request_id,
140
- revision=args.revision or new_request_id(),
141
- source=source,
142
- created_at=args.created_at or int(time.time()),
143
- expires_at=args.expires_at or 0,
144
- expected_interface=args.expected_interface,
145
- output_limit=args.output_limit,
146
- expect_revision=args.expect_revision,
147
- )
148
- print(json.dumps({
149
- "taskId": definition["taskId"],
150
- "requestId": definition["requestId"],
151
- "revision": definition["revision"],
152
- "sourceBytes": definition["sourceBytes"],
153
- "fileHash": definition["fileHash"],
154
- }, sort_keys=True))
155
- return 0
156
-
157
-
158
- # --- profile ------------------------------------------------------------------
159
-
160
- def load_profile(session: session_mod.Session, name: str) -> dict:
161
- profile = session.load_json("profiles.json").get(name)
162
- if not profile:
163
- raise CliError(f"profile {name!r} is not configured; use 'profile set' first")
164
- return profile
165
-
166
-
167
- def save_profile(session: session_mod.Session, name: str, profile: dict) -> None:
168
- profiles = session.load_json("profiles.json")
169
- profiles[name] = profile
170
- session.save_json("profiles.json", profiles)
171
-
172
-
173
- def cmd_profile(args) -> int:
174
- session = session_mod.Session(data_dir=args.data_dir,
175
- installation=args.installation)
176
- if args.profile_command == "show":
177
- print(json.dumps(load_profile(session, args.name), sort_keys=True, indent=2))
178
- return 0
179
- for flag in ("client", "wow_root", "addon_dir"):
180
- if not getattr(args, flag):
181
- raise CliError(f"profile set requires --{flag.replace('_', '-')}")
182
- if not os.path.isdir(args.addon_dir):
183
- raise CliError(f"addon directory not found: {args.addon_dir}")
184
- if not os.path.isdir(args.wow_root):
185
- raise CliError(f"WoW root directory not found: {args.wow_root}")
186
- folders = CLIENT_FOLDERS[args.client]
187
- profile = {
188
- "client": args.client,
189
- # The first entry is the default; clientFolders keeps every accepted
190
- # location so a client that moved folders still resolves.
191
- "clientFolder": folders[0],
192
- "clientFolders": list(folders),
193
- "wow_root": os.path.abspath(args.wow_root),
194
- "addon_dir": os.path.abspath(args.addon_dir),
195
- "sv_path": os.path.abspath(args.sv_path) if args.sv_path else None,
196
- }
197
- save_profile(session, args.name, profile)
198
- session.log_event("profile_set", name=args.name, client=args.client)
199
- print(f"profile {args.name} saved")
200
- return 0
201
-
202
-
203
- # --- saved variables ----------------------------------------------------------
204
-
205
- def resolve_client_root(profile: dict) -> str:
206
- """Resolve the client folder (`_retail_`, ...) under the configured WoW root.
207
-
208
- A profile may point either at the WoW root that contains ``_retail_`` or at
209
- the client folder itself; the account tree decides which one is right. Every
210
- accepted folder for the client is tried, so a build that moved folders still
211
- resolves without rewriting the profile.
212
- """
213
-
214
- root = os.path.abspath(profile.get("wow_root") or "")
215
- recorded = profile.get("clientFolders")
216
- if not recorded:
217
- recorded = [profile.get("clientFolder")] if profile.get("clientFolder") else []
218
- folders = list(recorded) + list(CLIENT_FOLDERS.get(profile.get("client"), ()))
219
- candidates = []
220
- for folder in folders:
221
- if not folder:
222
- continue
223
- path = os.path.join(root, folder)
224
- if path not in candidates:
225
- candidates.append(path)
226
- if root not in candidates:
227
- candidates.append(root)
228
- for candidate in candidates:
229
- if os.path.isdir(os.path.join(candidate, "WTF", "Account")):
230
- return candidate
231
- raise CliError(
232
- f"account root not found for client {profile.get('client')!r}; checked "
233
- + ", ".join(candidates))
234
-
235
-
236
- def retry_read(loader, *, attempts: int, delay: float, on_retry=None,
237
- sleep=time.sleep):
238
- """Bounded retry for a torn, replaced or temporarily unreadable SV file.
239
-
240
- Returns ``(value, error, attempts_used)``. The loader is called at most
241
- ``attempts`` times; when every attempt fails the last error is returned.
242
- """
243
-
244
- last_error: Exception | None = None
245
- used = 0
246
- for attempt in range(1, max(1, attempts) + 1):
247
- used = attempt
248
- try:
249
- return loader(), None, used
250
- except (SavedVariablesError, UnicodeDecodeError, OSError, ValueError) as error:
251
- last_error = error
252
- if on_retry is not None:
253
- on_retry(attempt, error)
254
- if attempt < max(1, attempts):
255
- sleep(delay)
256
- return None, last_error, used
257
-
258
-
259
- def _load_ticket(sv_path: str, args) -> tuple[dict, str, dict]:
260
- database = svlib.load_database(sv_path)
261
- record = svlib.get_record(database, args.ticket)
262
- failures = svlib.verify_evidence(
263
- record,
264
- ticket=args.ticket,
265
- created_at=args.created_at,
266
- task_id=args.task,
267
- execution_id=args.request_id,
268
- revision=args.revision,
269
- )
270
- if failures:
271
- raise SavedVariablesError("; ".join(failures))
272
- content = record["payload"]["content"]
273
- report = svlib.parse_inner_report(
274
- content,
275
- task_id=args.task,
276
- execution_id=args.request_id,
277
- revision=args.revision,
278
- request_type=getattr(args, "request_type", None),
279
- metadata=record.get("metadata"),
280
- )
281
- return record, content, report
282
-
283
-
284
- def cmd_sv(args) -> int:
285
- session = session_mod.Session(data_dir=args.data_dir,
286
- installation=args.installation)
287
-
288
- if args.sv_command == "find":
289
- if not args.profile:
290
- raise CliError("sv find requires --profile")
291
- profile = load_profile(session, args.profile)
292
- account_root = os.path.join(resolve_client_root(profile), "WTF", "Account")
293
- found = []
294
- for entry in sorted(os.listdir(account_root)):
295
- candidate = os.path.join(account_root, entry, "SavedVariables",
296
- "Lychee Dev.lua")
297
- if entry != "SavedVariables" and os.path.isfile(candidate):
298
- found.append(candidate)
299
- for candidate in found:
300
- print(candidate)
301
- if not found:
302
- print(f"no account-level 'Lychee Dev.lua' found under {account_root}",
303
- file=sys.stderr)
304
- return EXIT_USAGE
305
- return 0
306
-
307
- if not args.ticket:
308
- raise CliError("sv read requires --ticket")
309
- sv_path = args.sv
310
- if not sv_path and args.profile:
311
- sv_path = (load_profile(session, args.profile) or {}).get("sv_path")
312
- if not sv_path:
313
- raise CliError("saved variables file not found; bind it via "
314
- "'profile set --sv-path'")
315
- if os.path.basename(sv_path) != "Lychee Dev.lua" or sv_path.endswith(".bak"):
316
- raise CliError("refusing to read anything but the live 'Lychee Dev.lua' file")
317
- if not os.path.isfile(sv_path):
318
- raise CliError(f"saved variables file not found: {sv_path}")
319
-
320
- session.log_event("sv_read_started", ticket=args.ticket, path=sv_path)
321
- before = session.file_snapshot(sv_path)
322
- attempts = max(1, int(args.retries) + 1)
323
- result, error, used = retry_read(
324
- lambda: _load_ticket(sv_path, args),
325
- attempts=attempts,
326
- delay=args.retry_delay,
327
- on_retry=lambda attempt, failure: session.log_event(
328
- "sv_read_retry", ticket=args.ticket, attempt=attempt,
329
- reason=str(failure)),
330
- )
331
- if result is None:
332
- session.log_event("sv_read_failed", ticket=args.ticket, reason=str(error))
333
- print(f"saved variables read failed after {used} attempt(s): {error}",
334
- file=sys.stderr)
335
- return EXIT_SV_READ
336
- record, content, report = result
337
- after = session.file_snapshot(sv_path)
338
-
339
- content_bytes = content.encode("utf-8")
340
- sha256 = hashlib.sha256(content_bytes).hexdigest()
341
- paths = {
342
- "evidence": session.save_artifact(
343
- args.ticket, "evidence.json",
344
- json.dumps(record, ensure_ascii=False, indent=2, sort_keys=True)),
345
- "report": session.save_artifact(
346
- args.ticket, "report.json",
347
- json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True)),
348
- "content": session.save_artifact(args.ticket, "content.json", content),
349
- }
350
- session.log_event(
351
- "received",
352
- ticket=args.ticket,
353
- requestId=args.request_id,
354
- taskId=args.task,
355
- revision=args.revision,
356
- status=report.get("status"),
357
- complete=report.get("complete"),
358
- byteCount=len(content_bytes),
359
- sha256=sha256,
360
- attempts=used,
361
- fileChanged=(before != after),
362
- artifacts=paths,
363
- )
364
- print(json.dumps({
365
- "ticket": args.ticket,
366
- "status": report.get("status"),
367
- "complete": report.get("complete"),
368
- "byteCount": len(content_bytes),
369
- "sha256": sha256,
370
- "attempts": used,
371
- "artifacts": paths,
372
- }, sort_keys=True, indent=2))
373
- return 0
374
-
375
-
376
- # --- window input and capture --------------------------------------------------
377
-
378
- def _window_module():
379
- try:
380
- from automation import windows
381
- return windows
382
- except Exception as error: # pragma: no cover - non-Windows hosts
383
- raise CliError(f"window control requires Windows: {error}")
384
-
385
-
386
- def _deliver(session: session_mod.Session, windows, args, text: str) -> None:
387
- """Log the intent, then send exactly one command (design section 6.2)."""
388
-
389
- mode = getattr(args, "mode", "messages")
390
- session.log_event("command_prepared", hwnd=args.hwnd, text=text, mode=mode)
391
- try:
392
- windows.send_command(args.hwnd, text, pid=getattr(args, "pid", None),
393
- exe_path=getattr(args, "exe_path", None),
394
- mode=mode)
395
- except (windows.WindowIdentityError, windows.InputError) as error:
396
- session.log_event("command_failed", hwnd=args.hwnd, text=text,
397
- mode=mode, reason=str(error))
398
- raise CliError(f"command delivery failed: {error}", code=EXIT_INPUT)
399
- session.log_event("command_submitted", hwnd=args.hwnd, text=text, mode=mode)
400
-
401
-
402
- def cmd_send(args) -> int:
403
- """Deliver one command through the host log and the reload dedup."""
404
-
405
- windows = _window_module()
406
- session = session_mod.Session(data_dir=args.data_dir,
407
- installation=args.installation)
408
- if args.text == "/reload" and args.request_id and args.ticket:
409
- if not session.mark_reload_requested(args.request_id, args.ticket):
410
- raise CliError(
411
- f"reload for {args.ticket} was already requested; check the saved "
412
- "variables file before repeating it")
413
- _deliver(session, windows, args, args.text)
414
- print("submitted; game execution is not yet confirmed")
415
- return 0
416
-
417
-
418
- def ack_command(ticket: str, outcome: str, nonce: str | None = None) -> str:
419
- """Build the in-game command that reports a ticket's read outcome.
420
-
421
- The plugin cannot see whether the host read a result, so the host says so
422
- through the same chat-command channel it already uses for run/bug.
423
- """
424
-
425
- if outcome not in ("received", "failed"):
426
- raise CliError("ack status must be 'received' or 'failed'")
427
- if not svlib.TICKET_PATTERN.fullmatch(ticket) or len(ticket) > 64:
428
- raise CliError("invalid acknowledgement ticket")
429
- if nonce is not None and not registry.REQUEST_ID_PATTERN.fullmatch(nonce):
430
- raise CliError("invalid acknowledgement nonce")
431
- return f"/dev auto ack {ticket} {outcome}" + (f" {nonce}" if nonce else "")
432
-
433
-
434
- def cmd_ack(args) -> int:
435
- """Tell the running game that a ticket was read (or failed to be read)."""
436
-
437
- windows = _window_module()
438
- session = session_mod.Session(data_dir=args.data_dir,
439
- installation=args.installation)
440
- nonce = new_request_id()
441
- text = ack_command(args.ticket, args.status, nonce)
442
- _deliver(session, windows, args, text)
443
- session.log_event("ticket_ack_submitted", ticket=args.ticket, status=args.status)
444
- notice = poll_notice(windows, session, args, expected_task="ack", expected_run=nonce,
445
- expected_ticket=args.ticket, expected_status=args.status)
446
- if notice is None:
447
- session.log_event("ticket_ack_unresolved", ticket=args.ticket, nonce=nonce)
448
- raise CliError("ack was submitted but no matching game receipt arrived",
449
- code=EXIT_NOTICE_TIMEOUT)
450
- session.log_event("ticket_ack_confirmed", ticket=args.ticket, status=args.status, nonce=nonce)
451
- _deliver(session, windows, args, f"/dev auto unidentify {nonce}")
452
- if not wait_ack_cleared(windows, args, nonce):
453
- session.log_event("ticket_ack_cleanup_unresolved", ticket=args.ticket, nonce=nonce)
454
- raise CliError("ack confirmed, but its marker cleanup was not observed",
455
- code=EXIT_NOTICE_TIMEOUT)
456
- session.log_event("ticket_ack_cleared", ticket=args.ticket, nonce=nonce)
457
- print(f"ack confirmed: {args.ticket} {args.status}")
458
- return 0
459
-
460
-
461
- def wait_ack_cleared(windows, args, nonce: str) -> bool:
462
- """Observe removal of this receipt; never dismiss a newer marker by nonce."""
463
- interval = getattr(args, "interval", None) or DEFAULT_INTERVAL
464
- deadline = time.monotonic() + min(args.timeout, 5.0)
465
- absent = 0
466
- with windows.open_notice_capture(args.hwnd, pid=getattr(args, "pid", None),
467
- exe_path=getattr(args, "exe_path", None),
468
- interval=interval) as capture:
469
- while time.monotonic() < deadline:
470
- if capture.window_closed:
471
- return False
472
- roi = capture.latest_roi()
473
- if roi is not None:
474
- visible = False
475
- for payload in windows.decode_qr(roi):
476
- try:
477
- marker = json.loads(payload)
478
- except (ValueError, TypeError):
479
- continue
480
- if isinstance(marker, dict) and marker.get("task") == "ack" and marker.get("run") == nonce:
481
- visible = True
482
- absent = 0 if visible else absent + 1
483
- if absent >= 2:
484
- return True
485
- time.sleep(interval)
486
- return False
487
-
488
-
489
- def validate_notice(json_text: str) -> dict:
490
- if not isinstance(json_text, str) or not json_text:
491
- raise SavedVariablesError("notice payload is empty")
492
- if len(json_text.encode("utf-8")) > NOTICE_MAX_BYTES:
493
- raise SavedVariablesError("notice payload exceeds 512 bytes")
494
- try:
495
- notice = json.loads(json_text)
496
- except ValueError as error:
497
- raise SavedVariablesError(f"notice is not valid JSON: {error}") from error
498
- if not isinstance(notice, dict) or notice.get("v") != 1:
499
- raise SavedVariablesError("unsupported notice protocol version")
500
- limits = {"ticket": 64, "task": 64, "run": 128}
501
- for key, limit in limits.items():
502
- value = notice.get(key)
503
- if not isinstance(value, str) or not value:
504
- raise SavedVariablesError(f"notice field {key} is missing")
505
- if len(value) > limit:
506
- raise SavedVariablesError(f"notice field {key} exceeds {limit} chars")
507
- if not svlib.TICKET_PATTERN.match(notice["ticket"]):
508
- raise SavedVariablesError("notice ticket has an invalid format")
509
- if not registry.TASK_ID_PATTERN.match(notice["task"]):
510
- raise SavedVariablesError("notice task id has an invalid format")
511
- if not registry.REQUEST_ID_PATTERN.match(notice["run"]):
512
- raise SavedVariablesError("notice run id has an invalid format")
513
- if not isinstance(notice.get("ts"), int) or isinstance(notice["ts"], bool) \
514
- or notice["ts"] <= 0:
515
- raise SavedVariablesError("notice ts is missing or invalid")
516
- return notice
517
-
518
-
519
- def notice_identity_problems(notice: dict, *, expected_task: str | None,
520
- expected_run: str | None) -> list[str]:
521
- """Compare a decoded notice against the request this run actually delivered.
522
-
523
- A static QR left on screen from an older run must never be accepted, so the
524
- task and request identity are cross-checked before any reload (design
525
- section 6.2).
526
- """
527
-
528
- problems = []
529
- if expected_task is not None and notice["task"] != expected_task:
530
- problems.append(f"notice task {notice['task']!r} != expected {expected_task!r}")
531
- if expected_run is not None and notice["run"] != expected_run:
532
- problems.append(f"notice run {notice['run']!r} != expected {expected_run!r}")
533
- return problems
534
-
535
-
536
- def poll_notice(windows, session: session_mod.Session, args, *,
537
- expected_task: str | None = None,
538
- expected_run: str | None = None,
539
- expected_ticket: str | None = None,
540
- expected_status: str | None = None) -> dict | None:
541
- """Keep one WGC session open and poll until a matching notice or the deadline.
542
-
543
- The session outlives a single frame because a task can run far longer than
544
- one capture interval. Stale notices (older task or request identity) are
545
- logged and ignored; only the exact expected notice is returned.
546
- """
547
-
548
- interval = getattr(args, "interval", None) or DEFAULT_INTERVAL
549
- deadline = time.monotonic() + args.timeout
550
- with windows.open_notice_capture(args.hwnd, pid=getattr(args, "pid", None),
551
- exe_path=getattr(args, "exe_path", None),
552
- interval=interval) as capture:
553
- while time.monotonic() < deadline:
554
- if capture.window_closed:
555
- session.log_event("notice_capture_closed", hwnd=args.hwnd)
556
- return None
557
- roi = capture.latest_roi()
558
- if roi is not None:
559
- for payload in windows.decode_qr(roi):
560
- try:
561
- notice = validate_notice(payload)
562
- except (SavedVariablesError, ValueError) as error:
563
- session.log_event("notice_rejected", reason=str(error))
564
- continue
565
- problems = notice_identity_problems(
566
- notice, expected_task=expected_task,
567
- expected_run=expected_run)
568
- if expected_ticket is not None and notice["ticket"] != expected_ticket:
569
- problems.append("receipt ticket mismatch")
570
- if expected_status is not None and notice.get("status") != expected_status:
571
- problems.append("receipt status mismatch")
572
- if problems:
573
- session.log_event("notice_identity_mismatch",
574
- ticket=notice["ticket"],
575
- task=notice["task"],
576
- requestId=notice["run"],
577
- reason="; ".join(problems))
578
- continue
579
- session.log_event(
580
- "notice_seen", ticket=notice["ticket"], task=notice["task"],
581
- requestId=notice["run"], ts=notice["ts"])
582
- return notice
583
- time.sleep(interval)
584
- return None
585
-
586
-
587
- def cmd_capture(args) -> int:
588
- windows = _window_module()
589
- session = session_mod.Session(data_dir=args.data_dir,
590
- installation=args.installation)
591
- notice = poll_notice(windows, session, args)
592
- if notice is None:
593
- print("no completion notice decoded before the timeout (or the capture "
594
- "session closed)", file=sys.stderr)
595
- return EXIT_NOTICE_TIMEOUT
596
- print(json.dumps(notice, sort_keys=True))
597
- return 0
598
-
599
-
600
- def cmd_identify(args) -> int:
601
- """Read the in-game identity marker from one or more game windows.
602
-
603
- Nothing observable from outside the game says which character sits behind
604
- which window, so with several windows open a slash command cannot be aimed
605
- without guessing. The addon can display a marker on request
606
- (``/dev auto identify``); this reads it out of each window so the caller can
607
- offer the user a character-based choice instead of an arbitrary index.
608
-
609
- Capture does not need the foreground, so this is safe before any input is
610
- sent. A window with no visible marker is reported with ``identity: null``
611
- rather than treated as an error: that is the normal state until the user
612
- asks the game to show one.
613
- """
614
-
615
- windows = _window_module()
616
- targets = _identify_targets(args)
617
- if not targets:
618
- raise CliError("identify needs at least one window: pass --hwnd, or "
619
- "--windows-json with the instances list")
620
-
621
- # Only forward an explicit timeout: passing None would override the helper's
622
- # own measured default rather than selecting it.
623
- options = {"interval": args.interval}
624
- if args.timeout is not None:
625
- options["timeout"] = args.timeout
626
- results = windows.read_identities(targets, **options)
627
- print(json.dumps(results, ensure_ascii=False, sort_keys=True))
628
- # Every window unreadable is a real failure; a partly readable set is not.
629
- if results and all(entry["identity"] is None and entry["error"] for entry in results):
630
- return EXIT_NOTICE_TIMEOUT
631
- return 0
632
-
633
-
634
- def _identify_targets(args) -> list[dict]:
635
- """Build the probe list from repeated --hwnd flags or a windows JSON file."""
636
-
637
- targets: list[dict] = []
638
- if args.windows_json:
639
- try:
640
- with open(args.windows_json, encoding="utf-8") as handle:
641
- loaded = json.load(handle)
642
- except OSError as error:
643
- raise CliError(f"could not read --windows-json: {error}") from error
644
- except ValueError as error:
645
- raise CliError(f"--windows-json is not valid JSON: {error}") from error
646
- if not isinstance(loaded, list):
647
- raise CliError("--windows-json must contain a JSON array of windows")
648
- for entry in loaded:
649
- if not isinstance(entry, dict) or entry.get("hwnd") is None:
650
- raise CliError("every --windows-json entry needs an 'hwnd'")
651
- targets.append({
652
- "hwnd": entry.get("hwnd"),
653
- "pid": entry.get("pid"),
654
- "exePath": entry.get("exePath"),
655
- "flavorFolder": entry.get("flavorFolder"),
656
- "flavorId": entry.get("flavorId"),
657
- "flavorLabel": entry.get("flavorLabel"),
658
- })
659
- return targets
660
-
661
- for hwnd in args.hwnd or ():
662
- targets.append({"hwnd": hwnd, "pid": args.pid, "exePath": args.exe_path,
663
- "flavorFolder": None, "flavorId": None, "flavorLabel": None})
664
- return targets
665
-
666
-
667
- # --- orchestrated flows ---------------------------------------------------------
668
-
669
- def _notice_to_sv(session: session_mod.Session, windows, notice: dict, args,
670
- *, revision: str | None, request_type: str) -> int:
671
- """Validate a notice, request one reload, wait, then read the ticket."""
672
-
673
- task = notice["task"]
674
- request_id = notice["run"]
675
- ticket = notice["ticket"]
676
- if not session.mark_reload_requested(request_id, ticket, task=task):
677
- raise CliError(
678
- f"reload for {ticket} was already requested; check the saved "
679
- "variables file before repeating the reload")
680
- baseline = session.file_snapshot(args.sv)
681
- _deliver(session, windows, args, "/reload")
682
- if not session.wait_for_saved_variables(args.sv, timeout=args.timeout,
683
- baseline=baseline):
684
- session.log_event("sv_write_timeout", ticket=ticket)
685
- raise CliError("the game did not rewrite its saved variables in time",
686
- code=EXIT_NOTICE_TIMEOUT)
687
- read_args = argparse.Namespace(
688
- sv_command="read", data_dir=args.data_dir, installation=args.installation,
689
- profile=None, sv=args.sv, ticket=ticket, task=task, request_id=request_id,
690
- revision=revision, created_at=notice["ts"], request_type=request_type,
691
- retries=SV_READ_RETRIES, retry_delay=SV_READ_RETRY_DELAY,
692
- all_installations=False,
693
- )
694
- code = cmd_sv(read_args)
695
- if code != 0:
696
- raise CliError(f"saved variables read failed for {ticket}", code=code)
697
- return 0
698
-
699
-
700
- def _installed_definition(install_dir: str, task_id: str) -> dict:
701
- task_path = os.path.join(install_dir, "Modules", "Automation", "auto", "auto.lua")
702
- definition = registry.TaskRegistry(task_path).read().get(task_id)
703
- if definition is None:
704
- raise CliError(f"task {task_id!r} is not present in {task_path}")
705
- return definition
706
-
707
-
708
- def cmd_run(args) -> int:
709
- windows = _window_module()
710
- session = session_mod.Session(data_dir=args.data_dir,
711
- installation=args.installation)
712
- install_dir = resolve_install_dir(args, required=False)
713
- expected_request_id = args.request_id
714
- revision = args.revision
715
- if install_dir:
716
- definition = _installed_definition(install_dir, args.task)
717
- if args.request_id is not None and args.request_id != definition["requestId"]:
718
- raise CliError(
719
- f"--request-id {args.request_id!r} does not match the loaded block "
720
- f"requestId {definition['requestId']!r}")
721
- expected_request_id = args.request_id or definition["requestId"]
722
- revision = args.revision or definition["revision"]
723
-
724
- if not registry.TASK_ID_PATTERN.fullmatch(args.task):
725
- raise CliError("invalid task id")
726
- if not expected_request_id or not registry.REQUEST_ID_PATTERN.fullmatch(expected_request_id):
727
- raise CliError("run requires an installed task block or an explicit --request-id")
728
-
729
- session.log_event("run_started", task=args.task,
730
- requestId=expected_request_id, revision=revision)
731
- _deliver(session, windows, args, f"/dev auto run {args.task}")
732
- notice = poll_notice(windows, session, args, expected_task=args.task,
733
- expected_run=expected_request_id)
734
- if notice is None:
735
- session.log_event("run_unresolved", task=args.task,
736
- requestId=expected_request_id)
737
- raise CliError("no completion notice decoded before the timeout (or the "
738
- "capture session closed); the run stays unresolved in the "
739
- "host log", code=EXIT_NOTICE_TIMEOUT)
740
- return _notice_to_sv(session, windows, notice, args, revision=revision,
741
- request_type="task")
742
-
743
-
744
- def cmd_bugs(args) -> int:
745
- windows = _window_module()
746
- if not 1 <= args.count <= 100:
747
- raise CliError("--count must be an integer between 1 and 100")
748
- session = session_mod.Session(data_dir=args.data_dir,
749
- installation=args.installation)
750
- args.request_id = args.request_id or new_request_id()
751
- if not registry.REQUEST_ID_PATTERN.fullmatch(args.request_id):
752
- raise CliError("invalid bug request id")
753
- session.log_event("bugs_started", count=args.count, requestId=args.request_id)
754
- _deliver(session, windows, args, f"/dev auto bug {args.count} {args.request_id}")
755
- notice = poll_notice(windows, session, args, expected_task=BUG_TASK_ID,
756
- expected_run=args.request_id)
757
- if notice is None:
758
- session.log_event("bugs_unresolved", count=args.count)
759
- raise CliError("no completion notice decoded before the timeout (or the "
760
- "capture session closed); the run stays unresolved in the "
761
- "host log", code=EXIT_NOTICE_TIMEOUT)
762
- return _notice_to_sv(session, windows, notice, args, revision=args.revision,
763
- request_type="bug")
764
-
765
-
766
- # --- session --------------------------------------------------------------------
767
-
768
- def _tail(records: list[dict], limit: int) -> list[dict]:
769
- if limit <= 0:
770
- return records
771
- return records[-limit:]
772
-
773
-
774
- def _log_scope(args) -> str | None:
775
- if getattr(args, "all_installations", False):
776
- return session_mod.ALL_INSTALLATIONS
777
- return None
778
-
779
-
780
- def cmd_status(args) -> int:
781
- session = session_mod.Session(data_dir=args.data_dir,
782
- installation=args.installation)
783
- events = _tail(session.read_events(args.event, installation=_log_scope(args)),
784
- args.limit)
785
- for record in events:
786
- print(json.dumps(record, ensure_ascii=False, sort_keys=True))
787
- if not events:
788
- print(f"no matching host log events in installation "
789
- f"{session.installation!r}")
790
- return 0
791
-
792
-
793
- def cmd_recover(args) -> int:
794
- session = session_mod.Session(data_dir=args.data_dir,
795
- installation=args.installation)
796
- scope = _log_scope(args)
797
- events = _tail(session.read_events(installation=scope), args.limit)
798
- for record in events:
799
- print(json.dumps(record, ensure_ascii=False, sort_keys=True))
800
- reloads = {r.get("ticket") for r in
801
- session.read_events("reload_requested", installation=scope)}
802
- received = {r.get("ticket") for r in
803
- session.read_events("received", installation=scope)}
804
- pending = sorted(t for t in reloads if t not in received)
805
- for ticket in pending:
806
- print(f"UNRESOLVED: reload requested for {ticket} but not received yet; "
807
- "inspect the saved variables file manually before any retry")
808
- if not pending:
809
- print(f"no unresolved reload requests in installation "
810
- f"{session.installation!r}")
811
- return 0
812
-
813
-
814
- # --- parser ----------------------------------------------------------------------
815
-
816
- def build_parser() -> argparse.ArgumentParser:
817
- parser = argparse.ArgumentParser(prog="automation.py",
818
- description=__doc__)
819
- parser.add_argument("--data-dir", default=session_mod.default_data_dir(),
820
- help="host data directory (log, artifacts, profiles)")
821
- parser.add_argument("--installation", default="default",
822
- help="installation name used as the dedup/log scope "
823
- "(default: default)")
824
- sub = parser.add_subparsers(dest="command", required=True)
825
-
826
- task = sub.add_parser("task", help="update the installed auto.lua registry")
827
- task.add_argument("task_command", choices=["upsert", "remove", "list"])
828
- task.add_argument("--install-dir", help="installed addon directory (contains "
829
- "Modules/Automation/auto/auto.lua)")
830
- task.add_argument("--profile", help="profile name to take --install-dir from")
831
- task.add_argument("--id", help="task id ([A-Za-z0-9_-]{1,64})")
832
- task.add_argument("--source-file", help="UTF-8 Lua source file for the task")
833
- task.add_argument("--request-id", help="request id for this execution "
834
- "(default: generated)")
835
- task.add_argument("--revision", help="source revision (default: generated)")
836
- task.add_argument("--expect-revision",
837
- help="replace only when the stored revision matches")
838
- task.add_argument("--created-at", type=int, help="creation timestamp (epoch)")
839
- task.add_argument("--expires-at", type=int, default=0,
840
- help="expiry timestamp (epoch, 0 = never)")
841
- task.add_argument("--expected-interface", type=int,
842
- help="expected client Interface version")
843
- task.add_argument("--output-limit", type=int,
844
- help="captured stdout limit in bytes")
845
- task.set_defaults(func=cmd_task)
846
-
847
- profile = sub.add_parser("profile", help="bind one client installation")
848
- profile.add_argument("profile_command", choices=["set", "show"])
849
- profile.add_argument("--name", required=True, help="profile name")
850
- profile.add_argument("--client", choices=sorted(CLIENT_FOLDERS),
851
- help="client type: retail, classic, titan or forever; the "
852
- "client folder is resolved from the WoW root")
853
- profile.add_argument("--wow-root", help="WoW root that contains the client folder")
854
- profile.add_argument("--addon-dir", help="installed addon directory")
855
- profile.add_argument("--sv-path", help="exact 'Lychee Dev.lua' path to read")
856
- profile.set_defaults(func=cmd_profile)
857
-
858
- sv = sub.add_parser("sv", help="find or read SavedVariables")
859
- sv.add_argument("sv_command", choices=["find", "read"])
860
- sv.add_argument("--profile", help="profile name (install dir and SV path)")
861
- sv.add_argument("--sv", help="exact 'Lychee Dev.lua' path")
862
- sv.add_argument("--ticket", help="exact Ticket to read (required for read)")
863
- sv.add_argument("--task", help="expected task id")
864
- sv.add_argument("--request-id", help="expected execution/request id")
865
- sv.add_argument("--revision", help="expected source revision")
866
- sv.add_argument("--created-at", type=int, help="expected record createdAt")
867
- sv.add_argument("--request-type", choices=["task", "bug"],
868
- help="expected inner report request type")
869
- sv.add_argument("--retries", type=int, default=SV_READ_RETRIES,
870
- help="additional read attempts for a torn or replaced file "
871
- f"(default: {SV_READ_RETRIES})")
872
- sv.add_argument("--retry-delay", type=float, default=SV_READ_RETRY_DELAY,
873
- help="seconds between read attempts "
874
- f"(default: {SV_READ_RETRY_DELAY})")
875
- sv.set_defaults(func=cmd_sv)
876
-
877
- window = argparse.ArgumentParser(add_help=False)
878
- window.add_argument("--hwnd", type=lambda value: int(value, 0), required=True,
879
- help="target window handle (decimal or 0x...)")
880
- window.add_argument("--pid", type=int, help="expected process id")
881
- window.add_argument("--exe-path", help="expected executable path")
882
- window.add_argument(
883
- "--mode", choices=("foreground", "messages"), default="messages",
884
- help="foreground uses clipboard readback; messages posts input to the "
885
- "target HWND without changing foreground (execution needs a receipt)")
886
-
887
- polling = argparse.ArgumentParser(add_help=False)
888
- polling.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT,
889
- help="seconds to keep polling for the notice "
890
- f"(default: {DEFAULT_TIMEOUT})")
891
- polling.add_argument("--interval", type=float, default=DEFAULT_INTERVAL,
892
- help="seconds between notice polls "
893
- f"(default: {DEFAULT_INTERVAL})")
894
-
895
- send = sub.add_parser("send", parents=[window],
896
- help="deliver one slash command")
897
- send.add_argument("--text", required=True, help="exact slash command to send")
898
- send.add_argument("--request-id",
899
- help="request id used to dedup a '/reload' command")
900
- send.add_argument("--ticket", help="ticket used to dedup a '/reload' command")
901
- send.set_defaults(func=cmd_send)
902
-
903
- ack = sub.add_parser("ack", parents=[window, polling],
904
- help="report a ticket's read outcome to the running game")
905
- ack.add_argument("--ticket", required=True, help="exact ticket that was read")
906
- ack.add_argument("--status", required=True, choices=("received", "failed"),
907
- help="'received' when the report was read, 'failed' otherwise")
908
- ack.set_defaults(func=cmd_ack)
909
-
910
- capture = sub.add_parser("capture", parents=[window, polling],
911
- help="poll the window and decode the notice QR")
912
- capture.set_defaults(func=cmd_capture)
913
-
914
- identify = sub.add_parser(
915
- "identify",
916
- help="read the character/build identity marker from game windows")
917
- identify.add_argument("--hwnd", type=lambda value: int(value, 0), action="append",
918
- help="a window to probe; repeat for several windows")
919
- identify.add_argument("--windows-json",
920
- help="JSON file with the instance list to probe instead "
921
- "of --hwnd (the shape 'lycheedev instances' prints)")
922
- identify.add_argument("--pid", type=int, help="expected process id")
923
- identify.add_argument("--exe-path", help="expected executable path")
924
- identify.add_argument("--timeout", type=float, default=None,
925
- help="seconds to wait per window for its marker "
926
- "(default: the helper's measured budget)")
927
- identify.add_argument("--interval", type=float, default=DEFAULT_INTERVAL,
928
- help=f"seconds between polls per window "
929
- f"(default: {DEFAULT_INTERVAL})")
930
- identify.set_defaults(func=cmd_identify)
931
-
932
- run = sub.add_parser("run", parents=[window, polling],
933
- help="deliver and resolve one task run")
934
- run.add_argument("--task", required=True, help="task id to run")
935
- run.add_argument("--sv", required=True, help="'Lychee Dev.lua' path to read")
936
- run.add_argument("--install-dir",
937
- help="installed addon directory used to resolve the expected "
938
- "request id and revision")
939
- run.add_argument("--profile", help="profile name for --install-dir")
940
- run.add_argument("--request-id", help="expected request id (default: the "
941
- "loaded block's requestId)")
942
- run.add_argument("--revision", help="expected source revision (default: the "
943
- "loaded block's revision)")
944
- run.set_defaults(func=cmd_run)
945
-
946
- bugs = sub.add_parser("bugs", parents=[window, polling],
947
- help="snapshot recent errors and resolve the run")
948
- bugs.add_argument("--count", type=int, required=True,
949
- help="error records to snapshot (1-100)")
950
- bugs.add_argument("--sv", required=True, help="'Lychee Dev.lua' path to read")
951
- bugs.add_argument("--request-id", help="expected request id, when known")
952
- bugs.add_argument("--revision", help="expected source revision, when known")
953
- bugs.set_defaults(func=cmd_bugs)
954
-
955
- status = sub.add_parser("status", help="print host log events")
956
- status.add_argument("--event", help="only this event name")
957
- status.add_argument("--limit", type=int, default=20,
958
- help="most recent records to print (0 = all, default: 20)")
959
- status.add_argument("--all-installations", action="store_true",
960
- help="include every installation scope, not just this one")
961
- status.set_defaults(func=cmd_status)
962
-
963
- recover = sub.add_parser("recover", help="show unresolved reload intents")
964
- recover.add_argument("--limit", type=int, default=50,
965
- help="most recent records to print (0 = all, default: 50)")
966
- recover.add_argument("--all-installations", action="store_true",
967
- help="include every installation scope, not just this one")
968
- recover.set_defaults(func=cmd_recover)
969
-
970
- return parser
971
-
972
-
973
- def _expected_error_types() -> tuple:
974
- errors = [RegistryError, SavedVariablesError, UnicodeDecodeError,
975
- json.JSONDecodeError, OSError]
976
- try:
977
- from automation import windows
978
- except Exception: # pragma: no cover - non-Windows hosts
979
- return tuple(errors)
980
- errors.extend([windows.WindowIdentityError, windows.InputError,
981
- windows.CaptureDependencyError])
982
- return tuple(errors)
983
-
984
-
985
- def _window_error_types() -> tuple:
986
- """Errors that mean the game window, its identity, or the capture
987
- dependency failed. They map to the documented window/input exit code.
988
-
989
- The result must never be an empty tuple: ``except`` with no exception
990
- types falls back to catching BaseException, and an exception group is
991
- rejected outright by ``except``. Non-Windows hosts return a harmless
992
- unused placeholder so the handler simply never fires.
993
- """
994
-
995
- try:
996
- from automation import windows
997
- except Exception: # pragma: no cover - non-Windows hosts
998
- return (RuntimeError,)
999
- return (windows.WindowIdentityError, windows.InputError,
1000
- windows.CaptureDependencyError)
1001
-
1002
-
1003
- def main(argv=None) -> int:
1004
- parser = build_parser()
1005
- args = parser.parse_args(argv)
1006
- try:
1007
- return args.func(args)
1008
- except CliError as error:
1009
- print(f"error: {error}", file=sys.stderr)
1010
- return error.code
1011
- except RegistryError as error:
1012
- print(f"error: task registry failed: {error}", file=sys.stderr)
1013
- return EXIT_REGISTRY
1014
- except SavedVariablesError as error:
1015
- print(f"error: saved variables failed: {error}", file=sys.stderr)
1016
- return EXIT_SV_READ
1017
- except _window_error_types() as error:
1018
- print(f"error: {error}", file=sys.stderr)
1019
- return EXIT_INPUT
1020
- except _expected_error_types() as error:
1021
- print(f"error: {error}", file=sys.stderr)
1022
- return EXIT_USAGE
1023
- except KeyboardInterrupt:
1024
- print("error: interrupted", file=sys.stderr)
1025
- return EXIT_USAGE
1026
- except Exception as error: # unexpected: keep the traceback, stay non-zero
1027
- print(f"unexpected failure: {type(error).__name__}: {error}",
1028
- file=sys.stderr)
1029
- traceback.print_exc()
1030
- return EXIT_USAGE
1031
-
1032
-
1033
- if __name__ == "__main__":
1034
- sys.exit(main())