Author SHA1 Message Date
DSH e490a29ceb 记录: 经验本编队拖拽缺陷、101 项测试输出与养成进展 2026-10-03 11:26:19 +08:00
DSH 66418dce22 修复内置流程编队滑动被当成拖拽卡片: 补 Windows 队伍滑动手势并暴露任务日志报错
- aalc_input_patch: 上游只有 MuMu 适配器覆盖 mouse_swipe_for_team_scroll,
  Windows 前台/后台适配器用普通列表手势(30px/0.01s escape), 在编队列表里
  会被当成拖动罪人卡: 队伍被拖乱, 缺人时后续 battle.py 报'未能进入战斗'。
  按 MuMu 参数(缩放 60px escape/保持 0.1s/分段/停稳 0.5s)补等价实现, 不改 AALC 源码。
- tasks: 退出码 0 但日志里有 [ERROR]/异常时, task_status 增加 errors 字段
  (AALC 单次战斗失败后仍会正常退出, 只看 succeeded 会被误导)。
- 新增 7 项回归测试, 全套 101 项通过。
2026-10-03 11:24:15 +08:00
32 changed files with 484 additions and 2396 deletions
+14 -30
View File
@@ -89,6 +89,18 @@ codex mcp add limbus --env PYTHONUTF8=1 -- D:\lc-mcp\vendor\aalc\.venv\Scripts\p
`超出最大尝试次数,未能进入战斗`)后仍会继续跑完并正常退出,所以 `task_status`
会把日志尾部的 `[ERROR]`/异常行放进 `errors` 字段:**看到 `succeeded` 也要先看 `errors`。**
### 与上游 AALC 的差异(不改其源码)
`lc_mcp/aalc_input_patch.py` 在 `bootstrap()` 时给 Windows 输入适配器打补丁,只补上游缺的东西:
- **编队列表滑动**:AALC 基类要求适配器覆盖 `mouse_swipe_for_team_scroll` 以"规避队伍拖拽判定",
但上游只有 MuMu 模拟器适配器覆盖了它(见 `input_handlers/__init__.py` 注释)。Windows 前台/后台适配器
仍用普通列表手势 `build_windows_scroll_swipe_plan`(escape 30px/0.01s),在游戏的编队列表里不足以脱离
"按住罪人卡"判定,滑动会被当成拖动卡片:队伍顺序被拖乱,缺人时后续还会"未能进入战斗"。
补丁按 MuMu 的参数(按 `set_win_size` 缩放 60px escape、保持 0.1s、分段走完、松手前停稳 0.5s)
在 `Input`(前台)和 `BackgroundInput`(后台)上补上等价实现;`WindowMoveInput` 没有
`set_mouse_pos`,保持原样。
## 环境变量
| 变量 | 默认 | 说明 |
@@ -138,7 +150,7 @@ vendor\aalc\.venv\Scripts\python.exe -X utf8 scripts\mcp_probe.py find_image '{"
## Jev 镜牢执行器与真实反馈
`scripts/jev_mirror_agent.py` 通过 MCP bridge 操作游戏,普通分支经统一接口交给 Jev 或执行模型;战斗采用 P → 回车宏,事件先 SKIP,回车失效时使用当前按钮。它保留用户已配好的队伍,商店无可替换出战角色时至多刷新 4 次,加载期间不读取旧库存继续操作。
`scripts/jev_mirror_agent.py` 通过 MCP bridge 操作游戏,普通分支交给 Jev;战斗采用 P → 回车宏,事件先 SKIP,回车失效时使用当前按钮。它保留用户已配好的队伍,商店无可替换出战角色时至多刷新 4 次,加载期间不读取旧库存继续操作。
安装 AALC 依赖并启动常驻服务后,把 `OPENCODE_API_KEY` 设为自己的凭据,再运行:
@@ -147,37 +159,9 @@ vendor\aalc\.venv\Scripts\python.exe -X utf8 scripts\jev_mirror_agent.py scripts
```
运行数据默认写到 `~/lc_mcp/jev`,可用 `LC_JEV_HOME` 指定其他目录。创建该目录下的 `JEV_STOP` 文件即可停止;续跑前移除它。不要与 AALC 完整任务或另一个游戏执行器同时操作。
中途续跑沿用 `jev_shop_context.json`;一局领取完成后它会归档为 `jev_shop_context.<时间>.json`,下一局从干净状态开始。
工具调用失败(截图暂不可用、按钮已消失等)会记入日志并重新观察画面,同一画面上同一动作最多尝试两次,不会因单次失败整局退出。
每局运行现在有独立标识。默认续跑尚未结束且上下文一致的当前局;已完成或没有运行记录时建立新局。重新开一局时使用 `--new-run`,明确要求续跑时使用 `--resume`。旧版本未完成记录会保留楼层和强化进度,但旧的领取及战斗标记不会作为本局完成证据;只有上下文而没有运行记录时会重置它。领取截图和返回大厅截图必须属于当前局,才能记录完成。
```powershell
# 新开一局:清除上一局的楼层、饰品与领取状态
vendor\aalc\.venv\Scripts\python.exe -X utf8 scripts\jev_mirror_agent.py scripts\jev_config.example.json --new-run --seconds 1800
# 续跑已保存的未完成局,保持原计时起点
vendor\aalc\.venv\Scripts\python.exe -X utf8 scripts\jev_mirror_agent.py scripts\jev_config.example.json --resume --seconds 1800
```
MCP 客户端默认每次请求等待 30 秒,文字等待工具按自身时长延长响应期限。等待回复期间也检查停止标记和本次运行的时间预算。超时或中断时关闭客户端连接,并记录结果可能未知;不会自动重发点击或按键。常驻服务已经接收的操作可能仍会完成,需核对当前画面后再续跑。`battle_batch.py` 与主执行器共用判定、奖励、死亡和地图等战斗退出条件,并在每个按键前检查停止标记。
设置 `LC_FIXED_FALLBACK=1` 可只使用固定候选,无需 Jev API 密钥;仍需运行 MCP 服务。完整 AALC 任务启动时,如有 MCP 工具正在执行,会立即返回忙碌错误,避免与当前输入交错;查询与停止任务不受影响。
`decisionEngine` 支持 `auto`(默认)、`jev`、`executor`、`fixed`,也可用 `--decision-engine` 覆盖。只有指定非空 `model` 并提供凭据时,`auto`/`jev` 才调用 Jev。未指定模型、缺少凭据或 Jev 请求失败时,转交执行模型;固定策略需显式选择。Python 实际使用配置中的模型,并在动作日志保留概率、confidence 和实际决策来源。
不用 Jev 时可以省略配置文件:
```powershell
vendor\aalc\.venv\Scripts\python.exe -X utf8 scripts\jev_mirror_agent.py --decision-engine executor --seconds 1800
```
独立脚本在需要模型判断时输出 `requires_decision`,将页面观测、合法候选、当前局标识和请求标识写入 `decision_request.json` 及状态文件,随后释放连接与执行器互斥句柄。调用它的执行模型读取该请求,重新核对当前页面后处理动作,再用 `--resume` 继续同一局。请求文件是交接通知,旧请求不能直接用于输入。脚本本身没有访问当前聊天模型的 API。
嵌入执行端时,`scripts/decision_router.py` 的 `DecisionRouter` 及主脚本 `main(executor_decider=...)` 接受 `executor_decider(request)` 回调;返回候选 ID,或带同一 `request_id` 及 `choice` 的对象。回调只获得观测和候选,输入仍由执行器完成。未列出的候选、错误请求标识和无效概率会被拒绝。执行端应为自己的模型调用设置等待期限。长期混合执行器由这一接口接入当前执行模型,避免每个分支都重新启动脚本。
Jev 与 AALC 配置复用方案、离线页面样例及实测耗时统计见 [2026-10-03 自动化研究](docs/jev_aalc_automation_research_20261003.md)。
本轮修复、验证范围与已知限制见 [2026-10-03 运行可靠性改进](docs/mcp_runtime_improvements_20261003.md)。
本次修复、实际失败反馈、操作日志、截图清单、修改源码快照和速通 skill 见 [2026-10-02 实测记录](docs/feedback/2026-10-02/README.md);安装与测试说明见 [INSTALL_TEST_REPORT.md](INSTALL_TEST_REPORT.md)。这些是开发中的真实记录,包含失败和仍未验证的步骤。
[2026-10-03 主线实测与耗时复盘](docs/feedback/2026-10-03/README.md)记录了 4-48 未通关、三次 Jev 抉择耗时、混合操作限制、输入修复的验证边界及 94 项回归结果。
@@ -1,71 +0,0 @@
# 当前执行流程与速通资料覆盖
核对日期:2026-10-03。代码基线:`6c2d26e`。本次核对范围是现有基础执行能力,DS 适配留到后续。
## 两条现存的执行路径
`run_task` 启动 AALC 原生任务进程,读取 AALC 配置并执行镜牢、经验本、纽本等已有流程。它使用 AALC 的模板、队伍配置、卡包权重和商店策略,不调用当前 Jev 辅助脚本,也不自动加载本仓库的速通 skill。
`scripts/jev_mirror_agent.py` 则通过 MCP bridge 观察与操作游戏,以当前镜牢规则生成候选,交给 Jev 或执行模型选择。这是此前实测反馈和近期可靠性、决策接口改进主要涉及的路径。
## 辅助脚本每轮怎样推进
```mermaid
flowchart TD
A[MCP 截图与 OCR / 本地模板匹配] --> B[读取本局标识与保存进度]
B --> C[识别当前界面 / 更新可识别的楼层]
C --> D[生成并过滤合法动作候选]
D --> E{是否为确定步骤}
E -->|加载 / 战斗 / 跳对话 / 结果推进| F[执行有界动作宏]
E -->|路线 / 卡包 / 事件 / 奖励等分支| G[Jev或执行模型选择候选ID]
G --> F
F --> H[记录结果 / 更新部分进度]
H --> A
```
1. `get_state` 返回截图路径、尺寸、OCR 文字、位置和 OCR 分数。地图另外使用 AALC 图片资源和 OpenCV 识别公交位置、连接箭头和节点类型。
2. 保存上下文包含楼层、商店刷新次数、部分饰品取得/强化标志、战斗状态和领取状态。楼层遇到可识别的探索或主题包文字时更新,否则沿用上下文;它不是点击一次就自动加一,也尚不是完整的库存状态表。
3. `candidates()` 先处理加载、上层弹窗、死亡/错误、奖励等界面,再生成当前能执行的动作。部分攻略规则在这里直接过滤,例如二号线楼层限制、技能替换目标和商店刷新上限。
4. 战斗 P→Enter、SKIP 和已知结果后续推进等确定操作直接执行。其他分支经 `DecisionRouter` 选择;显式 fixed 模式使用已有固定优先级。模型的选择范围限于当前候选。
5. `execute()` 把路线方向+回车、连续确认及战斗短批次合成动作。下一轮重新观察,比较有效文字并记录重复尝试;部分快捷键未生效时改点对应按钮。
当前位置、候选控件、预期效果与实际结果仍没有全部形成统一状态合同。目前点击成功不等于某个饰品已经取得或升到 ++。`symbol_upgraded`、`thrill_upgraded` 等标志仍依赖外层核实和维护,自动库存识别及付款后目标核验是基础能力的重要缺口。
## 楼层规划怎样落地
规划来源:[rupture-route.md](skills/limbus-mirror-speedrun/references/rupture-route.md) 和 [速通笔记](mirror_dungeon_speedrun_notes.md)。下表的“计划”是资料与用户要求,不能当成每局已经完成的事实。
| 阶段 | 资料中的目标 | 当前脚本覆盖 |
| --- | --- | --- |
| 开局 | 基础等级的指定恩惠、荆棘套索/荧光灯、三级电池 | 电池必选和确认候选已有;完整开局配置尚未统一转成脚本策略输入 |
| 1F | 优先取得成捆的符咒 | 核心保留规则和模型提示已有;尚无可靠的“卡包奖励解析→缺失核心补全”规划器 |
| 2F | 符咒 ++,缺鸡胸时优先地狱鸡,技能替换 | 符咒未确认强化时限制商店推进;完整强化购买及库存确认仍需外层处理。鸡胸条件选包没有完整自动化 |
| 3F | 辛克莱改为 1→3,尽量完成快感 ++,选可纯 P 的较短卡包 | 辛克莱楼层技能规则已写入候选;卡包机制比较、合成预算与材料计算尚未完整接入 |
| 4F | 换技能,补缺失快感 ++,继续推进 | 对已有快感的待强化入口有部分支持;实际付款和强化完成状态仍依赖核验 |
| 5F | 二号线、技能替换、通关并确认领取 | 二号线候选过滤和剩余刷新已实现;刷新耗尽后的观测及不可选原因仍需外层处理。最终领取与当前局完成证据已有流程 |
路线层面,现有识别器能找可达节点;模型按当前候选选择。固定策略倾向商店、事件,再普通战斗,降低精英/集中战斗优先级。它尚未根据全部库存、剩余预算和每层目标计算整局最优路线。AALC 原生任务另有节点图和路线缓存,后续需要在同一执行进程中复用。
## skill、参考文件和笔记实际怎么利用
| 资料 | 当前用途 | 尚未自动化的部分 |
| --- | --- | --- |
| [SKILL.md](skills/limbus-mirror-speedrun/SKILL.md) | 执行助手读取的总流程:沿用队伍、按需查资料、快捷键、停止及完成标准 | Python 没有读取这个文件来自动装配执行策略 |
| [rupture-route.md](skills/limbus-mirror-speedrun/references/rupture-route.md) | 楼层目标、核心保护、技能表和商店策略;部分内容被人工转入 `SYSTEM_RULES` 和候选过滤 | 修改文档不会自动修改代码;完整目标与预算尚未形成机器可读配置 |
| [event-choices.md](skills/limbus-mirror-speedrun/references/event-choices.md) | 主助手按事件名及选项文字查对应条目,核对收益和额外分支 | 当前 Jev 请求未自动检索并附上相关事件条目,只依赖 OCR、候选描述和通用规则 |
| [mechanics.md](skills/limbus-mirror-speedrun/references/mechanics.md) | 解释核心强化、合成、恢复和版本差异,供助手核实 | 数量、预算、材料组合等应进入代码计算;机制说明本身不会产生执行动作 |
| [shortcuts.md](skills/limbus-mirror-speedrun/references/shortcuts.md) | 用户确认过的操作方式;部分已写成路线、确认和战斗宏 | 还需继续按场景边界复用,不能把快捷键扩展成所有界面的盲输入 |
| [mirror_dungeon_speedrun_notes.md](mirror_dungeon_speedrun_notes.md) | 攻略整理、用户修正和历史实测记录,帮助修订上述资料与代码 | 历史局面不是当前库存;当前运行状态保存在带 run ID 的运行上下文中 |
源码搜索中,`scripts/export_feedback.py` 对笔记和 skill 的引用用于导出反馈副本,并不是决策加载。当前 `lc_mcp` 与辅助脚本的决策循环没有读取这些攻略文件。
本次已同步三项资料说明:旧电脑的绝对执行器路径改为仓库相对路径与运行目录;决策失败改为最新的执行模型交接方式;死亡/重试识别标注为已做离线修复、尚待新实机验证。历史实测记录保留原貌。
## 接下来基础开发的顺序
1. **统一策略来源。** 将明确的楼层目标、技能表、核心保护和刷新限制转成机器可读 profile;skill 与说明引用同一配置。事件资料按当前事件检索,避免每次传全文。
2. **补齐真实状态。** 当前楼层、已持有饰品、强化等级、经费、材料等级和技能状态分别保存证据;未知不等于没有取得,付款成功不等于目标核验完成。
3. **按目标生成动作。** 由本层未完成目标和预算筛选可执行动作,代码计算合成材料点数及资源约束;模型处理剩余语义选择。
4. **复用 AALC 场景执行。** 保持一个游戏执行进程,复用地图缓存及可靠的场景操作;完成一次场景目标后核验,再继续推进。
以上四项是后续基础实现范围。本次流程核对与文档同步不会启动游戏,也没有新增实际通关或提速证据。
+17
View File
@@ -56,3 +56,20 @@ Windows / Python 3.12.14;基础提交 `030527f5de5c83dd8ea6e53288c1c52f3b4a85b
## 导出边界
仅包含本次报告、人工时间线、清理后的三条 Jev 日志、本次时段的服务日志片段、四张游戏截图及测试输出。未包含 API key、MCP token、私有配置、Codex 聊天文件或其他桌面应用截图。代码修复随本反馈分支提供,未推送到默认分支。
## 追加:内置经验本流程的编队拖拽缺陷(同分支后续提交)
原记录把"3 次经验本"当成成功,**这个结论是错的**:只有 2 次真正打完,另一次没进战斗。
- `~/lc_mcp/runs/task_20261003_105743_daily.log`:`11:05:55 [ERROR] tasks\battle\battle.py:83: 超出最大尝试次数,未能进入战斗`。任务子进程仍 exit 0,所以 `task_status` 当时报 `succeeded`——只看退出码会把这次失败算成成功。
- 同日志 `team_formation.py`:`对于配队人数OCR得到:7/5` → `6/5` → `5/5`。AALC 为了进入 5 人副本**点击移除了 TEAMS#1 的两名成员**(实测是六协会以实玛利与 G 公司格里高尔)。这是对用户预设队伍的实际改动,不是只读操作。
根因(按 submodule 约定不改 AALC 源码,从 lc-mcp 侧打补丁):
- AALC 基类要求适配器覆盖 `mouse_swipe_for_team_scroll` 以"规避队伍拖拽判定"(`module/automation/input_handlers/__init__.py` 注释),但上游只有 MuMu 模拟器适配器覆盖了它。Windows 前台(本机 `win_input_type=foreground`,日志确认 `使用前台点击模块`)与后台适配器仍用普通列表手势 `build_windows_scroll_swipe_plan`:escape 仅 30px / 0.01s,在编队列表里不足以脱离"按住罪人卡"判定,滑动被当成拖动卡片。
- 新增 `lc_mcp/aalc_input_patch.py`:按 MuMu 的参数(按 `set_win_size` 缩放 60px escape、保持 0.1s、分段走完、松手前停稳 0.5s)给 `Input`(前台)与 `BackgroundInput`(后台)补等价实现,在 `bootstrap()` 时安装;`WindowMoveInput` 没有 `set_mouse_pos`,保持原样。
- `lc_mcp/tasks.py`:退出码为 0 但日志尾部含 `[ERROR]`/异常行时,`task_status` 增加 `errors` 字段,避免只凭 `succeeded` 判断。
**验证范围**:滑动的几何与补丁安装有单元测试,101 项回归通过(见 [test-results.txt](test-results.txt),已更新为本次 101 项输出)。**真实编队界面上的滑动没有复测**——当时体力 6/120,不足以进入任何副本。下一次有体力跑经验本时应同时核对编队人数与 `errors`。
同一时段另有一项与 AALC 流程无关的养成操作:W Corp L3 堂吉诃德人格等级 35 → 37(HP 161→166、防御等级 34→36),消耗 12 张 III 级经验票,剩余 II 级经验票 19 张;升级时游戏服务器报错一次,点 Retry 后成功。
-75
View File
@@ -1,75 +0,0 @@
# Jev deployment and live mirror controller feedback (2026-10-03)
This is a live deployment record, not a completed speedrun claim. Run
`mirror_20261003_142030` started at `2026-10-03T14:20:30.186+08:00`.
The timer includes English UI compatibility work and all interruptions.
## Deployment
- Updated main from `97eca20` to `95ae060`, preserving local AALC files.
- Restarted `LcMCPServer` and validated a fresh MCP session, screenshot/OCR,
and idle AALC task state. The desktop's old exposed transport stayed closed;
fresh subprocess MCP sessions work without another desktop restart.
- The runtime launcher now imports the repository controller and matching
modules instead of retaining an older independent script copy.
- Configured the actual `jev-1.13-free` choice endpoint at
`https://opencode.ai/zen/v1/systemone`. Credentials stay in private runtime
configuration and are excluded from this repository and feedback.
- An isolated identical route probe took 5468 ms with curl and 1859 ms with
urllib. Switched the live configuration to urllib. Actual subsequent route
calls included 1313 and 1484 ms; there are also slow requests and timeouts.
The isolated probe is not counted as a live game decision.
## Live findings and repairs
1. The restarted Steam game uses English labels. Added controller-side label
compatibility for entry, gift selection, event choices, judgement and
confirmation boundaries. Preserve the original OCR text for diagnostics.
2. `Receive` incorrectly matched the old substring check for `REC`, causing
unnecessary event advancement. Match the recording label exactly.
3. English OCR merges adjacent `Very High` labels. Derive separate explicit
rate spans; normalization is idempotent and does not invent a high rate
where OCR only says low or normal.
4. English event outcome text was offered as clickable choices. Exclude
`check`, `gain` and E.G.O Gift description lines from event buttons.
5. Repeated generic confirmation requests added API latency. Execute a sole
validated confirmation directly. Route and branch choices still use Jev.
6. Route and sinner API requests now contain current relevant observations,
rather than unrelated entry, fusion and party setup requirements.
7. Sinner candidates are constrained to the explicitly highest visible rate;
explicit OCR rates precede ambiguous colour-only candidates. The log saves
the provider's scored candidate scope. Zeros outside that scope represent
constraints, not extra probabilities returned by the API.
8. Initial candidate pruning caused a probability-set validation error. Fixed
the adaptation between scoped provider probabilities and router validation,
and added an integration regression test.
9. An enabled Commence button initially competed with sinner selection, causing
repeated selection. An enabled judgement button now takes priority.
10. Enter sometimes fails on event judgement. Added the actual observed button
as its mouse fallback. The original fallback list omitted judgement.
11. A changing event video clock reset repeat detection. Ignore both colon and
decimal clock formats when detecting unsuccessful confirmations.
12. After combat, OCR read the map heading as `Exploring Floor` or
`Exploring FloorT` without a valid digit. The old normalizer failed to mark
this as a map, so P/Enter batches continued on the map for several minutes.
Recognize the map heading independently of its floor number and retain
the previously known floor. Added a regression against continuing battle.
## Progress verified so far
- Entry blessings: base 1, 3 and 10; no enhanced blessings.
- Starter gifts: Barbed Lasso and Fluorescent Lamp.
- Actual Battery and permitted Thunderbranch obtained.
- Floor 1 pack: Nest, Workshop, and Technology, with Talisman Bundle in the
displayed clear rewards. One pack refresh was used before finding it.
- Kept the user's seven-character preset and used Enter to enter combat.
- First battle completed, then two event nodes completed. At 15:27 the
controller entered another battle using its P/Enter macro.
- No final reward or dungeon completion has been verified in this record.
The preceding interruptions do not qualify as a successful fast run.
The controller sends background game inputs. There is one game executor;
root interventions occur only after it hands off or stops. Battle batches
use P/Enter, and deterministic confirmations and event advancement avoid
per-key model decisions. Each action and timing remains in the private
runtime JSONL log; no provider key is written into it.
+12 -6
View File
@@ -2,7 +2,7 @@
"exported_at_utc": "2026-10-03T02:55:31.845399+00:00",
"base_commit": "030527f5de5c83dd8ea6e53288c1c52f3b4a85bb",
"test_exit_code": 0,
"tests_passed": 94,
"tests_passed": 101,
"main_story_cleared": false,
"jev_calls_logged": 3,
"simultaneous_human_input_confirmed": true,
@@ -49,18 +49,24 @@
},
{
"path": "README.md",
"bytes": 7606,
"sha256": "518dea5f19e2dd3beec627a173e86337f2a31e4e8020dab523cd407cf1bb33cc"
"bytes": 10061,
"sha256": "304d6a53972561e3638d16e5f76f71d738070646375f1439810c013a873d61de"
},
{
"path": "test-results.txt",
"bytes": 14030,
"sha256": "0e1fd946db3376cd7b727b2f28edfd8955c2e6427895f5a339593589f3c262a0"
"bytes": 14939,
"sha256": "c6e6d0fccddfd05ba67ef618fd449561543135f570357e9a2b1d2e796d8b385b"
},
{
"path": "timeline.jsonl",
"bytes": 3103,
"sha256": "965f2195f3af3e554b89089cc4735ee3cfcc656f31065a72e7ce59027e58fc83"
}
]
],
"followup": {
"date": "2026-10-03",
"summary": "内置经验本流程的编队滑动补丁 + task_status errors 字段; 真实编队界面滑动未复测",
"third_exp_run_battle_error": true,
"teams_1_members_removed_by_aalc": 2
}
}
+13 -7
View File
@@ -1,12 +1,11 @@
{"step": 0, "choice": "run_complete", "action": {"tool": "run_complete", "args": {}}, "jev_ms": 0, "ocr_ms": 0, "screen": null, "at": "2026-10-03T10:55:22", "state": "completed"}
{"step": 0, "choice": "wait", "action": {"tool": "wait", "args": {"seconds": 0.7}}, "jev_ms": 0, "ocr_ms": 0, "screen": null, "at": "2026-10-03T10:55:22", "action_ms": 0, "finished_at": "2026-10-03T10:55:22", "result": {"ok": true, "waited": 0.7}, "state": "running", "battle_context": false}
{"step": 1, "choice": "wait", "action": {"tool": "wait", "args": {"seconds": 0.7}}, "jev_ms": 0, "ocr_ms": 0, "screen": null, "at": "2026-10-03T10:55:22", "action_ms": 0, "finished_at": "2026-10-03T10:55:22", "result": {"ok": true, "waited": 0.7}, "state": "running", "battle_context": false}
test_choice_outside_permitted_actions_is_rejected (test_jev_client.JevClientTest.test_choice_outside_permitted_actions_is_rejected) ... ok
test_configured_model_endpoint_session_and_instructions_reach_api (test_jev_client.JevClientTest.test_configured_model_endpoint_session_and_instructions_reach_api) ... ok
test_curl_credentials_only_on_stdin_and_http_errors_not_retried (test_jev_client.JevClientTest.test_curl_credentials_only_on_stdin_and_http_errors_not_retried) ... ok
test_session_id_stays_stable_across_decisions (test_jev_client.JevClientTest.test_session_id_stays_stable_across_decisions) ... ok
{"step": 0, "choice": "run_complete", "action": {"tool": "run_complete", "args": {}}, "jev_ms": 0, "ocr_ms": 0, "screen": null, "at": "2026-10-03T11:25:38", "state": "completed"}
test_completed_run_archives_context_for_next_run (test_jev_mirror_agent.MainLoopTest.test_completed_run_archives_context_for_next_run) ... ok
{"step": 0, "choice": "wait", "action": {"tool": "wait", "args": {"seconds": 0.7}}, "jev_ms": 0, "ocr_ms": 0, "screen": null, "at": "2026-10-03T11:25:38", "action_ms": 0, "finished_at": "2026-10-03T11:25:38", "result": {"ok": true, "waited": 0.7}, "state": "running", "battle_context": false}
{"step": 1, "choice": "wait", "action": {"tool": "wait", "args": {"seconds": 0.7}}, "jev_ms": 0, "ocr_ms": 0, "screen": null, "at": "2026-10-03T11:25:38", "action_ms": 0, "finished_at": "2026-10-03T11:25:38", "result": {"ok": true, "waited": 0.7}, "state": "running", "battle_context": false}
test_tool_errors_are_observed_instead_of_aborting (test_jev_mirror_agent.MainLoopTest.test_tool_errors_are_observed_instead_of_aborting) ... ok
test_ambiguous_event_is_not_assumed_free (test_jev_mirror_agent.SceneRegressionTest.test_ambiguous_event_is_not_assumed_free) ... ok
test_battle_cinematic_keeps_macro_available (test_jev_mirror_agent.SceneRegressionTest.test_battle_cinematic_keeps_macro_available) ... ok
@@ -90,18 +89,25 @@ test_pythonw_streams_are_redirected_to_log (test_lc_mcp.RuntimeTest.test_pythonw
test_stdio_isolates_bootstrap_output_and_uses_utf8 (test_lc_mcp.RuntimeTest.test_stdio_isolates_bootstrap_output_and_uses_utf8) ... ok
test_template_list_is_scanned_once (test_lc_mcp.RuntimeTest.test_template_list_is_scanned_once) ... ok
test_template_scale_tracks_client_and_restores_config_on_error (test_lc_mcp.RuntimeTest.test_template_scale_tracks_client_and_restores_config_on_error) ... ok
test_clean_log_has_no_errors_field (test_lc_mcp.TaskErrorSurfaceTest.test_clean_log_has_no_errors_field) ... ok
test_exit_zero_with_battle_error_is_reported (test_lc_mcp.TaskErrorSurfaceTest.test_exit_zero_with_battle_error_is_reported) ... ok
test_leftover_restored_before_next_start_or_start_refused (test_lc_mcp.TaskRestoreTest.test_leftover_restored_before_next_start_or_start_refused) ... ok
test_stop_restores_overridden_config (test_lc_mcp.TaskRestoreTest.test_stop_restores_overridden_config) ... ok
test_downward_swipe_shifts_start_into_visible_rows (test_lc_mcp.TeamScrollPatchTest.test_downward_swipe_shifts_start_into_visible_rows) ... ok
test_escape_leg_has_requested_length (test_lc_mcp.TeamScrollPatchTest.test_escape_leg_has_requested_length) ... ok
test_install_patches_team_scroll_on_windows_adapters (test_lc_mcp.TeamScrollPatchTest.test_install_patches_team_scroll_on_windows_adapters) ... ok
test_upward_swipe_escapes_first_then_travels_nominal_delta (test_lc_mcp.TeamScrollPatchTest.test_upward_swipe_escapes_first_then_travels_nominal_delta) ... ok
test_zero_distance_is_noop (test_lc_mcp.TeamScrollPatchTest.test_zero_distance_is_noop) ... ok
test_bridge_end_to_end (test_lc_mcp.TransportTest.test_bridge_end_to_end) ... ok
test_bridge_offline (test_lc_mcp.TransportTest.test_bridge_offline) ... ok
test_client_disconnect_is_not_a_server_error (test_lc_mcp.TransportTest.test_client_disconnect_is_not_a_server_error) ... ok
test_non_ascii_token_is_denied_not_crashed (test_lc_mcp.TransportTest.test_non_ascii_token_is_denied_not_crashed) ... [lc_mcp] rejected connection from ('127.0.0.1', 56231)
test_non_ascii_token_is_denied_not_crashed (test_lc_mcp.TransportTest.test_non_ascii_token_is_denied_not_crashed) ... [lc_mcp] rejected connection from ('127.0.0.1', 51723)
ok
test_stdio_server (test_lc_mcp.TransportTest.test_stdio_server) ... ok
test_wrong_token_rejected (test_lc_mcp.TransportTest.test_wrong_token_rejected) ... [lc_mcp] rejected connection from ('127.0.0.1', 56234)
test_wrong_token_rejected (test_lc_mcp.TransportTest.test_wrong_token_rejected) ... [lc_mcp] rejected connection from ('127.0.0.1', 51726)
ok
----------------------------------------------------------------------
Ran 94 tests in 8.693s
Ran 101 tests in 8.912s
OK
-141
View File
@@ -1,141 +0,0 @@
{
"schema_version": 1,
"logs": [
{
"source": "docs/feedback/2026-10-02/logs/jev_mirror_log.jsonl",
"sha256": "2763abd957bcec7cb7ad0b0b9e29ec9f1f09501f44e506f7d359047397d133e0",
"records": 273,
"action_records": 273,
"tool_counts": {
"advance_dialog": 11,
"battle": 74,
"click": 47,
"click_text": 28,
"drag": 7,
"keypress": 22,
"route": 14,
"wait": 70
},
"state_counts": {
"running": 273
},
"recorded_latency_ms": {
"jev_ms": {
"present_records": 273,
"missing_records": 0,
"invalid_records": 0,
"zero_records": 51,
"positive_records": 222,
"sum_ms": 331526,
"positive_median_ms": 1203.0,
"positive_p95_nearest_rank_ms": 2296,
"positive_max_ms": 8875
},
"ocr_ms": {
"present_records": 0,
"missing_records": 273,
"invalid_records": 0,
"zero_records": 0,
"positive_records": 0,
"sum_ms": null,
"positive_median_ms": null,
"positive_p95_nearest_rank_ms": null,
"positive_max_ms": null
},
"action_ms": {
"present_records": 0,
"missing_records": 273,
"invalid_records": 0,
"zero_records": 0,
"positive_records": 0,
"sum_ms": null,
"positive_median_ms": null,
"positive_p95_nearest_rank_ms": null,
"positive_max_ms": null
}
},
"battle_pair_attempts": {
"reported_batches": 74,
"unreported_batches": 0,
"sum": 842
},
"action_timestamp_spans": {
"naive_local": {
"records": 273,
"first": "2026-10-02T12:09:25",
"last": "2026-10-02T13:50:40",
"span_seconds": 6075.0
}
},
"missing_or_invalid_action_timestamps": 0
},
{
"source": "docs/feedback/mirror_20261002_181322/actions.jsonl",
"sha256": "91ddc1edce0b952df9faad3974d008d37d608f0819995d09a6c8115c326741a0",
"records": 409,
"action_records": 408,
"tool_counts": {
"advance_dialog": 35,
"battle": 51,
"click": 92,
"click_text": 28,
"keypress": 31,
"route": 27,
"wait": 144
},
"state_counts": {
"new_run": 1,
"running": 408
},
"recorded_latency_ms": {
"jev_ms": {
"present_records": 408,
"missing_records": 0,
"invalid_records": 0,
"zero_records": 408,
"positive_records": 0,
"sum_ms": 0,
"positive_median_ms": null,
"positive_p95_nearest_rank_ms": null,
"positive_max_ms": null
},
"ocr_ms": {
"present_records": 0,
"missing_records": 408,
"invalid_records": 0,
"zero_records": 0,
"positive_records": 0,
"sum_ms": null,
"positive_median_ms": null,
"positive_p95_nearest_rank_ms": null,
"positive_max_ms": null
},
"action_ms": {
"present_records": 0,
"missing_records": 408,
"invalid_records": 0,
"zero_records": 0,
"positive_records": 0,
"sum_ms": null,
"positive_median_ms": null,
"positive_p95_nearest_rank_ms": null,
"positive_max_ms": null
}
},
"battle_pair_attempts": {
"reported_batches": 51,
"unreported_batches": 0,
"sum": 1080
},
"action_timestamp_spans": {
"naive_local": {
"records": 408,
"first": "2026-10-02T18:17:21",
"last": "2026-10-02T20:52:04",
"span_seconds": 9283.0
}
},
"missing_or_invalid_action_timestamps": 0
}
]
}
@@ -1,232 +0,0 @@
# Jev 决策与 AALC 自动化复用研究
研究日期:2026-10-03。分析基线:远端 lc-mcp `97eca204`、本地可靠性修复 `7188b4a`,AALC 子模块 `7452fad5`(V1.6.1-beta.3)。
本次交付包括代码研究、离线识别样例、可复现日志统计,以及 Jev/执行模型共用的决策预留接口。完整 AALC 混合执行器尚未接入,尚未进行新的游戏速度实测。
## 结论:本地识别页面,Jev 判断选择,AALC 执行流程
采用用户明确提出的流程:AALC 的图片匹配、地图识别及 OCR 产出页面状态,交给 Jev 判断。Jev 接收文字或结构化状态;截图留在本地用于识别和复核。
官方说明 Jev 不支持图片、音频和视频输入,支持字符串、JSON 对象或数组。官方也提示其中文等 CJK 输入准确率目前低于英文。因此应优先用稳定的英文枚举描述场景和节点,保留中文原文供事件判断与审计,实际准确率需要用本项目样本测量。[TypeSafe:State](https://docs.typesafe.ai/concepts/state)
```mermaid
flowchart LR
A[MCP 启动任务和查询状态] --> B[唯一游戏执行进程]
B --> C[AALC 截图 / 模板匹配 / 局部 OCR]
C --> D[页面状态与证据]
D --> E[代码筛选合法候选]
E --> F{是否需要语义判断}
F -->|需要| G[Jev 选择候选 ID]
F -->|确定步骤| H[AALC 场景流程]
G --> H
H --> I[检查页面变化与目标结果]
I --> C
```
这里的自动化单位应是“进入一个节点”“处理一个商店目标”“完成一次事件判定”,让一次决策对应一段有终点的动作。确认按钮、加载等待、已知事件的后续对话、战斗输入等确定步骤可由代码推进。地图及商店需要新的信息或发生分支时再决策。
## 当前实现已有的能力与缺口
| 位置 | 已有能力 | 对此次优化的影响 |
| --- | --- | --- |
| `lc_mcp/aalc_engine.py:79–114` | AALC 截图与 OCR;返回文字、位置、OCR 分数 | 已能在本地生成文字观测。当前每次 `get_state` 都保存 PNG 并做整帧 OCR |
| `scripts/jev_mirror_agent.py:57–127` | 复用 AALC 总线、箭头、节点图片,以 OpenCV 匹配和 ORB 识别可达节点 | 已能直接产出地图候选,无需视觉模型;匹配数和亮度阈值不是校准后的正确率 |
| `scripts/jev_mirror_agent.py:130–539` | 页面文字规则、卡包限制、场景动作候选 | 部分硬约束已在代码内生效;许多信息仍藏在描述文字或手工更新的运行上下文中 |
| `scripts/jev_mirror_agent.py` 的 `decide()` | 向 Zen System One 发送 OCR 文字,接收候选 ID | 研究开始时硬编码免费模型并丢弃概率;本次已改为读取实际模型、保留概率及 confidence |
| `scripts/jev_decision_client.mjs` | 返回 choice、confidence、probabilities、model | 是独立实现,Python 主循环没有调用它;需要统一行为与配置 |
| `scripts/jev_mirror_agent.py` 的决策分支 | 原来 401/403/429 后持续规则回退 | 本次已改为执行模型交接,并记录决策来源;自动冷却恢复仍待长期执行器实现 |
| `lc_mcp/aalc_task.py` | 通过 `run_task` 启动完整 AALC 镜牢任务 | 当前镜牢参数仅覆盖次数,未提供配置预览、策略选择或决策钩子 |
| `lc_mcp/tasks.py:62–79` | 根据任务子进程退出码报告成功 | 退出码 0 只说明进程结束,不能直接代表完成镜牢及领取奖励 |
目前 Jev 输入包含全屏 OCR、候选描述、最近动作和所有全局规则。应改成针对当前页面的状态及规则,避免将楼层、技能、卡包、商店、战斗等要求同时塞入每次选择。
## 离线证明:现成识别代码已经能输出可用状态
对 `tests/fixtures/floor4_white_events.png` 调用现有 `map_candidates()`,识别出:
- `route_w`:上方可达事件节点,ORB 匹配数 53。
- `route_d`:正前方可达事件节点,ORB 匹配数 30。
导出文件:[页面状态与 Jev 请求样例](jev_page_state_example_20261003.json)。此次只读取现有测试图片,未向 Jev 请求,也未向游戏发送输入。样例中的楼层明确标为未提取,不能因为文件名带有 floor4 就当成识别结果。
现成函数返回的是候选描述。下一步应让识别器直接返回 `node_type`、`reachable`、匹配分数、证据区域和动作引用,减少再次解析自然语言描述。候选坐标由执行器持有,Jev 只需要知道节点语义及合法候选 ID。
建议的页面状态合同如下,数值仅用于说明结构:
```json
{
"schema_version": 1,
"observation_id": "frame-123",
"scene": {"value": "shop", "status": "observed", "evidence": ["shop_coins_template"]},
"floor": {"value": 3, "status": "confirmed"},
"coins": {"value": 350, "status": "observed", "source": "shop_coin_ocr"},
"goals": ["enhance_core_gift", "replace_allowed_skills"],
"legal_candidates": [
{"id": "enhance_core", "kind": "enhance", "affordable": true},
{"id": "leave_shop", "kind": "leave"}
],
"unknown_fields": ["current_gift_upgrade_level"],
"last_action": {"id": "open_enhance", "verified_effect": false}
}
```
`status` 要区分本帧观测、先前确认、未知及冲突。OCR 分数、模板分数、场景识别强度、Jev 的 confidence 分别记录,不能混成一个“可信度”。空 OCR 可能是动画或加载,必须结合场景证据和前一动作判断。
同一帧的观测供识别与候选生成共用;输入后使旧观测失效。执行前校验 observation ID、页面关键标志和候选是否仍可用。结果没有证据时保留“待确认”,不能仅因点击 API 返回 `ok` 就把库存升级等目标标为完成。
## 可以复用的 AALC 配置与流程
配置来源为 `vendor/aalc/module/config/config_typing.py`、`assets/config/config.example.yaml`,以下映射根据实际消费配置的代码核对。
| 场景 | 现有配置 | 现有执行点 | 复用边界 |
| --- | --- | --- | --- |
| 任务与队伍 | `teams_active_queue`、`teams`、`fixed_team_use`、`fixed_team_use_select`、`hard_mirror` | `script_task_scheme.Mirror_task()`,`Mirror` 初始化与选队 | 复用有效队伍队列及普通/困难适用范围,启动前检查确有可执行队伍 |
| 队伍与编队 | `sinner_order`、`chosen_sinners`、`team_number`、`re_formation_each_floor` | `Mirror.select_mirror_team()`、战斗编队流程 | `sinner_order` 是各罪人的优先序,不能直接当成角色 ID 数组 |
| 开局增益与饰品 | `opening_bonus`、`opening_items`、`opening_items_select`、`opening_items_system`、`use_starlight` | `Mirror.enter_mir_with_star()`、开局饰品选择 | 优先使用已有配置;枚举索引与用户指定饰品需用资源及页面核对 |
| 地图 | `mirror_keyboard_navigation`、`mirror_keyboard_simple_pathfinding` | `MirrorMap`、`Mirror.search_road()`、`enter_next_node()` | 正常模式已有节点图及路线缓存;简单模式总选上方,不能保证更快通关 |
| 卡包 | `theme_pack_list.yaml`、每队 `theme_pack_weight_team_N.yaml`、`use_custom_theme_pack_weight` | `select_theme_pack()` | 权重是偏好,低权重仍可能在最终回退时被选中;不等价于按楼层禁选 |
| 商店购物与刷新 | `shopping_strategy`、`shopping_strategy_select`、`max_keyword_refresh`、`max_normal_refresh`、`ignore_shop` | `Shop.buy_gifts()`、`Shop.in_shop()` | 可复用商品识别及购买流程;需要与当前 MCP 的每店刷新限制统一 |
| 合成与强化 | `shop_strategy`、`do_not_fuse`、`do_not_enhance`、`aggressive_save_systems`、`second_system*` | `Shop.fuse_gift()`、`enhance_gifts()`、`ego_gift_to_power_up()` | 支持体系策略,但不是任意指定核心饰品的保护与预算规则 |
| 技能替换 | `skill_replacement`、`skill_replacement_select`、`skill_replacement_mode` | `Shop.replacement_skill()` | 原生模式按优先角色集合使用同一个替换模式,缺少每角色、每楼层规则 |
| 事件与判定 | 原生事件模板及判定识别 | `Mirror.event_handling()`、`tasks/event` | 复用判定及后续点击;选项未知时需要 Jev 判断,不能套用首项回退 |
| 奖励与结束 | `reward_cards*`、`save_rewards`、`no_weekly_bonuses` 等 | `Mirror.run()` 结算流程、`run_state.py` | 根据配置明确是否领取;正常完整运行需有实际结算与返回大厅的证据 |
| 战斗 | `defense_*` 等 | `battle.fight()` 或已验证的 P+Enter 宏 | 原生完整战斗逻辑包含不同策略,需要匹配本次运行策略后才能替换 |
### 三个不能只靠原配置解决的要求
1. **按楼层严格选择卡包。** 当前 MCP 已实现前四层不选 2 号线、第五层指定 2 号线的部分候选过滤。AALC `select_theme_pack.py:111–149` 在刷新回退后仍选择最高权重,所以把禁选包权重设为 -5 不保证禁选。应保留硬过滤,再复用卡包识别、权重及拖动动作。`select_event_pack` 只是第五层选最左侧包,也不是指定包名。
2. **按罪人及楼层替换技能。** AALC `in_shop.py:1210–1233` 选择前 1/3/7/12 个优先罪人,所有人用同一 `skill_replacement_mode`。当前规则中的奥提斯 2→3、其他角色 1→3、辛克莱从第三层开始,需额外策略表及对应执行适配。
3. **跨体系保护核心与先后预算。** AALC 激进合成保护表及体系保护见 `in_shop.py:417–445`,普通合成还依赖舍弃体系及固定资源列表。不能假定破裂队配置会保护标准负载电池等全部指定核心。原生商店顺序为技能→治疗→出售→购买→合成→强化;“先把核心强化到目标等级并保留技能预算”需要明确动作顺序和每次付款后的验证。
这些确定约束应放在代码和配置里。Jev 只在通过约束的候选之间判断。
## 已接入的决策预留接口
新增 `scripts/decision_router.py`,并接入当前 `jev_mirror_agent.py`。支持四个模式:
| 模式 | 行为 |
| --- | --- |
| `auto`(缺省) | 指定 Jev model 且有凭据时调用 Jev;否则交给执行模型 |
| `jev` | 使用明确配置的 Jev;未配置完整或调用失败时交给执行模型 |
| `executor` | 交给当前执行模型,即使配置里有 Jev 凭据也不调用 Jev |
| `fixed` | 显式使用原固定策略;保留 `LC_FIXED_FALLBACK=1` 的覆盖行为 |
统一接口接收页面状态、合法候选、最近动作和 run ID,返回候选 ID 及决策来源。Jev 成功时保留 model、confidence、probabilities 和耗时;失败时使用执行模型回调或发布交接请求。
嵌入运行时的回调形式是 `executor_decider(request)`,可传给 `DecisionRouter` 或当前主脚本的 `main(executor_decider=...)`。它可返回候选 ID,或 `{"request_id": "同一个请求 ID", "choice": "合法候选 ID"}`。执行模型得到独立的观测和候选副本,不能通过修改请求来改变执行器持有的动作。未列出的候选和不匹配的请求 ID 被拒绝。凭据及 Provider 配置不在交接内容中。
独立脚本没有访问当前聊天模型的 API,因此通过 stdout、状态文件及 `decision_request.json` 发布 `requires_decision` 并退出当前控制循环。调用方的执行模型接收交接、重新检查页面并处理,然后 `--resume` 继续本局;这类状态已加入可续跑集合。嵌入长期执行器时由调用方提供回调,可在同一进程中连续完成选择与执行。
交接请求包括 run ID、request ID、观测、候选、规则和最近动作,并明确要求外部输入前重新观察。它是一次观测的决策通知,不能自动执行遗留请求文件。当前实现尚未提供从响应文件自动消费答案的命令,也尚未实现执行模型的自动调度连接。
### 启动前需要的配置检查
本地当前 checkout 没有 `vendor/aalc/config.yaml`,其他电脑实测反馈也没有提供完整运行配置。配置表依据源码和示例文件,不代表已读取另一台电脑的实际配置。
未来增加只读配置预览,列出有效队伍、队列、镜牢模式、开局配置、商店策略、卡包权重及与额外约束的冲突。沿用 AALC 现有队列迁移规则,不能随意重建队伍序号。
`Mirror_task()` 在没有适用队伍或队列为空时直接退出循环(`script_task_scheme.py:321–325`),当前任务包装仍可能以 0 退出并报告 `succeeded`。启动预检查应阻止这种空执行;运行结果应包含请求次数、实际完成次数和结算状态。
## Jev 接入方案
OpenCode 官方列出 `jev-1.13`、`jev-1.13-free` 及 `https://opencode.ai/zen/v1/systemone`,支持 `choice`、`noul`、`score` 和单请求多问题。免费别名被标为限时提供,不能把它硬编码为长期可用前提。[OpenCode:Jev](https://opencode.ai/docs/zen/#jev)
TypeSafe 直连接口使用 `https://api.typesafe.ai/v1/systemone`。Provider、model、endpoint 和对应凭据应成套配置;不能直接把 Zen 凭据或模型别名套入另一个 Provider。[TypeSafe:API](https://docs.typesafe.ai/api)
统一 Provider 选择已由本次 `DecisionRouter` 落地;后续完善场景输入及客户端生命周期:
- 已读取实际 model,校验候选 ID 和响应类型;Provider endpoint 与 timeout 的完整配置仍待扩展。
- 已保留 choice、probabilities、confidence、返回 model 和请求耗时,并记录交接原因。
- `choice` 用于当前路线、事件选项或合法商品选择;`noul` 可判断某事件描述是否包含额外战斗;数量、预算、刷新次数和楼层比较由代码计算。
- 同一页面上相互独立的问题可以合并成一次请求,例如事件选项分类与选项选择;需要先买入商品才能知道的新库存不能在旧状态下并行决定。[TypeSafe:多问题模式](https://docs.typesafe.ai/patterns/fan-out)
- 429 使用有上限的退避及可恢复的冷却状态;可行时读取 Retry-After。401/403 单独记录配置问题。重试失败不自动切换到付费模型。
- 合法确定动作在回退期间可继续执行。未知选择按当前策略重新观察或暂停,不能将回退称为 Jev 已成功判断。
Confidence 是根据选项概率计算的统计量,不能直接当作“动作正确率”。应保存它及前两名的差距,用本项目标注样本分别校准事件、卡包和商店阈值。[TypeSafe:Confidence](https://docs.typesafe.ai/confidence)
官方明确指出 Jev 的精确计算、复杂间接推理、无关长状态和候选顺序等局限。对应本项目应做候选预过滤、使用每场景短规则,并在离线评测中变换候选顺序检查一致性。[TypeSafe:Jev 1.13 局限](https://docs.typesafe.ai/model-jaggedness/jev-1.13)
JSON 状态经 Zen 网关的实际兼容性仍需真实请求确认;适配层可先将精简 JSON 序列化为字符串,保留同样字段与语义。此次没有做 API 可用性或中文准确率实测。
## 实测日志对速度优化的约束
由新工具 `scripts/analyze_feedback.py` 统计,完整数据和输入 SHA-256 见 [统计结果](feedback_latency_profile_20261003.json)。
| 指标 | 2026-10-02 第一批日志 | mirror_20261002_181322 |
| --- | ---: | ---: |
| JSONL 记录数 | 273 | 409 |
| 动作记录数 | 273 | 408(另 1 条为 new_run) |
| 正值 `jev_ms` 记录 | 222 | 0 |
| 记录的 Jev 耗时之和 | 331.526 秒 | 0 秒 |
| 正值 Jev 中位数 / P95 | 1.203 / 2.296 秒 | 无 |
| battle 批次数 | 74 | 51 |
| 记录的 P+Enter 尝试数 | 842 | 1080 |
| wait 动作数 | 70 | 144 |
| 单独记录 `ocr_ms` / `action_ms` | 均无 | 均无 |
第一批日志是过程快照,最终记录说明通关后由用户按 Enter 确认领取,不能作为全自动完成证据。第二轮 `run.json` 记录因 HTTP 429 回退、两次游戏重启及最终人工接管,总时长 9738.9 秒;没有记录完成镜牢或领取最终奖励。
正值 `jev_ms` 是日志所记录请求耗时,失败或未落盘的请求可能不在其中。P+Enter 次数是输入尝试,不是游戏接受次数或战斗回合数。动作时间戳跨度包含加载、停顿与人工处理,不能按截图或时间差推断 OCR、游戏动画和人工时间的各自占比。
从现有证据可以得出:降低 Jev 延迟是可测量的一部分,但无法单独解决第二轮的长时间卡住和接管。必须同时提高状态识别、关键目标完成率和无进展恢复能力。
### 优先验证的速度改进
| 改进 | 源码依据 | 测量方式 |
| --- | --- | --- |
| 模板先识别场景,再按场景做局部 OCR | 当前 `get_state` 整帧 OCR;许多页面已有 AALC 特征模板 | 同一截图集对比识别准确率与 capture/template/OCR 耗时 |
| 复用一帧观测及已核实目标坐标 | 当前 `click_text` 在 `get_state` 后又做一次 OCR(`protocol.py:151–164`) | 统计一次场景动作中的 OCR 调用数;输入后检查观测失效 |
| 一次 Jev 决策运行一段 AALC 流程 | 当前路线、事件、商店多次 MCP 往返,确定步骤也可能反复决策 | 每节点、每商店的 Jev 次数、MCP 次数、耗时与失败率 |
| 保留地图路线缓存,按需求更新节点成本 | AALC `MirrorMap` 缓存路线;图权重 event=1、shop=2、battle=4 | 选路误判率、实际战斗次数、每层耗时;不能用“总选上方”代替 |
| 以场景变化结束等待,保留有上限的重试 | AALC 商店、卡包、路线有固定等待;当前 agent 也有固定 sleep | 动画完成到下一动作的空闲时间、漏输入率及卡住时间 |
| 检测语义状态无进展并重新识别 | 旧记录存在重复战斗输入、特殊商店漏判和无响应 | 当前回合/场景关键标志等语义状态的停留时间,避免把战斗动画当无进展 |
**不能仅调配置就宣称当前 MCP 加速。** AALC `auto.take_screenshot()` 默认按 `screenshot_interval`(0.85 秒)节流,但 MCP `_grab()` 直接调用 `ScreenShot.take_screenshot()`,不经过该节流。把配置间隔调小不会直接改变当前 `get_state` 的耗时。`mouse_action_interval` 也只覆盖相关 AALC 操作,不能替代 agent 内部固定等待。
当前后台按键的按下/释放持续时间是先前可靠性验证的一部分。应先减少重复观测和跨进程往返,再根据游戏接受率调整间隔,不能用按键尝试数增长作为速度改善证据。
## 单一执行进程与接入边界
当前 MCP 已在 AALC 长任务运行时阻止手动输入(`protocol.py:145–146`)。混合模式应让同一个任务进程读取配置、观察页面、请求 Jev、执行 AALC 动作并发布状态;主 MCP 负责启动、状态和停止。
`Mirror` 初始化时复制 TeamSetting,并持有 Shop、地图缓存与统计状态,适合在一次运行中持续复用。不能每次 Jev 选择后重新启动整套 AALC 任务,也不能让外部 agent 与正在运行的 AALC 同时操作。
原生 AALC 尚没有通用决策插件接口。`Mirror.run()` 直接调用模块级 `select_theme_pack()`;仅继承 `Mirror` 不能自动接管该分支。接入需要明确边界:
1. 先在 lc-mcp 增加配置检查、统一 DecisionClient 和页面状态层。
2. 建立一个持续的混合任务进程,持有本次 Mirror/Shop 状态。
3. 为地图、卡包、事件、商店目标添加小范围决策钩子或适配入口;保留已有执行方法。涉及 AALC 调用点的改动需以独立、可维护的补丁管理,避免全局 monkeypatch。
4. 对带有角色、楼层及核心预算要求的商店流程使用专门适配,不能直接调用整段 `Shop.in_shop()` 并假定其固定顺序符合额外规则。
## 实施顺序与验收
| 阶段 | 交付 | 先通过的检查 |
| --- | --- | --- |
| 1. 状态与配置 | 只读 profile 预览、队伍预检查、页面状态合同、分段计时 | 不导入有副作用的配置初始化来做静态预览;不泄漏凭据;空队列明确报错 |
| 2. Jev 决策 | 统一 Python 客户端、紧凑输入、概率保留、429 冷却恢复 | 离线响应回放覆盖未知候选、低信息、限流、超时和中止;真实连接测试单独记录 |
| 3. AALC 复用 | 单进程混合执行、地图/事件/卡包入口,再逐步接商店 | 关键目标有结果证据;候选过期停止;运行中可取消;原配置与额外约束同时遵守 |
| 4. 提速实测 | 基线与混合模式在同机、同队伍/规则/分辨率下比较多次运行 | 全自动完成及确认领取、人工接管次数、每层/每商店耗时、无进展时间、OCR/Jev/MCP 次数 |
新增计时应至少分为 capture、template、ocr、decision、input、等待及验证;为失败的 Jev 请求另记 attempt 延迟。保存实际决策引擎、model、profile 摘要哈希、页面类型、执行目标和结果证据。此前 `ocr_ms` 实际包裹整个 `get_state` 往返,不能称为纯 OCR 内核耗时。
离线截图集先覆盖已知问题:紫色可达节点、特殊商店、加载中的旧库存、事件判定、卡包楼层限制、最终领取及返回大厅。用标注页面/选项评估识别和决策,随后做实机验证。没有相同条件的新实测前,不承诺具体通关分钟数。
## 本次可复现产物
- 本报告:`docs/jev_aalc_automation_research_20261003.md`。
- 离线页面状态及请求样例:`docs/jev_page_state_example_20261003.json`。
- 日志统计:`docs/feedback_latency_profile_20261003.json`。
- 统计工具:`scripts/analyze_feedback.py`(标准库,只读日志,不连接游戏、MCP 或网络)。
在仓库根目录运行:
```powershell
python scripts/analyze_feedback.py docs/feedback/2026-10-02/logs/jev_mirror_log.jsonl docs/feedback/mirror_20261002_181322/actions.jsonl
```
决策接口实现:`scripts/decision_router.py`,主脚本接入及续跑支持:`scripts/jev_mirror_agent.py`、`scripts/run_state.py`。验证覆盖 Provider 路由、无配置交接、Jev 限流/超时/无效回复、候选及请求 ID 校验、交接无输入和本局续跑。
本次全量离线回归:124 项全部通过,耗时 8.670 秒。执行模型回调到路线动作的闭环使用 mock MCP 验证;图片匹配使用真实测试截图离线验证。日志统计重新生成一致,缺失耗时没有被当成 0。`git diff --check` 通过。
本次未改变正在运行的输入方式、系统驱动或 AALC 运行配置;未发送真实 Jev 请求。完整 AALC 混合执行器、配置工具和分段识别方案仍为后续实施设计。
-69
View File
@@ -1,69 +0,0 @@
{
"schema_version": 1,
"source": {
"mode": "offline_fixture",
"fixture": "tests/fixtures/floor4_white_events.png",
"sha256": "55ecd21353493b15c2967a7f6a0de34ce6ce9e3402eac63a42a69f74234ebcc8",
"recognizer": "scripts/jev_mirror_agent.py:map_candidates",
"method": "OpenCV template matching, arrow brightness and ORB icon matching; no vision-model API"
},
"observed_candidates": {
"route_w": {
"description": "上方有高亮可达节点:事件,图标匹配数53,中心(1059,343)。按方向键选中后直接回车进入,无需二次确认。",
"action": {
"tool": "route",
"args": {
"key": "w"
}
}
},
"route_d": {
"description": "正前方有高亮可达节点:事件,图标匹配数30,中心(1059,680)。按方向键选中后直接回车进入,无需二次确认。",
"action": {
"tool": "route",
"args": {
"key": "d"
}
}
}
},
"jev_request_example": {
"model": "jev-1.13-free",
"state": {
"scene": "map",
"scene_evidence": "Bus template and adjacent-node observations from the offline map fixture",
"floor": {
"value": null,
"status": "not_extracted_from_this_image"
},
"routes": [
{
"id": "route_w",
"observation": "上方有高亮可达节点:事件,图标匹配数53,中心(1059,343)。按方向键选中后直接回车进入,无需二次确认。"
},
{
"id": "route_d",
"observation": "正前方有高亮可达节点:事件,图标匹配数30,中心(1059,680)。按方向键选中后直接回车进入,无需二次确认。"
}
],
"goal": "Prefer a reachable event or shop over battle when the node type is reliably identified."
},
"questions": {
"next_route": {
"type": "choice",
"instructions": "Choose one supplied route from the current observations. Choose reobserve if the available information is insufficient.",
"criteria": {
"route_w": "上方有高亮可达节点:事件,图标匹配数53,中心(1059,343)。按方向键选中后直接回车进入,无需二次确认。",
"route_d": "正前方有高亮可达节点:事件,图标匹配数30,中心(1059,680)。按方向键选中后直接回车进入,无需二次确认。",
"reobserve": "Refresh the local template/OCR observation if no route has a reliably identified type."
}
}
}
},
"limitations": [
"Offline recognition only; the example request was not sent to Jev.",
"The existing recognizer emits textual node descriptions rather than typed node fields.",
"Reachability/icon-match observations do not establish a calibrated accuracy or confidence probability.",
"The adapter must validate structured state support at the configured gateway; JSON-as-text is a compatible fallback."
]
}
-23
View File
@@ -1,23 +0,0 @@
# MCP 运行可靠性改进(2026-10-03)
基于 `97eca204` 的代码与另一台电脑提交的 2026-10-02 实测资料,修复离线复现确认的问题。改动未修改 AALC 子模块、输入后端或系统驱动;未启动游戏或重启常驻服务。
原先运行结束后,`claim_requested` 等上下文会遗留在磁盘。下一次执行器若读到这个标记与大厅文字,会把一个新的运行记录直接写成完成。现在运行记录与上下文共享 `run_id`;已完成局的状态不会被新局复用。领取和返回截图绑定当前局,缺少证据时不能设置完成字段。默认续跑有效的未完成记录;`--new-run` 建立全新状态,`--resume` 要求已有未完成记录。
旧版本未完成记录允许迁移:保留楼层、强化等进度,删除未绑定当前局的领取及战斗标记。没有运行记录的孤立上下文会重置。两份记录的标识不一致时停止并报告原因。JSON 快照改为临时文件写完后原子替换,中断不再留下半份 JSON。战斗上下文随当前局保存,也不再为推断它而读取全部历史动作日志。
原先客户端会无限阻塞在回复读取上;标准错误管道无人读取时也可能堵住子进程。现在标准输入、输出和错误流由独立线程处理,请求有期限,并在等待期间检查停止标记与运行预算。默认期限 30 秒,文字等待工具按其轮询时长增加 5 秒余量,仍受控制器总预算约束。初始化失败、超时、停止或无效回复均清理客户端子进程和管道。错误日志仅保留有限尾部供本地诊断。
超时不代表远端动作没有执行。客户端关闭连接后不会重放请求;状态日志记录 `outcome_unknown` 和相关工具名。停止或总预算耗尽时标记 stopped;超时和其他异常标记 requires_analysis。领取、完成、要求分析和异常终止会留下日志;步骤上限到达时也有明确停止状态。固定候选模式不再强制要求无用的 API 密钥。连接清理即使出错,也会释放执行器互斥句柄。
独立 `battle_batch.py` 原先漏掉判定、奖励卡与全员死亡界面。现在两个战斗入口共享场景识别,并在每个按键前检查停止标记和预算;空 OCR 的特写仍允许继续当前战斗,明确的退出界面则返回。新客户端在等待 MCP 回复期间也能响应停止。普通睡眠与已接收的服务端操作不保证立即取消。
MCP 请求现在先验证 JSON-RPC 外层、参数对象与工具名称/参数类型。坏请求返回协议错误,后续合法请求继续处理;通知不返回响应,也不能作为无 ID 的输入调用执行。`null` 请求不再被当作空行忽略。另修复完整任务启动与已经开始的手动输入之间的竞态:忙碌时立即拒绝启动完整任务,查询与停止任务仍不等待游戏工具锁。
验证使用 Python 3.12 的临时环境。全套 unittest:**105 项通过,无跳过**,其中原有 73 项,新增 32 项。新增测试包含真实子进程管道的无响应、阻塞写入、密集 stderr、中文响应、初始化失败与取消;还通过实际 bridge 连入隔离的 FakeEngine TCP 服务,验证新客户端与原有桥接的兼容性。其他测试核对旧状态迁移、领取证据、原子写入失败、任务并发、按键中途停止和终止界面。所有游戏输入均为 mock 或 FakeEngine,没有操作真实游戏。
测试通过证明这些离线边界已修复,不能证明自动通关或提速。另一台电脑的第一局最后确认由用户完成,第二局以人工接管结束;后续完整流程、截图识别和速度效果仍需要新的一局实测。商店合成/强化、未明确识别的事件等仍可能要求主助手核对。约 70 MB 历史截图压缩包未下载,已分析保存的独立证据截图与日志。
下一轮实测应从开局到领取后返回大厅使用同一 run_id,保留人工干预记录;出现 outcome_unknown 时先核对游戏画面,避免重复确认已经执行的操作。新开局使用 --new-run,重启游戏后继续同一存档使用 --resume。停止文件需要在准备继续时移除。
本轮提交只包含程序、测试和说明文件,没有包含个人运行记录、凭据、虚拟环境或历史物理驱动资料。
+2 -6
View File
@@ -35,7 +35,7 @@ description: 继续或重开边狱公司(Limbus Company)的镜像迷宫/
## 速度与完成标准
用户最初指定 Jev 负责场景、路线及常规操作决策。后续指令(2026-10-03)要求保留执行模型接管:配置 Jev 模型和凭据时使用 Jev,未配置或调用失败时交给执行模型。调用方式见 [决策接入](references/jev.md)。最新战斗指令优先:一旦战斗开始,仅执行 P+回车直到结算,不再逐批请求模型;有界批次末只检查是否结算,未结算继续下一批。执行器仅暴露当前画面核对过的候选动作,不能执行模型返回的任意代码。仓库执行器为 [scripts/jev_mirror_agent.py](../../../scripts/jev_mirror_agent.py),运行目录默认是 `~/lc_mcp/jev`,可用 `LC_JEV_HOME` 覆盖;状态文件为 `jev_mirror_status.json`。
用户已明确指定 Jev 负责固定场景、路线及常规操作决策。调用方式见 [Jev 接入](references/jev.md)。主助手只在 Jev 返回 `requires_analysis` 或出现具体接口故障时分析、修复,然后交回 Jev。最新战斗指令优先:一旦战斗开始,仅执行 P+回车直到结算,不再逐批请求模型;有界批次末只检查是否结算,未结算继续下一批。执行器仅暴露当前画面核对过的候选动作,不能执行模型返回的任意代码。当前执行器为 lc-mcp 仓库的 `scripts/jev_mirror_agent.py`,状态与问题保存在运行目录(默认 `~/lc_mcp/jev`,可用 `LC_JEV_HOME` 指定)的 `jev_mirror_status.json`。
略过无关观测、采购、调队和反复比较,保留符咒 ++、快感 ++ 与关键技能替换。雷枝是用户允许的观测例外,不将此授权扩展为所有饰品的无界观测。大量理智损失可能增加纯 P 战斗回合,不能只按当前事件点击次数选择。
@@ -43,8 +43,4 @@ description: 继续或重开边狱公司(Limbus Company)的镜像迷宫/
持续到本局通关结算,或用户中止/必须手动接管的具体步骤。只有看到最终通关结算才能报告完成。研究完攻略或做完一层不算通关;不承诺复现视频的 12 分钟用时。
用户纠正流程时,在授权范围内更新相应参考文件和仓库 [速通笔记](../../mirror_dungeon_speedrun_notes.md);先读笔记,保留用户其他编辑。攻略资料核对日期:2026-10-02;执行接口说明更新于 2026-10-03。
## 文档与程序的对应范围
本 skill 和参考文件是执行助手的工作说明,文件存在不表示 Python 自动加载全部攻略。当前脚本把部分用户规则写入 `SYSTEM_RULES`、候选筛选和动作宏;楼层完整目标、事件速查与合成预算还需要进一步接入。按当前游戏文字核实强化、库存和预算,不能用文档中的期望状态代替实际持有状态。具体对应关系见 [执行流程与资料覆盖](../../execution_flow_and_guide_coverage_20261003.md)。
用户纠正流程时,在授权范围内更新相应参考文件和现有速通笔记(lc-mcp 仓库 `docs/mirror_dungeon_speedrun_notes.md`);先读笔记,保留用户其他编辑。资料核对日期:2026-10-02。
@@ -3,14 +3,14 @@
2026-10-01 用户授权通过其 OpenCode API 接入 Jev,目标为加快镜牢推进。
- 官方接口:`https://opencode.ai/zen/v1/systemone`;用户给的 Go 模型列表中没有 Jev,不把 Go chat/completions 当作 Jev 接口。
- 历史实测 `jev-1.13-free` 返回 HTTP 200,结构为 `answers.action.choice`,当时请求耗时约 1.3–1.5 秒。这不代表当前接口已连接,也不是整局速度保证。
- 当前 Python 执行路径为仓库 [jev_mirror_agent.py](../../../../scripts/jev_mirror_agent.py),通过 [decision_router.py](../../../../scripts/decision_router.py) 选择 Jev 或执行模型,并返回候选 ID、概率及耗时;Jev 请求由 [jev_client.py](../../../../scripts/jev_client.py) 发出(支持 `baseUrl`、`transport: curl`)。仓库另有独立的 `scripts/jev_decision_client.mjs`,Python 主循环不调用它。
- 已实测 `jev-1.13-free` 返回 HTTP 200,结构为 `answers.action.choice`,当前请求耗时约 1.3–1.5 秒。这不是整局速度保证。
- 现有客户端:lc-mcp 仓库的 `scripts/jev_decision_client.mjs`,导出的 `decide(state, criteria, options)` 返回有限选项编号、概率和请求耗时。
- 密钥从 `options.apiKey`、`OPENCODE_API_KEY` 或用户已有本机配置注入;不把密钥复制到脚本、笔记、skill 或日志,也不打印配置全文。重启后若没有凭据,不能假装已接通。
- 只发送精简游戏状态和选项文字,避免整段聊天、其他窗口、完整桌面截图等无关内容。
- 先按用户规则排除不合适的选项,再将候选交给模型。当前界面和用户新指令优先;不把模型置信度当作游戏事实。
- 用户更新(2026-10-02):固定场景、路线及所有常规动作均由 Jev 从候选中选择;主助手仅在 `requires_analysis` 或具体接口故障后介入。战斗动作可包含有界 P→回车短批次。API 短暂错误可重试一次,持续失败交回主助手修复。
- 后续战斗指令覆盖逐批决策:战斗开始后仅 P+回车循环直至结算;有界批次末检查结束标志,战斗中不再调用 Jev 或分析拼点。结算后恢复 Jev 决策。
- 执行器通过 limbus MCP 操作;Windows 单实例互斥避免输入交叠。运行目录默认 `~/lc_mcp/jev`,可用 `LC_JEV_HOME` 覆盖;状态为 `jev_mirror_status.json`,动作日志为 `jev_mirror_log.jsonl`。确认弹窗候选使用当前截图坐标并排除背景按钮。商店没有出战角色技能替换时,每店最多刷新 4 次。
- 执行器 lc-mcp 仓库的 `scripts/jev_mirror_agent.py` 通过 limbus MCP 操作;Windows 单实例互斥避免输入交叠。状态为 `jev_mirror_status.json`,动作日志为 `jev_mirror_log.jsonl`。确认弹窗候选使用当前截图坐标并排除背景按钮。商店没有出战角色技能替换时,每店最多刷新 4 次。
## 已落实的执行边界(2026-10-02)
@@ -18,7 +18,7 @@
- 层末选择数达到要求后,一次发送三个回车;事件结果用短批次回车。同一画面仍未推进时,点击本候选绑定的确认控件,避免命中背景按钮。
- 判定优先 OCR 明确的极高/非常高,其次高;没有清晰文字才按金黄色标识选。没有结果文字的事件选项不能当免费奖励;明确触发战斗的选项排除,选择前读取事件速查。
- 雷枝观测领取后记为待强化,商店打开强化面板;快感取得后记为待 ++。主助手付款并确认实际库存后清除对应待办标记;雷枝预算不足可记录延后,不能把预览当完成。快感尽量在第二、三层处理。
- 2026-10-03 后续指令与实现:未指定 Jev 模型、缺少凭据或 Jev 请求失败时交给执行模型。嵌入运行可提供 `executor_decider(request)` 回调;独立脚本发布 `requires_decision` 和 `decision_request.json`,由调用方读取、重新核对页面并处理,再续跑同一局。固定候选回退需显式设置 `decisionEngine=fixed` 或 `LC_FIXED_FALLBACK=1`。回退和接管均不记为 Jev 成功决策。
- Jev 返回 401/403/429 时不反复等待请求,当前执行会话转为固定候选回退,并将 HTTP 原因写入日志;回退不是 Jev 成功决策。
- 用户接管时逐键检查停止标记。日志新增 OCR 毫秒、动作毫秒、动作结束时间;未执行完的批次不伪造完整按键数。优化代码期间保持停止状态。
依据:[OpenCode Zen:Jev](https://opencode.ai/docs/zen/#jev)。
@@ -24,7 +24,7 @@
- **商店资料**:100 经费可用于单人恢复 50% 体力、45 理智,或全队恢复 20% 体力、15 理智;也有复活选项。1→2/2→3/1→3 技能替换报价分别为 45/75/120。实际购买以当前界面为准。[镜牢商店](https://wikiwiki.jp/lcbwiki/鏡ダンジョン)
- **速通推断**:明显低血、低理智时,最后商店一次有用恢复可能比团灭重试省时;这不是每店必买的新规则。不假定能回到已经离开的商店。
- **E.G.O.**:有浮士德不代表装备了治疗 E.G.O.;手动处理先看实际装备、资源和效果。普通战斗仍执行用户的 P+回车;上一局头目手动授权仅适用于那次尝试。[E.G.O. 使用机制](https://limbuscompany.huijiwiki.com/wiki/E.G.O)
- **结束识别**:全体死亡/重试界面也是战斗结束,不能继续 P+回车,也不能自动接受死亡或放弃本局。此项来自上局执行缺陷;2026-10-03 主脚本与 `battle_batch.py` 已共用 `game_scenes.py` 的死亡/重试识别,并通过离线回归,新的整局实机验证仍待完成。
- **结束识别**:全体死亡/重试界面也是战斗结束,不能继续 P+回车,也不能自动接受死亡或放弃本局。此项来自上局执行缺陷,当前控制器仍待补充终止识别。
- **计时**:包含配置、模型等待、加载、修复、失败和所有停顿。用户接管后只记交接前耗时;未取得最终通关奖励不能记为自动成功。
## 资料入口
+4
View File
@@ -43,6 +43,10 @@ def bootstrap():
from module.logger.my_log import Logger
Logger()
_booted = d
# 编队列表滑动: Windows 输入适配器缺队伍拖拽规避, 上游只有模拟器适配器有。
# 在导入 AALC 之后立即打补丁, 服务的 MCP 输入与 run_task 子进程都会生效。
from . import aalc_input_patch
aalc_input_patch.install()
return d
+151
View File
@@ -0,0 +1,151 @@
# -*- coding: utf-8 -*-
"""编队列表滑动补丁: 给 Windows 输入适配器补上队伍拖拽规避。
AALC 基类注释说明 ``mouse_swipe_for_team_scroll`` 需要适配器覆盖以"规避队伍
拖拽判定", 但上游只有 MuMu 模拟器适配器覆盖了它; Windows 的前台(Input)与后台
(BackgroundInput)适配器仍在用普通列表滚动手势 ``build_windows_scroll_swipe_plan``:
按下后只 escape 30px / 0.01s。在游戏的编队列表里这不足以脱离"按住罪人卡"的
判定, 滑动会被当成拖动卡片 —— 队伍顺序被拖乱, 编队人数不足时还会让后续的
"进入战斗"失败(battle.py 报"未能进入战斗")。
这里按 MuMu 的参数(按 set_win_size 缩放的 60px escape、保持 0.1s、分段走完、
松手前停稳 0.5s)在 Windows 适配器上补一份等价实现, 不改 AALC 源码。
"""
import time
from math import hypot
# 与 MuMu 覆盖实现保持一致的量级
ESCAPE_AT_1080P = 60
ESCAPE_HOLD_SECONDS = 0.1
SETTLE_SECONDS = 0.5
POINT_SPACING_AT_1080P = 8
MIN_SEGMENT_DURATION = 0.05
def team_scroll_plan(x, y, dx, dy, duration, escape_distance):
"""编队列表滑动的几何路径(纯函数, 便于单测)。
返回 ``(start, escape, end, duration)``; ``distance == 0`` 时返回 None。
向下滑动(dy > 0)时把起点沿反向偏移 escape, 终点沿正向多走 escape,
这样手指/指针能落在可见行内, 同时保持总位移不变。
"""
distance = hypot(dx, dy)
if distance == 0:
return None
unit_x, unit_y = dx / distance, dy / distance
if dy > 0:
start = (x - unit_x * escape_distance, y - unit_y * escape_distance)
else:
start = (float(x), float(y))
end = (start[0] + dx + unit_x * escape_distance,
start[1] + dy + unit_y * escape_distance)
escape = (start[0] + unit_x * escape_distance,
start[1] + unit_y * escape_distance)
return start, escape, end, max(0.0, float(duration))
def _scaled_escape():
from module.config import cfg
return ESCAPE_AT_1080P * cfg.set_win_size / 1080
def _segment_steps(escape_point, end):
"""把 escape 之后的剩余位移切成小段, 返回 (段数, 位移x, 位移y)。"""
from module.config import cfg
move_x = end[0] - escape_point[0]
move_y = end[1] - escape_point[1]
distance = hypot(move_x, move_y)
if distance == 0:
return 0, 0.0, 0.0
spacing = POINT_SPACING_AT_1080P * cfg.set_win_size / 1080
steps = max(int(distance / max(spacing, 1.0)), 1)
return steps, move_x, move_y
def _foreground_team_scroll(self, x, y, duration=0.3, dx=0, dy=0, move_back=True):
"""前台输入(pyautogui)下的编队列表滑动。"""
import pyautogui
plan = team_scroll_plan(x, y, dx, dy, duration, _scaled_escape())
if plan is None:
return
start, escape, end, total_duration = plan
restore = self.get_mouse_position() if move_back else None
sx, sy = self.pos_offset(*start)
ex, ey = self.pos_offset(*escape)
fx, fy = self.pos_offset(*end)
pyautogui.moveTo(sx, sy)
pyautogui.mouseDown(sx, sy)
try:
pyautogui.moveTo(ex, ey, duration=MIN_SEGMENT_DURATION)
# 让游戏渲染一帧, 确认这是滚动而不是按住卡片。
time.sleep(ESCAPE_HOLD_SECONDS)
steps, move_x, move_y = _segment_steps(escape, end)
if steps:
step_duration = max(total_duration, MIN_SEGMENT_DURATION) / steps
for index in range(1, steps + 1):
ratio = index / steps
pyautogui.moveTo(ex + move_x * ratio, ey + move_y * ratio,
duration=step_duration)
time.sleep(SETTLE_SECONDS)
finally:
pyautogui.mouseUp(fx, fy)
if restore:
self.mouse_move(restore)
def _adapter_team_scroll(self, x, y, duration=0.3, dx=0, dy=0, move_back=True):
"""后台/其它 Windows 适配器下的编队列表滑动(走适配器自身的原语)。"""
plan = team_scroll_plan(x, y, dx, dy, duration, _scaled_escape())
if plan is None:
return
start, escape, end, total_duration = plan
restore = self.get_mouse_position() if move_back else None
self.set_active()
self.set_mouse_pos(*start)
self.mouse_down(*start)
try:
self.set_mouse_pos(*escape, duration=MIN_SEGMENT_DURATION)
time.sleep(ESCAPE_HOLD_SECONDS)
steps, move_x, move_y = _segment_steps(escape, end)
if steps:
step_duration = max(total_duration, MIN_SEGMENT_DURATION) / steps
for index in range(1, steps + 1):
ratio = index / steps
self.set_mouse_pos(escape[0] + move_x * ratio,
escape[1] + move_y * ratio,
duration=step_duration)
time.sleep(SETTLE_SECONDS)
finally:
self.mouse_up(*end)
if restore:
self.mouse_move(restore)
def install():
"""给 AALC 的 Windows 输入适配器装上队伍安全滑动。幂等。"""
from module.automation.input_handlers import input as input_module
patched = []
cls = getattr(input_module, 'Input', None)
if cls is not None and getattr(cls, 'mouse_swipe_for_team_scroll', None) \
is not _foreground_team_scroll:
cls.mouse_swipe_for_team_scroll = _foreground_team_scroll
patched.append('Input')
for name in ('BackgroundInput', 'WindowMoveInput'):
cls = getattr(input_module, name, None)
if cls is None or not hasattr(cls, 'set_mouse_pos'):
continue
if getattr(cls, 'mouse_swipe_for_team_scroll', None) is _adapter_team_scroll:
continue
cls.mouse_swipe_for_team_scroll = _adapter_team_scroll
patched.append(name)
return patched
+7 -29
View File
@@ -78,18 +78,6 @@ class Server:
if not isinstance(msg, dict):
return _error(None, -32600, 'request must be a JSON object')
method, mid = msg.get('method'), msg.get('id')
valid_id = (mid is None or isinstance(mid, str) or
isinstance(mid, (int, float)) and not isinstance(mid, bool) and
(not isinstance(mid, float) or math.isfinite(mid)))
if msg.get('jsonrpc') != '2.0' or not isinstance(method, str) or not method or not valid_id:
return _error(mid if valid_id else None, -32600, 'invalid JSON-RPC request')
notification = 'id' not in msg
params = msg.get('params', {})
if not isinstance(params, dict):
return None if notification else _error(mid, -32602, 'params must be an object')
# Notifications never produce responses or trigger request-only tools.
if notification:
return None
if method == 'initialize':
return _ok(mid, {'protocolVersion': '2024-11-05',
'capabilities': {'tools': {'listChanged': False}},
@@ -99,17 +87,17 @@ class Server:
if method == 'tools/list':
return _ok(mid, {'tools': TOOLS})
if method == 'tools/call':
name, arguments = params.get('name'), params.get('arguments', {})
if not isinstance(name, str) or not name.strip() or not isinstance(arguments, dict):
return _error(mid, -32602, 'tools/call requires a name and object arguments')
result = self.call_tool(name, arguments)
params = msg.get('params') or {}
result = self.call_tool(params.get('name'), params.get('arguments') or {})
return _ok(mid, {'content': [{'type': 'text', 'text': json.dumps(result, ensure_ascii=False)}],
'isError': not result.get('ok', False)})
if mid is None:
return None # 通知 (notifications/*) 不回
return _error(mid, -32601, 'method not found: %s' % method)
def call_tool(self, name, args):
try:
if name in TASK_TOOLS: # 查任务/停任务不等待正在执行的游戏工具
if name in TASK_TOOLS: # 不抢游戏锁: wait_for_text 期间也能查任务/停任务
return self._task_tool(name, args)
with self.lock:
return self._call(name, args)
@@ -125,14 +113,7 @@ class Server:
if task not in TASKS:
raise ValueError('unknown task %r' % task)
params = {k: int(a[k]) for k in TASKS[task] if a.get(k) is not None}
# Starting must not race a click that has already checked running().
# Reject promptly when busy instead of waiting behind a long OCR poll.
if not self.lock.acquire(blocking=False):
return {'ok': False, 'error': 'MCP 工具正在执行,完成后再启动 AALC 任务'}
try:
return self.tasks.start(task, params)
finally:
self.lock.release()
return self.tasks.start(task, params)
if name == 'task_status':
return self.tasks.status(a.get('lines', 30))
return self.tasks.stop()
@@ -235,9 +216,6 @@ def parse_line(line):
if not line:
return None, None
try:
msg = json.loads(line)
if msg is None:
return None, _error(None, -32600, 'request must be a JSON object')
return msg, None
return json.loads(line), None
except ValueError as e:
return None, _error(None, -32700, 'parse error: %s' % e)
-128
View File
@@ -1,128 +0,0 @@
#!/usr/bin/env python3
"""Summarize recorded MCP actions without starting the game or importing AALC.
Only records containing an action object contribute to action/latency statistics.
These records do not prove that the game accepted an input. Missing timings
remain missing: older logs cannot separate observation and execution.
Positive jev_ms values are recorded request latencies, not proof of a successful
decision or an exhaustive account of all API attempts.
"""
import argparse
from collections import Counter
from datetime import datetime
import hashlib
import json
import math
from pathlib import Path
import statistics
def latency_summary(records, field):
values = []
invalid = 0
for record in records:
if field not in record:
continue
value = record[field]
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value < 0:
invalid += 1
continue
values.append(value)
positive = sorted(value for value in values if value > 0)
return {
'present_records': len(values),
'missing_records': sum(field not in record for record in records),
'invalid_records': invalid,
'zero_records': sum(value == 0 for value in values),
'positive_records': len(positive),
'sum_ms': round(sum(values), 3) if values else None,
'positive_median_ms': statistics.median(positive) if positive else None,
'positive_p95_nearest_rank_ms': positive[math.ceil(len(positive) * .95) - 1] if positive else None,
'positive_max_ms': positive[-1] if positive else None,
}
def summarize(path):
path = Path(path)
raw = path.read_bytes()
records = []
for line_number, line in enumerate(raw.decode('utf-8-sig').splitlines(), 1):
if not line.strip():
continue
value = json.loads(line)
if not isinstance(value, dict):
raise ValueError(f'{path}:{line_number}: expected a JSON object')
records.append(value)
actions = [row for row in records if isinstance(row.get('action'), dict)]
tools = Counter(str(row['action'].get('tool', 'unknown')) for row in actions)
states = Counter(str(row.get('state', 'missing')) for row in records)
battle_pairs = []
for row in actions:
if row['action'].get('tool') != 'battle':
continue
result = row.get('result')
value = result.get('pairs') if isinstance(result, dict) else None
if isinstance(value, int) and not isinstance(value, bool) and value >= 0:
battle_pairs.append(value)
# Split aware/naive timestamps rather than silently invent a timezone.
timestamp_groups = {'naive_local': [], 'aware': []}
bad_timestamps = 0
for row in actions:
stamp = row.get('at')
if not isinstance(stamp, str):
bad_timestamps += 1
continue
try:
parsed = datetime.fromisoformat(stamp.replace('Z', '+00:00'))
except ValueError:
bad_timestamps += 1
continue
group = 'aware' if parsed.utcoffset() is not None else 'naive_local'
timestamp_groups[group].append(parsed)
spans = {}
for name, stamps in timestamp_groups.items():
if not stamps:
continue
ordered = sorted(stamps)
spans[name] = {
'records': len(ordered),
'first': ordered[0].isoformat(),
'last': ordered[-1].isoformat(),
'span_seconds': (ordered[-1] - ordered[0]).total_seconds(),
}
return {
'source': path.as_posix(),
'sha256': hashlib.sha256(raw).hexdigest(),
'records': len(records),
'action_records': len(actions),
'tool_counts': dict(sorted(tools.items())),
'state_counts': dict(sorted(states.items())),
'recorded_latency_ms': {field: latency_summary(actions, field) for field in ('jev_ms', 'ocr_ms', 'action_ms')},
'battle_pair_attempts': {
'reported_batches': len(battle_pairs),
'unreported_batches': tools.get('battle', 0) - len(battle_pairs),
'sum': sum(battle_pairs) if battle_pairs else None,
},
'action_timestamp_spans': spans,
'missing_or_invalid_action_timestamps': bad_timestamps,
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('logs', nargs='+', type=Path, help='JSONL action logs')
parser.add_argument('--output', type=Path, help='Save the summary as JSON; otherwise print it')
args = parser.parse_args()
try:
report = {'schema_version': 1, 'logs': [summarize(path) for path in args.logs]}
except (OSError, ValueError) as error:
parser.error(str(error))
payload = json.dumps(report, ensure_ascii=False, indent=2) + '\n'
if args.output:
args.output.write_text(payload, encoding='utf-8')
else:
print(payload, end='')
if __name__ == '__main__':
main()
+29 -46
View File
@@ -1,18 +1,16 @@
"""Bounded Win Rate batches through MCP, with a fresh UI check per turn."""
import argparse
import json
import math
import os
import time
from pathlib import Path
from mcp_session import Session, SessionCancelled, SessionTimeout
from game_scenes import battle_is_terminal, battle_is_visible
STOP_FILE = Path(os.environ.get('LC_JEV_HOME', str(Path.home() / 'lc_mcp' / 'jev'))) / 'JEV_STOP'
from mcp_session import Session
def is_terminal(state):
return battle_is_terminal(state)
texts = [item['text'].replace(' ', '') for item in state.get('items', [])]
return any(text.upper() in ('VICTORY', 'DEFEAT') or
any(marker in text for marker in ('正在探索', '获得E.G.O饰品', '选择主题卡包',
'开始战斗', '选择一位罪人', '选项事件'))
for text in texts)
def main():
@@ -20,47 +18,32 @@ def main():
parser.add_argument('--seconds', type=float, default=40)
parser.add_argument('--battle-confirmed', action='store_true')
args = parser.parse_args()
if not math.isfinite(args.seconds) or args.seconds <= 0:
parser.error('--seconds must be finite and positive')
deadline = time.monotonic() + min(50, max(1, args.seconds))
pairs = 0
state = {}
def cancelled():
return STOP_FILE.exists() or time.monotonic() >= deadline
try:
if cancelled():
raise SessionCancelled('Battle batch stopped before connecting')
with Session(cancelled=cancelled, raise_on_error=False) as client:
with Session(raise_on_error=False) as client:
state = client.call('get_state')
texts = ' '.join(item['text'] for item in state.get('items', []))
active = args.battle_confirmed or any(marker in texts.upper() for marker in ('WAVE', 'TURN', 'DURANTE', '胜率', '伤害'))
while time.monotonic() < deadline:
# 战斗特写会隐藏 HUD;只有明确的结算/地图/选项信号才退出。
if not active or is_terminal(state):
break
# P cycles between Win Rate and Damage in current game versions.
# Only start a turn when its explicit Win Rate control is visible.
labels = [item['text'].replace(' ', '').lower()
for item in state.get('items', [])]
target = next((item['text'] for item in state.get('items', [])
if item['text'].replace(' ', '').lower()
in ('win', 'winrate', '胜率')), None)
if target and any(label in ('turn', 'wave', '回合', '波次') for label in labels):
selected = client.call('click_text', {'text': target})
if selected.get('ok'):
time.sleep(.5)
client.call('keypress', {'key': 'enter'})
pairs += 1
time.sleep(2.5)
state = client.call('get_state')
active = args.battle_confirmed or battle_is_visible(state)
while not cancelled():
# Cinematics hide the HUD; explicit scene boundaries end combat.
if not state.get('ok') or not active or is_terminal(state):
break
# P cycles between Win Rate and Damage in current game versions.
# Only start a turn when its explicit Win Rate control is visible.
items = state.get('items', [])
labels = [item['text'].replace(' ', '').lower() for item in items]
target = next((item['text'] for item, label in zip(items, labels)
if label in ('win', 'winrate', '胜率')), None)
# OCR 常把回合数连在一起(如 'WAVE 1' -> 'wave1'), 用包含匹配
if target and any(m in label for label in labels for m in ('turn', 'wave', '回合', '波次')):
selected = client.call('click_text', {'text': target})
if selected.get('ok'):
time.sleep(.5)
if cancelled():
raise SessionCancelled('Battle batch stopped between Win Rate and Enter')
client.call('keypress', {'key': 'enter'})
pairs += 1
time.sleep(min(2.5, max(0, deadline - time.monotonic())))
if cancelled():
break
state = client.call('get_state')
result = {'pairs': pairs, 'state': state, 'stopped': cancelled()}
except (SessionCancelled, SessionTimeout) as error:
result = {'pairs': pairs, 'state': state, 'stopped': True,
'error': str(error), 'outcome_unknown': error.outcome_unknown}
print(json.dumps(result, ensure_ascii=False))
print(json.dumps({'pairs': pairs, 'state': state}, ensure_ascii=False))
if __name__ == '__main__':
-134
View File
@@ -1,134 +0,0 @@
"""Select a decision provider without giving providers control of game input.
An embedding controller can supply executor_decider(request) for its active
model. Standalone scripts publish DecisionRequired for their caller to handle;
they cannot invoke the caller's model themselves.
"""
from dataclasses import dataclass
import json
import math
import time
import urllib.error
import uuid
class DecisionRequired(RuntimeError):
def __init__(self, request):
super().__init__('The execution model must choose a candidate')
self.request = request
@dataclass
class Decision:
choice: str
engine: str
latency_ms: int
jev_ms: int = 0
confidence: float | None = None
probabilities: dict | None = None
model: str | None = None
fallback_reason: str | None = None
failed_jev_ms: int | None = None
candidate_scope: list | None = None
def _answer(answer, options):
if isinstance(answer, str):
answer = {'choice': answer, 'latency_ms': 0}
elif isinstance(answer, tuple) and len(answer) == 2:
answer = {'choice': answer[0], 'latency_ms': answer[1]}
if not isinstance(answer, dict) or not isinstance(answer.get('choice'), str) or answer['choice'] not in options:
raise ValueError('Decision provider returned an unsupported candidate')
latency = answer.get('latency_ms', 0)
if isinstance(latency, bool) or not isinstance(latency, (int, float)) or not math.isfinite(latency) or latency < 0:
raise ValueError('Decision latency must be a finite non-negative number')
confidence = answer.get('confidence')
if confidence is not None and (isinstance(confidence, bool) or not isinstance(confidence, (int, float))
or not math.isfinite(confidence) or not 0 <= confidence <= 1):
raise ValueError('Decision confidence must be between 0 and 1')
probabilities = answer.get('probabilities')
if probabilities is not None:
if not isinstance(probabilities, dict) or set(probabilities) != set(options):
raise ValueError('Decision probabilities must describe the supplied candidates')
if any(isinstance(p, bool) or not isinstance(p, (int, float)) or not math.isfinite(p) or not 0 <= p <= 1
for p in probabilities.values()) or not math.isclose(sum(probabilities.values()), 1, abs_tol=.01):
raise ValueError('Decision probabilities must form a probability distribution')
return answer['choice'], round(latency), confidence, probabilities, answer.get('model')
class DecisionRouter:
def __init__(self, config, jev_decider, executor_decider=None, fixed_decider=None,
rules='', force_fixed=False):
self.config = dict(config)
self.mode = 'fixed' if force_fixed else self.config.get('decisionEngine', 'auto')
if self.mode not in ('auto', 'jev', 'executor', 'fixed'):
raise ValueError('decisionEngine must be auto, jev, executor or fixed')
self.jev_decider = jev_decider
self.executor_decider = executor_decider
self.fixed_decider = fixed_decider
self.rules = rules
def choose(self, state, options, recent=(), run_id=None):
if not options:
raise ValueError('Decision requires at least one candidate')
if self.mode == 'fixed':
if self.fixed_decider is None:
raise ValueError('Fixed decision provider is not configured')
choice, latency, confidence, probabilities, model = _answer(self.fixed_decider(options), options)
return Decision(choice, 'fixed', latency, confidence=confidence, probabilities=probabilities, model=model)
reason = 'configured_executor'
model = self.config.get('model')
configured_model = isinstance(model, str) and bool(model.strip())
if self.mode in ('auto', 'jev'):
if not configured_model:
reason = 'no_jev_model'
elif not self.config.get('apiKey'):
reason = 'missing_jev_credentials'
else:
started = time.monotonic()
try:
answer = self.jev_decider(self.config, state, options, recent)
choice, latency, confidence, probabilities, returned_model = _answer(answer, options)
return Decision(choice, 'jev', latency, jev_ms=latency, confidence=confidence,
probabilities=probabilities, model=returned_model or model,
candidate_scope=answer.get('candidate_scope') if isinstance(answer, dict) else None)
except urllib.error.HTTPError as error:
reason = 'jev_http_%d' % error.code
except (OSError, TimeoutError, ValueError) as error:
reason = 'jev_unavailable_%s' % type(error).__name__
failed_jev_ms = round((time.monotonic() - started) * 1000)
else:
configured_model = False
request = {
'schema_version': 1,
'request_id': uuid.uuid4().hex,
'run_id': run_id,
'reason': reason,
'requested_engine': 'executor',
'page_state': state,
'candidates': options,
'rules': self.rules,
'recent': list(recent)[-4:],
'execution_contract': {
'response': {'request_id': '<same request_id>', 'choice': '<candidate ID>'},
'requires_fresh_observation_before_external_input': True,
'note': 'The caller handles this decision. No game input is sent while handing off.',
},
}
if self.mode in ('auto', 'jev') and configured_model and self.config.get('apiKey'):
request['failed_jev_ms'] = failed_jev_ms
# The request contains observations and candidates, never provider config
# or credentials. Detach it so the callback cannot alter executable actions.
request = json.loads(json.dumps(request, ensure_ascii=False))
if self.executor_decider is None:
raise DecisionRequired(request)
started = time.monotonic()
expected_request_id = request['request_id']
answer = self.executor_decider(request)
if isinstance(answer, dict) and answer.get('request_id') != expected_request_id:
raise ValueError('Execution-model response belongs to a different decision request')
choice, _, confidence, probabilities, returned_model = _answer(answer, options)
latency = round((time.monotonic() - started) * 1000)
return Decision(choice, 'executor', latency, confidence=confidence, probabilities=probabilities,
model=returned_model, fallback_reason=reason, failed_jev_ms=request.get('failed_jev_ms'))
-28
View File
@@ -1,28 +0,0 @@
"""Shared battle boundaries for all MCP controllers."""
def normalized_texts(state):
return [item['text'].replace(' ', '') for item in state.get('items', [])]
def death_retry_screen(texts):
combined = '\n'.join(texts)
return ('全体罪人' in combined and '死亡' in combined
or '当前剩余人员' in combined and '重试关卡' in combined)
def battle_is_terminal(state):
texts = normalized_texts(state)
markers = ('正在探', '获得E.G.O饰品', '选择E.G.O饰品', '饰品观测',
'开始战斗', '主题卡包', '应该让谁', '选择一位罪人', '进行判定',
'选择遭遇战奖励卡', '选项事件', '选择苦难', '选项', '结果',
'探索完成', '探索结束', '驾驶席', '服务器发生错误', '重试关卡')
return death_retry_screen(texts) or any(
text.upper() in ('VICTORY', 'DEFEAT') or any(marker in text for marker in markers)
for text in texts)
def battle_is_visible(state):
texts = normalized_texts(state)
return (any(marker in '\n'.join(texts).upper() for marker in ('WAVE', 'TURN', 'DURANTE'))
or any(text in ('胜率', '伤害') for text in texts))
+3 -12
View File
@@ -54,15 +54,13 @@ def _post(cfg, body):
return json.loads(content)
def request_answer(cfg, state, criteria, instructions):
"""返回 {'choice', 'latency_ms', 'confidence', 'probabilities', 'model'}; 候选之外的结果会被拒绝。"""
def request_decision(cfg, state, criteria, instructions):
if not cfg.get('apiKey'):
raise ValueError('Jev API key is required')
if not criteria:
raise ValueError('Jev requires permitted choices')
model = cfg.get('model', 'jev-1.13-free')
body = {
'model': model,
'model': cfg.get('model', 'jev-1.13-free'),
'state': state,
'questions': {'action': {'type': 'choice', 'instructions': instructions,
'criteria': criteria}},
@@ -84,14 +82,7 @@ def request_answer(cfg, state, criteria, instructions):
choice = answer.get('choice')
if answer.get('type') != 'choice' or choice not in criteria:
raise ValueError('Jev returned an unsupported candidate')
return {'choice': choice, 'latency_ms': round((time.monotonic() - started) * 1000),
'confidence': answer.get('confidence'), 'probabilities': answer.get('probabilities'),
'model': result.get('model') or model}
def request_decision(cfg, state, criteria, instructions):
answer = request_answer(cfg, state, criteria, instructions)
return answer['choice'], answer['latency_ms']
return choice, round((time.monotonic() - started) * 1000)
def main():
+102 -200
View File
@@ -5,14 +5,12 @@ import json
import os
import re
import time
import urllib.error
import urllib.request
from pathlib import Path
from mcp_session import Session as Bridge, SessionCancelled, SessionTimeout
from game_scenes import battle_is_terminal, battle_is_visible, death_retry_screen
from run_state import prepare_run, save_json, record_claim, claim_is_current, complete_run
from decision_router import DecisionRouter, DecisionRequired
from jev_client import request_answer
from lc_scene_aliases import normalize
from mcp_session import Session as Bridge
from jev_client import request_decision
REPO_ROOT = Path(__file__).resolve().parents[1]
MIRROR_ASSETS = REPO_ROOT / 'vendor' / 'aalc' / 'assets' / 'images' / 'default' / 'share' / 'mirror'
@@ -27,7 +25,6 @@ SYSTEM_RULES = (
'事件当前有“选择后获得”且无需判定、无需战斗的选项时直接选择它,不反复滚动;避开写着战斗胜利后的选项。'
'确定确认/进入/开始战斗直接执行。地图优先可达事件和商店,减少战斗。'
'选好路线直接回车进入,关卡编队界面也直接回车开战;保留原编队,不再检查人员。'
'候选路线已由程序核对可达和节点类型,无需再确认已完成的开局配置。多个同类型节点都可达时默认正前方,不因没有事件节点而要求分析。'
'保留当前编队。开局三级饰品三选一必须选择标准负载电池,再确认领取;不能当成额外观测拒绝。'
'成捆的符咒++、标准负载电池和鸡胸为核心,保留不可出售或合成;仅略过单独的额外观测。其他苦难避开敌方体力上限和防御等级。'
'3层起辛克莱1换3,黑兽奥提斯2换3,其他出战1换3。只在商店强化饰品。'
@@ -43,11 +40,10 @@ def text_items(state):
return state.get('items') or []
def scene_fingerprint(state):
"""Ignore changing clocks and counters when checking failed confirmations."""
return tuple(item['text'] for item in text_items(state)
if item.get('score', 0) > .93
and not re.fullmatch(r'[0-9:.]+', item['text'].replace(' ', '')))
def death_retry_screen(texts):
combined = '\n'.join(texts)
return ('全体罪人' in combined and '死亡' in combined
or '当前剩余人员' in combined and '重试关卡' in combined)
_SCREEN_CACHE = {}
@@ -243,7 +239,7 @@ def candidates(state, previous_battle=False, refresh_used=0):
'y': item['y'] + item['h']//2}},
}
return options
if any(re.fullmatch(r'REC[●.]*', t, re.I) for t in texts) and '选项' not in texts and not any(t in combined for t in ('选择一位罪人', '进行判定', '判定成功', '判定失败', '结果')):
if any('REC' in t.upper() for t in texts) and '选项' not in texts and not any(t in combined for t in ('选择一位罪人', '进行判定', '判定成功', '判定失败', '结果')):
options['event_advance'] = {'description':'事件选项已经确定,按回车快速推进后续文本。', 'action':{'tool':'advance_dialog','args':{'presses':5}}}
return options
if '应该让谁' in combined and '选择一位罪人' not in combined and '进行判定' not in combined:
@@ -510,8 +506,9 @@ def candidates(state, previous_battle=False, refresh_used=0):
'action': {'tool': 'click', 'args': {'x': item['x'] + item['w'] // 2,
'y': item['y'] + item['h'] // 2}},
}
end_screen = battle_is_terminal(state)
battle = battle_is_visible(state)
end_screen = any(t.upper() in ('VICTORY', 'DEFEAT') or any(m in t for m in
('正在探', '获得E.G.O饰品', '选择E.G.O饰品', '饰品观测', '开始战斗', '主题卡包', '应该让谁', '选择一位罪人', '进行判定', '选择遭遇战奖励卡')) for t in texts)
battle = any(m in combined.upper() for m in ('WAVE', 'TURN', 'DURANTE')) or any(t in ('胜率', '伤害') for t in texts)
if not end_screen and (battle or previous_battle):
options['battle'] = {'description': '仍处于战斗或特写:执行短批次 P→回车,两次后检查结算,不分析拼点。',
'action': {'tool': 'battle', 'args': {'rounds': 2}}}
@@ -525,14 +522,10 @@ def candidates(state, previous_battle=False, refresh_used=0):
options['button_%d' % index] = {
'description': '当前可见且非灰色按钮:%s;点击 OCR 中心。' % label,
# 直接点已核对过的这一项: 重新按文字搜索要多一次截图+OCR, 还可能命中背景里的同名按钮
'action': ({'tool': 'keypress', 'args': {'key': 'enter'}} if label in ('进入', '开始战斗', '进行判定')
'action': ({'tool': 'keypress', 'args': {'key': 'enter'}} if label in ('进入', '开始战斗')
else {'tool': 'click', 'args': {'x': item['x'] + item['w']//2,
'y': item['y'] + item['h']//2}}),
}
if options['button_%d' % index]['action']['tool'] == 'keypress':
options['button_%d' % index]['fallback_action'] = {
'tool': 'click', 'args': {'x': item['x'] + item['w']//2,
'y': item['y'] + item['h']//2}}
if (not battle and not in_shop and state.get('screen', {}).get('path')
and Path(state['screen']['path']).is_file()
and not any(t in combined for t in ('确认', '继续', '获得E.G.O', 'SKIP', '选项'))):
@@ -571,9 +564,7 @@ def candidates(state, previous_battle=False, refresh_used=0):
}
for index, item in enumerate(items):
if item['x'] > width * 0.52 and height * 0.23 < item['y'] < height * 0.75 and item['h'] > height * 0.025 and item.get('score', 0) > 0.93:
if (not any(t in item['text'] for t in ('判定', '获得', '成功', '全体', '战斗胜利'))
and not re.search(r'check\b|\bgain\b|\be\.?g\.?o\.?\s*gift|(?:advantage|guilt)check',
item['text'], re.I)):
if not any(t in item['text'] for t in ('判定', '获得', '成功', '全体', '战斗胜利')):
outcome = ';'.join(i['text'] for i in items if i['x'] > width*.52
and item['y']+item['h'] < i['y'] < item['y']+height*.085)
options['event_%d' % index] = {'description': '当前事件选项:' + item['text'] + ';结果:' + outcome,
@@ -582,67 +573,14 @@ def candidates(state, previous_battle=False, refresh_used=0):
def decide(cfg, state, options, recent):
actions = [key for key in options if key not in ('wait', 'requires_analysis')]
route_scene = actions and all(key.startswith('route_') for key in actions)
sinner_scene = actions and all(key.startswith(('sinner_', 'button_')) for key in actions) and any(key.startswith('sinner_') for key in actions)
if route_scene or sinner_scene:
permitted = options
if sinner_scene:
# All explicit maximum-probability cards are legal. An uncertain
# colour-only estimate must not compete with an OCR-labelled rate.
rated = [(key, re.search(r'预计成功率(极高|非常高|高)', options[key]['description']))
for key in actions if key.startswith('sinner_')]
rated = [(key, match[1]) for key, match in rated if match]
if rated:
best = 0 if any(rate != '高' for _, rate in rated) else 1
permitted = {key: options[key] for key, rate in rated
if (0 if rate != '高' else 1) == best}
# These candidates have already been validated against the live scene.
# Party setup, gifts and fusion do not affect this immediate choice.
instructions = (
'目标是最快完成镜牢,只选择所给候选。候选已核对当前画面,不需要再次核对编队或开局配置。'
+ ('地图优先商店、事件,再普通战斗,避免精英或集中战斗。同类型默认正前方 route_d;没有事件也直接选择可达战斗。'
if route_scene else
'当前是事件判定。已有进行判定按钮则选择该按钮;否则选择明确标注极高成功率的 sinner 候选,极高优于高;同档任选一个。不需要额外角色技能信息。')
+ '仅在候选互相矛盾或没有有效动作时选择 requires_analysis。')
scene = ('镜牢地图,当前高亮可达节点如下:' if route_scene else '事件选择罪人界面,已识别当前可选择的罪人和成功率如下:')
description = scene + ';'.join(options[key]['description'] for key in actions)
answer = request_answer(cfg, description,
{key: val['description'] for key, val in permitted.items()}, instructions)
if permitted is not options and answer.get('probabilities') is not None:
# The provider only scored permitted cards. The surrounding router
# validates a distribution across its original candidate set.
answer['candidate_scope'] = list(permitted)
answer['probabilities'] = {key: answer['probabilities'].get(key, 0) for key in options}
return answer
description = ('当前楼层:%s\n当前游戏文字:\n' % state.get('floor', '尚未识别') +
'\n'.join(dict.fromkeys(i['text'] for i in text_items(state)
if not i['text'].upper().startswith('STEAM'))) +
'\n最近执行结果:' + json.dumps(recent[-2:], ensure_ascii=False))
return request_answer(cfg, description,
{key: val['description'] for key, val in options.items()}, SYSTEM_RULES)
def unambiguous_routine(options):
"""Execute one validated confirmation; choices still go through the model."""
judges = [key for key, value in options.items() if key.startswith('button_')
and '进行判定' in value['description']]
if len(judges) == 1:
return judges[0]
actions = [key for key in options if key not in ('wait', 'requires_analysis')]
if len(actions) != 1:
return None
key = actions[0]
safe = ('modal_confirm', 'select_startup_battery', 'confirm_startup_battery',
'confirm_thunderbranch', 'confirm_reward', 'hardship_confirm',
'confirm_swap', 'buy_swap', 'claim_final', 'run_complete', 'retry_network')
if key in safe:
return key
if key.startswith('button_') and options[key]['action']['tool'] in ('click', 'keypress'):
description = options[key]['description']
if any(label in description for label in ('确认', '继续', '进入', '开始战斗', '离开', '下一层', '进行判定')):
return key
return None
description = ('目标:按用户已配置的队伍和速通规则推进当前镜牢。当前楼层:%s\n当前游戏 OCR(坐标仅供辨识):\n' % state.get('floor', '尚未识别') +
'\n'.join('%s @%d,%d' % (i['text'], i['x'], i['y']) for i in text_items(state)
if not i['text'].upper().startswith('STEAM')) +
'\n截图视觉与可用控件观察(不是预先做出的决定):\n' +
'\n'.join(val['description'] for key,val in options.items() if key != 'requires_analysis') +
'\n最近动作和执行结果:' + json.dumps(recent[-4:], ensure_ascii=False))
return request_decision(cfg, description,
{key: val['description'] for key, val in options.items()}, SYSTEM_RULES)
def fixed_fallback(options):
@@ -694,12 +632,11 @@ def fixed_fallback(options):
return 'requires_analysis'
def execute(bridge, action, deadline=None):
def execute(bridge, action):
def call(tool, args=None):
if STOP_FILE.exists() or deadline is not None and time.monotonic() >= deadline:
if STOP_FILE.exists():
return {'ok':False,'stopped':True}
result = bridge.call(tool, args)
return normalize(result) if tool == 'get_state' else result
return bridge.call(tool, args)
if action['tool'] == 'claim_final':
result = call('click', action['args'])
if not result.get('ok'):
@@ -727,9 +664,9 @@ def execute(bridge, action, deadline=None):
time.sleep(0.7)
return {'ok': True, 'waited': 0.7}
if action['tool'] == 'battle':
battle_deadline = min(deadline if deadline is not None else float('inf'), time.monotonic() + 45)
deadline = time.monotonic() + 45
pairs = 0
while time.monotonic() < battle_deadline and not STOP_FILE.exists():
while time.monotonic() < deadline and not STOP_FILE.exists():
for _ in range(2):
for key in ('p', 'enter'):
result = call('keypress', {'key': key})
@@ -741,10 +678,13 @@ def execute(bridge, action, deadline=None):
state = call('get_state')
if not state.get('ok'):
return state
if battle_is_terminal(state):
texts = [i['text'].replace(' ', '') for i in text_items(state)]
terminal = death_retry_screen(texts) or any(t.upper() in ('VICTORY', 'DEFEAT') or any(m in t for m in
('正在探', '获得E.G.O饰品', '选择E.G.O饰品', '饰品观测', '开始战斗', '主题卡包',
'应该让谁', '选择一位罪人', '进行判定', '选择遭遇战奖励卡', '选项事件', '选择苦难', '选项', '结果')) for t in texts)
if terminal:
return {'ok': True, 'pairs': pairs, 'terminal': True, 'screen': state.get('screen')}
stopped = STOP_FILE.exists() or deadline is not None and time.monotonic() >= deadline
return {'ok': not stopped, 'stopped': stopped, 'pairs': pairs, 'terminal': False}
return {'ok': not STOP_FILE.exists(), 'stopped':STOP_FILE.exists(), 'pairs': pairs, 'terminal': False}
return call(action['tool'], action.get('args'))
@@ -766,76 +706,73 @@ def acquire_single_instance():
return lambda: kernel.CloseHandle(lease)
def main(executor_decider=None):
def archive_context(context_path):
"""一局结束后归档本局状态。claim_requested 等标记若留给下一局, 新局一启动就会被判定为已完成。"""
if context_path.exists():
context_path.replace(context_path.with_name('jev_shop_context.%s.json' % time.strftime('%Y%m%d_%H%M%S')))
def main():
parser = argparse.ArgumentParser()
parser.add_argument('config', nargs='?', help='Optional Jev JSON config; omit for execution-model handoff')
parser.add_argument('--decision-engine', choices=('auto', 'jev', 'executor', 'fixed'))
parser.add_argument('config')
parser.add_argument('--steps', type=int, default=250)
parser.add_argument('--seconds', type=int, default=1200)
mode = parser.add_mutually_exclusive_group()
mode.add_argument('--new-run', action='store_true', help='Start fresh state for a new dungeon')
mode.add_argument('--resume', action='store_true', help='Require an unfinished run with matching state')
args = parser.parse_args()
if args.steps <= 0 or args.seconds <= 0:
parser.error('--steps and --seconds must be positive')
release = acquire_single_instance()
if release is None:
print(json.dumps({'state':'already_running'}), flush=True)
return
cfg = json.loads(Path(args.config).read_text(encoding='utf-8'))
cfg['apiKey'] = os.environ.get('OPENCODE_API_KEY') or cfg.get('apiKey')
if not cfg['apiKey']:
release()
raise RuntimeError('Set OPENCODE_API_KEY or use an untracked local config with apiKey')
RUNTIME_HOME.mkdir(parents=True, exist_ok=True)
log = RUNTIME_HOME / 'jev_mirror_log.jsonl'
status = RUNTIME_HOME / 'jev_mirror_status.json'
# 工具失败按 {'ok': False} 返回: 截图暂不可用、按钮已消失等情况观察后继续, 而不是整局退出
bridge = Bridge(raise_on_error=False)
deadline = time.monotonic() + args.seconds
bridge = None
run = None
recent = []
repeats = {}
previous_battle = False
if log.exists():
last_lines = log.read_text(encoding='utf-8').splitlines()
if last_lines:
last_record = json.loads(last_lines[-1])
previous_battle = last_record.get('battle_context', last_record.get('action', {}).get('tool') == 'battle')
context_path = RUNTIME_HOME / 'jev_shop_context.json'
context = json.loads(context_path.read_text(encoding='utf-8')) if context_path.exists() else {'refresh_used': 0}
stable_since = time.monotonic()
last_fingerprint = None
unknown_since = None
decision_fallback_reason = None
try:
RUNTIME_HOME.mkdir(parents=True, exist_ok=True)
cfg = json.loads(Path(args.config).read_text(encoding='utf-8-sig')) if args.config else {}
cfg['apiKey'] = os.environ.get('OPENCODE_API_KEY') or cfg.get('apiKey')
if args.decision_engine:
cfg['decisionEngine'] = args.decision_engine
router = DecisionRouter(cfg, decide, executor_decider=executor_decider,
fixed_decider=fixed_fallback, rules=SYSTEM_RULES,
force_fixed=os.environ.get('LC_FIXED_FALLBACK') == '1')
if STOP_FILE.exists():
save_json(status, {'state': 'stopped', 'reason': 'stop_requested'})
return
run, context = prepare_run(RUNTIME_HOME, args.new_run, args.resume)
previous_battle = context.get('battle_context', False)
# 工具失败按 {'ok': False} 返回: 截图暂不可用、按钮已消失等情况观察后继续, 而不是整局退出
bridge = Bridge(cancelled=lambda: STOP_FILE.exists() or time.monotonic() >= deadline,
raise_on_error=False)
for step in range(args.steps):
if STOP_FILE.exists() or time.monotonic() > deadline:
run['status'] = 'stopped'
save_json(RUNTIME_HOME / 'mirror_current_run.json', run)
save_json(status, {'state': 'stopped', 'step': step, 'run_id': run['run_id']})
status.write_text(json.dumps({'state': 'stopped', 'step': step}), encoding='utf-8')
return
observation_started = time.monotonic()
state = normalize(bridge.call('get_state'))
state = bridge.call('get_state')
observation_ms = round((time.monotonic()-observation_started)*1000)
if not state.get('ok'):
state = {'ok': False, 'items': [{'text': 'MCP 截图暂不可用;游戏窗口可能正在重建。' + str(state.get('error','')),
'x':0,'y':0,'w':0,'h':0,'score':1.0}]}
fingerprint = scene_fingerprint(state)
fingerprint = tuple(item['text'] for item in text_items(state)
if item.get('score', 0) > 0.93 and not item['text'].replace('.', '').isdigit() and not re.fullmatch(r'[0-9:]+', item['text']))
if any('正在探' in i['text'] or '主题卡包' in i['text'] for i in text_items(state)):
context['refresh_used'] = 0
for item in text_items(state):
match = re.search(r'(?:第|选择)([1-5])层', item['text'].replace(' ', ''))
if match:
context['floor'] = int(match[1])
save_json(context_path, context)
state['floor'] = context.get('floor', 1)
context_path.write_text(json.dumps(context), encoding='utf-8')
state['floor'] = context.get('floor', 3)
state['symbol_upgraded'] = context.get('symbol_upgraded', False)
state['battery_obtained'] = context.get('battery_obtained', False)
state['thunderbranch_pending'] = context.get('thunderbranch_pending',False)
state['thrill_pending'] = context.get('thrill_obtained',False) and not context.get('thrill_upgraded',False)
state['claim_requested'] = claim_is_current(run, context)
state['claim_requested'] = context.get('claim_requested', False)
options = candidates(state, previous_battle, context['refresh_used'])
if fingerprint != last_fingerprint:
stable_since = time.monotonic()
@@ -850,7 +787,7 @@ def main(executor_decider=None):
and repeats.get((fingerprint, action_id), 0) >= 1):
fallback = options[key].get('fallback_action')
button = next((i for i in text_items(state)
if i['text'].replace(' ', '') in ('进入', '开始战斗', '确认', '继续', '进行判定')
if i['text'].replace(' ', '') in ('进入', '开始战斗', '确认', '继续')
and button_enabled(state, i)), None)
if fallback or button:
options[key]['action'] = fallback or {'tool': 'click', 'args': {
@@ -865,7 +802,6 @@ def main(executor_decider=None):
unknown_since = None
# User explicitly prescribed the complete battle loop. Only scene
# transitions return to Jev; combat does not require new decisions.
decision = None
if any(re.search(r'CON+ECTING|LOADING', i['text'].upper()) for i in text_items(state)):
choice, latency = 'wait', 0
elif len(options)==2 and time.monotonic() - unknown_since < 10:
@@ -878,118 +814,84 @@ def main(executor_decider=None):
choice, latency = 'event_advance', 0
elif 'battle' in options:
choice, latency = 'battle', 0
elif unambiguous_routine(options):
choice, latency = unambiguous_routine(options), 0
else:
try:
decision = router.choose(state, options, recent, run['run_id'])
choice, latency = decision.choice, decision.jev_ms
except DecisionRequired as required:
record = {'state': 'requires_decision', 'step': step, 'run_id': run['run_id'],
'decision_engine': 'executor', 'decision_request': required.request,
'ocr_ms': observation_ms, 'screen': state.get('screen'),
'at': time.strftime('%Y-%m-%dT%H:%M:%S')}
if 'failed_jev_ms' in required.request:
record['failed_jev_ms'] = required.request['failed_jev_ms']
run['status'] = 'requires_decision'
save_json(RUNTIME_HOME / 'mirror_current_run.json', run)
save_json(RUNTIME_HOME / 'decision_request.json', required.request)
save_json(status, record)
with log.open('a', encoding='utf-8') as output:
output.write(json.dumps(record, ensure_ascii=False) + '\n')
print(json.dumps(record, ensure_ascii=False), flush=True)
return
if os.environ.get('LC_FIXED_FALLBACK') == '1' or decision_fallback_reason:
choice, latency = fixed_fallback(options), 0
else:
try:
choice, latency = decide(cfg, state, options, recent)
except urllib.error.HTTPError as error:
if error.code not in (401,403,429):
raise
decision_fallback_reason='Jev HTTP %d; deterministic fallback for this session' % error.code
choice, latency=fixed_fallback(options),0
action = options[choice]['action']
record = {'step': step, 'run_id': run['run_id'], 'choice': choice, 'action': action, 'jev_ms': latency,
record = {'step': step, 'choice': choice, 'action': action, 'jev_ms': latency,
'ocr_ms':observation_ms,'screen': state.get('screen'), 'at': time.strftime('%Y-%m-%dT%H:%M:%S')}
record['decision_engine'] = decision.engine if decision else 'rules'
if decision:
record.update(decision_ms=decision.latency_ms + (decision.failed_jev_ms or 0), confidence=decision.confidence,
probabilities=decision.probabilities, model=decision.model)
if decision.failed_jev_ms is not None:
record['failed_jev_ms'] = decision.failed_jev_ms
if decision.fallback_reason:
record['decision_fallback_reason'] = decision.fallback_reason
if decision.candidate_scope is not None:
record['provider_candidate_scope'] = decision.candidate_scope
if decision_fallback_reason:
record['decision_fallback_reason']=decision_fallback_reason
if choice == 'run_complete':
complete_run(RUNTIME_HOME, run, context, state.get('screen'))
record['state'] = 'completed'
save_json(status, record)
with log.open('a', encoding='utf-8') as output:
output.write(json.dumps(record, ensure_ascii=False) + '\n')
status.write_text(json.dumps(record, ensure_ascii=False), encoding='utf-8')
run_path = RUNTIME_HOME / 'mirror_current_run.json'
if run_path.exists():
from datetime import datetime, timezone
run = json.loads(run_path.read_text(encoding='utf-8'))
now = datetime.now(timezone.utc)
run.update(status='completed', dungeon_completed=True, final_reward_claimed=True,
end_utc=now.isoformat(), elapsed_seconds=(now-datetime.fromisoformat(run['start_utc'])).total_seconds(),
completion_evidence=state.get('screen'))
run_path.write_text(json.dumps(run, ensure_ascii=False, indent=2), encoding='utf-8')
archive_context(context_path)
print(json.dumps(record, ensure_ascii=False), flush=True)
return
if choice == 'requires_analysis':
record.update(state='requires_analysis', items=text_items(state))
run['status'] = 'requires_analysis'
save_json(RUNTIME_HOME / 'mirror_current_run.json', run)
save_json(status, record)
with log.open('a', encoding='utf-8') as output:
output.write(json.dumps(record, ensure_ascii=False) + '\n')
status.write_text(json.dumps(record, ensure_ascii=False), encoding='utf-8')
print(json.dumps(record, ensure_ascii=False), flush=True)
return
action_id = json.dumps(action, sort_keys=True)
repeats[(fingerprint, action_id)] = repeats.get((fingerprint, action_id), 0) + 1
action_started = time.monotonic()
result = execute(bridge, action, deadline=deadline)
result = execute(bridge, action)
record['action_ms'] = round((time.monotonic()-action_started)*1000)
record['finished_at'] = time.strftime('%Y-%m-%dT%H:%M:%S')
if result.get('stopped'):
record.update(result=result,state='stopped',battle_context=previous_battle)
with log.open('a',encoding='utf-8') as output:
output.write(json.dumps(record,ensure_ascii=False)+'\n')
run['status'] = 'stopped'
save_json(RUNTIME_HOME / 'mirror_current_run.json', run)
save_json(status, record)
status.write_text(json.dumps(record,ensure_ascii=False),encoding='utf-8')
return
if choice == 'claim_final' and result.get('ok'):
record_claim(RUNTIME_HOME, run, context, state.get('screen'))
context['claim_requested'] = True
context_path.write_text(json.dumps(context), encoding='utf-8')
if choice in ('confirm_startup_battery','confirm_thunderbranch') and result.get('ok'):
context['battery_obtained' if choice == 'confirm_startup_battery' else 'thunderbranch_pending'] = True
save_json(context_path, context)
context_path.write_text(json.dumps(context),encoding='utf-8')
if choice=='modal_confirm' and result.get('ok') and any(i['text'].replace(' ','')=='快感' for i in text_items(state)) and any('获得E.G.O' in i['text'].replace(' ','') for i in text_items(state)):
context['thrill_obtained']=True
save_json(context_path, context)
context_path.write_text(json.dumps(context),encoding='utf-8')
if choice == 'shop_refresh' and result.get('ok'):
context['refresh_used'] += 1
save_json(context_path, context)
context_path.write_text(json.dumps(context), encoding='utf-8')
started_battle = choice.startswith('button_') and bool(result.get('ok')) and any(
i['text'].replace(' ', '') == '开始战斗' for i in text_items(state))
previous_battle = ((action['tool'] == 'battle' and not result.get('terminal')) or started_battle
or (previous_battle and action['tool'] == 'wait'))
context['battle_context'] = previous_battle
save_json(context_path, context)
record.update(result=result, state='running', battle_context=previous_battle)
with log.open('a', encoding='utf-8') as output:
output.write(json.dumps(record, ensure_ascii=False) + '\n')
save_json(status, record)
status.write_text(json.dumps(record, ensure_ascii=False), encoding='utf-8')
recent.append({'action': action, 'ok': result.get('ok'), 'unchanged_attempt': repeats[(fingerprint, action_id)]})
print(json.dumps({k:v for k,v in record.items() if k != 'items'}, ensure_ascii=False), flush=True)
time.sleep(0.35)
run['status'] = 'stopped'
save_json(RUNTIME_HOME / 'mirror_current_run.json', run)
save_json(status, {'state': 'stopped', 'reason': 'step_limit', 'run_id': run['run_id']})
except Exception as error:
state = 'stopped' if isinstance(error, SessionCancelled) else 'requires_analysis'
record = {'state': state, 'error': '%s: %s' % (type(error).__name__, str(error))}
if isinstance(error, (SessionCancelled, SessionTimeout)):
record['outcome_unknown'] = error.outcome_unknown
record['pending_tool'] = getattr(error, 'tool', None)
if run is not None:
run['status'] = state
record['run_id'] = run['run_id']
save_json(RUNTIME_HOME / 'mirror_current_run.json', run)
save_json(status, record)
with log.open('a', encoding='utf-8') as output:
output.write(json.dumps(record, ensure_ascii=False) + '\n')
record = {'state': 'requires_analysis', 'error': '%s: %s' % (type(error).__name__, str(error))}
status.write_text(json.dumps(record, ensure_ascii=False), encoding='utf-8')
print(json.dumps(record, ensure_ascii=False), flush=True)
finally:
try:
if bridge is not None:
bridge.close()
finally:
release()
bridge.close()
release()
if __name__ == '__main__':
-85
View File
@@ -1,85 +0,0 @@
"""Normalize observed English UI labels for the existing mirror controller."""
import re
LABELS = {
'confirm':'确认', 'continue':'继续', 'proceed':'继续', 'enter':'进入', 'cancel':'取消',
'leave':'离开', 'close':'关闭', 'startbattle':'开始战斗', 'startcombat':'开始战斗',
'battle!':'开始战斗', 'chainbattle!':'开始战斗',
'select':'选择', 'selectasinner':'选择一位罪人', 'chooseasinner':'选择一位罪人',
'commence':'进行判定', 'commencecheck':'进行判定', 'performcheck':'进行判定', 'checksuccess':'判定成功',
'checkfailure':'判定失败', 'checkpassed':'判定成功', 'checkfailed':'判定失败',
'result':'结果', 'options':'选项', 'choices':'选项', 'veryhigh':'极高',
'high':'高', 'shop':'商店', 'specialshop':'特殊商店', 'refresh':'刷新',
'enhancegifts':'强化饰品', 'enhancee.g.ogifts':'强化饰品', 'purchase':'购买',
'buy':'购买', 'purchased':'已购买', 'currentownedskills':'当前持有技能',
'thunderbranch':'雷枝', '雷击木':'雷枝', 'talismanbundle':'成捆的符咒',
'standard-dutybattery':'标准负载电池', 'standarddutybattery':'标准负载电池',
'thrill':'快感', 'selecte.g.ogifts':'选择E.G.O饰品',
'selecte.g.ogift':'选择E.G.O饰品', 'declinegifts':'拒绝饰品',
'declinegift':'拒绝饰品', 'refusegifts':'拒绝饰品',
'refusegift':'拒绝饰品', 'selectede.g.ogift':'选择E.G.O饰品',
'gaine.g.ogift':'获得E.G.O饰品', 'gaine.g.ogift!':'获得E.G.O饰品!',
'obtaine.g.ogift!':'获得E.G.O饰品!', 'e.g.ogiftobservation':'饰品观测',
'e.g.ogiftget!':'获得E.G.O饰品!',
'e.g.ogiftsearch':'额外观测', 'eg.dgiftsearch':'额外观测',
'nextfloor':'下一层', 'gotonextfloor':'前往下一层', 'proceedtonextfloor':'前往下一层', 'claim':'领取',
'additionalhardship':'追加的苦难', 'additionalhardships':'追加的苦难',
'obtaine.g.ogift':'获得E.G.O饰品', 'obtaine.g.ogifts':'获得E.G.O饰品',
'claimrewards':'领取奖励', 'explorationcomplete':'探索完成',
'explorationcompleted':'探索完成', 'dungeoncomplete':'探索完成',
'drive':'驾驶席', 'sinners':'罪人', 'exploring:':'探索状态',
'beforeentry':'入场前', 'retry':'重试', 'dungeonprogress':'迷宫进度',
}
def normalize(state):
if state.get('_lc_labels_normalized'):
return state
rate_items = []
for item in state.get('items') or []:
raw = item['text']
compact = re.sub(r'\s+', '', raw).lower().lstrip('×x')
compact = compact.replace('e.g.0', 'e.g.o')
text = LABELS.get(compact, raw)
if text == raw:
match = re.search(r'select(?:the)?(?:floor)?(\d+)(?:st|nd|rd|th)?floorthemepack', compact)
if not match:
match = re.search(r'selectfloorthemepack(?:for)?floor(\d+)', compact)
if not match:
match = re.search(r'selectfloor(\d+)themepack', compact)
if match:
text = '选择%s层主题卡包' % match[1]
elif re.search(r'(?:select|choose).*encounterreward', compact):
text = '选择遭遇战奖励卡'
elif re.search(r'exploring(?:floor)?\d+', compact):
text = '正在探索第%s层' % re.search(r'\d+', compact)[0]
elif compact.startswith('exploringfloor'):
# A missing/misread floor number still identifies the map.
# Leave the stored floor unchanged rather than invent a digit.
text = '正在探索 ' + raw
elif compact.startswith('select') and re.search(r'\d+/\d+', compact):
text = '选择' + re.search(r'\d+/\d+', compact)[0]
elif compact.startswith('refresh'):
text = raw.replace(raw[:7], '刷新')
elif compact.startswith('chooseacharactertoperform'):
text = '选择一位罪人'
elif re.match(r'who(?:will|should)', compact):
text = '应该让谁 ' + raw
elif compact.startswith('skillreplacement') or compact.startswith('replaceskill'):
text = '技能替换 ' + raw
# English OCR sometimes merges several adjacent probability labels.
# Keep each explicit Very High span as a separate observed candidate.
if item.get('y', 0) > state.get('screen', {}).get('h', 1080) * .8 and 'veryhigh' in compact:
for match in re.finditer('veryhigh', compact):
center = item['x'] + (match.start() + len(match[0]) / 2) * item['w'] / len(compact)
rate_items.append(dict(item, text='极高', original_text=raw,
x=round(center - 25), w=50))
for english, chinese in [('Sinclair','辛克莱'), ('Hong Lu','鸿璐'),
('Heathcliff','希斯克利夫'), ('Outis','奥提斯'), ('Gregor','格里高尔'),
('Ryoshu','良秀'), ('Faust','浮士德')]:
text = text.replace(english, chinese)
if text != raw:
item['original_text'] = raw
item['text'] = text
state['items'] = (state.get('items') or []) + rate_items
state['_lc_labels_normalized'] = True
return state
+27 -145
View File
@@ -1,41 +1,15 @@
"""Reusable client for the installed stdio MCP bridge; no direct game input."""
import json
import math
import os
import queue
import subprocess
import sys
import threading
import time
from collections import deque
from pathlib import Path
class SessionCancelled(InterruptedError):
"""The caller stopped waiting; a sent remote action may have completed."""
def __init__(self, message, outcome_unknown=False):
super().__init__(message)
self.outcome_unknown = outcome_unknown
class SessionTimeout(TimeoutError):
outcome_unknown = True
class Session:
def __init__(self, timeout=30, cancelled=None, raise_on_error=True):
self.timeout = float(timeout)
if not math.isfinite(self.timeout) or self.timeout <= 0:
raise ValueError('MCP timeout must be finite and positive')
self.cancelled = cancelled or (lambda: False)
def __init__(self, raise_on_error=True):
# False: 工具失败按 {'ok': False, ...} 返回, 由调用方观察后继续; 协议层错误仍抛异常
self.raise_on_error = raise_on_error
self._closed = False
self._lock = threading.Lock()
self._responses = queue.Queue()
self._outgoing = queue.Queue()
self.stderr_tail = deque(maxlen=20)
root = Path(__file__).resolve().parents[1]
self.process = subprocess.Popen(
[sys.executable, '-X', 'utf8', str(root / 'lc_mcp' / 'bridge.py')],
@@ -44,137 +18,45 @@ class Session:
text=True, encoding='utf-8', bufsize=1,
)
self.sequence = 0
# Windows pipes cannot be polled with select(). Dedicated readers and
# a writer let the caller cancel even if a pipe read/write is blocked.
self._threads = [threading.Thread(target=target, daemon=True) for target in
(self._read_responses, self._write_requests, self._drain_stderr)]
for thread in self._threads:
thread.start()
try:
self.request('initialize', {
'protocolVersion': '2024-11-05', 'capabilities': {},
'clientInfo': {'name': 'lc-mcp-session', 'version': '1'},
})
self._send({'jsonrpc': '2.0', 'method': 'notifications/initialized'})
except BaseException:
self._abort()
raise
self.request('initialize', {
'protocolVersion': '2024-11-05', 'capabilities': {},
'clientInfo': {'name': 'lc-mcp-session', 'version': '1'},
})
self.process.stdin.write(json.dumps({'jsonrpc': '2.0', 'method': 'notifications/initialized'}) + '\n')
self.process.stdin.flush()
def _read_responses(self):
try:
for line in self.process.stdout:
self._responses.put(line)
except (OSError, ValueError, UnicodeError) as error:
self._responses.put(error)
finally:
self._responses.put(None)
def _write_requests(self):
try:
while True:
line = self._outgoing.get()
if line is None:
break
self.process.stdin.write(line)
self.process.stdin.flush()
except (OSError, ValueError) as error:
self._responses.put(error)
finally:
try:
self.process.stdin.close()
except (OSError, ValueError):
pass
def _drain_stderr(self):
try:
for line in self.process.stderr:
self.stderr_tail.append(line.rstrip()[-2000:])
except (OSError, ValueError, UnicodeError):
return
def _send(self, message):
if self._closed:
raise ConnectionError('MCP session is closed')
self._outgoing.put(json.dumps(message, ensure_ascii=False) + '\n')
def request(self, method, params, timeout=None):
limit = self.timeout if timeout is None else float(timeout)
if not math.isfinite(limit) or limit <= 0:
raise ValueError('MCP timeout must be finite and positive')
with self._lock:
if self.cancelled():
self._abort()
raise SessionCancelled('MCP request cancelled before sending')
self.sequence += 1
mid = self.sequence
self._send({'jsonrpc': '2.0', 'id': mid, 'method': method, 'params': params})
deadline = time.monotonic() + limit
while True:
if self.cancelled():
self._abort()
error = SessionCancelled('MCP request cancelled; remote outcome unknown', True)
error.tool = params.get('name') if isinstance(params, dict) else None
raise error
remaining = deadline - time.monotonic()
if remaining <= 0:
self._abort()
error = SessionTimeout('MCP %s timed out; remote outcome unknown; request was not retried' % method)
error.tool = params.get('name') if isinstance(params, dict) else None
raise error
try:
line = self._responses.get(timeout=min(.1, remaining))
except queue.Empty:
continue
if line is None or isinstance(line, Exception):
self._abort()
raise ConnectionError('MCP bridge closed') from (line if isinstance(line, Exception) else None)
try:
result = json.loads(line)
if not isinstance(result, dict):
raise ValueError('response must be an object')
except ValueError as error:
self._abort()
raise ConnectionError('MCP bridge returned invalid JSON-RPC') from error
if result.get('id') == mid:
if 'error' in result:
raise RuntimeError(result['error']['message'])
return result['result']
def request(self, method, params):
self.sequence += 1
mid = self.sequence
request = {'jsonrpc': '2.0', 'id': mid, 'method': method, 'params': params}
self.process.stdin.write(json.dumps(request, ensure_ascii=False) + '\n')
self.process.stdin.flush()
while True:
line = self.process.stdout.readline()
if not line:
raise ConnectionError('MCP bridge closed')
result = json.loads(line)
if result.get('id') == mid:
if 'error' in result:
raise RuntimeError(result['error']['message'])
return result['result']
def call(self, name, arguments=None):
arguments = {} if arguments is None else arguments
timeout = self.timeout
if name in ('wait_for_text', 'wait_for_text_gone') and isinstance(arguments, dict):
try:
wait = float(arguments.get('timeout', 30))
if math.isfinite(wait):
timeout = max(timeout, min(300, max(0, wait)) + 5)
except (TypeError, ValueError):
pass # The server reports invalid tool arguments.
result = self.request('tools/call', {'name': name, 'arguments': arguments}, timeout)
result = self.request('tools/call', {'name': name, 'arguments': arguments or {}})
data = json.loads(result['content'][0]['text'])
if result.get('isError') and self.raise_on_error:
raise RuntimeError(data)
return data
def _abort(self):
if self.process.poll() is None:
self.process.kill()
self.close()
def close(self):
if self._closed:
return
self._closed = True
self._outgoing.put(None)
self.process.stdin.close()
try:
self.process.wait(1)
self.process.wait(5)
except subprocess.TimeoutExpired:
self.process.kill()
self.process.wait()
for thread in self._threads:
thread.join(1)
for stream in (self.process.stdin, self.process.stdout, self.process.stderr):
stream.close()
self.process.stdout.close()
self.process.stderr.close()
def __enter__(self):
return self
-99
View File
@@ -1,99 +0,0 @@
"""Persist one mirror run without carrying completed-run state into a new run."""
import json
import os
import tempfile
import uuid
from datetime import datetime, timezone
from pathlib import Path
RESUMABLE = {'running', 'requires_analysis', 'requires_decision', 'stopped', 'user_takeover'}
def save_json(path, value):
"""Replace complete snapshots atomically so interruption cannot truncate them."""
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
temporary = None
try:
with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=path.parent,
prefix=path.name + '.', suffix='.tmp', delete=False) as output:
temporary = Path(output.name)
json.dump(value, output, ensure_ascii=False, indent=2)
output.write('\n')
os.replace(temporary, path)
finally:
if temporary is not None and temporary.exists():
temporary.unlink()
def load_json(path):
if not path.exists():
return None
value = json.loads(path.read_text(encoding='utf-8-sig'))
if not isinstance(value, dict):
raise ValueError('%s must contain an object' % path.name)
return value
def prepare_run(home, new_run=False, resume=False):
home = Path(home)
run_path = home / 'mirror_current_run.json'
context_path = home / 'jev_shop_context.json'
# Explicit new-run also recovers from corrupt or legacy state files.
run = None if new_run else load_json(run_path)
resumable = run is not None and run.get('status') in RESUMABLE
if resume and not resumable:
raise ValueError('No unfinished run to resume; use --new-run for a new dungeon')
if resumable:
started = datetime.fromisoformat(run['start_utc'])
if started.tzinfo is None:
raise ValueError('Run start_utc must include a timezone')
context = load_json(context_path) or {}
run_id = run.get('run_id') or uuid.uuid4().hex
if context.get('run_id') not in (None, run_id):
raise ValueError('Run/context IDs differ; inspect the state or use --new-run')
if context.get('run_id') is None:
# Keep legacy floor/upgrades for an unfinished run, but an unbound
# claim or battle flag cannot establish current-run completion.
for key in ('claim_requested', 'claim_run_id', 'claim_screen', 'claim_at_utc', 'battle_context'):
context.pop(key, None)
run['legacy_context_migrated'] = True
context.setdefault('refresh_used', 0)
context.setdefault('floor', 1)
context['run_id'] = run_id
run['run_id'] = run_id
run['status'] = 'running'
else:
run_id = uuid.uuid4().hex
run = {'run_id': run_id, 'start_utc': datetime.now(timezone.utc).isoformat(),
'status': 'running', 'dungeon_completed': False, 'final_reward_claimed': False}
context = {'run_id': run_id, 'refresh_used': 0, 'floor': 1}
save_json(run_path, run)
save_json(context_path, context)
return run, context
def claim_is_current(run, context):
screen = context.get('claim_screen')
return bool(context.get('claim_requested') and context.get('run_id') == run['run_id']
and context.get('claim_run_id') == run['run_id']
and isinstance(screen, dict) and screen.get('path'))
def record_claim(home, run, context, screen):
if not screen or not screen.get('path'):
raise ValueError('Final claim requires an observed completion screenshot')
context.update(claim_requested=True, claim_run_id=run['run_id'], claim_screen=screen,
claim_at_utc=datetime.now(timezone.utc).isoformat())
save_json(Path(home) / 'jev_shop_context.json', context)
def complete_run(home, run, context, screen):
if not claim_is_current(run, context) or not screen or not screen.get('path'):
raise ValueError('Completion requires current-run claim and return-screen evidence')
now = datetime.now(timezone.utc)
run.update(status='completed', dungeon_completed=True, final_reward_claimed=True,
end_utc=now.isoformat(),
elapsed_seconds=(now-datetime.fromisoformat(run['start_utc'])).total_seconds(),
claim_evidence=context['claim_screen'], completion_evidence=screen)
save_json(Path(home) / 'mirror_current_run.json', run)
-220
View File
@@ -1,220 +0,0 @@
"""Controller lifecycle and battle regressions using mocked MCP only."""
import contextlib
import ctypes
import io
import json
import os
from pathlib import Path
import sys
import tempfile
import unittest
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
import battle_batch
import jev_mirror_agent as agent
from mcp_session import SessionCancelled, SessionTimeout
from run_state import save_json
class BattleBatchTest(unittest.TestCase):
def setUp(self):
self.folder = tempfile.TemporaryDirectory()
self.addCleanup(self.folder.cleanup)
self.stop = Path(self.folder.name) / 'JEV_STOP'
def run_helper(self, client):
session = mock.MagicMock()
session.__enter__.return_value = client
output = io.StringIO()
with mock.patch.object(battle_batch, 'Session', return_value=session), \
mock.patch.object(battle_batch, 'STOP_FILE', self.stop), \
mock.patch.object(sys, 'argv', ['battle_batch.py', '--seconds', '1', '--battle-confirmed']), \
mock.patch.object(battle_batch.time, 'sleep'), contextlib.redirect_stdout(output):
battle_batch.main()
return json.loads(output.getvalue())
def test_terminal_screens_never_receive_more_keys(self):
for text in ('进行判定', '选择遭遇战奖励卡', '参加战斗的全体罪人已经死亡。'):
with self.subTest(text=text):
client = mock.Mock()
client.call.return_value = {'ok': True, 'items': [{'text': text}]}
result = self.run_helper(client)
self.assertEqual(result['pairs'], 0)
self.assertEqual(client.call.call_args_list, [mock.call('get_state')])
def test_stop_after_win_rate_prevents_enter(self):
client = mock.Mock()
def call(tool, args=None):
if tool == 'get_state':
return {'ok': True, 'items': [{'text': 'WAVE 1'}, {'text': 'Win Rate'}]}
self.stop.touch()
return {'ok': True}
client.call.side_effect = call
result = self.run_helper(client)
self.assertTrue(result['stopped'])
self.assertFalse(result['outcome_unknown'])
self.assertEqual(client.call.call_args_list,
[mock.call('get_state'), mock.call('click_text', {'text': 'Win Rate'})])
def test_judgement_after_one_turn_ends_without_more_input(self):
client = mock.Mock()
frames = iter([[{'text': 'WAVE 1'}, {'text': '胜率'}], [{'text': '选择一位罪人来进行判定'}]])
client.call.side_effect = lambda tool, args=None: (
{'ok': True, 'items': next(frames)} if tool == 'get_state' else {'ok': True})
result = self.run_helper(client)
self.assertEqual(result['pairs'], 1)
self.assertEqual([c.args[0] for c in client.call.call_args_list],
['get_state', 'click_text', 'keypress', 'get_state'])
def test_cinematic_without_win_rate_sends_no_input(self):
# P 会在胜率/伤害之间切换, 看不到胜率按钮(特写)时只重新观察
client = mock.Mock()
client.call.return_value = {'ok': True, 'items': [{'text': 'TURN 2'}]}
result = self.run_helper(client)
self.assertEqual(result['pairs'], 0)
self.assertTrue(all(c.args[0] == 'get_state' for c in client.call.call_args_list))
class AgentRuntimeTest(unittest.TestCase):
def setUp(self):
self.folder = tempfile.TemporaryDirectory()
self.addCleanup(self.folder.cleanup)
self.home = Path(self.folder.name)
self.config = self.home / 'config.json'
self.config.write_text('{}')
self.kernel = mock.Mock()
self.kernel.CreateMutexW.return_value = 12345
self.kernel.GetLastError.return_value = 0
def run_agent(self, bridge, extra_args=(), constructor_error=None, fixed=True, executor_decider=None):
output = io.StringIO()
environment = dict(os.environ, LC_FIXED_FALLBACK='1' if fixed else '0')
environment.pop('OPENCODE_API_KEY', None)
with mock.patch.object(agent, 'RUNTIME_HOME', self.home), \
mock.patch.object(agent, 'STOP_FILE', self.home / 'JEV_STOP'), \
mock.patch.object(agent, 'Bridge', return_value=bridge, side_effect=constructor_error) as factory, \
mock.patch.object(ctypes, 'WinDLL', return_value=self.kernel, create=True), \
mock.patch.object(ctypes, 'get_last_error', side_effect=lambda: self.kernel.GetLastError(), create=True), \
mock.patch.object(sys, 'argv', ['jev_mirror_agent.py', str(self.config), '--steps', '1', *extra_args]), \
mock.patch.dict(os.environ, environment, clear=True), \
mock.patch.object(agent.time, 'sleep'), \
mock.patch.object(agent, 'button_enabled', return_value=False), \
contextlib.redirect_stdout(output):
agent.main(executor_decider=executor_decider)
status = json.loads((self.home / 'jev_mirror_status.json').read_text(encoding='utf-8'))
return status, factory
def test_old_claim_context_does_not_complete_new_run_at_lobby(self):
save_json(self.home / 'jev_shop_context.json', {'floor': 5, 'claim_requested': True})
save_json(self.home / 'mirror_current_run.json', {
'start_utc': '2026-10-02T00:00:00+00:00', 'status': 'running',
'dungeon_completed': False, 'final_reward_claimed': False})
bridge = mock.Mock()
bridge.call.return_value = {'ok': True, 'items': [
{'text': text, 'score': 1} for text in ('探索状态', '进入', '名与蛛之镜')]}
status, _ = self.run_agent(bridge)
run = json.loads((self.home / 'mirror_current_run.json').read_text())
self.assertEqual(status['state'], 'stopped')
self.assertFalse(run['dungeon_completed'])
self.assertFalse(run['final_reward_claimed'])
bridge.close.assert_called_once()
self.assertEqual(self.kernel.CloseHandle.call_count, 1)
def test_bridge_initialization_failure_records_error_and_releases_mutex(self):
status, _ = self.run_agent(mock.Mock(), constructor_error=SessionTimeout('initialization hung'))
self.assertEqual(status['state'], 'requires_analysis')
self.assertTrue(status['outcome_unknown'])
self.assertEqual(self.kernel.CloseHandle.call_count, 1)
def test_stop_file_prevents_bridge_startup(self):
(self.home / 'JEV_STOP').touch()
status, factory = self.run_agent(mock.Mock())
self.assertEqual(status['state'], 'stopped')
factory.assert_not_called()
self.assertEqual(self.kernel.CloseHandle.call_count, 1)
def test_pending_request_cancellation_marks_run_stopped_and_logs_uncertainty(self):
bridge = mock.Mock()
bridge.call.side_effect = SessionCancelled('cancelled pending get_state', True)
status, _ = self.run_agent(bridge)
self.assertEqual(status['state'], 'stopped')
self.assertTrue(status['outcome_unknown'])
run = json.loads((self.home / 'mirror_current_run.json').read_text())
self.assertEqual(run['status'], 'stopped')
rows = (self.home / 'jev_mirror_log.jsonl').read_text().splitlines()
self.assertEqual(json.loads(rows[-1])['state'], 'stopped')
bridge.close.assert_called_once()
def test_expired_budget_prevents_execute_from_sending_any_key(self):
bridge = mock.Mock()
with mock.patch.object(agent, 'STOP_FILE') as stop:
stop.exists.return_value = False
result = agent.execute(bridge, {'tool': 'keypress', 'args': {'key': 'enter'}}, deadline=0)
self.assertTrue(result['stopped'])
bridge.call.assert_not_called()
def test_close_error_still_releases_controller_mutex(self):
bridge = mock.Mock()
bridge.call.return_value = {'ok': True, 'items': []}
bridge.close.side_effect = RuntimeError('close failed')
with self.assertRaisesRegex(RuntimeError, 'close failed'):
self.run_agent(bridge)
self.assertEqual(self.kernel.CloseHandle.call_count, 1)
def test_no_jev_config_publishes_execution_model_request_without_input(self):
bridge = mock.Mock()
bridge.call.return_value = {'ok': True, 'items': [{'text': '路线', 'score': 1}]}
options = {
'wait': {'description': 'wait', 'action': {'tool': 'wait', 'args': {'seconds': .7}}},
'requires_analysis': {'description': 'inspect', 'action': {'tool': 'requires_analysis', 'args': {}}},
'route_w': {'description': 'event above', 'action': {'tool': 'route', 'args': {'key': 'w'}}},
}
with mock.patch.object(agent, 'candidates', return_value=options), mock.patch.object(agent, 'decide') as decide:
status, _ = self.run_agent(bridge, fixed=False)
self.assertEqual(status['state'], 'requires_decision')
self.assertEqual(status['decision_request']['reason'], 'no_jev_model')
self.assertEqual(bridge.call.call_args_list, [mock.call('get_state')])
decide.assert_not_called()
bridge.close.assert_called_once()
self.assertEqual(self.kernel.CloseHandle.call_count, 1)
pending = json.loads((self.home / 'decision_request.json').read_text(encoding='utf-8'))
run = json.loads((self.home / 'mirror_current_run.json').read_text())
self.assertEqual(pending['run_id'], run['run_id'])
self.assertEqual(run['status'], 'requires_decision')
def test_pending_execution_model_decision_can_resume_same_run(self):
save_json(self.home / 'mirror_current_run.json', {
'run_id': 'pending-run', 'start_utc': '2026-10-02T00:00:00+00:00',
'status': 'requires_decision', 'dungeon_completed': False, 'final_reward_claimed': False})
save_json(self.home / 'jev_shop_context.json', {'run_id': 'pending-run', 'floor': 3})
bridge = mock.Mock()
bridge.call.return_value = {'ok': True, 'items': []}
status, _ = self.run_agent(bridge, extra_args=['--resume'])
self.assertEqual(status['state'], 'stopped')
self.assertEqual(status['run_id'], 'pending-run')
def test_embedded_execution_model_selects_and_executes_without_jev(self):
bridge = mock.Mock()
bridge.call.return_value = {'ok': True, 'items': [{'text': '路线', 'score': 1}]}
options = {
'wait': {'description': 'wait', 'action': {'tool': 'wait', 'args': {'seconds': .7}}},
'requires_analysis': {'description': 'inspect', 'action': {'tool': 'requires_analysis', 'args': {}}},
'route_w': {'description': 'event above', 'action': {'tool': 'route', 'args': {'key': 'w'}}},
}
executor = mock.Mock(side_effect=lambda request: {'request_id': request['request_id'], 'choice': 'route_w'})
with mock.patch.object(agent, 'candidates', return_value=options), mock.patch.object(agent, 'decide') as decide:
status, _ = self.run_agent(bridge, fixed=False, executor_decider=executor)
self.assertEqual(status['state'], 'stopped')
executor.assert_called_once()
decide.assert_not_called()
self.assertEqual(bridge.call.call_args_list, [mock.call('get_state'),
mock.call('keypress', {'key': 'w'}), mock.call('keypress', {'key': 'enter'}),
mock.call('keypress', {'key': 'enter'})])
rows = [json.loads(line) for line in (self.home / 'jev_mirror_log.jsonl').read_text(encoding='utf-8').splitlines()]
self.assertEqual(rows[-1]['decision_engine'], 'executor')
self.assertEqual(rows[-1]['jev_ms'], 0)
if __name__ == '__main__':
unittest.main()
-125
View File
@@ -1,125 +0,0 @@
"""Provider routing regressions; no game or network calls."""
import json
from pathlib import Path
import sys
import unittest
from unittest import mock
import urllib.error
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
from decision_router import DecisionRequired, DecisionRouter
class DecisionRouterTest(unittest.TestCase):
def setUp(self):
self.options = {
'route_up': {'description': 'Reachable event', 'action': {'tool': 'route', 'args': {'key': 'w'}}},
'wait': {'description': 'Observe again', 'action': {'tool': 'wait', 'args': {'seconds': .7}}},
}
self.state = {'scene': 'map', 'items': [{'text': '事件'}]}
self.jev = mock.Mock(return_value={'choice': 'route_up', 'latency_ms': 10,
'confidence': .8, 'probabilities': {'route_up': .9, 'wait': .1}})
self.config = {'decisionEngine': 'jev', 'model': 'jev-test', 'apiKey': 'private-key'}
def router(self, config=None, **kwargs):
return DecisionRouter(self.config if config is None else config, self.jev, **kwargs)
def test_configured_jev_keeps_model_and_probabilities(self):
result = self.router().choose(self.state, self.options)
self.assertEqual((result.engine, result.choice, result.model, result.jev_ms), ('jev', 'route_up', 'jev-test', 10))
self.assertEqual(result.confidence, .8)
self.assertEqual(result.probabilities, {'route_up': .9, 'wait': .1})
def test_no_model_hands_off_without_using_a_key_from_environment(self):
with self.assertRaises(DecisionRequired) as raised:
self.router({'apiKey': 'private-key'}).choose(self.state, self.options, run_id='run-1')
self.jev.assert_not_called()
request = raised.exception.request
self.assertEqual((request['reason'], request['run_id']), ('no_jev_model', 'run-1'))
self.assertEqual(request['candidates'], self.options)
self.assertNotIn('private-key', json.dumps(request))
def test_model_without_credentials_hands_off(self):
with self.assertRaises(DecisionRequired) as raised:
self.router({'model': 'jev-test'}).choose(self.state, self.options)
self.assertEqual(raised.exception.request['reason'], 'missing_jev_credentials')
self.jev.assert_not_called()
def test_executor_mode_never_calls_jev_even_when_configured(self):
result = self.router(dict(self.config, decisionEngine='executor'), executor_decider=lambda request: 'wait').choose(self.state, self.options)
self.assertEqual((result.engine, result.choice, result.jev_ms), ('executor', 'wait', 0))
self.jev.assert_not_called()
def test_auto_uses_jev_when_model_and_key_are_both_present(self):
executor = mock.Mock()
result = self.router({'model': 'jev-test', 'apiKey': 'private-key'}, executor_decider=executor).choose(self.state, self.options)
self.assertEqual(result.engine, 'jev')
executor.assert_not_called()
def test_callback_receives_request_and_returns_matching_id(self):
def executor(request):
self.assertEqual(request['page_state']['scene'], 'map')
self.assertNotIn('apiKey', request)
return {'request_id': request['request_id'], 'choice': 'route_up', 'model': 'active-executor'}
result = self.router({}, executor_decider=executor).choose(self.state, self.options)
self.assertEqual((result.engine, result.model), ('executor', 'active-executor'))
def test_http_limit_hands_off_with_failed_attempt_timing(self):
self.jev.side_effect = urllib.error.HTTPError('https://example.invalid', 429, 'rate limit', {}, None)
with self.assertRaises(DecisionRequired) as raised:
self.router().choose(self.state, self.options)
request = raised.exception.request
self.assertEqual(request['reason'], 'jev_http_429')
self.assertGreaterEqual(request['failed_jev_ms'], 0)
self.assertNotIn('private-key', json.dumps(request))
def test_timeout_uses_available_execution_model(self):
self.jev.side_effect = TimeoutError('timed out')
result = self.router(executor_decider=lambda request: 'route_up').choose(self.state, self.options)
self.assertEqual((result.engine, result.choice), ('executor', 'route_up'))
self.assertEqual(result.fallback_reason, 'jev_unavailable_TimeoutError')
def test_jev_unknown_candidate_hands_off_instead_of_sending_input(self):
self.jev.return_value = {'choice': 'invented_click'}
result = self.router(executor_decider=lambda request: 'wait').choose(self.state, self.options)
self.assertEqual(result.fallback_reason, 'jev_unavailable_ValueError')
def test_executor_cannot_return_unlisted_action(self):
with self.assertRaisesRegex(ValueError, 'unsupported candidate'):
self.router({}, executor_decider=lambda request: 'invented_click').choose(self.state, self.options)
def test_executor_response_from_another_request_is_rejected(self):
with self.assertRaisesRegex(ValueError, 'different decision request'):
self.router({}, executor_decider=lambda request: {'request_id': 'old-request', 'choice': 'wait'}).choose(self.state, self.options)
def test_callback_cannot_change_request_id_or_executable_actions(self):
def executor(request):
request['request_id'] = 'changed'
request['candidates']['route_up']['action']['args']['key'] = 'enter'
return {'request_id': 'changed', 'choice': 'route_up'}
with self.assertRaisesRegex(ValueError, 'different decision request'):
self.router({}, executor_decider=executor).choose(self.state, self.options)
self.assertEqual(self.options['route_up']['action']['args']['key'], 'w')
def test_forced_fixed_mode_preserves_explicit_legacy_choice(self):
result = self.router(force_fixed=True, fixed_decider=lambda options: 'wait').choose(self.state, self.options)
self.assertEqual((result.engine, result.choice), ('fixed', 'wait'))
self.jev.assert_not_called()
def test_empty_candidates_and_invalid_mode_are_errors(self):
with self.assertRaisesRegex(ValueError, 'at least one candidate'):
self.router().choose(self.state, {})
with self.assertRaisesRegex(ValueError, 'decisionEngine'):
self.router({'decisionEngine': 'unknown'})
def test_non_finite_confidence_or_invalid_probabilities_hands_off(self):
for invalid in ({'confidence': float('nan')}, {'probabilities': {'route_up': 1}},
{'probabilities': {'route_up': .8, 'wait': .8}}):
with self.subTest(invalid=invalid):
self.jev.return_value = dict(choice='route_up', **invalid)
result = self.router(executor_decider=lambda request: 'wait').choose(self.state, self.options)
self.assertEqual(result.engine, 'executor')
if __name__ == '__main__':
unittest.main()
+22 -46
View File
@@ -7,7 +7,6 @@ from pathlib import Path
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
import jev_mirror_agent as agent
import jev_client # noqa: E402 Jev 请求经由 jev_client 发出
class SceneRegressionTest(unittest.TestCase):
@@ -93,29 +92,13 @@ class SceneRegressionTest(unittest.TestCase):
self.assertEqual(agent.fixed_fallback(options),'prepare_thunderbranch')
def test_jev_rate_limit_fails_without_sleep_or_second_request(self):
error=jev_client.urllib.error.HTTPError('https://example.test',429,'rate limit',{},None)
with mock.patch.object(jev_client.urllib.request,'urlopen',side_effect=error) as request, mock.patch.object(jev_client.time,'sleep') as sleep:
with self.assertRaises(jev_client.urllib.error.HTTPError):
agent.decide({'apiKey':'test','model':'jev-test'}, {'items':[]},{'wait':{'description':'wait'}},[])
error=agent.urllib.error.HTTPError('https://example.test',429,'rate limit',{},None)
with mock.patch.object(agent.urllib.request,'urlopen',side_effect=error) as request, mock.patch.object(agent.time,'sleep') as sleep:
with self.assertRaises(agent.urllib.error.HTTPError):
agent.decide({'apiKey':'test'}, {'items':[]},{'wait':{'description':'wait'}},[])
self.assertEqual(request.call_count,1)
sleep.assert_not_called()
def test_jev_uses_configured_model_and_returns_probabilities_without_images(self):
response = mock.MagicMock()
response.__enter__.return_value = response
response.read.return_value = b'{"model":"jev-test","answers":{"action":{"type":"choice","choice":"wait","confidence":0.5,"probabilities":{"wait":0.75,"inspect":0.25}}}}'
state = {'screen': {'path': 'LOCAL_SCREENSHOT_ONLY.png'},
'items': [{'text': 'EVENT', 'x': 10, 'y': 20}]}
options = {'wait': {'description': 'wait'}, 'inspect': {'description': 'inspect'}}
with mock.patch.object(jev_client.urllib.request, 'urlopen', return_value=response) as request:
result = agent.decide({'apiKey': 'test', 'model': 'jev-test'}, state, options, [])
payload = agent.json.loads(request.call_args.args[0].data.decode('utf-8'))
self.assertEqual(payload['model'], 'jev-test')
self.assertIsInstance(payload['state'], str)
self.assertNotIn('LOCAL_SCREENSHOT_ONLY', payload['state'])
self.assertEqual(result['confidence'], .5)
self.assertEqual(result['probabilities'], {'wait': .75, 'inspect': .25})
def test_single_extra_gift_decline_preserves_core_and_multi_cards(self):
state = {'items': [{'text':t,'x':100,'y':100,'w':100,'h':40} for t in
('获得E.G.O饰品','石版字符','拒绝饰品','选择')]}
@@ -281,24 +264,6 @@ class SceneRegressionTest(unittest.TestCase):
self.assertEqual(options['skip_dialog']['action'],
{'tool': 'click', 'args': {'x': 1260, 'y': 420}})
def test_english_receiving_text_is_not_event_rec_indicator(self):
state = {'items': [{'text': 'Receive this E.G.O Gift', 'x': 600,
'y': 300, 'w': 320, 'h': 40}]}
self.assertNotIn('event_advance', agent.candidates(state))
def test_exact_event_rec_indicator_still_advances_dialogue(self):
state = {'items': [{'text': 'REC', 'x': 900, 'y': 200, 'w': 50, 'h': 30}]}
self.assertIn('event_advance', agent.candidates(state))
def test_single_validated_confirmation_needs_no_model(self):
options = {'wait': {}, 'requires_analysis': {}, 'confirm_startup_battery': {}}
self.assertEqual(agent.unambiguous_routine(options), 'confirm_startup_battery')
def test_route_choices_and_unknown_single_actions_still_need_model(self):
for actions in ({'route_1': {}}, {'event_scroll': {}},
{'modal_confirm': {}, 'route_1': {}}):
self.assertIsNone(agent.unambiguous_routine(dict(wait={}, requires_analysis={}, **actions)))
def test_floor_three_sinclair_cannot_choose_first_floor_swap(self):
state = {'floor': 3, 'items': [
{'text': '当前持有技能', 'x': 900, 'y': 160, 'w': 100, 'h': 30},
@@ -547,19 +512,30 @@ class MainLoopTest(unittest.TestCase):
agent.main()
return make_bridge
def test_completed_run_archives_context_for_next_run(self):
with tempfile.TemporaryDirectory() as folder:
home = Path(folder)
(home / 'jev_shop_context.json').write_text(json.dumps(
{'refresh_used': 0, 'floor': 5, 'claim_requested': True, 'battery_obtained': True}))
bridge = mock.Mock()
bridge.call.return_value = {'ok': True, 'items': [
{'text': t, 'x': 0, 'y': 0, 'w': 1, 'h': 1, 'score': 1.0} for t in ('探索状态', '进入')]}
self.run_main(home, bridge)
self.assertEqual(json.loads((home / 'jev_mirror_status.json').read_text())['state'], 'completed')
# 否则下一局一启动就因 claim_requested 被判定为“已完成”
self.assertFalse((home / 'jev_shop_context.json').exists())
self.assertEqual(len(list(home.glob('jev_shop_context.*.json'))), 1)
def test_tool_errors_are_observed_instead_of_aborting(self):
with tempfile.TemporaryDirectory() as folder:
home = Path(folder)
bridge = mock.Mock()
bridge.call.return_value = {'ok': False, 'error': '截图失败'}
make_bridge = self.run_main(home, bridge, steps=2)
make_bridge.assert_called_once()
self.assertIs(make_bridge.call_args.kwargs['raise_on_error'], False)
make_bridge.assert_called_once_with(raise_on_error=False)
status = json.loads((home / 'jev_mirror_status.json').read_text())
# 没有因异常退出, 而是按“截图暂不可用”等待到步数用完
self.assertEqual((status['state'], status.get('reason')), ('stopped', 'step_limit'))
records = [json.loads(line) for line in (home / 'jev_mirror_log.jsonl').read_text().splitlines()]
self.assertEqual([r['choice'] for r in records], ['wait', 'wait'])
self.assertNotIn('error', status) # 没有因异常退出, 而是按“截图暂不可用”继续等待
self.assertEqual(status['choice'], 'wait')
class SessionTest(unittest.TestCase):
@@ -569,7 +545,7 @@ class SessionTest(unittest.TestCase):
session = mcp_session.Session.__new__(mcp_session.Session)
session.request = mock.Mock(return_value={'isError': True, 'content': [
{'type': 'text', 'text': json.dumps({'ok': False, 'error': 'text not found'})}]})
session.raise_on_error, session.timeout = False, 30
session.raise_on_error = False
self.assertEqual(session.call('click_text', {'text': 'x'}), {'ok': False, 'error': 'text not found'})
session.raise_on_error = True
with self.assertRaises(RuntimeError):
+76 -57
View File
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
"""不需要 Windows/AALC 的测试: python -m unittest discover -s tests"""
import json
import io
import os
import socket
import subprocess
@@ -16,6 +15,7 @@ REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, REPO)
from lc_mcp import server as srv_mod # noqa: E402
from lc_mcp import aalc_input_patch # noqa: E402
from lc_mcp.engine import find_hits # noqa: E402
from lc_mcp.fake_engine import FakeEngine # noqa: E402
from lc_mcp.protocol import Server, TOOLS # noqa: E402
@@ -85,55 +85,6 @@ class ProtocolTest(unittest.TestCase):
self.assertIn('bad arguments', r['error'])
self.assertFalse(call(self.s, 'click')['ok'])
def test_invalid_request_shapes_do_not_escape_or_send_input(self):
for params in (['invalid'], 'invalid', 1, True, None):
response = self.s.handle({'jsonrpc': '2.0', 'id': 7, 'method': 'tools/call', 'params': params})
self.assertEqual(response['error']['code'], -32602)
for arguments in ([], 'invalid', 1, True, None):
response = self.s.handle({'jsonrpc': '2.0', 'id': 8, 'method': 'tools/call',
'params': {'name': 'click', 'arguments': arguments}})
self.assertEqual(response['error']['code'], -32602)
self.assertEqual(self.engine.actions, [])
def test_notifications_never_reply_or_perform_request_only_actions(self):
message = {'jsonrpc': '2.0', 'method': 'tools/call',
'params': {'name': 'click', 'arguments': {'x': 1, 'y': 2}}}
self.assertIsNone(self.s.handle(message))
self.assertEqual(self.engine.actions, [])
self.assertIsNotNone(self.s.handle(dict(message, id=None)))
def test_malformed_messages_allow_following_valid_request(self):
messages = ['null', '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":[1]}',
'{"jsonrpc":"2.0","id":2,"method":"ping"}']
stdin, stdout = io.StringIO('\n'.join(messages) + '\n'), io.StringIO()
srv_mod.serve_lines(self.s, stdin.readline, stdout.write)
responses = [json.loads(line) for line in stdout.getvalue().splitlines()]
self.assertEqual([r.get('error', {}).get('code') for r in responses[:2]], [-32600, -32602])
self.assertEqual(responses[2], {'jsonrpc': '2.0', 'id': 2, 'result': {}})
def test_invalid_envelope_returns_request_error(self):
for updates in ({'jsonrpc': '1.0'}, {'method': []}, {'id': True}, {'id': []}):
message = dict({'jsonrpc': '2.0', 'id': 9, 'method': 'ping'}, **updates)
self.assertEqual(self.s.handle(message)['error']['code'], -32600)
def test_task_start_cannot_race_an_input_already_in_progress(self):
entered, release = threading.Event(), threading.Event()
self.engine.click = lambda *args: (entered.set(), release.wait(3))
worker = threading.Thread(target=lambda: call(self.s, 'click', x=1, y=2))
worker.start()
try:
self.assertTrue(entered.wait(2))
started = time.monotonic()
response = call(self.s, 'run_task', task='mirror')
self.assertFalse(response['ok'])
self.assertIsNone(self.tasks.proc)
self.assertLess(time.monotonic() - started, 1)
self.assertEqual(call(self.s, 'task_status')['state'], 'idle')
self.assertTrue(call(self.s, 'stop_task')['ok'])
finally:
release.set()
worker.join(3)
def test_drag_duration_and_rejected_arguments(self):
r = call(self.s, 'drag', from_x=200, from_y=300, to_x=200, to_y=600, duration=1.5)
self.assertTrue(r['ok'])
@@ -173,13 +124,8 @@ class ProtocolTest(unittest.TestCase):
self.assertIn('stop_task', call(self.s, 'drag', from_x=1, from_y=2,
to_x=3, to_y=4)['error'])
self.assertTrue(call(self.s, 'get_state')['ok']) # 只读工具仍可用
# 轮询等子进程输出, 不用固定等待 (机器负载高时 0.5s 不够)
deadline = time.time() + 10
while True:
st = call(self.s, 'task_status')
if st['log_tail'] or time.time() > deadline:
break
time.sleep(0.05)
time.sleep(0.5)
st = call(self.s, 'task_status')
self.assertEqual(st['state'], 'running')
self.assertEqual(st['params'], {'count': 2})
self.assertIn("child ['mirror', '{\"count\": 2}']", '\n'.join(st['log_tail']))
@@ -667,5 +613,78 @@ class TaskErrorSurfaceTest(unittest.TestCase):
self.assertNotIn('errors', status)
class TeamScrollPatchTest(unittest.TestCase):
"""编队列表滑动: Windows 适配器缺少队伍拖拽规避, 补丁的几何必须是
"先 escape 脱离按住判定, 再按名义位移走完"。
"""
def test_zero_distance_is_noop(self):
self.assertIsNone(aalc_input_patch.team_scroll_plan(10, 20, 0, 0, 0.3, 60))
def test_upward_swipe_escapes_first_then_travels_nominal_delta(self):
start, escape, end, duration = aalc_input_patch.team_scroll_plan(100, 200, 0, -200, 0.4, 60)
self.assertEqual(start, (100.0, 200.0))
self.assertEqual(escape, (100.0, 140.0))
self.assertEqual(end, (100.0, -60.0))
self.assertAlmostEqual(end[1] - escape[1], -200.0)
self.assertEqual(duration, 0.4)
def test_downward_swipe_shifts_start_into_visible_rows(self):
start, escape, end, _ = aalc_input_patch.team_scroll_plan(100, 200, 0, 200, 0.4, 60)
self.assertEqual(start, (100.0, 140.0))
self.assertEqual(escape, (100.0, 200.0))
self.assertEqual(end, (100.0, 400.0))
self.assertAlmostEqual(end[1] - escape[1], 200.0)
def test_escape_leg_has_requested_length(self):
start, escape, end, _ = aalc_input_patch.team_scroll_plan(0, 0, 300, -400, 0.5, 50)
leg = (escape[0] - start[0], escape[1] - start[1])
self.assertAlmostEqual((leg[0] ** 2 + leg[1] ** 2) ** 0.5, 50.0)
self.assertAlmostEqual(end[0] - escape[0], 300.0)
self.assertAlmostEqual(end[1] - escape[1], -400.0)
def test_install_patches_team_scroll_on_windows_adapters(self):
import types
class FakeInput:
def mouse_swipe_for_team_scroll(self, *args, **kwargs):
raise AssertionError('未打补丁')
class FakeBackground:
def set_mouse_pos(self, *args, **kwargs):
pass
def mouse_swipe_for_team_scroll(self, *args, **kwargs):
raise AssertionError('未打补丁')
class FakeWindowMove:
"""没有 set_mouse_pos 的适配器保持原样。"""
def mouse_swipe_for_team_scroll(self, *args, **kwargs):
raise AssertionError('未打补丁')
leaf = types.ModuleType('module.automation.input_handlers.input')
leaf.Input = FakeInput
leaf.BackgroundInput = FakeBackground
leaf.WindowMoveInput = FakeWindowMove
parents = {}
for name in ('module', 'module.automation', 'module.automation.input_handlers'):
parents[name] = types.ModuleType(name)
parents[name].__path__ = []
parents['module.automation.input_handlers'].input = leaf
parents['module.automation'].input_handlers = parents['module.automation.input_handlers']
parents['module'].automation = parents['module.automation']
with mock.patch.dict(sys.modules, parents):
patched = aalc_input_patch.install()
self.assertEqual(patched, ['Input', 'BackgroundInput'])
self.assertIs(FakeInput.mouse_swipe_for_team_scroll,
aalc_input_patch._foreground_team_scroll)
self.assertIs(FakeBackground.mouse_swipe_for_team_scroll,
aalc_input_patch._adapter_team_scroll)
# 幂等: 再装一次不再重复补
self.assertEqual(aalc_input_patch.install(), [])
if __name__ == '__main__':
unittest.main()
-110
View File
@@ -1,110 +0,0 @@
import sys
import unittest
from pathlib import Path
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
from lc_scene_aliases import normalize
import jev_mirror_agent as agent
from decision_router import DecisionRouter
class EnglishMirrorBoundaryTest(unittest.TestCase):
def test_map_header_without_recognized_floor_number_stops_battle(self):
for label in ('Exploring Floor', 'Exploring FloorT'):
with self.subTest(label=label):
state = normalize({'items': [{'text': label, 'x': 60, 'y': 131,
'w': 302, 'h': 51, 'score': .975}]})
self.assertTrue(agent.battle_is_terminal(state))
with mock.patch.object(agent, 'map_candidates', return_value={}):
self.assertNotIn('battle', agent.candidates(state, previous_battle=True))
def test_enabled_commence_precedes_reselecting_sinners(self):
options = {'button_20': {'description': '当前可见且非灰色按钮:进行判定',
'action': {'tool': 'keypress', 'args': {'key': 'enter'}}},
'sinner_1': {'description': '选择预计成功率高的罪人卡'},
'requires_analysis': {'description': '分析'}, 'wait': {'description': '等待'}}
self.assertEqual(agent.unambiguous_routine(options), 'button_20')
def test_video_clock_does_not_reset_failed_enter_detection(self):
def observation(clock, button='Proceed'):
return {'items': [{'text': text, 'score': 1} for text in (clock, button)]}
self.assertEqual(agent.scene_fingerprint(observation('00:00:42.48')),
agent.scene_fingerprint(observation('00:00:43:02')))
self.assertNotEqual(agent.scene_fingerprint(observation('00:00:43:02')),
agent.scene_fingerprint(observation('00:00:43:02', 'Commence')))
def test_commence_and_split_sinner_header_reach_judgement_boundary(self):
state = {'screen': {'w': 1920, 'h': 1080}, 'items': [
{'text': text, 'x': 1200, 'y': y, 'w': 200, 'h': 40, 'score': 1}
for text, y in [('Choose a character toperform', 445), ('Commence', 949)]]}
state = normalize(state)
self.assertTrue(agent.battle_is_terminal(state))
with mock.patch.object(agent, 'button_enabled', return_value=True):
options = agent.candidates(state)
self.assertTrue(any('进行判定' in option['description'] for option in options.values()))
judge = next(option for key, option in options.items() if key.startswith('button_')
and '进行判定' in option['description'])
self.assertEqual(judge['action']['tool'], 'keypress')
self.assertEqual(judge['fallback_action']['tool'], 'click')
def test_merged_english_probabilities_are_explicit_and_idempotent(self):
state = {'screen': {'w': 1920, 'h': 1080}, 'items': [
{'text': 'NormalVeryLowVeryHighVeryHigh', 'x': 906, 'y': 912,
'w': 400, 'h': 29, 'score': .946}]}
normalize(state)
labels = [item for item in state['items'] if item['text'] == '极高']
self.assertEqual(len(labels), 2)
self.assertTrue(all(1100 < item['x'] < 1300 for item in labels))
normalize(state)
self.assertEqual(len(state['items']), 3)
def test_english_outcome_lines_are_not_event_buttons(self):
state = {'screen': {'w': 1920, 'h': 1080}, 'items': [
{'text': text, 'x': 1096, 'y': y, 'w': 300, 'h': 31, 'score': 1}
for text, y in [('Choices', 168), ('Accept the surgery.', 295),
('RunaSloth&GloomAdvantagechecktogaina', 332),
('Keywordless E.G.O Gift.', 362),
('Break the light and run away.', 518)]]}
with mock.patch.object(agent, 'button_enabled', return_value=True):
options = agent.candidates(normalize(state))
descriptions = [value['description'] for key, value in options.items()
if key.startswith('event_') and key != 'event_scroll']
self.assertEqual(len(descriptions), 2)
self.assertTrue(any('Advantagecheck' in value for value in descriptions))
def test_empty_observation_is_not_a_normalization_error(self):
self.assertEqual(normalize({'items': None})['items'], [])
def test_route_request_keeps_observed_route_facts_and_omits_unrelated_setup(self):
options = {'route_d': {'description': '正前方有可达事件'},
'route_w': {'description': '上方有可达普通战斗'},
'wait': {'description': '等待'},
'requires_analysis': {'description': '需要分析'}}
with mock.patch.object(agent, 'request_answer', return_value={'choice': 'route_d'}) as request:
agent.decide({}, {'items': [{'text': 'irrelevant party text'}]}, options, [])
self.assertIn('正前方有可达事件', request.call_args.args[1])
self.assertNotIn('irrelevant party text', request.call_args.args[1])
self.assertNotIn('合成', request.call_args.args[3])
def test_sinner_request_only_offers_explicit_maximum_probability(self):
options = {'sinner_1': {'description': '选择预计成功率高的罪人卡'},
'sinner_2': {'description': '选择预计成功率极高的罪人卡'},
'sinner_card_3': {'description': '金黄色(高/极高)'},
'requires_analysis': {'description': '分析'}, 'wait': {'description': '等待'}}
with mock.patch.object(agent, 'request_answer', return_value={'choice': 'sinner_2'}) as request:
agent.decide({}, {}, options, [])
self.assertEqual(set(request.call_args.args[2]), {'sinner_2'})
def test_scoped_probability_distribution_passes_router_and_keeps_scope(self):
options = {'sinner_1': {'description': '选择预计成功率高的罪人卡'},
'sinner_2': {'description': '选择预计成功率极高的罪人卡'},
'requires_analysis': {'description': '分析'}, 'wait': {'description': '等待'}}
router = DecisionRouter({'model': 'test-model', 'apiKey': 'test-key'}, agent.decide)
response = {'choice': 'sinner_2', 'latency_ms': 1, 'probabilities': {'sinner_2': 1}}
with mock.patch.object(agent, 'request_answer', return_value=response):
decision = router.choose({}, options)
self.assertEqual(decision.choice, 'sinner_2')
self.assertEqual(decision.candidate_scope, ['sinner_2'])
self.assertEqual(decision.probabilities, {'sinner_1': 0, 'sinner_2': 1,
'requires_analysis': 0, 'wait': 0})
-156
View File
@@ -1,156 +0,0 @@
"""Real pipe regressions with a dummy worker; never connects to a game service."""
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import threading
import time
import unittest
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
from mcp_session import Session, SessionCancelled, SessionTimeout
WORKER = '''import json,os,sys,time
mode=os.environ['WORKER_MODE']
for line in sys.stdin:
message=json.loads(line)
with open(os.environ['WORKER_LOG'],'a',encoding='utf-8') as log:
log.write(json.dumps(message)+'\\n')
mid=message.get('id')
if mode=='initialize-failure':
sys.exit(1)
if mid is None:
continue
if message['method']=='initialize':
if mode=='stderr-burst':
sys.stderr.write('diagnostic\\n'*50000)
sys.stderr.flush()
result={}
elif mode=='silent':
continue
elif mode=='malformed':
print('invalid json',flush=True)
continue
else:
result={'content':[{'type':'text','text':json.dumps({'ok':True,'text':'中文'})}]}
print(json.dumps({'jsonrpc':'2.0','id':mid,'result':result}),flush=True)
if mode=='no-read':
time.sleep(60)
'''
class SessionTest(unittest.TestCase):
def setUp(self):
self.folder = tempfile.TemporaryDirectory()
self.addCleanup(self.folder.cleanup)
self.log = Path(self.folder.name) / 'requests.jsonl'
self.children = []
def worker(self, mode, **options):
real_popen = subprocess.Popen
def launch(*args, **kwargs):
kwargs['env'] = dict(kwargs['env'], WORKER_MODE=mode, WORKER_LOG=str(self.log))
child = real_popen([sys.executable, '-u', '-c', WORKER], **kwargs)
self.children.append(child)
return child
with mock.patch('mcp_session.subprocess.Popen', side_effect=launch):
return Session(**options)
def test_silent_response_times_out_without_retry_and_closes_child(self):
client = self.worker('silent', timeout=.5)
self.addCleanup(client.close)
started = time.monotonic()
with self.assertRaises(SessionTimeout) as caught:
client.call('click', {'x': 1, 'y': 2})
self.assertTrue(caught.exception.outcome_unknown)
self.assertEqual(caught.exception.tool, 'click')
self.assertLess(time.monotonic() - started, 3)
self.assertIsNotNone(client.process.poll())
rows = [json.loads(line) for line in self.log.read_text().splitlines()]
self.assertEqual(sum(row['method'] == 'tools/call' for row in rows), 1)
with self.assertRaises(ConnectionError):
client.call('get_state')
def test_stop_interrupts_pending_response(self):
cancelled = threading.Event()
client = self.worker('silent', timeout=5, cancelled=cancelled.is_set)
self.addCleanup(client.close)
timer = threading.Timer(.2, cancelled.set)
timer.start()
self.addCleanup(timer.cancel)
started = time.monotonic()
with self.assertRaises(SessionCancelled) as caught:
client.call('keypress', {'key': 'enter'})
self.assertTrue(caught.exception.outcome_unknown)
self.assertLess(time.monotonic() - started, 3)
self.assertIsNotNone(client.process.poll())
def test_stderr_burst_does_not_block_handshake_and_chinese_response(self):
with self.worker('stderr-burst', timeout=5) as client:
self.assertEqual(client.call('get_state')['text'], '中文')
self.assertLessEqual(len(client.stderr_tail), 20)
def test_initialization_failure_closes_every_pipe(self):
with self.assertRaises(ConnectionError):
self.worker('initialize-failure', timeout=2)
child = self.children[0]
self.assertIsNotNone(child.poll())
self.assertTrue(all(stream.closed for stream in (child.stdin, child.stdout, child.stderr)))
def test_invalid_response_closes_session(self):
client = self.worker('malformed', timeout=2)
self.addCleanup(client.close)
with self.assertRaises(ConnectionError):
client.call('get_state')
self.assertIsNotNone(client.process.poll())
def test_blocked_stdin_write_is_also_bounded(self):
client = self.worker('no-read', timeout=.5)
self.addCleanup(client.close)
started = time.monotonic()
with self.assertRaises(SessionTimeout):
client.call('type_text', {'text': 'x' * 500000})
self.assertLess(time.monotonic() - started, 3)
self.assertIsNotNone(client.process.poll())
self.assertFalse(any(thread.is_alive() for thread in client._threads))
def test_long_wait_tool_has_a_response_budget_beyond_its_polling_timeout(self):
client = Session.__new__(Session)
client.timeout = 30
client.request = mock.Mock(return_value={'content': [{'text': '{"ok":true}'}]})
client.call('wait_for_text', {'text': '开始', 'timeout': 300})
self.assertEqual(client.request.call_args.args[2], 305)
def test_session_uses_real_bridge_against_isolated_fake_server(self):
from lc_mcp.fake_engine import FakeEngine
from lc_mcp.protocol import Server
from lc_mcp.server import make_tcp
from lc_mcp.tasks import TaskRunner
home = Path(self.folder.name)
runtime = home / 'lc_mcp'
runtime.mkdir()
(runtime / 'token').write_text('test-only-token')
engine = FakeEngine()
tcp = make_tcp(Server(engine, TaskRunner(str(home / 'runs'))), '127.0.0.1', 0, 'test-only-token')
serving = threading.Thread(target=tcp.serve_forever, daemon=True)
serving.start()
try:
with mock.patch.dict(os.environ, {'LCP_PORT': str(tcp.server_address[1]),
'HOME': str(home), 'USERPROFILE': str(home)}):
with Session(timeout=5) as client:
self.assertTrue(client.call('get_state')['ok'])
self.assertTrue(client.call('drag', {'from_x': 1, 'from_y': 2,
'to_x': 3, 'to_y': 4})['ok'])
self.assertTrue(client.call('type_text', {'text': '中文'})['ok'])
self.assertEqual(engine.actions[-1], ('type', '中文'))
finally:
tcp.shutdown()
tcp.server_close()
serving.join(2)
if __name__ == '__main__':
unittest.main()
-111
View File
@@ -1,111 +0,0 @@
import json
from pathlib import Path
import sys
import tempfile
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
from run_state import prepare_run, save_json, record_claim, claim_is_current, complete_run
class RunStateTest(unittest.TestCase):
def setUp(self):
self.folder = tempfile.TemporaryDirectory()
self.addCleanup(self.folder.cleanup)
self.home = Path(self.folder.name)
self.run_path = self.home / 'mirror_current_run.json'
self.context_path = self.home / 'jev_shop_context.json'
def test_completed_run_starts_with_fresh_floor_and_no_claim_or_upgrades(self):
old_run, old_context = prepare_run(self.home)
old_run['status'] = 'completed'
old_context.update(floor=5, claim_requested=True, symbol_upgraded=True, battle_context=True)
save_json(self.run_path, old_run)
save_json(self.context_path, old_context)
run, context = prepare_run(self.home)
self.assertNotEqual(run['run_id'], old_run['run_id'])
self.assertEqual(context, {'run_id': run['run_id'], 'floor': 1, 'refresh_used': 0})
self.assertFalse(claim_is_current(run, context))
def test_resume_keeps_matching_run_and_verified_claim(self):
old_run, context = prepare_run(self.home)
context.update(floor=4, symbol_upgraded=True)
record_claim(self.home, old_run, context, {'path': 'completion.png'})
run, resumed = prepare_run(self.home, resume=True)
self.assertEqual(run['run_id'], old_run['run_id'])
self.assertEqual(run['start_utc'], old_run['start_utc'])
self.assertEqual(resumed['floor'], 4)
self.assertTrue(resumed['symbol_upgraded'])
self.assertTrue(claim_is_current(run, resumed))
def test_explicit_new_run_discards_even_unfinished_state(self):
old_run, _ = prepare_run(self.home)
run, _ = prepare_run(self.home, new_run=True)
self.assertNotEqual(run['run_id'], old_run['run_id'])
def test_resume_requires_an_unfinished_record(self):
with self.assertRaises(ValueError):
prepare_run(self.home, resume=True)
run, _ = prepare_run(self.home)
run['status'] = 'completed'
save_json(self.run_path, run)
with self.assertRaises(ValueError):
prepare_run(self.home, resume=True)
def test_orphan_context_does_not_supply_completion_to_new_run(self):
save_json(self.context_path, {'floor': 5, 'claim_requested': True})
run, context = prepare_run(self.home)
self.assertEqual(context['floor'], 1)
self.assertFalse(claim_is_current(run, context))
def test_legacy_unfinished_run_preserves_upgrades_but_discards_unbound_claim(self):
save_json(self.run_path, {'start_utc': '2026-10-02T18:13:22+08:00', 'status': 'user_takeover'})
save_json(self.context_path, {'floor': 5, 'symbol_upgraded': True,
'claim_requested': True, 'battle_context': True})
run, context = prepare_run(self.home, resume=True)
self.assertEqual(context['floor'], 5)
self.assertTrue(context['symbol_upgraded'])
self.assertNotIn('battle_context', context)
self.assertFalse(claim_is_current(run, context))
self.assertTrue(run['legacy_context_migrated'])
def test_mismatched_ids_fail_before_overwriting_the_context(self):
prepare_run(self.home)
save_json(self.context_path, {'run_id': 'another-run', 'floor': 5})
before = self.context_path.read_bytes()
with self.assertRaises(ValueError):
prepare_run(self.home)
self.assertEqual(self.context_path.read_bytes(), before)
def test_completion_requires_matching_claim_and_keeps_both_screens(self):
run, context = prepare_run(self.home)
with self.assertRaises(ValueError):
complete_run(self.home, run, context, {'path': 'home.png'})
record_claim(self.home, run, context, {'path': 'completion.png'})
context['claim_run_id'] = 'another-run'
with self.assertRaises(ValueError):
complete_run(self.home, run, context, {'path': 'home.png'})
context['claim_run_id'] = run['run_id']
complete_run(self.home, run, context, {'path': 'home.png'})
saved = json.loads(self.run_path.read_text())
self.assertTrue(saved['dungeon_completed'])
self.assertEqual(saved['claim_evidence']['path'], 'completion.png')
self.assertEqual(saved['completion_evidence']['path'], 'home.png')
def test_atomic_snapshot_retains_old_data_if_serialization_fails(self):
save_json(self.context_path, {'floor': 2})
with self.assertRaises(TypeError):
save_json(self.context_path, {'bad': {1, 2}})
self.assertEqual(json.loads(self.context_path.read_text()), {'floor': 2})
self.assertFalse(list(self.home.glob('*.tmp')))
def test_new_run_can_recover_from_corrupt_old_files(self):
self.run_path.write_text('truncated')
self.context_path.write_text('truncated')
run, context = prepare_run(self.home, new_run=True)
self.assertEqual(run['status'], 'running')
self.assertEqual(context['floor'], 1)
if __name__ == '__main__':
unittest.main()