From 2190f57abeba9c467603cab611f80a417230c491 Mon Sep 17 00:00:00 2001 From: ywsabc2 Date: Tue, 13 Oct 2026 03:12:19 +0000 Subject: [PATCH] =?UTF-8?q?=E6=97=A0=E4=BA=BA=E5=80=BC=E5=AE=88=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E5=8C=96:=20=E9=85=8D=E7=BD=AE=E9=A2=84=E6=A3=80?= =?UTF-8?q?=E3=80=81=E9=80=89=E9=98=9F=E7=B2=BE=E7=A1=AE=E5=8C=B9=E9=85=8D?= =?UTF-8?q?=E3=80=81=E7=AA=97=E5=8F=A3=E5=AE=88=E6=8A=A4=E3=80=81=E5=8D=A1?= =?UTF-8?q?=E6=AD=BB=E9=87=8D=E8=B7=91=E3=80=81=E8=AE=A1=E5=88=92=E4=BB=BB?= =?UTF-8?q?=E5=8A=A1,=20AALC=20=E5=8D=87=E7=BA=A7=E5=88=B0=20b0f4393?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - lc_mcp/preflight.py: 启动前拦截 sinner_order 全 0、会花狂气、窗口放不进桌面 (退出码 3) - lc_mcp/aalc_patches.py: 队伍名按编号精确匹配 (TEAMS #1 不再命中 #10); 后台守护客户区 16:9 - auto_cycle.py: AALC 卡死后停掉重跑; --mirror 打镜牢; 每轮写 cycle_*.log/.json 报告 - install_unattended.ps1: 注册会话看门狗 (每 5 分钟) 与每日一轮计划任务 - lc_ui.py: pythonw 启动时子进程改用 python 且不弹窗 - vendor/aalc: 7452fad -> b0f4393 (镜牢楼层识别、困牢奖励、排队启动修复) Co-Authored-By: Claude Opus 5.5 --- README.md | 30 ++++++ lc_mcp/aalc_patches.py | 96 +++++++++++++++++++ lc_mcp/aalc_task.py | 27 +++++- lc_mcp/preflight.py | 72 ++++++++++++++ scripts/auto_cycle.py | 160 ++++++++++++++++++++----------- scripts/install_unattended.ps1 | 74 +++++++++++++++ scripts/lc_ui.py | 16 +++- tests/test_auto_cycle.py | 84 ++++++++++++++++ tests/test_preflight_patches.py | 163 ++++++++++++++++++++++++++++++++ vendor/aalc | 2 +- 10 files changed, 664 insertions(+), 60 deletions(-) create mode 100644 lc_mcp/aalc_patches.py create mode 100644 lc_mcp/preflight.py create mode 100644 scripts/install_unattended.ps1 create mode 100644 tests/test_auto_cycle.py create mode 100644 tests/test_preflight_patches.py diff --git a/README.md b/README.md index 574e25e..e7c3e3a 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,34 @@ codex mcp add limbus --env PYTHONUTF8=1 -- D:\lc-mcp\vendor\aalc\.venv\Scripts\p `超出最大尝试次数,未能进入战斗`)后仍会继续跑完并正常退出,所以 `task_status` 会把日志尾部的 `[ERROR]`/异常行放进 `errors` 字段:**看到 `succeeded` 也要先看 `errors`。** +任务运行中如果 `task_status` 带 `stall` 字段,说明 AALC 在原地空转(例如选中了空队伍, +编队人数检查一直刷屏)。它不会自己报错退出,应当 `stop_task` 后重跑。 + +### 任务进程里的保护 + +`run_task` 启动的任务子进程在调用 AALC 之前会做三件事,都不改 `vendor/aalc` 源码: + +- **配置预检**:发现下列问题就直接拒绝启动(退出码 3,原因写在 `errors` 里): + - 镜牢队伍的 `sinner_order` 全是 0:这会让 AALC 选出空队伍,然后无限重试编队; + - `set_lunacy_to_enkephalin` 不为 0:体力不足时会花狂气换体力。确需使用时设 `LCP_ALLOW_LUNACY=1`; + - `set_win_size` 加上标题栏后放不进当前桌面:窗口会被压扁成非 16:9。 +- **队伍名精确匹配**:AALC 按子串找队伍,`TEAMS #1` 会命中 `TEAMS #10`。补丁要求编号完全相同。 +- **窗口比例守护**:每 15 秒检查一次客户区。RDP 重连后窗口被拉伸时,自动调回 `set_win_size` 对应的 16:9 尺寸。 + +## 无人值守 + +`scripts/auto_cycle.py` 每次跑一轮,流程是:刷材料(daily)→ 镜牢(`--mirror N`)→ 把队内人格升级、同步到 `--target`。 +AALC 卡死时,脚本会停掉任务并重跑一次。每轮在 `~/lc_mcp/cycles/` 写一份 `cycle_*.log` 和一份 `cycle_*.json` 报告。 + +```powershell +# 先手动跑一轮确认 +vendor\aalc\.venv\Scripts\python.exe scripts\auto_cycle.py --mirror 1 +# 再注册计划任务: 每 5 分钟的会话看门狗 + 每天 05:30 一轮 +powershell -ExecutionPolicy Bypass -File scripts\install_unattended.ps1 -At 05:30 -Mirror 1 +``` + +`scripts/levelup.py` 和 `auto_cycle.py` 里的坐标都按 1600×900 客户区书写,运行时会按实际客户区大小缩放。 + ## 环境变量 | 变量 | 默认 | 说明 | @@ -104,6 +132,8 @@ codex mcp add limbus --env PYTHONUTF8=1 -- D:\lc-mcp\vendor\aalc\.venv\Scripts\p | `AALC_DIR` | `vendor/aalc` | 使用其他位置的 AALC 源码 | | `LCP_PORT` | 8765 | 服务/bridge 端口 | | `LCP_KEEP_SHOTS` | 30 | 截图保留张数 | +| `LCP_ALLOW_LUNACY` | 未设置 | 设为 `1` 时允许预检放行 `set_lunacy_to_enkephalin` 不为 0 的配置 | +| `LC_PY` | 当前解释器 | `levelup.py`/`auto_cycle.py` 调用 MCP 用的 Python | ## 开发 / 测试 diff --git a/lc_mcp/aalc_patches.py b/lc_mcp/aalc_patches.py new file mode 100644 index 0000000..57d8e5a --- /dev/null +++ b/lc_mcp/aalc_patches.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +"""任务子进程里对 AALC 的运行时补丁。不改 vendor/aalc 的源码。 + +1. 队伍名精确匹配 + AALC 的 find_str_in_text 用子串匹配, "TEAMS #1" 会命中 "TEAMS #10"(中文 "编队#1" + 同理)。账号有 10 个以上预设时就会选中别的(常常是空)队伍, 然后在编队人数检查里 + 无限空转——2026-10-05 一次空转了 27 分钟。这里只接管队伍名这一种目标, 要求编号 + 完全相同, 其他文本仍走 AALC 原逻辑。 + +2. 窗口比例守护 + RDP 重连改变桌面分辨率后, Unity 会把窗口拉伸成非 16:9。AALC 只在任务开始时校正 + 一次, 之后全部模板匹配分数掉到阈值以下, 表现为原地空转、不报错。这里在后台定期 + 检查客户区尺寸, 偏离 set_win_size 时调回去。 +""" +import re +import threading +import time + +TEAM_TARGET = re.compile(r'(?:TEAMS|TFAMS|编队)#(\d+)', re.IGNORECASE) + + +def team_number(text): + """'TEAMS #12' / 'TFAMS#3' / '编队#1' -> '12' / '3' / '1'; 不是队伍名返回 None。""" + m = TEAM_TARGET.fullmatch(text.replace(' ', '').strip()) + return m.group(1) if m else None + + +def find_team_text(want, ocr_dict): + """在 OCR 结果里找编号恰好为 want 的队伍名, 返回其坐标或 False。""" + for text, position in ocr_dict.items(): + for hit in TEAM_TARGET.finditer(text.replace(' ', '')): + if hit.group(1) == want: + return position + return False + + +def install_exact_team_match(auto, log=print): + original = auto.find_str_in_text + + def find_str_in_text(target, ocr_dict): + want = team_number(str(target)) + if want is None: + return original(target, ocr_dict) + return find_team_text(want, ocr_dict) + + auto.find_str_in_text = find_str_in_text + log('[lc_mcp] patch: 队伍名改为编号精确匹配') + + +class WindowGuard(threading.Thread): + """后台检查游戏客户区, 不是 set_win_size 对应的 16:9 尺寸就调回去。""" + + def __init__(self, screen, cfg, interval=15.0, log=print): + super().__init__(name='lc_mcp-window-guard', daemon=True) + self.screen, self.cfg, self.interval, self.log = screen, cfg, interval, log + self.stopped = threading.Event() + self.fixes = 0 + self._failed = None # 同一尺寸调不回来只报一次, 免得每 15 秒刷一条 ERROR + + def want(self): + size = int(self.cfg.set_win_size) + return int(size * 16 / 9), size + + def check_once(self): + """返回 'ok' / 'fixed' / 'failed' / None(没有可检查的窗口)。""" + handle = self.screen.handle + # set_windows 关闭表示用户自己管窗口, AALC 也不调, 这里同样不插手 + if self.cfg.simulator or not self.cfg.set_windows or not handle._hwnd or handle.isMinimized: + return None + current = (handle.width(True), handle.height(True)) + want = self.want() + if current == want or 0 in current: + return 'ok' if current == want else None + self.screen.adjust_win_size(want) + time.sleep(1) + after = (handle.width(True), handle.height(True)) + if after == want: + self.fixes += 1 + self._failed = None + self.log('[lc_mcp] window guard: 客户区 %sx%s 已调回 %sx%s' % (current + want)) + return 'fixed' + if after != self._failed: + self._failed = after + self.log('[ERROR] [lc_mcp] window guard: 客户区 %sx%s 调整后仍为 %sx%s(目标 %sx%s),' + ' 桌面可能放不下窗口' % (current + after + want)) + return 'failed' + + def run(self): + while not self.stopped.wait(self.interval): + try: + self.check_once() + except Exception as e: # 守护线程不能把任务带崩 + self.log('[lc_mcp] window guard: 检查出错 %s: %s' % (type(e).__name__, e)) + + def stop(self): + self.stopped.set() diff --git a/lc_mcp/aalc_task.py b/lc_mcp/aalc_task.py index 06bf31f..c05b7e8 100644 --- a/lc_mcp/aalc_task.py +++ b/lc_mcp/aalc_task.py @@ -9,7 +9,9 @@ import json import os import sys +from . import preflight from .aalc_engine import bootstrap +from .aalc_patches import WindowGuard, install_exact_team_match # 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效 TASKS = { @@ -20,6 +22,11 @@ TASKS = { 'mirror': {'count': 'set_mirror_count'}, } RESTORE_ENV = 'LCP_RESTORE_FILE' +PREFLIGHT_EXIT = 3 + + +def log(msg): + print(msg, flush=True) def apply_overrides(cfg, task, params, restore_path=None): @@ -61,17 +68,28 @@ def run(task, params): bootstrap() from module.automation import auto from module.config import cfg + from module.game_and_screen import screen from tasks.base import script_task_scheme as scheme from tasks.base.retry_monitor import retry_monitor from tasks.battle import battle from utils.path_manager import path_manager + 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) + guard = WindowGuard(screen, cfg, log=log) + guard.start() restore_path = os.environ.get(RESTORE_ENV) originals = apply_overrides(cfg, task, params, restore_path) try: if task == 'all': scheme.script_task() - return + return 0 # 与 script_task() 相同的前置步骤 scheme.init_game() path_manager.initialize_paths() @@ -87,7 +105,9 @@ def run(task, params): 'enkephalin': scheme.Buy_enkephalin, 'mirror': scheme.Mirror_task, }[task]() + return 0 finally: + guard.stop() retry_monitor.stop() restore(cfg, originals, restore_path) @@ -107,7 +127,10 @@ def main(argv): print('unknown params for %s: %s' % (task, ', '.join(sorted(unknown))), file=sys.stderr) return 2 print('[lc_mcp] task %s start %s' % (task, json.dumps(params)), flush=True) - run(task, params) + code = run(task, params) + if code: + print('[lc_mcp] task %s aborted (exit %s)' % (task, code), flush=True) + return code print('[lc_mcp] task %s done' % task, flush=True) return 0 diff --git a/lc_mcp/preflight.py b/lc_mcp/preflight.py new file mode 100644 index 0000000..eabd55f --- /dev/null +++ b/lc_mcp/preflight.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +"""任务启动前的配置检查。 + +10-04/05 的几次长时间空转都源于配置: AALC 不报错, 只是一直原地打转。 +这里把已知的坑在启动前拦下来, 返回人能看懂的原因。 + +check() 只吃普通 dict, 不依赖 AALC, 便于单测; collect() 负责从 AALC cfg 取值。 +""" +import os + +# 窗口边框 + 标题栏(100% 缩放下实测 16x39, 留一点余量) +FRAME_W, FRAME_H = 16, 40 +ALLOW_LUNACY_ENV = 'LCP_ALLOW_LUNACY' + + +def collect(cfg): + teams = {} + for key, team in (cfg.get_value('teams') or {}).items(): + data = team.model_dump() if hasattr(team, 'model_dump') else dict(team) + teams[str(key)] = data + return { + 'simulator': bool(cfg.get_value('simulator')), + 'mirror': bool(cfg.get_value('mirror')), + 'set_win_size': int(cfg.get_value('set_win_size')), + 'set_lunacy_to_enkephalin': int(cfg.get_value('set_lunacy_to_enkephalin') or 0), + 'teams_active_queue': list(cfg.get_value('teams_active_queue') or []), + 'teams': teams, + } + + +def desktop_size(): + """主显示器分辨率(进程已由 bootstrap 设为 DPI aware, 取到的是物理像素)。""" + from ctypes import windll + return windll.user32.GetSystemMetrics(0), windll.user32.GetSystemMetrics(1) + + +def check(values, task, desktop=None, env=None): + """返回问题列表; 空列表表示可以启动。""" + env = os.environ if env is None else env + problems = [] + + lunacy = values.get('set_lunacy_to_enkephalin', 0) + if lunacy and task != 'enkephalin' and env.get(ALLOW_LUNACY_ENV) != '1': + problems.append( + 'set_lunacy_to_enkephalin=%s: 体力不足时会花狂气换体力。狂气只用于抽卡, 请在 AALC 里改成 0' + '(确需使用时设环境变量 %s=1)' % (lunacy, ALLOW_LUNACY_ENV)) + + # all 只在 AALC 里勾选了镜牢时才会编队 + if task == 'mirror' or (task == 'all' and values.get('mirror')): + teams = values.get('teams', {}) + for num in values.get('teams_active_queue', []): + team = teams.get(str(num)) + if team is None: + problems.append('teams_active_queue 里的队伍 %s 没有配置' % num) + continue + order = list(team.get('sinner_order') or []) + # team_formation 从 1 开始按顺序找罪人, 缺 1 就一个都不选, 然后无限重试编队 + if 1 not in order: + problems.append( + '队伍 %s 的 sinner_order 没有罪人(全是 0): 镜牢编队会选空队伍并无限重试。' + '在 AALC 队伍设置里勾选罪人并排序' % num) + + if not values.get('simulator') and desktop: + size = values.get('set_win_size', 0) + need_w = int(size * 16 / 9) + FRAME_W + need_h = size + FRAME_H + if need_w > desktop[0] or need_h > desktop[1]: + problems.append( + 'set_win_size=%s 需要 %sx%s 的窗口(含标题栏), 桌面只有 %sx%s: 窗口会被压扁成非 16:9,' + ' 模板匹配全部失效。改小 set_win_size(如 720)或调大桌面分辨率' + % (size, need_w, need_h, desktop[0], desktop[1])) + return problems diff --git a/scripts/auto_cycle.py b/scripts/auto_cycle.py index fc2f6ec..cdcdca4 100644 --- a/scripts/auto_cycle.py +++ b/scripts/auto_cycle.py @@ -1,12 +1,17 @@ # -*- coding: utf-8 -*- -"""一轮自动推进: 刷材料 -> 升级最弱人格 -> 同步 -> 报告。 +"""一轮自动推进: 刷材料 -> (镜牢) -> 升级最弱人格 -> 同步 -> 报告。 -用法: python auto_cycle.py [--rounds N] +用法: python auto_cycle.py [--mirror N] [--target LV] [--retries N] [--report-dir DIR] 退出码: 0 正常完成一轮 / 1 失败 +每轮在 report-dir(默认 ~/lc_mcp/cycles)写一份 cycle_<时间>.log 与同名 .json 报告, +计划任务无人值守跑完后据此核对。 + 设计: 只做"一轮",不做无限循环——由外层(goal 轮次)负责重复与判断, 避免无人监督地长时间空转。每轮输出结构化报告供上层核对。 """ +import argparse +import json import os import time @@ -21,14 +26,25 @@ BACK = (85, 75) # 只在 Sinners 内部退层用, 主界面上按 BTN_SINNERS = (1130, 805) # 主界面底部 Sinners TAB_ALL_IDENTITIES = (1472, 245) # TEAMS 页 -> All Identities -# daily 轮询上限 +# AALC 任务轮询上限 DAILY_TIMEOUT_S = 45 * 60 -# task_status 连续几次报 stall 就判定卡死并停任务(每次轮询间隔 60 秒) +MIRROR_TIMEOUT_S = 70 * 60 # 每局镜牢; 10-04 首次一局 39 分钟 +POLL_S = 60 +# task_status 连续几次报 stall 就判定卡死并停任务 STALL_POLLS = 2 +# 卡死后重跑次数。AALC 任务开头会自己回主界面, 重跑通常就能脱困 +STALL_RETRIES = 1 +DEFAULT_REPORT_DIR = os.path.expanduser(os.path.join('~', 'lc_mcp', 'cycles')) + +_log_file = None def log(msg): - print('[%s] %s' % (time.strftime('%H:%M:%S'), msg), flush=True) + line = '[%s] %s' % (time.strftime('%H:%M:%S'), msg) + print(line, flush=True) + if _log_file: + with open(_log_file, 'a', encoding='utf-8') as f: + f.write(line + '\n') def goto_identities(): @@ -101,34 +117,46 @@ def ensure_team1(): return False -def run_daily(): - log('起 daily(经验本x3 + 纽本x3)') - r = probe('run_task', {'task': 'daily'}) - if not r.get('ok'): - return False, 'run_task 失败: %s' % r - log('daily 已启动, 开始轮询') +def poll_task(task, timeout_s, sleep=time.sleep): + """轮询到任务结束。返回 (ok, 说明, 是否因卡死被停)。""" t0 = time.time() stalled = 0 - while time.time() - t0 < DAILY_TIMEOUT_S: - time.sleep(60) + while time.time() - t0 < timeout_s: + sleep(POLL_S) st = probe('task_status', {'lines': 1}) s = st.get('state') el = int(time.time() - t0) if s != 'running': - log('daily 结束: state=%s elapsed=%ds exit=%s' - % (s, el, st.get('exit_code'))) + log('%s 结束: state=%s elapsed=%ds exit=%s' % (task, s, el, st.get('exit_code'))) # AALC 单次战斗失败后仍会 exit 0, succeeded 还要看 errors - if s == 'succeeded' and st.get('errors'): - return False, 'exit 0 但日志有报错: %s' % st['errors'][-1] - return s == 'succeeded', 'state=%s elapsed=%ds' % (s, el) + if st.get('errors'): + return False, '%s: %s' % (s, st['errors'][-1]), False + return s == 'succeeded', 'state=%s elapsed=%ds' % (s, el), False stalled = stalled + 1 if st.get('stall') else 0 if stalled >= STALL_POLLS: probe('stop_task') - return False, '卡死(%s), 已停止任务 elapsed=%ds' % (st['stall'], el) - if el % 600 < 60: - log(' ...running %ds' % el) + return False, '卡死(%s), 已停止任务 elapsed=%ds' % (st['stall'], el), True + if el % 600 < POLL_S: + log(' ...%s running %ds' % (task, el)) probe('stop_task') - return False, '超时 %ds' % DAILY_TIMEOUT_S + return False, '超时 %ds' % timeout_s, False + + +def run_aalc(task, params, timeout_s, retries=STALL_RETRIES, sleep=time.sleep): + """跑一个 AALC 任务; 卡死时停掉重跑, 最多 retries 次。返回 (ok, 说明)。""" + info = '' + for attempt in range(retries + 1): + if attempt: + log('%s 卡死后重跑 (%d/%d)' % (task, attempt, retries)) + sleep(10) + r = probe('run_task', dict(params, task=task)) + if not r.get('ok'): + return False, 'run_task 失败: %s' % r.get('error', r) + log('%s 已启动 %s, 开始轮询' % (task, params or '')) + ok, info, stalled = poll_task(task, timeout_s, sleep=sleep) + if ok or not stalled: + return ok, info + return False, info def report_grid(): @@ -184,57 +212,79 @@ def lunacy_guard(): return True, '狂气 %d 未变' % cur -def main(): +def main(argv=None): + global _log_file + ap = argparse.ArgumentParser(description='一轮: 刷材料 -> 镜牢 -> 升级/同步') + ap.add_argument('--mirror', type=int, default=0, help='本轮镜牢局数, 默认 0') + ap.add_argument('--target', type=int, default=34, help='把队内人格升到的等级') + ap.add_argument('--retries', type=int, default=STALL_RETRIES, help='AALC 卡死后重跑次数') + ap.add_argument('--report-dir', default=DEFAULT_REPORT_DIR) + args = ap.parse_args(argv) + + os.makedirs(args.report_dir, exist_ok=True) + base = os.path.join(args.report_dir, 'cycle_' + time.strftime('%Y%m%d_%H%M%S')) + _log_file = base + '.log' t_start = time.time() + steps = [] + + def step(name, ok, info): + steps.append({'step': name, 'ok': ok, 'info': info, 'at': time.strftime('%H:%M:%S')}) + log('%s: %s (%s)' % (name, 'OK' if ok else 'FAIL', info)) + return ok + + def finish(code, why): + log('=== %s, 耗时 %ds ===' % (why, int(time.time() - t_start))) + report = {'ok': code == 0, 'result': why, 'started': time.strftime( + '%Y-%m-%d %H:%M:%S', time.localtime(t_start)), 'elapsed_s': int(time.time() - t_start), + 'args': vars(args), 'steps': steps, 'log': _log_file} + with open(base + '.json', 'w', encoding='utf-8') as f: + json.dump(report, f, ensure_ascii=False, indent=2) + return code + log('=== 一轮开始 ===') + if not step('狂气校验', *lunacy_guard()): + return finish(1, '中止: 狂气被消耗, 按用户要求不得使用') - ok, info = lunacy_guard() - log('狂气校验: %s (%s)' % ('OK' if ok else 'FAIL', info)) - if not ok: - log('=== 中止: 狂气被消耗, 按用户要求不得使用 ===') - return 1 - - # 先把预设列表拉回顶部并选中 TEAMS #1——否则 AALC 会"找不到队伍 # 1" - if ensure_team1(): - log('已选中 TEAMS #1') - else: + # 先把预设列表拉回顶部并选中 TEAMS #1——AALC 只朝列表下方找, 停在底部会找不到 + if not ensure_team1(): log('[warn] 未能确认选中 TEAMS #1, 继续尝试') - ok, info = run_daily() - log('刷材料: %s (%s)' % ('OK' if ok else 'FAIL', info)) - if not ok: - log('=== 本轮失败: 刷材料未成功 ===') - return 1 + if not step('刷材料', *run_aalc('daily', {}, DAILY_TIMEOUT_S, args.retries)): + return finish(1, '本轮失败: 刷材料未成功') - # daily 结束后正在主界面, 这里才是能读到 LUNACY 的时机 + if args.mirror > 0: + # 镜牢掉落自我碎片, 同步到 IV 阶要用 + ok, info = run_aalc('mirror', {'count': args.mirror}, + MIRROR_TIMEOUT_S * args.mirror, args.retries) + if not step('镜牢 x%d' % args.mirror, ok, info): + log('[warn] 镜牢未完成, 继续升级') + + # AALC 任务结束后在主界面, 这里才是能读到 LUNACY 的时机 time.sleep(8) - ok, info = lunacy_guard() - log('狂气校验(刷后): %s (%s)' % ('OK' if ok else 'FAIL', info)) - if not ok: - log('=== 中止: 狂气被消耗, 按用户要求不得使用 ===') - return 1 + if not step('狂气校验(刷后)', *lunacy_guard()): + return finish(1, '中止: 狂气被消耗, 按用户要求不得使用') if not goto_identities(): - log('无法进入 Identities 网格, 放弃本轮') - return 1 - log('已进入 Identities 网格') + step('进入 Identities 网格', False, '找不到网格') + return finish(1, '本轮失败: 无法进入 Identities 网格') log('升级前:\n' + report_grid()) - log('对队内低于 Lv.34 的人格升级 + 同步') + log('对队内低于 Lv.%d 的人格升级 + 同步' % args.target) # 用 progress 而非 weakest: 网格 OCR 会把 LV14 读成 Lv.1, # progress 会逐个打开详情页以真实等级判断目标。 - out = run([PY, '-X', 'utf8', LEVELUP, 'progress', '34', '--uptie']) - for line in out.strip().splitlines(): + out = run([PY, '-X', 'utf8', LEVELUP, 'progress', str(args.target), '--uptie']) + lines = out.strip().splitlines() + for line in lines: log(' ' + line) + step('升级/同步', not any('FAIL' in l for l in lines), + '; '.join(l.strip() for l in lines if '升级:' in l or '同步:' in l) or '无需升级') time.sleep(5) if not goto_identities(): - log('升级后无法回到网格') - return 1 + step('回到网格', False, '升级后无法回到网格') + return finish(1, '本轮失败: 升级后无法回到网格') log('升级后:\n' + report_grid()) - - log('=== 一轮结束, 耗时 %ds ===' % int(time.time() - t_start)) - return 0 + return finish(0, '一轮结束') if __name__ == '__main__': diff --git a/scripts/install_unattended.ps1 b/scripts/install_unattended.ps1 new file mode 100644 index 0000000..f026956 --- /dev/null +++ b/scripts/install_unattended.ps1 @@ -0,0 +1,74 @@ +# 注册无人值守用的两个计划任务 (在跑游戏的那个账号下, 普通 PowerShell 即可): +# LcMCPKeepDisplay 每 5 分钟跑 keep_display.ps1: 会话掉到 Disc 时重挂 console, 防止截图全黑 +# LcMCPDailyCycle 每天定时跑 auto_cycle.py: 刷材料 -> 镜牢 -> 升级/同步, 报告写到 ~\lc_mcp\cycles +# +# 用法: +# powershell -ExecutionPolicy Bypass -File scripts\install_unattended.ps1 +# 可选: -At 05:30 每日运行时间。游戏每日重置为 06:00 (KST), 即北京时间 05:00 +# -Mirror 1 每轮镜牢局数, 0 = 不打镜牢 +# -Target 34 把队内人格升到的等级 +# -Python <路径> 默认 vendor\aalc\.venv\Scripts\pythonw.exe (无窗口, 不抢游戏焦点) +# -NoWatchdog 只装每日任务 +# -Uninstall +# +# 前提: LcMCPServer 已用 install_logon_task.ps1 装好并在运行。 +# 先手动跑一轮确认无误再装: python scripts\auto_cycle.py --mirror 1 +param( + [string]$At = "05:30", + [int]$Mirror = 1, + [int]$Target = 34, + [string]$Python = "", + [switch]$NoWatchdog, + [switch]$Uninstall +) +$ErrorActionPreference = "Stop" +$Repo = Split-Path -Parent $PSScriptRoot +$Watchdog = "LcMCPKeepDisplay" +$Daily = "LcMCPDailyCycle" + +if ($Uninstall) { + foreach ($name in @($Watchdog, $Daily)) { + Unregister-ScheduledTask -TaskName $name -Confirm:$false -ErrorAction SilentlyContinue + Write-Output "removed $name" + } + exit 0 +} + +if (-not $Python) { $Python = Join-Path $Repo "vendor\aalc\.venv\Scripts\pythonw.exe" } +if (-not (Test-Path $Python)) { + throw "找不到 Python: $Python`n先在 vendor\aalc 里执行 uv sync, 或用 -Python 指定" +} +if (-not (Get-ScheduledTask -TaskName "LcMCPServer" -ErrorAction SilentlyContinue)) { + Write-Warning "没有找到 LcMCPServer 计划任务, 每日任务需要它: 先运行 scripts\install_logon_task.ps1" +} + +$user = "$env:USERDOMAIN\$env:USERNAME" +# Limited: keep_display.ps1 自己用 RunAs 静默提权跑 tscon (需要 ConsentPromptBehaviorAdmin=0) +$principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited + +if (-not $NoWatchdog) { + $ps = "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" + $script = Join-Path $PSScriptRoot "keep_display.ps1" + $action = New-ScheduledTaskAction -Execute $ps -WorkingDirectory $Repo ` + -Argument "-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$script`"" + $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) ` + -RepetitionInterval (New-TimeSpan -Minutes 5) -RepetitionDuration (New-TimeSpan -Days 3650) + $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries ` + -ExecutionTimeLimit (New-TimeSpan -Minutes 3) -MultipleInstances IgnoreNew + Register-ScheduledTask -TaskName $Watchdog -Action $action -Trigger $trigger -Principal $principal ` + -Settings $settings -Force | Out-Null + Write-Output "registered $Watchdog (every 5 min) -> $script" +} + +$cycle = Join-Path $PSScriptRoot "auto_cycle.py" +$action = New-ScheduledTaskAction -Execute $Python -WorkingDirectory $Repo ` + -Argument "-X utf8 `"$cycle`" --mirror $Mirror --target $Target" +$trigger = New-ScheduledTaskTrigger -Daily -At $At +# 一轮 daily 约 20 分钟, 每局镜牢约 40 分钟; 超过上限由计划任务强杀 +$limit = New-TimeSpan -Minutes (60 + 75 * [Math]::Max($Mirror, 0)) +$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries ` + -StartWhenAvailable -ExecutionTimeLimit $limit -MultipleInstances IgnoreNew +Register-ScheduledTask -TaskName $Daily -Action $action -Trigger $trigger -Principal $principal ` + -Settings $settings -Force | Out-Null +Write-Output "registered $Daily (daily at $At, mirror=$Mirror, target=Lv.$Target, limit=$limit)" +Write-Output "reports -> $env:USERPROFILE\lc_mcp\cycles\cycle_*.json" diff --git a/scripts/lc_ui.py b/scripts/lc_ui.py index 6ec922f..6473773 100644 --- a/scripts/lc_ui.py +++ b/scripts/lc_ui.py @@ -13,9 +13,21 @@ import subprocess import sys HERE = os.path.dirname(os.path.abspath(__file__)) + + +def _console_python(exe): + """计划任务用 pythonw 启动(不弹窗、不抢游戏焦点), 但子进程要读 stdout, 换成同目录的 python。""" + head, name = os.path.split(exe) + if name.lower() == 'pythonw.exe' and os.path.exists(os.path.join(head, 'python.exe')): + return os.path.join(head, 'python.exe') + return exe + + # 默认用运行本脚本的解释器(AALC 的 venv); 需要时用 LC_PY 指定 -PY = os.environ.get('LC_PY') or sys.executable +PY = os.environ.get('LC_PY') or _console_python(sys.executable) PROBE = os.path.join(HERE, 'mcp_probe.py') +# Windows 上不给子进程弹控制台窗口(从 pythonw 启动时每次调用都会闪一下) +NO_WINDOW = {'creationflags': 0x08000000} if os.name == 'nt' else {} BASE_W, BASE_H = 1600, 900 _scale = None @@ -23,7 +35,7 @@ _scale = None def run(cmd): r = subprocess.run(cmd, capture_output=True, text=True, - encoding='utf-8', errors='replace') + encoding='utf-8', errors='replace', **NO_WINDOW) return (r.stdout or '') + (r.stderr or '') diff --git a/tests/test_auto_cycle.py b/tests/test_auto_cycle.py new file mode 100644 index 0000000..a2cc014 --- /dev/null +++ b/tests/test_auto_cycle.py @@ -0,0 +1,84 @@ +from pathlib import Path +import sys +import unittest +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts')) +import auto_cycle # noqa: E402 + + +class FakeMcp: + """按脚本返回 task_status, 记录 run_task / stop_task 调用。""" + + def __init__(self, *runs): + self.runs = [list(r) for r in runs] # 每次 run_task 后依次返回的状态 + self.calls = [] + + def probe(self, tool, args=None, quiet=True): + self.calls.append((tool, args)) + if tool == 'run_task': + self.current = self.runs.pop(0) + return {'ok': True} + if tool == 'task_status': + return self.current.pop(0) if len(self.current) > 1 else self.current[0] + return {'ok': True} + + +RUNNING = {'state': 'running'} +STALL = {'state': 'running', 'stall': {'empty_team': 30}} +DONE = {'state': 'succeeded', 'exit_code': 0} + + +class RunAalcTest(unittest.TestCase): + + def run_aalc(self, mcp, **kw): + with mock.patch.object(auto_cycle, 'probe', mcp.probe), \ + mock.patch.object(auto_cycle, 'log', lambda m: None): + return auto_cycle.run_aalc('daily', {}, 3600, sleep=lambda s: None, **kw) + + def tools(self, mcp): + return [t for t, _ in mcp.calls if t != 'task_status'] + + def test_stall_is_stopped_and_rerun_once(self): + mcp = FakeMcp([RUNNING, STALL, STALL], [RUNNING, DONE]) + ok, info = self.run_aalc(mcp) + self.assertTrue(ok, info) + self.assertEqual(self.tools(mcp), ['run_task', 'stop_task', 'run_task']) + + def test_single_stall_poll_is_not_enough(self): + mcp = FakeMcp([STALL, RUNNING, DONE]) + ok, info = self.run_aalc(mcp) + self.assertTrue(ok, info) + self.assertEqual(self.tools(mcp), ['run_task']) + + def test_gives_up_after_retries(self): + mcp = FakeMcp([STALL, STALL], [STALL, STALL]) + ok, info = self.run_aalc(mcp, retries=1) + self.assertFalse(ok) + self.assertIn('卡死', info) + self.assertEqual(self.tools(mcp), ['run_task', 'stop_task', 'run_task', 'stop_task']) + + def test_preflight_failure_is_not_retried(self): + failed = {'state': 'failed', 'exit_code': 3, + 'errors': ['[ERROR] [lc_mcp] preflight: 队伍 1 的 sinner_order 没有罪人']} + mcp = FakeMcp([failed]) + ok, info = self.run_aalc(mcp) + self.assertFalse(ok) + self.assertIn('preflight', info) + self.assertEqual(self.tools(mcp), ['run_task']) + + def test_exit_zero_with_errors_is_failure(self): + mcp = FakeMcp([dict(DONE, errors=['[ERROR] 超出最大尝试次数,未能进入战斗'])]) + ok, info = self.run_aalc(mcp) + self.assertFalse(ok) + + def test_mirror_params_are_passed_with_task(self): + mcp = FakeMcp([DONE]) + with mock.patch.object(auto_cycle, 'probe', mcp.probe), \ + mock.patch.object(auto_cycle, 'log', lambda m: None): + auto_cycle.run_aalc('mirror', {'count': 2}, 3600, sleep=lambda s: None) + self.assertEqual(mcp.calls[0], ('run_task', {'count': 2, 'task': 'mirror'})) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_preflight_patches.py b/tests/test_preflight_patches.py new file mode 100644 index 0000000..c3e8b40 --- /dev/null +++ b/tests/test_preflight_patches.py @@ -0,0 +1,163 @@ +import os +import sys +import unittest +from unittest import mock + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +from lc_mcp import aalc_patches, preflight # noqa: E402 + + +def values(**over): + v = {'simulator': False, 'mirror': True, 'set_win_size': 720, 'set_lunacy_to_enkephalin': 0, + 'teams_active_queue': [1], + 'teams': {'1': {'sinner_order': [1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0]}}} + v.update(over) + return v + + +class PreflightTest(unittest.TestCase): + + def test_healthy_config_passes(self): + self.assertEqual(preflight.check(values(), 'mirror', desktop=(1600, 900), env={}), []) + + def test_default_all_zero_sinner_order_is_rejected_for_mirror(self): + v = values(teams={'1': {'sinner_order': [0] * 12}}) + problems = preflight.check(v, 'mirror', env={}) + self.assertEqual(len(problems), 1) + self.assertIn('sinner_order', problems[0]) + # 日常本只按预设编号选队, 不用 sinner_order + self.assertEqual(preflight.check(v, 'daily', env={}), []) + # all 只在勾选了镜牢时检查 + self.assertEqual(preflight.check(dict(v, mirror=False), 'all', env={}), []) + self.assertEqual(len(preflight.check(v, 'all', env={})), 1) + + def test_missing_team_in_queue(self): + problems = preflight.check(values(teams_active_queue=[2]), 'mirror', env={}) + self.assertIn('队伍 2', problems[0]) + + def test_lunacy_spending_is_rejected_unless_explicit(self): + v = values(set_lunacy_to_enkephalin=2) + self.assertIn('狂气', preflight.check(v, 'daily', env={})[0]) + self.assertEqual(preflight.check(v, 'enkephalin', env={}), []) + self.assertEqual(preflight.check(v, 'daily', env={preflight.ALLOW_LUNACY_ENV: '1'}), []) + + def test_window_that_cannot_fit_desktop_is_rejected(self): + # 10-04 坑 4: 900 高的客户区加标题栏放不进 1600x900 桌面 + problems = preflight.check(values(set_win_size=900), 'daily', desktop=(1600, 900), env={}) + self.assertIn('1616x940', problems[0]) + self.assertEqual(preflight.check(values(set_win_size=900), 'daily', desktop=(1920, 1080), env={}), []) + self.assertEqual(preflight.check(values(set_win_size=900, simulator=True), 'daily', + desktop=(1600, 900), env={}), []) + + def test_collect_reads_pydantic_teams(self): + class Team: + def model_dump(self): + return {'sinner_order': [1]} + + class Cfg: + data = {'simulator': False, 'mirror': True, 'set_win_size': 720, + 'set_lunacy_to_enkephalin': None, 'teams_active_queue': [1], 'teams': {1: Team()}} + + def get_value(self, key): + return self.data[key] + + v = preflight.collect(Cfg()) + self.assertEqual(v['teams'], {'1': {'sinner_order': [1]}}) + self.assertEqual(v['set_lunacy_to_enkephalin'], 0) + + +class ExactTeamMatchTest(unittest.TestCase): + + class Auto: + def find_str_in_text(self, target, ocr_dict): + # AALC 原逻辑: 子串匹配 + for text, pos in ocr_dict.items(): + if target.replace(' ', '').lower() in text.replace(' ', '').lower(): + return pos + return False + + def setUp(self): + self.auto = self.Auto() + aalc_patches.install_exact_team_match(self.auto, log=lambda m: None) + + def test_team_1_does_not_match_team_10(self): + ocr = {'TEAMS #10': [10, 10], 'TEAMS #11': [10, 20], 'TEAMS #1': [10, 30]} + self.assertEqual(self.auto.find_str_in_text('TEAMS #1', ocr), [10, 30]) + self.assertFalse(self.auto.find_str_in_text('TEAMS #1', {'TEAMS #10': [1, 1]})) + + def test_ocr_variants_and_chinese(self): + self.assertEqual(self.auto.find_str_in_text('TFAMS#1', {'TEAMS # 1': [5, 5]}), [5, 5]) + self.assertEqual(self.auto.find_str_in_text('编队#1', {'编队#12': [1, 1], '编队#1': [2, 2]}), [2, 2]) + self.assertEqual(self.auto.find_str_in_text('TEAMS #12', {'TEAMS #12': [3, 3]}), [3, 3]) + + def test_other_targets_keep_aalc_substring_logic(self): + self.assertEqual(self.auto.find_str_in_text('Hong Lu', {'W HongLu': [7, 7]}), [7, 7]) + + +class FakeHandle: + def __init__(self, size): + self._hwnd = 1 + self.size = size + self.isMinimized = False + + def width(self, client=False): + return self.size[0] + + def height(self, client=False): + return self.size[1] + + +class FakeScreen: + def __init__(self, size, resizable=True): + self.handle = FakeHandle(size) + self.resizable = resizable + self.calls = [] + + def adjust_win_size(self, want): + self.calls.append(want) + if self.resizable: + self.handle.size = want + + +class Cfg: + simulator = False + set_windows = True + set_win_size = 720 + + +class WindowGuardTest(unittest.TestCase): + + def guard(self, screen, cfg=Cfg): + self.logs = [] + return aalc_patches.WindowGuard(screen, cfg, log=self.logs.append) + + def test_correct_size_is_left_alone(self): + screen = FakeScreen((1280, 720)) + self.assertEqual(self.guard(screen).check_once(), 'ok') + self.assertEqual(screen.calls, []) + + def test_stretched_window_is_restored(self): + # 10-04 坑 5: RDP 重连后被拉伸成 1872x898 + screen = FakeScreen((1872, 898)) + with mock.patch.object(aalc_patches.time, 'sleep'): + self.assertEqual(self.guard(screen).check_once(), 'fixed') + self.assertEqual(screen.calls, [(1280, 720)]) + + def test_unfixable_size_is_reported_once(self): + screen = FakeScreen((1600, 877), resizable=False) + guard = self.guard(screen) + with mock.patch.object(aalc_patches.time, 'sleep'): + self.assertEqual(guard.check_once(), 'failed') + self.assertEqual(guard.check_once(), 'failed') + self.assertEqual(len([m for m in self.logs if '[ERROR]' in m]), 1) + + def test_user_managed_window_is_not_touched(self): + class Manual(Cfg): + set_windows = False + screen = FakeScreen((1872, 898)) + self.assertIsNone(self.guard(screen, Manual).check_once()) + self.assertEqual(screen.calls, []) + + +if __name__ == '__main__': + unittest.main() diff --git a/vendor/aalc b/vendor/aalc index 7452fad..b0f4393 160000 --- a/vendor/aalc +++ b/vendor/aalc @@ -1 +1 @@ -Subproject commit 7452fad5a45a0fadb59a753fafbf40434d987c19 +Subproject commit b0f439321987f5f7b126ebbc424f6ef144c1bff0