合并 main 的合并前复核修复到镜牢选队分支

Browse Source
分支从 8a9495b 分出,缺 main 上 a74fda0 的急停与驱动复核修复。
两边都保留,不取单边:

- 急停:沿用分支的 GetAsyncKeyState 轮询与 End 键(pynput 钩子在该
  机器收不到键,F12 是 Steam 截图键);移植 main 的 on_stop 释放驱动
  按住的鼠标键、250 毫秒强退兜底、listening() 管理监听生命周期。
  按键状态改为独立绑定(SHORT 返回值),接口不可用时启动即报告。
- 驱动输入:同时保留句柄级前台校验、press_ms/settle 与 main 的
  停止标志、输入锁和按键记录;点击经 down()/up() 以便急停释放。
  前台校验改用本模块的类型化 _api 绑定。
- 代理每次点击按当前句柄重新 bind_window:代理复用时不再拿安装时
  的旧句柄拒绝游戏重启后的全部点击。
- aalc_task:listening() 包住整个任务,内部安装两个选队补丁。
- 分支新增测试改为替换模块接口,不再直接 patch ctypes.windll
  (Linux 上 9 项报错);README 急停键改为 End。

验证:Linux / Python 3.12 全套 474 项通过;git diff --check 通过。
Windows 热键、驱动和选队仍需实机回归。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
yws
2026-11-14 03:19:53 +00:00
co-authored by Claude Opus 5.5
14 changed files with 490 additions and 182 deletions
+11 -2
View File
@@ -182,6 +182,10 @@ class DriverClickProxy:
handle.setForeground()
if foreground_window() != hwnd:
raise OSError('无法激活游戏窗口, 未发送驱动输入')
# 游戏重启后句柄会变; 每次按当前句柄重新绑定, 免得前台校验拿旧句柄拒绝所有点击。
bind = getattr(self._driver, 'bind_window', None)
if bind is not None:
bind(hwnd)
return client_to_screen(hwnd, x, y)
def _trace(self, msg):
@@ -228,8 +232,7 @@ class DriverClickProxy:
sx, sy = self._screen_pos(x, y)
if not self._driver.move_to(sx, sy):
return False
self._driver.down(1)
return True
return self._driver.down(1) is not False
def mouse_up(self, x, y):
try:
@@ -282,6 +285,12 @@ def install_driver_click(auto, screen, driver=None, log=print):
return drv
def stop_driver_click(auto):
handler = auto.input_handler
if isinstance(handler, DriverClickProxy):
handler._driver.emergency_stop()
@contextmanager
def driver_click_tasks(scheme, auto, screen, cfg, log=print):
"""每次游戏初始化完成后接管, 包括 all 任务和故障重启。"""
+46 -50
View File
@@ -9,12 +9,11 @@ import json
import os
import sys
from . import preflight
from . import killswitch, preflight
from .aalc_engine import bootstrap
from . import killswitch
from .aalc_patches import (WindowGuard, driver_click_tasks, install_default_battle_team,
install_exact_team_match, install_robust_set_foreground,
install_system_team_selection)
install_system_team_selection, stop_driver_click)
# 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效
TASKS = {
@@ -77,55 +76,52 @@ def run(task, params):
from tasks.battle import battle
from utils.path_manager import path_manager
# 急停热键: 装得越早越好。驱动级点击期间鼠标被人和程序抢来抢去,
# 用户没法用鼠标点停止按钮, 键盘是唯一可靠的中断手段。
kill_listener = killswitch.install(log=log)
with killswitch.listening(log=log, on_stop=lambda: stop_driver_click(auto)):
problems = preflight.check(preflight.collect(cfg), task,
desktop=None if cfg.simulator else preflight.desktop_size())
if problems:
for p in problems:
log('[ERROR] [lc_mcp] preflight: %s' % p)
return PREFLIGHT_EXIT
problems = preflight.check(preflight.collect(cfg), task,
desktop=None if cfg.simulator else preflight.desktop_size())
if problems:
for p in problems:
log('[ERROR] [lc_mcp] preflight: %s' % p)
return PREFLIGHT_EXIT
install_exact_team_match(auto, log)
install_robust_set_foreground(screen, log=log)
# 日常本(经验/纽本)不翻队伍列表: 队伍是自定义名字时按名字找必然失败,
# 白等 60 秒还会把界面滚乱, 后面 to_battle 就找不到 "进入战斗" 了。
if task in ('daily', 'all'):
install_default_battle_team(scheme, log=log)
# 镜牢: 编队是自定义名字(体系名), AALC 只会找 "编队#N"; 改成按体系名点选。
if task in ('mirror', 'all'):
install_system_team_selection(log=log)
guard = WindowGuard(screen, cfg, log=log)
guard.start()
restore_path = os.environ.get(RESTORE_ENV)
originals = apply_overrides(cfg, task, params, restore_path)
with driver_click_tasks(scheme, auto, screen, cfg, log=log):
try:
if task == 'all':
scheme.script_task()
install_exact_team_match(auto, log)
install_robust_set_foreground(screen, log=log)
# 日常本(经验/纽本)不翻队伍列表: 队伍是自定义名字时按名字找必然失败,
# 白等 60 秒还会把界面滚乱, 后面 to_battle 就找不到 "进入战斗" 了。
if task in ('daily', 'all'):
install_default_battle_team(scheme, log=log)
# 镜牢: 编队是自定义名字(体系名), AALC 只会找 "编队#N"; 改成按体系名点选。
if task in ('mirror', 'all'):
install_system_team_selection(log=log)
guard = WindowGuard(screen, cfg, log=log)
guard.start()
restore_path = os.environ.get(RESTORE_ENV)
originals = apply_overrides(cfg, task, params, restore_path)
with driver_click_tasks(scheme, auto, screen, cfg, log=log):
try:
if task == 'all':
scheme.script_task()
return 0
# 与 script_task() 相同的前置步骤
scheme.init_game()
path_manager.initialize_paths()
auto.clear_img_cache()
retry_monitor.start()
get_reward = None
if auto.click_element('battle/turn_assets.png', take_screenshot=True):
print('[lc_mcp] 检测到正在战斗, 先打完', flush=True)
get_reward = battle.fight()
{
'daily': scheme.Daily_task_wrapper(get_reward=get_reward),
'reward': scheme.to_get_reward,
'enkephalin': scheme.Buy_enkephalin,
'mirror': scheme.Mirror_task,
}[task]()
return 0
# 与 script_task() 相同的前置步骤
scheme.init_game()
path_manager.initialize_paths()
auto.clear_img_cache()
retry_monitor.start()
get_reward = None
if auto.click_element('battle/turn_assets.png', take_screenshot=True):
print('[lc_mcp] 检测到正在战斗, 先打完', flush=True)
get_reward = battle.fight()
{
'daily': scheme.Daily_task_wrapper(get_reward=get_reward),
'reward': scheme.to_get_reward,
'enkephalin': scheme.Buy_enkephalin,
'mirror': scheme.Mirror_task,
}[task]()
return 0
finally:
guard.stop()
retry_monitor.stop()
restore(cfg, originals, restore_path)
finally:
guard.stop()
retry_monitor.stop()
restore(cfg, originals, restore_path)
def main(argv):
+48 -22
View File
@@ -22,6 +22,7 @@
import ctypes
import os
import time
import threading
from ctypes import wintypes
from functools import lru_cache
@@ -60,6 +61,14 @@ def foreground_window():
return _api('user32', 'GetForegroundWindow', wintypes.HWND, [])()
def window_title(hwnd, limit=64):
"""窗口标题, 只用于报错说明; 取不到返回空串。"""
buf = ctypes.create_unicode_buffer(limit)
_api('user32', 'GetWindowTextW', ctypes.c_int,
[wintypes.HWND, wintypes.LPWSTR, ctypes.c_int])(hwnd, buf, limit)
return buf.value
def is_console_session():
current = wintypes.DWORD()
query = _api('kernel32', 'ProcessIdToSessionId', wintypes.BOOL,
@@ -106,6 +115,9 @@ class DriverInput:
self.log = log
self._dll = None
self._open = False
self._stopped = False
self._input_lock = threading.RLock()
self._pressed = set()
# 目标窗口句柄。有它才能做句柄级前台校验 —— 几何校验在窗口重叠时没用:
# 实测把浏览器切到前台, 点游戏里同一个坐标, 只比矩形的话校验照样通过。
self.hwnd = 0
@@ -139,7 +151,14 @@ class DriverInput:
@property
def ready(self):
return self._open and self._dll is not None
return self._open and self._dll is not None and not self._stopped
def emergency_stop(self):
"""拒绝后续鼠标输入并释放本实例按住的按钮。急停线程另有退出超时。"""
self._stopped = True
with self._input_lock:
for button in tuple(self._pressed):
self.up(button)
def preflight(self):
"""返回 (能否用, 原因)。用之前调一次, 把不能用的原因说清楚。"""
@@ -160,12 +179,13 @@ class DriverInput:
# ---------------------------------------------------------------- 移动
def move_relative(self, dx, dy):
if not self.ready:
return False
if dx == 0 and dy == 0:
with self._input_lock:
if not self.ready:
return False
if dx == 0 and dy == 0:
return True
self._dll.moveR(int(dx), int(dy), True)
return True
self._dll.moveR(int(dx), int(dy), True)
return True
def move_to(self, sx, sy, tol=1, iters=10, settle=0.03):
"""把光标精确移到屏幕坐标 (sx, sy)。返回是否到位。"""
@@ -185,12 +205,19 @@ class DriverInput:
# ---------------------------------------------------------------- 按键
def down(self, button=1):
if self.ready:
self._dll.mouse_down(int(button))
with self._input_lock:
if not self.ready:
return False
button = int(button)
self._pressed.add(button)
self._dll.mouse_down(button)
return True
def up(self, button=1):
if self.ready:
self._dll.mouse_up(int(button))
with self._input_lock:
if self._open and self._dll is not None:
self._dll.mouse_up(int(button))
self._pressed.discard(int(button))
def click(self, sx, sy, times=1, tol=1, require_foreground=True,
press_ms=60, settle=0.05):
@@ -222,11 +249,12 @@ class DriverInput:
time.sleep(settle)
for _ in range(int(times)):
try:
self._dll.mouse_down(1)
if not self.down(1):
return False
time.sleep(press_ms / 1000.0)
finally:
self._dll.mouse_up(1)
return True
self.up(1)
return not self._stopped
def key_down(self, key):
if self.ready:
@@ -254,22 +282,20 @@ def click_point_is_on_foreground(sx, sy, hwnd=None):
所以: 给了 hwnd 就要求前台窗口**就是它**(或是它的子窗口); 没给 hwnd 时
退化成"有前台窗口且点在它矩形内", 可用性有限, 仅作兜底。
"""
user32 = ctypes.windll.user32
fg = user32.GetForegroundWindow()
fg = foreground_window()
if not fg:
return False, '当前没有前台窗口(GetForegroundWindow=0)'
if hwnd:
if fg == hwnd or user32.IsChild(hwnd, fg):
if fg == hwnd or _api('user32', 'IsChild', wintypes.BOOL,
[wintypes.HWND, wintypes.HWND])(hwnd, fg):
return True, 'ok'
buf = ctypes.create_unicode_buffer(64)
user32.GetWindowTextW(fg, buf, 64)
other = ctypes.create_unicode_buffer(64)
user32.GetWindowTextW(hwnd, other, 64)
return False, ('前台不是目标窗口(前台=%r, 目标=%r) —— 这次点击会打到别的窗口'
% (buf.value, other.value))
% (window_title(fg), window_title(hwnd)))
pt = wintypes.POINT(int(sx), int(sy))
rect = wintypes.RECT()
if not user32.GetWindowRect(fg, ctypes.byref(rect)):
get_rect = _api('user32', 'GetWindowRect', wintypes.BOOL,
[wintypes.HWND, ctypes.POINTER(wintypes.RECT)])
if not get_rect(fg, ctypes.byref(rect)):
return False, '取不到前台窗口的区域'
if not (rect.left <= pt.x < rect.right and rect.top <= pt.y < rect.bottom):
return False, ('点击点(%d,%d)不在前台窗口内(区域 %d,%d-%d,%d)'
+78 -21
View File
@@ -18,19 +18,25 @@
默认 End(小键盘区右下角, 好按且不冲突), 可用环境变量 LCP_KILL_KEY 改成 pause / scrolllock / f11 等。
⛔ 不要用 F12: 那是 Steam 的截图键(用户 2026-10-22 指出), 按下去会弹 Steam 截图
覆盖层, 而且可能被 Steam 抢先消费。Esc / F11 也不合适 —— 游戏里分别是关菜单
和切全屏。Pause 没有任何软件抢, 是最稳的选择。
按下后直接 os._exit —— 任务本来就是子进程, 硬退出不留锁或半截状态, 这与
aalc_task.py "停止 = 杀进程树" 的设计前提一致。监听器活在任务进程内,
所以即使 MCP 服务出问题、用户联系不上调用方, 按热键仍然能停。
和切全屏。
按下后终止任务子进程, 游戏保留。硬退出不会执行任务的 finally; 临时配置由
TaskRunner 的恢复文件机制处理。退出前先给驱动释放按住的鼠标键(on_stop),
清理或日志卡住时 STOP_TIMEOUT 后仍强制退出。监听器活在任务进程内, 所以即使
MCP 服务出问题、用户联系不上调用方, 按热键仍然能停。
"""
import ctypes
import os
import threading
import time
from contextlib import contextmanager
from functools import lru_cache
DEFAULT_KEY = 'end'
EXIT_CODE = 130 # 与 SIGINT 一致, 便于上层识别"被用户中止"
POLL_INTERVAL = 0.05 # 50ms 轮询, 人手按一下不会漏
STOP_TIMEOUT = 0.25 # 释放鼠标/写日志最多等这么久, 然后强退
START_DELAY = 0.3 # 先等一会儿, 避免把启动时按住的键当成急停
# 常用键 -> 虚拟键码。f12 保留是为了兼容旧配置, 但**不推荐** —— Steam 占用它。
VK = {
@@ -51,18 +57,28 @@ def resolve_vk(key):
return VK.get(name)
@lru_cache(maxsize=None)
def _key_state_api():
"""独立绑定 GetAsyncKeyState, 不改共用的 ctypes.windll 的类型声明。"""
fn = ctypes.WinDLL('user32', use_last_error=True).GetAsyncKeyState
fn.argtypes = [ctypes.c_int]
fn.restype = ctypes.c_short
return fn
def _pressed(vk):
"""GetAsyncKeyState 的最高位 = 当前是否按下。"""
return bool(ctypes.windll.user32.GetAsyncKeyState(vk) & 0x8000)
"""GetAsyncKeyState 的最高位 = 当前是否按下(低位只表示"按过", 不算)。"""
return bool(_key_state_api()(vk) & 0x8000)
class KillSwitch:
"""轮询线程。按住热键会立刻退出, 不会重复触发。"""
def __init__(self, vk, log=print, key_name=DEFAULT_KEY):
def __init__(self, vk, log=print, key_name=DEFAULT_KEY, on_stop=None):
self.vk = vk
self.log = log
self.key_name = key_name
self.on_stop = on_stop
self.fired = False
self._stopped = threading.Event()
self._thread = threading.Thread(target=self._run, daemon=True,
@@ -79,28 +95,54 @@ class KillSwitch:
self._stopped.set()
def _run(self):
# 先等一会儿, 避免把启动时按住的键当成急停
time.sleep(0.3)
if self._stopped.wait(START_DELAY):
return
while not self._stopped.is_set():
if _pressed(self.vk):
try:
pressed = _pressed(self.vk)
except Exception as e: # 接口失效: 说清楚后退出, 不刷满异常
try:
self.log('[lc_mcp] 急停热键失效(%s: %s), 请用 stop_task 或 Ctrl+Alt+Del 停止'
% (type(e).__name__, e))
except Exception:
pass
return
if pressed:
self._fire()
return
time.sleep(POLL_INTERVAL)
self._stopped.wait(POLL_INTERVAL)
def _fire(self):
if self.fired:
return
self.fired = True
# 释放驱动按键或写日志卡住时, 由计时器按时强退。
timer = threading.Timer(STOP_TIMEOUT, os._exit, args=(EXIT_CODE,))
timer.daemon = True
try:
self.log('[lc_mcp] ⛔ 急停热键 %s 被按下, 立即终止任务'
% self.key_name.upper())
self.log('[lc_mcp] 游戏窗口会保留, 可用 run_task 重新开始')
timer.start()
try:
if self.on_stop is not None:
self.on_stop()
except Exception:
pass # 释放失败也必须退出
try:
self.log('[lc_mcp] ⛔ 急停热键 %s 被按下, 终止任务; 游戏窗口保留, 可用 run_task 重新开始'
% self.key_name.upper())
except Exception:
pass # 日志坏了不能拦住急停
finally:
os._exit(EXIT_CODE)
try:
os._exit(EXIT_CODE)
finally:
timer.cancel() # 仅在测试替换 _exit 时才会走到
def install(log=print, key=None):
"""启动急停轮询线程。返回 KillSwitch, 失败返回 None(不抛异常)。"""
def install(log=print, key=None, on_stop=None):
"""启动急停轮询线程。返回 KillSwitch, 失败返回 None(不抛异常)。
急停装不上不该让任务起不来, 但必须把原因和应急手段说清楚。
"""
key = key or os.environ.get('LCP_KILL_KEY') or DEFAULT_KEY
vk = resolve_vk(key)
if vk is None:
@@ -108,21 +150,36 @@ def install(log=print, key=None):
% (key, ', '.join(sorted(VK))))
return None
try:
switch = KillSwitch(vk, log=log, key_name=key).start()
_key_state_api()
except Exception as e: # 非 Windows / user32 不可用
log('[lc_mcp] 急停热键不可用(读取键盘状态失败: %s: %s), 请用 Ctrl+Alt+Del 强制停止'
% (type(e).__name__, e))
return None
try:
switch = KillSwitch(vk, log=log, key_name=key, on_stop=on_stop).start()
except Exception as e:
log('[lc_mcp] 急停热键启动失败(%s: %s), 请用 Ctrl+Alt+Del 强制停止'
% (type(e).__name__, e))
return None
log('[lc_mcp] 急停热键已就绪: 按 %s 立即停止任务(键盘可用, 不需要鼠标, '
'也不依赖 MCP 服务)' % key.upper())
log('[lc_mcp] 急停热键已就绪: 按 %s 终止任务, 游戏窗口保留; 可用 run_task 重新开始'
'(键盘可用, 不需要鼠标, 也不依赖 MCP 服务)' % key.upper())
return switch
def stop(switch):
"""停止轮询(任务正常结束时调用)。"""
"""停止轮询(任务结束时调用, 免得线程残留)。"""
if switch is None:
return
try:
switch.stop()
except Exception:
pass
@contextmanager
def listening(log=print, on_stop=None):
switch = install(log=log, on_stop=on_stop)
try:
yield switch
finally:
stop(switch)
+3 -1
View File
@@ -12,6 +12,7 @@ import time
from collections import deque
from .aalc_task import RESTORE_ENV
from .killswitch import EXIT_CODE as USER_ABORT_EXIT
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
IS_WIN = sys.platform.startswith('win')
@@ -186,7 +187,8 @@ class TaskRunner:
state = 'running'
else:
self.info.setdefault('ended', time.time())
state = 'stopped' if self.info['stopped_by_user'] else 'succeeded' if code == 0 else 'failed'
state = ('stopped' if self.info['stopped_by_user'] or code == USER_ABORT_EXIT
else 'succeeded' if code == 0 else 'failed')
r = {'ok': True, 'state': state, 'task': self.info['task'], 'params': self.info['params'],
'elapsed_s': int((self.info.get('ended') or time.time()) - self.info['started']),
'log': self.info['log'], 'log_tail': tail(self.info['log'], max(1, min(int(lines), 200)))}