diff --git a/README.md b/README.md index 7bb1b1b..3a817d9 100644 --- a/README.md +++ b/README.md @@ -134,7 +134,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` 设为自己的凭据,再运行: @@ -143,9 +143,37 @@ 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 项回归结果。 diff --git a/docs/execution_flow_and_guide_coverage_20261003.md b/docs/execution_flow_and_guide_coverage_20261003.md new file mode 100644 index 0000000..b888a7e --- /dev/null +++ b/docs/execution_flow_and_guide_coverage_20261003.md @@ -0,0 +1,71 @@ +# 当前执行流程与速通资料覆盖 + +核对日期: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 场景执行。** 保持一个游戏执行进程,复用地图缓存及可靠的场景操作;完成一次场景目标后核验,再继续推进。 + +以上四项是后续基础实现范围。本次流程核对与文档同步不会启动游戏,也没有新增实际通关或提速证据。 diff --git a/docs/feedback_latency_profile_20261003.json b/docs/feedback_latency_profile_20261003.json new file mode 100644 index 0000000..8e0f244 --- /dev/null +++ b/docs/feedback_latency_profile_20261003.json @@ -0,0 +1,141 @@ +{ + "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 + } + ] +} diff --git a/docs/jev_aalc_automation_research_20261003.md b/docs/jev_aalc_automation_research_20261003.md new file mode 100644 index 0000000..8b8b42c --- /dev/null +++ b/docs/jev_aalc_automation_research_20261003.md @@ -0,0 +1,232 @@ +# 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 混合执行器、配置工具和分段识别方案仍为后续实施设计。 diff --git a/docs/jev_page_state_example_20261003.json b/docs/jev_page_state_example_20261003.json new file mode 100644 index 0000000..361097d --- /dev/null +++ b/docs/jev_page_state_example_20261003.json @@ -0,0 +1,69 @@ +{ + "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." + ] +} diff --git a/docs/mcp_runtime_improvements_20261003.md b/docs/mcp_runtime_improvements_20261003.md new file mode 100644 index 0000000..5d05541 --- /dev/null +++ b/docs/mcp_runtime_improvements_20261003.md @@ -0,0 +1,23 @@ +# 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。停止文件需要在准备继续时移除。 + +本轮提交只包含程序、测试和说明文件,没有包含个人运行记录、凭据、虚拟环境或历史物理驱动资料。 diff --git a/docs/skills/limbus-mirror-speedrun/SKILL.md b/docs/skills/limbus-mirror-speedrun/SKILL.md index cae2a58..643f6ac 100644 --- a/docs/skills/limbus-mirror-speedrun/SKILL.md +++ b/docs/skills/limbus-mirror-speedrun/SKILL.md @@ -35,7 +35,7 @@ description: 继续或重开边狱公司(Limbus Company)的镜像迷宫/ ## 速度与完成标准 -用户已明确指定 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`。 +用户最初指定 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`。 略过无关观测、采购、调队和反复比较,保留符咒 ++、快感 ++ 与关键技能替换。雷枝是用户允许的观测例外,不将此授权扩展为所有饰品的无界观测。大量理智损失可能增加纯 P 战斗回合,不能只按当前事件点击次数选择。 @@ -43,4 +43,8 @@ description: 继续或重开边狱公司(Limbus Company)的镜像迷宫/ 持续到本局通关结算,或用户中止/必须手动接管的具体步骤。只有看到最终通关结算才能报告完成。研究完攻略或做完一层不算通关;不承诺复现视频的 12 分钟用时。 -用户纠正流程时,在授权范围内更新相应参考文件和现有速通笔记(lc-mcp 仓库 `docs/mirror_dungeon_speedrun_notes.md`);先读笔记,保留用户其他编辑。资料核对日期:2026-10-02。 +用户纠正流程时,在授权范围内更新相应参考文件和仓库 [速通笔记](../../mirror_dungeon_speedrun_notes.md);先读笔记,保留用户其他编辑。攻略资料核对日期:2026-10-02;执行接口说明更新于 2026-10-03。 + +## 文档与程序的对应范围 + +本 skill 和参考文件是执行助手的工作说明,文件存在不表示 Python 自动加载全部攻略。当前脚本把部分用户规则写入 `SYSTEM_RULES`、候选筛选和动作宏;楼层完整目标、事件速查与合成预算还需要进一步接入。按当前游戏文字核实强化、库存和预算,不能用文档中的期望状态代替实际持有状态。具体对应关系见 [执行流程与资料覆盖](../../execution_flow_and_guide_coverage_20261003.md)。 diff --git a/docs/skills/limbus-mirror-speedrun/references/jev.md b/docs/skills/limbus-mirror-speedrun/references/jev.md index b03ed87..bc59bf4 100644 --- a/docs/skills/limbus-mirror-speedrun/references/jev.md +++ b/docs/skills/limbus-mirror-speedrun/references/jev.md @@ -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 秒。这不是整局速度保证。 -- 现有客户端:lc-mcp 仓库的 `scripts/jev_decision_client.mjs`,导出的 `decide(state, criteria, options)` 返回有限选项编号、概率和请求耗时。 +- 历史实测 `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 主循环不调用它。 - 密钥从 `options.apiKey`、`OPENCODE_API_KEY` 或用户已有本机配置注入;不把密钥复制到脚本、笔记、skill 或日志,也不打印配置全文。重启后若没有凭据,不能假装已接通。 - 只发送精简游戏状态和选项文字,避免整段聊天、其他窗口、完整桌面截图等无关内容。 - 先按用户规则排除不合适的选项,再将候选交给模型。当前界面和用户新指令优先;不把模型置信度当作游戏事实。 - 用户更新(2026-10-02):固定场景、路线及所有常规动作均由 Jev 从候选中选择;主助手仅在 `requires_analysis` 或具体接口故障后介入。战斗动作可包含有界 P→回车短批次。API 短暂错误可重试一次,持续失败交回主助手修复。 - 后续战斗指令覆盖逐批决策:战斗开始后仅 P+回车循环直至结算;有界批次末检查结束标志,战斗中不再调用 Jev 或分析拼点。结算后恢复 Jev 决策。 -- 执行器 lc-mcp 仓库的 `scripts/jev_mirror_agent.py` 通过 limbus MCP 操作;Windows 单实例互斥避免输入交叠。状态为 `jev_mirror_status.json`,动作日志为 `jev_mirror_log.jsonl`。确认弹窗候选使用当前截图坐标并排除背景按钮。商店没有出战角色技能替换时,每店最多刷新 4 次。 +- 执行器通过 limbus MCP 操作;Windows 单实例互斥避免输入交叠。运行目录默认 `~/lc_mcp/jev`,可用 `LC_JEV_HOME` 覆盖;状态为 `jev_mirror_status.json`,动作日志为 `jev_mirror_log.jsonl`。确认弹窗候选使用当前截图坐标并排除背景按钮。商店没有出战角色技能替换时,每店最多刷新 4 次。 ## 已落实的执行边界(2026-10-02) @@ -18,7 +18,7 @@ - 层末选择数达到要求后,一次发送三个回车;事件结果用短批次回车。同一画面仍未推进时,点击本候选绑定的确认控件,避免命中背景按钮。 - 判定优先 OCR 明确的极高/非常高,其次高;没有清晰文字才按金黄色标识选。没有结果文字的事件选项不能当免费奖励;明确触发战斗的选项排除,选择前读取事件速查。 - 雷枝观测领取后记为待强化,商店打开强化面板;快感取得后记为待 ++。主助手付款并确认实际库存后清除对应待办标记;雷枝预算不足可记录延后,不能把预览当完成。快感尽量在第二、三层处理。 -- Jev 返回 401/403/429 时不反复等待请求,当前执行会话转为固定候选回退,并将 HTTP 原因写入日志;回退不是 Jev 成功决策。 +- 2026-10-03 后续指令与实现:未指定 Jev 模型、缺少凭据或 Jev 请求失败时交给执行模型。嵌入运行可提供 `executor_decider(request)` 回调;独立脚本发布 `requires_decision` 和 `decision_request.json`,由调用方读取、重新核对页面并处理,再续跑同一局。固定候选回退需显式设置 `decisionEngine=fixed` 或 `LC_FIXED_FALLBACK=1`。回退和接管均不记为 Jev 成功决策。 - 用户接管时逐键检查停止标记。日志新增 OCR 毫秒、动作毫秒、动作结束时间;未执行完的批次不伪造完整按键数。优化代码期间保持停止状态。 依据:[OpenCode Zen:Jev](https://opencode.ai/docs/zen/#jev)。 diff --git a/docs/skills/limbus-mirror-speedrun/references/mechanics.md b/docs/skills/limbus-mirror-speedrun/references/mechanics.md index b497123..e351aba 100644 --- a/docs/skills/limbus-mirror-speedrun/references/mechanics.md +++ b/docs/skills/limbus-mirror-speedrun/references/mechanics.md @@ -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+回车,也不能自动接受死亡或放弃本局。此项来自上局执行缺陷,当前控制器仍待补充终止识别。 +- **结束识别**:全体死亡/重试界面也是战斗结束,不能继续 P+回车,也不能自动接受死亡或放弃本局。此项来自上局执行缺陷;2026-10-03 主脚本与 `battle_batch.py` 已共用 `game_scenes.py` 的死亡/重试识别,并通过离线回归,新的整局实机验证仍待完成。 - **计时**:包含配置、模型等待、加载、修复、失败和所有停顿。用户接管后只记交接前耗时;未取得最终通关奖励不能记为自动成功。 ## 资料入口 diff --git a/lc_mcp/protocol.py b/lc_mcp/protocol.py index 5ba0aff..bf97e7e 100644 --- a/lc_mcp/protocol.py +++ b/lc_mcp/protocol.py @@ -78,6 +78,18 @@ 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}}, @@ -87,17 +99,17 @@ class Server: if method == 'tools/list': return _ok(mid, {'tools': TOOLS}) if method == 'tools/call': - params = msg.get('params') or {} - result = self.call_tool(params.get('name'), params.get('arguments') or {}) + 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) 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: # 不抢游戏锁: wait_for_text 期间也能查任务/停任务 + if name in TASK_TOOLS: # 查任务/停任务不等待正在执行的游戏工具 return self._task_tool(name, args) with self.lock: return self._call(name, args) @@ -113,7 +125,14 @@ 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} - return self.tasks.start(task, params) + # 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() if name == 'task_status': return self.tasks.status(a.get('lines', 30)) return self.tasks.stop() @@ -216,6 +235,9 @@ def parse_line(line): if not line: return None, None try: - return json.loads(line), None + msg = json.loads(line) + if msg is None: + return None, _error(None, -32600, 'request must be a JSON object') + return msg, None except ValueError as e: return None, _error(None, -32700, 'parse error: %s' % e) diff --git a/scripts/analyze_feedback.py b/scripts/analyze_feedback.py new file mode 100644 index 0000000..a164737 --- /dev/null +++ b/scripts/analyze_feedback.py @@ -0,0 +1,128 @@ +#!/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() diff --git a/scripts/battle_batch.py b/scripts/battle_batch.py index cf301b8..3107f4f 100644 --- a/scripts/battle_batch.py +++ b/scripts/battle_batch.py @@ -1,16 +1,18 @@ """Bounded Win Rate batches through MCP, with a fresh UI check per turn.""" import argparse import json +import math +import os import time -from mcp_session import Session +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' def 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) + return battle_is_terminal(state) def main(): @@ -18,32 +20,47 @@ 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 - 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 = {} + 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: state = client.call('get_state') - print(json.dumps({'pairs': pairs, 'state': state}, ensure_ascii=False)) + 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)) if __name__ == '__main__': diff --git a/scripts/decision_router.py b/scripts/decision_router.py new file mode 100644 index 0000000..f5f4ec7 --- /dev/null +++ b/scripts/decision_router.py @@ -0,0 +1,132 @@ +"""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 + + +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) + 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': '', 'choice': ''}, + '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')) diff --git a/scripts/game_scenes.py b/scripts/game_scenes.py new file mode 100644 index 0000000..52823ea --- /dev/null +++ b/scripts/game_scenes.py @@ -0,0 +1,28 @@ +"""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)) diff --git a/scripts/jev_client.py b/scripts/jev_client.py index 7707f9c..806beb8 100644 --- a/scripts/jev_client.py +++ b/scripts/jev_client.py @@ -54,13 +54,15 @@ def _post(cfg, body): return json.loads(content) -def request_decision(cfg, state, criteria, instructions): +def request_answer(cfg, state, criteria, instructions): + """返回 {'choice', 'latency_ms', 'confidence', 'probabilities', 'model'}; 候选之外的结果会被拒绝。""" 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': cfg.get('model', 'jev-1.13-free'), + 'model': model, 'state': state, 'questions': {'action': {'type': 'choice', 'instructions': instructions, 'criteria': criteria}}, @@ -82,7 +84,14 @@ def request_decision(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, round((time.monotonic() - started) * 1000) + 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'] def main(): diff --git a/scripts/jev_mirror_agent.py b/scripts/jev_mirror_agent.py index 0979a89..ff067eb 100644 --- a/scripts/jev_mirror_agent.py +++ b/scripts/jev_mirror_agent.py @@ -5,12 +5,13 @@ 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 -from jev_client import request_decision +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 REPO_ROOT = Path(__file__).resolve().parents[1] MIRROR_ASSETS = REPO_ROOT / 'vendor' / 'aalc' / 'assets' / 'images' / 'default' / 'share' / 'mirror' @@ -40,12 +41,6 @@ def text_items(state): return state.get('items') or [] -def death_retry_screen(texts): - combined = '\n'.join(texts) - return ('全体罪人' in combined and '死亡' in combined - or '当前剩余人员' in combined and '重试关卡' in combined) - - _SCREEN_CACHE = {} @@ -506,9 +501,8 @@ 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 = 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) + end_screen = battle_is_terminal(state) + battle = battle_is_visible(state) if not end_screen and (battle or previous_battle): options['battle'] = {'description': '仍处于战斗或特写:执行短批次 P→回车,两次后检查结算,不分析拼点。', 'action': {'tool': 'battle', 'args': {'rounds': 2}}} @@ -574,13 +568,13 @@ def candidates(state, previous_battle=False, refresh_used=0): def decide(cfg, state, options, recent): 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) + '\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_answer(cfg, description, + {key: val['description'] for key, val in options.items()}, SYSTEM_RULES) def fixed_fallback(options): @@ -632,9 +626,9 @@ def fixed_fallback(options): return 'requires_analysis' -def execute(bridge, action): +def execute(bridge, action, deadline=None): def call(tool, args=None): - if STOP_FILE.exists(): + if STOP_FILE.exists() or deadline is not None and time.monotonic() >= deadline: return {'ok':False,'stopped':True} return bridge.call(tool, args) if action['tool'] == 'claim_final': @@ -664,9 +658,9 @@ def execute(bridge, action): time.sleep(0.7) return {'ok': True, 'waited': 0.7} if action['tool'] == 'battle': - deadline = time.monotonic() + 45 + battle_deadline = min(deadline if deadline is not None else float('inf'), time.monotonic() + 45) pairs = 0 - while time.monotonic() < deadline and not STOP_FILE.exists(): + while time.monotonic() < battle_deadline and not STOP_FILE.exists(): for _ in range(2): for key in ('p', 'enter'): result = call('keypress', {'key': key}) @@ -678,13 +672,10 @@ def execute(bridge, action): state = call('get_state') if not state.get('ok'): return 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: + if battle_is_terminal(state): return {'ok': True, 'pairs': pairs, 'terminal': True, 'screen': state.get('screen')} - return {'ok': not STOP_FILE.exists(), 'stopped':STOP_FILE.exists(), 'pairs': pairs, 'terminal': False} + stopped = STOP_FILE.exists() or deadline is not None and time.monotonic() >= deadline + return {'ok': not stopped, 'stopped': stopped, 'pairs': pairs, 'terminal': False} return call(action['tool'], action.get('args')) @@ -706,51 +697,55 @@ def acquire_single_instance(): return lambda: kernel.CloseHandle(lease) -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(): +def main(executor_decider=None): parser = argparse.ArgumentParser() - parser.add_argument('config') + 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('--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: - status.write_text(json.dumps({'state': 'stopped', 'step': step}), encoding='utf-8') + run['status'] = 'stopped' + save_json(RUNTIME_HOME / 'mirror_current_run.json', run) + save_json(status, {'state': 'stopped', 'step': step, 'run_id': run['run_id']}) return observation_started = time.monotonic() state = bridge.call('get_state') @@ -766,13 +761,13 @@ def main(): match = re.search(r'(?:第|选择)([1-5])层', item['text'].replace(' ', '')) if match: context['floor'] = int(match[1]) - context_path.write_text(json.dumps(context), encoding='utf-8') - state['floor'] = context.get('floor', 3) + save_json(context_path, context) + state['floor'] = context.get('floor', 1) 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'] = context.get('claim_requested', False) + state['claim_requested'] = claim_is_current(run, context) options = candidates(state, previous_battle, context['refresh_used']) if fingerprint != last_fingerprint: stable_since = time.monotonic() @@ -802,6 +797,7 @@ def main(): 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: @@ -815,83 +811,113 @@ def main(): elif 'battle' in options: choice, latency = 'battle', 0 else: - 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 + 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 action = options[choice]['action'] - record = {'step': step, 'choice': choice, 'action': action, 'jev_ms': latency, + record = {'step': step, 'run_id': run['run_id'], 'choice': choice, 'action': action, 'jev_ms': latency, 'ocr_ms':observation_ms,'screen': state.get('screen'), 'at': time.strftime('%Y-%m-%dT%H:%M:%S')} - if decision_fallback_reason: - record['decision_fallback_reason']=decision_fallback_reason + 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 choice == 'run_complete': + complete_run(RUNTIME_HOME, run, context, state.get('screen')) record['state'] = 'completed' - 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) + 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 choice == 'requires_analysis': record.update(state='requires_analysis', items=text_items(state)) - status.write_text(json.dumps(record, ensure_ascii=False), encoding='utf-8') + 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') 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) + result = execute(bridge, action, deadline=deadline) 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') - status.write_text(json.dumps(record,ensure_ascii=False),encoding='utf-8') + run['status'] = 'stopped' + save_json(RUNTIME_HOME / 'mirror_current_run.json', run) + save_json(status, record) return if choice == 'claim_final' and result.get('ok'): - context['claim_requested'] = True - context_path.write_text(json.dumps(context), encoding='utf-8') + record_claim(RUNTIME_HOME, run, context, state.get('screen')) if choice in ('confirm_startup_battery','confirm_thunderbranch') and result.get('ok'): context['battery_obtained' if choice == 'confirm_startup_battery' else 'thunderbranch_pending'] = True - context_path.write_text(json.dumps(context),encoding='utf-8') + save_json(context_path, context) 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 - context_path.write_text(json.dumps(context),encoding='utf-8') + save_json(context_path, context) if choice == 'shop_refresh' and result.get('ok'): context['refresh_used'] += 1 - context_path.write_text(json.dumps(context), encoding='utf-8') + save_json(context_path, context) 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') - status.write_text(json.dumps(record, ensure_ascii=False), encoding='utf-8') + save_json(status, record) 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: - record = {'state': 'requires_analysis', 'error': '%s: %s' % (type(error).__name__, str(error))} - status.write_text(json.dumps(record, ensure_ascii=False), encoding='utf-8') + 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') print(json.dumps(record, ensure_ascii=False), flush=True) finally: - bridge.close() - release() + try: + if bridge is not None: + bridge.close() + finally: + release() if __name__ == '__main__': diff --git a/scripts/mcp_session.py b/scripts/mcp_session.py index 8b7254d..979c38f 100644 --- a/scripts/mcp_session.py +++ b/scripts/mcp_session.py @@ -1,15 +1,41 @@ """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, raise_on_error=True): + 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) # 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')], @@ -18,45 +44,137 @@ class Session: text=True, encoding='utf-8', bufsize=1, ) self.sequence = 0 - 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() + # 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 - 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 _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 call(self, name, arguments=None): - result = self.request('tools/call', {'name': name, 'arguments': arguments or {}}) + 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) 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): - self.process.stdin.close() + if self._closed: + return + self._closed = True + self._outgoing.put(None) try: - self.process.wait(5) + self.process.wait(1) except subprocess.TimeoutExpired: self.process.kill() self.process.wait() - self.process.stdout.close() - self.process.stderr.close() + for thread in self._threads: + thread.join(1) + for stream in (self.process.stdin, self.process.stdout, self.process.stderr): + stream.close() def __enter__(self): return self diff --git a/scripts/run_state.py b/scripts/run_state.py new file mode 100644 index 0000000..577d9e3 --- /dev/null +++ b/scripts/run_state.py @@ -0,0 +1,99 @@ +"""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) diff --git a/tests/test_controller_runtime.py b/tests/test_controller_runtime.py new file mode 100644 index 0000000..e3d1c7c --- /dev/null +++ b/tests/test_controller_runtime.py @@ -0,0 +1,220 @@ +"""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() diff --git a/tests/test_decision_router.py b/tests/test_decision_router.py new file mode 100644 index 0000000..969d332 --- /dev/null +++ b/tests/test_decision_router.py @@ -0,0 +1,125 @@ +"""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() diff --git a/tests/test_jev_mirror_agent.py b/tests/test_jev_mirror_agent.py index 16fe12b..35b46f3 100644 --- a/tests/test_jev_mirror_agent.py +++ b/tests/test_jev_mirror_agent.py @@ -7,6 +7,7 @@ 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): @@ -92,13 +93,29 @@ 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=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'}},[]) + 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'}},[]) 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饰品','石版字符','拒绝饰品','选择')]} @@ -512,30 +529,19 @@ 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_with(raise_on_error=False) + make_bridge.assert_called_once() + self.assertIs(make_bridge.call_args.kwargs['raise_on_error'], False) status = json.loads((home / 'jev_mirror_status.json').read_text()) - self.assertNotIn('error', status) # 没有因异常退出, 而是按“截图暂不可用”继续等待 - self.assertEqual(status['choice'], 'wait') + # 没有因异常退出, 而是按“截图暂不可用”等待到步数用完 + 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']) class SessionTest(unittest.TestCase): @@ -545,7 +551,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 = False + session.raise_on_error, session.timeout = False, 30 self.assertEqual(session.call('click_text', {'text': 'x'}), {'ok': False, 'error': 'text not found'}) session.raise_on_error = True with self.assertRaises(RuntimeError): diff --git a/tests/test_lc_mcp.py b/tests/test_lc_mcp.py index 40e01f1..4461e2a 100644 --- a/tests/test_lc_mcp.py +++ b/tests/test_lc_mcp.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- """不需要 Windows/AALC 的测试: python -m unittest discover -s tests""" import json +import io import os import socket import subprocess @@ -84,6 +85,55 @@ 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']) @@ -123,8 +173,13 @@ 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']) # 只读工具仍可用 - time.sleep(0.5) - st = call(self.s, 'task_status') + # 轮询等子进程输出, 不用固定等待 (机器负载高时 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) self.assertEqual(st['state'], 'running') self.assertEqual(st['params'], {'count': 2}) self.assertIn("child ['mirror', '{\"count\": 2}']", '\n'.join(st['log_tail'])) diff --git a/tests/test_mcp_session.py b/tests/test_mcp_session.py new file mode 100644 index 0000000..1ad7d7f --- /dev/null +++ b/tests/test_mcp_session.py @@ -0,0 +1,156 @@ +"""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() diff --git a/tests/test_run_state.py b/tests/test_run_state.py new file mode 100644 index 0000000..81491b4 --- /dev/null +++ b/tests/test_run_state.py @@ -0,0 +1,111 @@ +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()