无人值守自动化: 配置预检、选队精确匹配、窗口守护、卡死重跑、计划任务, AALC 升级到 b0f4393

Browse Source
- 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 <noreply@anthropic.com>
This commit is contained in:
yws
2026-10-13 03:12:19 +00:00
co-authored by Claude Opus 5.5
parent 6b129ddba3
commit 2190f57abe
10 changed files with 664 additions and 60 deletions
+105 -55
View File
@@ -1,12 +1,17 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""一轮自动推进: 刷材料 -> 升级最弱人格 -> 同步 -> 报告。 """一轮自动推进: 刷材料 -> (镜牢) -> 升级最弱人格 -> 同步 -> 报告。
用法: python auto_cycle.py [--rounds N] 用法: python auto_cycle.py [--mirror N] [--target LV] [--retries N] [--report-dir DIR]
退出码: 0 正常完成一轮 / 1 失败 退出码: 0 正常完成一轮 / 1 失败
每轮在 report-dir(默认 ~/lc_mcp/cycles)写一份 cycle_<时间>.log 与同名 .json 报告,
计划任务无人值守跑完后据此核对。
设计: 只做"一轮",不做无限循环——由外层(goal 轮次)负责重复与判断, 设计: 只做"一轮",不做无限循环——由外层(goal 轮次)负责重复与判断,
避免无人监督地长时间空转。每轮输出结构化报告供上层核对。 避免无人监督地长时间空转。每轮输出结构化报告供上层核对。
""" """
import argparse
import json
import os import os
import time import time
@@ -21,14 +26,25 @@ BACK = (85, 75) # 只在 Sinners 内部退层用, 主界面上按
BTN_SINNERS = (1130, 805) # 主界面底部 Sinners BTN_SINNERS = (1130, 805) # 主界面底部 Sinners
TAB_ALL_IDENTITIES = (1472, 245) # TEAMS 页 -> All Identities TAB_ALL_IDENTITIES = (1472, 245) # TEAMS 页 -> All Identities
# daily 轮询上限 # AALC 任务轮询上限
DAILY_TIMEOUT_S = 45 * 60 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 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): 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(): def goto_identities():
@@ -101,34 +117,46 @@ def ensure_team1():
return False return False
def run_daily(): def poll_task(task, timeout_s, sleep=time.sleep):
log('起 daily(经验本x3 + 纽本x3)') """轮询到任务结束。返回 (ok, 说明, 是否因卡死被停)。"""
r = probe('run_task', {'task': 'daily'})
if not r.get('ok'):
return False, 'run_task 失败: %s' % r
log('daily 已启动, 开始轮询')
t0 = time.time() t0 = time.time()
stalled = 0 stalled = 0
while time.time() - t0 < DAILY_TIMEOUT_S: while time.time() - t0 < timeout_s:
time.sleep(60) sleep(POLL_S)
st = probe('task_status', {'lines': 1}) st = probe('task_status', {'lines': 1})
s = st.get('state') s = st.get('state')
el = int(time.time() - t0) el = int(time.time() - t0)
if s != 'running': if s != 'running':
log('daily 结束: state=%s elapsed=%ds exit=%s' log('%s 结束: state=%s elapsed=%ds exit=%s' % (task, s, el, st.get('exit_code')))
% (s, el, st.get('exit_code')))
# AALC 单次战斗失败后仍会 exit 0, succeeded 还要看 errors # AALC 单次战斗失败后仍会 exit 0, succeeded 还要看 errors
if s == 'succeeded' and st.get('errors'): if st.get('errors'):
return False, 'exit 0 但日志有报错: %s' % st['errors'][-1] return False, '%s: %s' % (s, st['errors'][-1]), False
return s == 'succeeded', 'state=%s elapsed=%ds' % (s, el) return s == 'succeeded', 'state=%s elapsed=%ds' % (s, el), False
stalled = stalled + 1 if st.get('stall') else 0 stalled = stalled + 1 if st.get('stall') else 0
if stalled >= STALL_POLLS: if stalled >= STALL_POLLS:
probe('stop_task') probe('stop_task')
return False, '卡死(%s), 已停止任务 elapsed=%ds' % (st['stall'], el) return False, '卡死(%s), 已停止任务 elapsed=%ds' % (st['stall'], el), True
if el % 600 < 60: if el % 600 < POLL_S:
log(' ...running %ds' % el) log(' ...%s running %ds' % (task, el))
probe('stop_task') 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(): def report_grid():
@@ -184,57 +212,79 @@ def lunacy_guard():
return True, '狂气 %d 未变' % cur 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() 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('=== 一轮开始 ===') log('=== 一轮开始 ===')
if not step('狂气校验', *lunacy_guard()):
return finish(1, '中止: 狂气被消耗, 按用户要求不得使用')
ok, info = lunacy_guard() # 先把预设列表拉回顶部并选中 TEAMS #1——AALC 只朝列表下方找, 停在底部会找不到
log('狂气校验: %s (%s)' % ('OK' if ok else 'FAIL', info)) if not ensure_team1():
if not ok:
log('=== 中止: 狂气被消耗, 按用户要求不得使用 ===')
return 1
# 先把预设列表拉回顶部并选中 TEAMS #1——否则 AALC 会"找不到队伍 # 1"
if ensure_team1():
log('已选中 TEAMS #1')
else:
log('[warn] 未能确认选中 TEAMS #1, 继续尝试') log('[warn] 未能确认选中 TEAMS #1, 继续尝试')
ok, info = run_daily() if not step('刷材料', *run_aalc('daily', {}, DAILY_TIMEOUT_S, args.retries)):
log('刷材料: %s (%s)' % ('OK' if ok else 'FAIL', info)) return finish(1, '本轮失败: 刷材料未成功')
if not ok:
log('=== 本轮失败: 刷材料未成功 ===')
return 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) time.sleep(8)
ok, info = lunacy_guard() if not step('狂气校验(刷后)', *lunacy_guard()):
log('狂气校验(刷后): %s (%s)' % ('OK' if ok else 'FAIL', info)) return finish(1, '中止: 狂气被消耗, 按用户要求不得使用')
if not ok:
log('=== 中止: 狂气被消耗, 按用户要求不得使用 ===')
return 1
if not goto_identities(): if not goto_identities():
log('无法进入 Identities 网格, 放弃本轮') step('进入 Identities 网格', False, '找不到网格')
return 1 return finish(1, '本轮失败: 无法进入 Identities 网格')
log('已进入 Identities 网格')
log('升级前:\n' + report_grid()) log('升级前:\n' + report_grid())
log('对队内低于 Lv.34 的人格升级 + 同步') log('对队内低于 Lv.%d 的人格升级 + 同步' % args.target)
# 用 progress 而非 weakest: 网格 OCR 会把 LV14 读成 Lv.1, # 用 progress 而非 weakest: 网格 OCR 会把 LV14 读成 Lv.1,
# progress 会逐个打开详情页以真实等级判断目标。 # progress 会逐个打开详情页以真实等级判断目标。
out = run([PY, '-X', 'utf8', LEVELUP, 'progress', '34', '--uptie']) out = run([PY, '-X', 'utf8', LEVELUP, 'progress', str(args.target), '--uptie'])
for line in out.strip().splitlines(): lines = out.strip().splitlines()
for line in lines:
log(' ' + line) 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) time.sleep(5)
if not goto_identities(): if not goto_identities():
log('升级后无法回到网格') step('回到网格', False, '升级后无法回到网格')
return 1 return finish(1, '本轮失败: 升级后无法回到网格')
log('升级后:\n' + report_grid()) log('升级后:\n' + report_grid())
return finish(0, '一轮结束')
log('=== 一轮结束, 耗时 %ds ===' % int(time.time() - t_start))
return 0
if __name__ == '__main__': if __name__ == '__main__':
+74
View File
@@ -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"
+14 -2
View File
@@ -13,9 +13,21 @@ import subprocess
import sys import sys
HERE = os.path.dirname(os.path.abspath(__file__)) 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 指定 # 默认用运行本脚本的解释器(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') 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 BASE_W, BASE_H = 1600, 900
_scale = None _scale = None
@@ -23,7 +35,7 @@ _scale = None
def run(cmd): def run(cmd):
r = subprocess.run(cmd, capture_output=True, text=True, 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 '') return (r.stdout or '') + (r.stderr or '')