lycheedev 1.1.0 → 1.2.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.
@@ -1,216 +1,51 @@
1
- # Clients, builds and instances
1
+ # 选择客户端、实例与证据位置
2
2
 
3
- How to tell which World of Warcraft client you are driving, and how to target
4
- one when several are running. Read this before any command that types into the
5
- game (`send`, `run`, `bugs`, `capture`, `ack`).
3
+ 发送前使用本节。目标顺序是 **版本 → 该版本实例 → 角色/服务器 → 安装目录与 SV**。PID/HWND 是内部绑定参数,不是要求用户理解的选择菜单。
6
4
 
7
- ## Supported builds
5
+ ## 产品识别
8
6
 
9
- The addon ships one catalog per supported build. Nothing else loads it.
7
+ | 产品 | 版本基线 | Interface | 常见位置 |
8
+ | --- | --- | --- | --- |
9
+ | retail | 12.1.0 | 120100 | `_retail_` |
10
+ | classic | 5.5.4 | 50504 | `_classic_` |
11
+ | titan | 3.80.2 | 38002 | `_classic_titan_` |
12
+ | forever | 1.60.1 | 16001 | `_classic_beta_` 或 `_forever_` |
10
13
 
11
- | Build | Version | Interface | Catalog | Install folder |
12
- | --- | --- | --- | --- | --- |
13
- | Retail | `12.1.0` | `120100` | `Lychee Dev_Mainline.toc` | `_retail_` |
14
- | Classic | `5.5.4` | `50504` | `Lychee Dev_Mists.toc` | `_classic_` |
15
- | Classic Titan | `3.80.2` | `38002` | `Lychee Dev_Wrath.toc` | `_classic_titan_` |
16
- | WoW: Forever (无限服) | `1.60.1` | `16001` | `Lychee Dev_Forever.toc` | `_classic_beta_` or `_forever_` |
14
+ 读取 `.flavor.info` 的 product code,再读取 `version.txt` 或可执行文件版本,最后才以文件夹名兜底。`_classic_beta_` 可能是 Forever,也可能是 MoP 测试轨;所有非 Retail 产品都可能使用 WowClassic.exe。窗口标题和 exe 文件名不证明产品。不自动扩展到 Era、Anniversary、PTR 等产品。
17
15
 
18
- Other folders may exist on a machine (`_classic_era_`, `_anniversary_`,
19
- `_beta_`). They are reported as **not served by the addon** and are deliberately
20
- skipped. Do not install into them and do not tell the user they are supported.
16
+ `lycheedev clients` 列出安装;`lycheedev instances` 枚举运行实例。用户已选版本就沿用;仅一种受支持版本运行时可直接使用,多种且未指定时先让用户选版本。只有选定产品的窗口进入后续扫描,不先把所有 PID 列给用户。
21
17
 
22
- `_classic_beta_` is the exception and must not be lumped in with those: it **is**
23
- served when it holds WoW: Forever (see below). Never decide either way from the
24
- folder name — read the client's own product code and build first.
18
+ ## 实例选择
25
19
 
26
- The Titan folder is `_classic_titan_`. An earlier release used
27
- `_classic_arena_`, which does not exist; that made an installed Titan client
28
- invisible to both `install` and `doctor`. If a user reports "Titan was never
29
- installed", check the folder name before anything else.
20
+ 选定版本只有一个实例:自动绑定该实例,不再问 PID。记录本次枚举得到的 HWND、PID、完整 exe 路径、实际版本和安装目录。对多个安装目录不能仅按产品名选配置。
30
21
 
31
- ## A folder is a location, not an identity
32
-
33
- Do not decide the build from the folder name. The launcher reuses a test folder
34
- for whatever is on the test track, so **WoW: Forever currently ships under
35
- `_classic_beta_`**, a folder that a MoP-era classic test client also uses. The
36
- same folder can therefore be two different products over time.
37
-
38
- The signal that actually identifies a client is the client's own files:
39
-
40
- | Signal | Where | Example |
41
- | --- | --- | --- |
42
- | product code | `.flavor.info` in the flavor folder | `wow_forever`, `wow_classic_titan`, `wow` |
43
- | build | `version.txt` in the flavor folder | `1.60.1.69893` |
44
- | exe version | file metadata on `WowClassic.exe` | `5.5.4.69585` |
45
-
46
- Resolution order the CLI uses, and that you should follow when reasoning about a
47
- machine: product code first, then the build, then the folder default. So
48
- `_classic_beta_` holding `1.60.x` / `wow_forever` is **Forever**, while the same
49
- folder holding `5.5.x` / `wow_classic_beta` is the **Classic Beta** test track.
50
-
51
- `_forever_` is also accepted, for installs that give Forever its own folder.
52
-
53
- ## The executable name does not identify the build
54
-
55
- Every non-retail client ships as `WowClassic.exe`. `Wow.exe` is retail,
56
- `WowB.exe` is beta, and `WowVoiceProxy.exe` is a helper, not a client.
57
-
58
- So the executable name narrows a running process to *some* non-retail client and
59
- nothing more. The install path narrows it to one install folder — but not to a
60
- product, because a folder can be reused (see above). Only the client's own
61
- `.flavor.info` product code and build settle which client it is:
62
-
63
- ```text
64
- D:\Game\World of Warcraft\_retail_\Wow.exe folder default: retail
65
- D:\Game\World of Warcraft\_classic_\WowClassic.exe folder default: classic
66
- D:\Game\World of Warcraft\_classic_titan_\WowClassic.exe folder default: titan
67
- D:\Game\World of Warcraft\_classic_beta_\WowClassic.exe product decides: forever or classicBeta
68
- ```
69
-
70
- Never infer the build from the window title. Retail's title is localized (for
71
- example `魔兽世界`) and gives no build information.
72
-
73
- ## Commands
74
-
75
- ### `lycheedev clients`
76
-
77
- Every build on disk, with its real version read from the executable, and whether
78
- the addon is installed:
79
-
80
- ```text
81
- retail _retail_ v12.1.0.69587 addon installed
82
- classic _classic_ v5.5.4.69585 addon installed
83
- titan _classic_titan_ v3.80.2.69496 addon installed
84
- forever _classic_beta_ v1.60.1.69893 addon installed
85
- classicEra _classic_era_ v1.15.9.69547 not served by the addon
86
- ```
87
-
88
- The `id` column already reflects the resolved product, so `forever` appearing
89
- next to `_classic_beta_` is expected and is exactly the case a folder name alone
90
- would get wrong. When the folder's own product code differs from the resolved
91
- one, it is shown in brackets before the version.
92
-
93
- ### `lycheedev instances`
94
-
95
- Which clients are running right now, with the pid, window handle and build:
96
-
97
- ```text
98
- running instances:
99
- [0] Retail pid=62460 hwnd=0x12410c7a "魔兽世界"
100
-
101
- commands target this instance automatically
102
- ```
103
-
104
- The `[index]` is what you pass to `--instance` and to `use`.
105
-
106
- ### `lycheedev instances --identify`
107
-
108
- Reads a small identity QR code from the top-left corner of each running window and
109
- prints the character and build behind it:
22
+ 同版本多个实例:逐个后台触发身份标记,然后读取该窗口;完成整轮后展示“角色—服务器”供选择。每个窗口使用本次枚举的精确参数:
110
23
 
111
24
  ```text
112
- running instances:
113
- [0] Retail pid=62460 hwnd=0x12410c7a v12.1.0.69587
114
- character: 荔枝-白银之手 client: retail build: 12.1.0
115
- [1] Forever pid=71824 hwnd=0x2b30e1f4 v1.60.1.69893
116
- character: 测试小号-白银之手 client: forever build: 1.60.1
117
-
118
- commands target this instance automatically
25
+ python <skill>/scripts/automation.py send --mode messages --hwnd <hwnd> --pid <pid> --exe-path <exe> --text "/dev auto identify"
26
+ python <skill>/scripts/automation.py identify --hwnd <hwnd> --pid <pid> --exe-path <exe> --timeout 3
119
27
  ```
120
28
 
121
- The marker is not shown by default: it occupies the same corner as the completion
122
- notice. Ask the user to run `/dev auto identify` **in each window they care about**,
123
- then run this command. `/dev auto unidentify` hides it again.
124
-
125
- Reading uses window capture (`Windows.Graphics.Capture`), so no window needs the
126
- foreground and nothing is typed into the game. A window that shows no marker is
127
- reported as having no identity rather than failing; that is the normal state until
128
- the user asks for one.
29
+ `identify` 是只读解码器,不会自动让游戏显示二维码。`instances --identify` 同样不能替代触发步骤。不要并发给多个窗口打字;当前 Python 批量读取器虽然支持并发捕获,编排时仍逐个触发和读取,以隔离窗口状态。
129
30
 
130
- Use this to turn an arbitrary index into a name the user can confirm. Tell the user
131
- which character you are about to drive before you send anything.
31
+ 核对身份 QR 的 `v/id/realm/client/build` 与所选产品和进程版本一致。完成标记含 `ticket`,不能当作角色身份标记。若有他人的运行中色块或待收取完成码,先处理其归属,不能用身份标记覆盖证据。只清理自己触发的身份码:`/dev auto unidentify`。
132
32
 
133
- ### `lycheedev use [index]`
33
+ 名字缺失、realm 缺失、重复角色+服务器或读取失败均保持未识别;不能静默挑第一个/ordinal 0。先说明未识别窗口的原因,继续可独立完成的读取;仍无法消歧时让用户指明角色或关闭多余实例。不要以“后台不需要焦点”为由跳过角色识别。
134
34
 
135
- Pin one running client as the default target, so later commands need no flag:
35
+ ## 绑定的有效期与现有 CLI 限制
136
36
 
137
- ```text
138
- lycheedev use # the only running client
139
- lycheedev use 1 # the instance at index 1, when the builds differ
140
- lycheedev use --character 荔枝-白银之手 # the window reporting that character
141
- lycheedev use --clear
142
- ```
143
-
144
- The pin stores the build and the instance ordinal, because pids and window handles
145
- change on every launch. When the window showed its identity marker the character is
146
- stored too, and that is the durable half: the pin then follows the character even if
147
- the windows are reopened in a different order. It re-resolves against whatever is
148
- running now, and if the pinned build is not running, commands fail with a clear
149
- message instead of typing into the wrong game.
150
-
151
- Pinning by name is how you choose **between windows of the same build**; see the
152
- ambiguity rule below for the case where even that cannot separate them.
153
-
154
- ## Choosing a target: precedence
37
+ 每次开始输入以及中断恢复时重新枚举。进程退出、重启、角色改变或安装目录改变后重新绑定;不要把旧 PID/HWND 或旧 ordinal 当作持久身份。
155
38
 
156
- 1. `--hwnd` / `--pid` — explicit, for scripted use
157
- 2. `--instance <index>` — one command only, overrides the pin
158
- 3. `--character <name>` — the window reporting that character (`Name` or `Name-Realm`)
159
- 4. the saved pin from `use`
160
- 5. `--client retail|classic|titan|forever` — filter by build
161
- 6. the single running instance, when there is exactly one
39
+ 当前 wrapper 的 pin 仍可能回退 ordinal,默认配置客户端也可能与选中运行实例不同。不要依赖这个回退;Agent 按上述步骤选择后,直接调用 Python,显式传 HWND/PID/exe、安装目录和 SV。当前 helper 只核对 PID/exe,尚未核对进程创建时间;不能声称它已排除所有句柄/PID 重用。
162
40
 
163
- Several instances of **different** builds are safe to keep open: the install path
164
- separates them, so `--client` picks one.
41
+ 同版本多实例扫描目前由 Agent 组织,CLI 没有完整的“先版本后角色”交互向导;不要编造参数或声称自动向导已实现。
165
42
 
166
- Several instances of the **same** build are distinguishable only when each window
167
- reports a different character. Show the markers (`/dev auto identify` in each
168
- window) and then either pass `--character <name>` or pin by name:
43
+ ## SavedVariables 绑定
169
44
 
170
- ```text
171
- lycheedev use --character 荔枝-白银之手
172
- ```
173
-
174
- `use` probes the markers by itself when several windows share a build, because
175
- reading them is capture-only and types nothing.
45
+ 每个安装的候选文件位于该客户端目录的 `WTF/Account/*/SavedVariables/Lychee Dev.lua`。配置中的 svPath 只是候选;最新 mtime 也不是账户身份。不要读取 `.bak` 代替当前数据。
176
46
 
177
- Two windows reporting the **same character and realm** — or two windows that show
178
- no marker at all — are genuinely indistinguishable. Pinning an ordinal there would
179
- only look precise while risking a slash command in the wrong game, so the CLI
180
- refuses and names the pids to close:
47
+ 已有 Ticket:在选中安装的候选文件中定位精确 Ticket,读完整报告后核对角色、服务器、产品与版本。
181
48
 
182
- ```text
183
- error: 2 Retail clients cannot be told apart
184
- close all but one, or close these pids: 62460, 71824
185
- or run `/dev auto identify` in each game window and then
186
- `lycheedev use --character <name>`
187
- ```
49
+ 新调查但账户未绑定:先准备任务并取得匹配完成码,执行一次有去重记录的输出 reload,然后在候选 SV 中查找精确 Ticket。唯一且环境吻合后才绑定该路径。不能给 `run --sv` 随便填一个账户再把读失败视作任务失败。不同文件出现同一 Ticket 时结合 requestId/revision/environment 消歧,仍不唯一就停在定位阶段。
188
50
 
189
- **In that case ask the user to close all but one window of that build.** Do not
190
- invent a way to pick between them, and do not offer to pin one by pid.
191
-
192
- ## Multiple installations
193
-
194
- A machine can hold more than one WoW root. `--wow-root <path>` selects which one
195
- to install into and is remembered in `~/.lycheedev/config.json`. `doctor`
196
- reports the root it is using. Run `lycheedev clients --wow-root <other>` to
197
- inspect a second root without changing the saved one.
198
-
199
- ## What cannot be done from outside the game
200
-
201
- - The **character** behind a window is not passively observable. It only becomes
202
- readable when the addon is loaded in that client and the user shows the identity
203
- marker (`/dev auto identify`), which `instances --identify` then reads. Without
204
- that cooperation, two instances of the same build can only be referred to by pid,
205
- window handle or index — never by name, and never guessed.
206
- - Two windows showing the **same character and realm** stay indistinguishable even
207
- with the marker, because the marker content is identical.
208
- - The **account** behind a running client is not exposed. SavedVariables files are
209
- per account, and the newest file is not necessarily the live session's account
210
- when several accounts are configured.
211
- - WoW ignores posted window messages, so keyboard delivery needs the window in the
212
- foreground. That is why targeting the right window matters.
213
-
214
- If the user must be certain which client is which, and the marker is unavailable,
215
- ask them to run a trivial in-game command (`/dev auto status <task>`) in the window
216
- they mean, or to close the others.
51
+ 从 QR 取得的版本可能只含语义版本;完整 build 用进程版本和报告 environment 补全。每次实机结论都记录实际版本,不拿本表基线代替现场版本。
@@ -1,5 +1,12 @@
1
1
  # Bounded memory and CPU investigations through Run
2
2
 
3
+ For authorized background investigations, deliver the probe through the task registry
4
+ and follow [automation.md](automation.md) through receipt and cleanup. The pasted
5
+ Run input guidance below applies when the user chooses that UI workflow; it is not
6
+ the default delivery path and does not require switching a background task to the
7
+ foreground.
8
+
9
+
3
10
  Use this reference when a Lychee Dev investigation concerns memory, CPU, stutter, startup or repeated operations. The output is a question-specific script and evidence interpretation, not a replacement background profiler.
4
11
 
5
12
  ## Define the question before the probe
@@ -0,0 +1,121 @@
1
+ """Nonce-bound reload readiness; images remain on the host, not in model input."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import re
7
+ import struct
8
+ import time
9
+ import zlib
10
+
11
+ NONCE = re.compile(r"[A-Za-z0-9.-]{1,64}\Z")
12
+
13
+
14
+ class ReloadError(Exception):
15
+ pass
16
+
17
+
18
+ def marker(payload, nonce):
19
+ if not isinstance(payload, str) or len(payload.encode("utf-8")) > 512:
20
+ return None
21
+ try:
22
+ value = json.loads(payload)
23
+ except (ValueError, TypeError):
24
+ return None
25
+ if not isinstance(value, dict) or value.get("v") != 1:
26
+ return None
27
+ if value.get("kind") != "reload" or value.get("run") != nonce or value.get("status") != "ready":
28
+ return None
29
+ if type(value.get("ts")) is not int or value["ts"] <= 0:
30
+ return None
31
+ if not all(isinstance(value.get(k), str) and 0 < len(value[k]) <= 64 for k in ("client", "build")):
32
+ return None
33
+ return value
34
+
35
+
36
+ def save_timeout_image(session, nonce, roi):
37
+ if roi is None:
38
+ return None
39
+ # WGC's bounded ROI is BGR(A); write RGB PNG with the stdlib, no new dependency.
40
+ height, width = roi.shape[:2]
41
+ raw = b"".join(b"\0" + roi[y, :, :3][:, ::-1].tobytes() for y in range(height))
42
+ def chunk(kind, data):
43
+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xffffffff)
44
+ png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
45
+ png += chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
46
+ directory = session.state_path(os.path.join("reload", nonce))
47
+ os.makedirs(directory, exist_ok=True)
48
+ path = os.path.join(directory, "timeout.png")
49
+ with open(path, "wb") as handle:
50
+ handle.write(png)
51
+ return path
52
+
53
+
54
+ def wait_ready(windows, session, args, nonce):
55
+ deadline = time.monotonic() + args.timeout
56
+ interval = getattr(args, "interval", None) or .1
57
+ last_roi = None
58
+ with windows.open_notice_capture(args.hwnd, pid=args.pid, exe_path=args.exe_path, interval=interval) as capture:
59
+ while time.monotonic() < deadline:
60
+ if capture.window_closed:
61
+ break
62
+ roi = capture.latest_roi()
63
+ if roi is not None:
64
+ last_roi = roi
65
+ for payload in windows.decode_qr(roi):
66
+ ready = marker(payload, nonce)
67
+ if ready:
68
+ return ready
69
+ time.sleep(interval)
70
+ path = save_timeout_image(session, nonce, last_roi)
71
+ session.log_event("reload_ready_timeout", nonce=nonce, screenshot=path)
72
+ raise ReloadError(f"reload readiness unresolved for {nonce}; resume this nonce without reloading; screenshot={path}")
73
+
74
+
75
+ def wait_cleared(windows, args, nonce):
76
+ deadline = time.monotonic() + min(args.timeout, 5)
77
+ interval = getattr(args, "interval", None) or .1
78
+ absent = 0
79
+ with windows.open_notice_capture(args.hwnd, pid=args.pid, exe_path=args.exe_path, interval=interval) as capture:
80
+ while time.monotonic() < deadline:
81
+ if capture.window_closed:
82
+ return False
83
+ roi = capture.latest_roi()
84
+ if roi is not None:
85
+ visible = any(marker(payload, nonce) for payload in windows.decode_qr(roi))
86
+ absent = 0 if visible else absent + 1
87
+ if absent >= 2:
88
+ return True
89
+ time.sleep(interval)
90
+ return False
91
+
92
+
93
+ def execute(windows, session, args, deliver, nonce, *, ticket=None, resume=False):
94
+ if not NONCE.fullmatch(nonce):
95
+ raise ReloadError("invalid reload nonce")
96
+ history = [e for e in session.read_events() if e.get("nonce") == nonce]
97
+ previous = next((e for e in history if e["event"] == "reload_handshake_requested"), None)
98
+ if resume:
99
+ if not previous or any(previous.get(k) != getattr(args, attr, None)
100
+ for k, attr in (("hwnd", "hwnd"), ("pid", "pid"), ("exePath", "exe_path"))):
101
+ raise ReloadError("reload resume requires the original nonce and window binding")
102
+ if any(e["event"] == "reload_ready_cleared" for e in history):
103
+ return {"status": "already_completed", "nonce": nonce}
104
+ else:
105
+ if previous:
106
+ raise ReloadError("reload nonce was already submitted; use --resume, do not reload again")
107
+ session.log_event("reload_handshake_requested", nonce=nonce, ticket=ticket,
108
+ hwnd=args.hwnd, pid=args.pid, exePath=args.exe_path)
109
+ deliver(session, windows, args, f"/dev auto reload {nonce}" + (f" {ticket}" if ticket else ""))
110
+ started = time.monotonic()
111
+ confirmed = next((e for e in history if e["event"] == "reload_ready_confirmed"), None)
112
+ ready = confirmed.get("ready") if confirmed else wait_ready(windows, session, args, nonce)
113
+ if not confirmed:
114
+ session.log_event("reload_ready_confirmed", nonce=nonce, ready=ready)
115
+ deliver(session, windows, args, f"/dev auto unidentify {nonce}")
116
+ if not wait_cleared(windows, args, nonce):
117
+ session.log_event("reload_ready_cleanup_unresolved", nonce=nonce)
118
+ raise ReloadError(f"reload ready, but marker cleanup unresolved; resume {nonce}")
119
+ session.log_event("reload_ready_cleared", nonce=nonce)
120
+ return {"status": "reload_ready", "nonce": nonce, "elapsedSeconds": round(time.monotonic() - started, 2),
121
+ "client": ready["client"], "build": ready["build"], "markerCleared": True}
@@ -1,9 +1,8 @@
1
1
  """Window identity, capture and controlled command input for Windows.
2
2
 
3
3
  Window identity is never guessed from the title alone: every use confirms the
4
- HWND against pid, process executable path and (best effort) the process
5
- creation time. Command input uses the controlled focus-verify-paste-confirm
6
- sequence; WGC capture and QR decoding are optional heavy imports that fail
4
+ HWND against pid and process executable path. Command input uses a controlled
5
+ focus-verify-paste-confirm sequence; WGC capture and QR decoding are optional heavy imports that fail
7
6
  with explicit messages when their packages are missing.
8
7
 
9
8
  The capture session is long lived: a task can run far longer than one frame, so
@@ -24,6 +23,8 @@ from __future__ import annotations
24
23
  import ctypes
25
24
  import ctypes.wintypes as wt
26
25
  import json
26
+ import ntpath
27
+ import uuid
27
28
  import time
28
29
  from collections import deque
29
30
  from concurrent.futures import ThreadPoolExecutor
@@ -37,6 +38,10 @@ KEYEVENTF_KEYUP = 0x0002
37
38
  VK_CONTROL = 0x11
38
39
  VK_RETURN = 0x0D
39
40
  VK_V = 0x56
41
+ VK_A = 0x41
42
+ VK_C = 0x43
43
+ VK_ESCAPE = 0x1B
44
+ VK_OEM_2 = 0xBF
40
45
  VK_MENU = 0x12
41
46
  WM_CHAR = 0x0102
42
47
  WM_KEYDOWN = 0x0100
@@ -74,7 +79,9 @@ class WindowIdentity:
74
79
  def matches(self, *, pid: int | None = None, exe_path: str | None = None) -> bool:
75
80
  if pid is not None and self.pid != pid:
76
81
  return False
77
- if exe_path is not None and (self.exe_path or "").lower() != exe_path.lower():
82
+ if exe_path is not None and (
83
+ ntpath.normcase(ntpath.normpath(self.exe_path or ""))
84
+ != ntpath.normcase(ntpath.normpath(exe_path))):
78
85
  return False
79
86
  return True
80
87
 
@@ -235,53 +242,84 @@ def _send_key(vk: int, *, ctrl: bool = False) -> None:
235
242
 
236
243
  def send_command(hwnd: int, command: str, *, pid: int | None = None,
237
244
  exe_path: str | None = None, clipboard=None,
238
- mode: str = "foreground") -> None:
239
- """Deliver one slash command through the game chat box.
245
+ mode: str = "messages") -> None:
246
+ """Replace a chat draft and verify the copied edit text before submitting.
240
247
 
241
- ``mode`` selects the injection strategy:
242
-
243
- - ``"foreground"`` (default): focus the window, open chat with Return,
244
- paste from the clipboard, submit with Return. Uses ``SendInput``, which
245
- only reaches the foreground window, so the window is focused first.
246
- - ``"messages"``: post the keystrokes straight into the target window's
247
- message queue. This needs no foreground at all, but the client only
248
- reacts when its chat edit box is already open and focused, and a client
249
- that reads raw input may ignore posted messages entirely.
250
-
251
- Both modes run the game's own command parser, so a slash command that the
252
- client cannot run (locked UI, unknown command) still fails inside the game.
253
-
254
- ``clipboard`` may be injected for tests; it needs ``copy_text``,
255
- ``read_text`` and ``clear``. The previous clipboard content is restored
256
- when it still belongs to this operation.
248
+ A successful return means keyboard submission, not game execution. Callers
249
+ must correlate the game's receipt. Messages mode is a separate HWND-bound
250
+ background transport and does not use focus or the clipboard.
257
251
  """
258
-
259
252
  if mode not in ("foreground", "messages"):
260
253
  raise InputError(f"unknown delivery mode: {mode}")
261
-
254
+ if (not isinstance(command, str) or not command.startswith("/")
255
+ or len(command.encode("utf-8")) > 255
256
+ or any(ord(char) < 32 or ord(char) == 127 for char in command)):
257
+ raise InputError("expected one slash command of at most 255 UTF-8 bytes")
262
258
  if mode == "messages":
263
- confirm_window(hwnd, pid=pid, exe_path=exe_path)
264
- send_command_messages(hwnd, command)
259
+ send_command_messages(hwnd, command, pid=pid, exe_path=exe_path)
265
260
  return
266
-
267
261
  if clipboard is None:
268
262
  clipboard = Clipboard()
269
- confirm_window(hwnd, pid=pid, exe_path=exe_path)
263
+ identity = confirm_window(hwnd, pid=pid, exe_path=exe_path)
264
+ # Freeze inferred identity too: callers need not supply both fields.
265
+ pid, exe_path = identity.pid, identity.exe_path
270
266
  focus_window(hwnd, pid=pid, exe_path=exe_path)
267
+ deadline = time.monotonic() + 5.0
268
+
269
+ def guard():
270
+ confirm_window(hwnd, pid=pid, exe_path=exe_path)
271
+ if not is_foreground(hwnd):
272
+ raise InputError("game lost foreground; input cancelled without retry")
273
+ if time.monotonic() >= deadline:
274
+ raise InputError("command input timed out; input cancelled without retry")
275
+
276
+ def key(vk, *, ctrl=False):
277
+ guard()
278
+ _send_key(vk, ctrl=ctrl)
279
+ time.sleep(0.10)
280
+ guard()
271
281
 
272
282
  previous = clipboard.read_text()
273
- clipboard.copy_text(command)
274
- if clipboard.read_text() != command:
275
- raise InputError("the clipboard did not accept the command text")
283
+ sentinel = "lycheedev-readback-" + uuid.uuid4().hex
284
+ owned = {command, sentinel}
276
285
  try:
286
+ # Open chat through the slash binding, never an initial Return: even
287
+ # an ignored Escape must not submit an existing public-chat draft.
288
+ key(VK_ESCAPE)
289
+ key(VK_OEM_2)
290
+ key(VK_A, ctrl=True)
291
+ clipboard.copy_text(command)
292
+ if clipboard.read_text() != command:
293
+ raise InputError("the clipboard did not accept the command text")
294
+ key(VK_V, ctrl=True)
295
+ key(VK_A, ctrl=True)
296
+ # Reading back the original clipboard would prove nothing. A unique
297
+ # sentinel makes missing/ignored Ctrl+C distinguishable from success.
298
+ clipboard.copy_text(sentinel)
299
+ key(VK_C, ctrl=True)
300
+ for _ in range(20):
301
+ guard()
302
+ copied = clipboard.read_text()
303
+ if copied == command:
304
+ break
305
+ if copied != sentinel:
306
+ raise InputError("chat edit text differs from the prepared command")
307
+ time.sleep(0.025)
308
+ else:
309
+ raise InputError("could not verify chat edit text before submission")
310
+ guard()
277
311
  _send_key(VK_RETURN)
278
- time.sleep(0.15)
279
- _send_key(VK_V, ctrl=True)
280
- time.sleep(0.15)
281
- _send_key(VK_RETURN)
282
- time.sleep(0.05)
312
+ except BaseException:
313
+ # Never send cleanup keys into another app or resume a deferred submit.
314
+ try:
315
+ confirm_window(hwnd, pid=pid, exe_path=exe_path)
316
+ if is_foreground(hwnd):
317
+ _send_key(VK_ESCAPE)
318
+ except (WindowIdentityError, InputError):
319
+ pass
320
+ raise
283
321
  finally:
284
- if clipboard.read_text() == command:
322
+ if clipboard.read_text() in owned:
285
323
  if previous is None:
286
324
  clipboard.clear()
287
325
  else:
@@ -304,6 +342,7 @@ def focus_window(hwnd: int, *, pid: int | None = None,
304
342
  if user32.SetForegroundWindow(hwnd):
305
343
  time.sleep(0.10)
306
344
  if is_foreground(hwnd):
345
+ confirm_window(hwnd, pid=pid, exe_path=exe_path)
307
346
  return
308
347
  if attempt == attempts - 1:
309
348
  break
@@ -318,7 +357,7 @@ def focus_window(hwnd: int, *, pid: int | None = None,
318
357
  if not is_foreground(hwnd):
319
358
  raise InputError(
320
359
  "could not bring the game window to the foreground; click the game "
321
- "window once, or use `send --mode messages`")
360
+ "window once and retry the command")
322
361
 
323
362
 
324
363
  def _key_lparam(vk: int, *, up: bool = False) -> int:
@@ -331,21 +370,51 @@ def _key_lparam(vk: int, *, up: bool = False) -> int:
331
370
  return lparam
332
371
 
333
372
 
334
- def send_command_messages(hwnd: int, command: str, *, delay: float = 0.03) -> None:
335
- """Type ``command`` into ``hwnd`` by posting messages; no focus needed.
373
+ def send_command_messages(hwnd: int, command: str, *, delay: float = 0.05,
374
+ pid: int | None = None, exe_path: str | None = None) -> None:
375
+ """Submit through the target HWND's queue without changing foreground.
336
376
 
337
- The chat edit box must already be open and focused in the game, because the
338
- client routes posted keys to whatever widget has focus. Characters go out
339
- as WM_CHAR (the client re-encodes them for IME), and Return submits.
377
+ PostMessage acceptance only means queued input. It cannot prove chat focus
378
+ or text consumption; callers must wait for a matching game receipt.
340
379
  """
380
+ if (not isinstance(command, str) or not command.startswith("/")
381
+ or len(command.encode("utf-8")) > 255
382
+ or any(ord(char) < 32 or ord(char) == 127 for char in command)):
383
+ raise InputError("expected one slash command of at most 255 UTF-8 bytes")
384
+ identity = confirm_window(hwnd, pid=pid, exe_path=exe_path)
385
+ pid, exe_path = identity.pid, identity.exe_path
386
+ deadline = time.monotonic() + 20.0
387
+
388
+ def post(message, value, lparam):
389
+ confirm_window(hwnd, pid=pid, exe_path=exe_path)
390
+ if time.monotonic() >= deadline:
391
+ raise InputError("background input timed out; submission is unresolved")
392
+ if not user32.PostMessageW(hwnd, message, value, lparam):
393
+ raise InputError("target rejected background input; submission is unresolved")
394
+
395
+ def key(vk):
396
+ post(WM_KEYDOWN, vk, _key_lparam(vk))
397
+ post(WM_KEYUP, vk, _key_lparam(vk, up=True))
398
+ time.sleep(0.15)
341
399
 
342
- for char in command:
343
- if not user32.PostMessageW(hwnd, WM_CHAR, ord(char), 0):
344
- raise InputError("the client window rejected a character message")
345
- time.sleep(delay)
346
- if not user32.PostMessageW(hwnd, WM_KEYDOWN, VK_RETURN, _key_lparam(VK_RETURN)):
347
- raise InputError("the client window rejected the submit key")
348
- user32.PostMessageW(hwnd, WM_KEYUP, VK_RETURN, _key_lparam(VK_RETURN, up=True))
400
+ try:
401
+ key(VK_ESCAPE)
402
+ key(VK_RETURN)
403
+ # WM_CHAR carries UTF-16 code units, not Python's Unicode code points.
404
+ encoded = command.encode("utf-16-le")
405
+ for offset in range(0, len(encoded), 2):
406
+ post(WM_CHAR, int.from_bytes(encoded[offset:offset + 2], "little"), 1)
407
+ time.sleep(delay)
408
+ key(VK_RETURN)
409
+ except BaseException:
410
+ # Queue cleanup only to the still-bound HWND, never to the foreground.
411
+ try:
412
+ confirm_window(hwnd, pid=pid, exe_path=exe_path)
413
+ user32.PostMessageW(hwnd, WM_KEYDOWN, VK_ESCAPE, _key_lparam(VK_ESCAPE))
414
+ user32.PostMessageW(hwnd, WM_KEYUP, VK_ESCAPE, _key_lparam(VK_ESCAPE, up=True))
415
+ except WindowIdentityError:
416
+ pass
417
+ raise
349
418
 
350
419
 
351
420
  class Clipboard: