lycheedev 1.2.0 → 2.0.1

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