合并 codex/mcp-runtime-reliability: 运行可靠性、局状态与决策交接

Browse Source
与 main 上的审查修复及 2131f89 (story-test) 合并, 冲突处理:
- mcp_session: 保留超时/取消客户端, 补回 raise_on_error
- 执行器: 局状态改用 run_state (run_id 绑定), 取代完成后归档 context;
  Jev 请求统一经 jev_client.request_answer (支持 baseUrl/curl, 返回置信度与概率);
  保留截图解码缓存、地图模板缓存、按坐标点按钮、use_last_error 单实例互斥;
  刷新计数与开战标记只在动作成功后更新
- battle_batch: 取消/预算框架 + 只在看到胜率按钮时点胜率再回车;
  回合标签改为包含匹配 (OCR 常输出 'wave1')
- 文档采用 reliability 版本 (已是仓库相对路径), 注明 jev_client
- 测试: 互斥量桩改为 WinDLL/get_last_error, 战斗批次测试按胜率语义重写,
  Jev 测试改为对 jev_client 打桩, 生命周期测试改为轮询; 145 项通过

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
yws
2026-10-03 03:12:48 +00:00
co-authored by Claude Opus 5.5
24 changed files with 2014 additions and 194 deletions
+128
View File
@@ -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()
+37 -20
View File
@@ -1,16 +1,18 @@
"""Bounded Win Rate batches through MCP, with a fresh UI check per turn.""" """Bounded Win Rate batches through MCP, with a fresh UI check per turn."""
import argparse import argparse
import json import json
import math
import os
import time 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): def is_terminal(state):
texts = [item['text'].replace(' ', '') for item in state.get('items', [])] return battle_is_terminal(state)
return any(text.upper() in ('VICTORY', 'DEFEAT') or
any(marker in text for marker in ('正在探索', '获得E.G.O饰品', '选择主题卡包',
'开始战斗', '选择一位罪人', '选项事件'))
for text in texts)
def main(): def main():
@@ -18,32 +20,47 @@ def main():
parser.add_argument('--seconds', type=float, default=40) parser.add_argument('--seconds', type=float, default=40)
parser.add_argument('--battle-confirmed', action='store_true') parser.add_argument('--battle-confirmed', action='store_true')
args = parser.parse_args() 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)) deadline = time.monotonic() + min(50, max(1, args.seconds))
pairs = 0 pairs = 0
with Session(raise_on_error=False) as client: 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') state = client.call('get_state')
texts = ' '.join(item['text'] for item in state.get('items', [])) active = args.battle_confirmed or battle_is_visible(state)
active = args.battle_confirmed or any(marker in texts.upper() for marker in ('WAVE', 'TURN', 'DURANTE', '胜率', '伤害')) while not cancelled():
while time.monotonic() < deadline: # Cinematics hide the HUD; explicit scene boundaries end combat.
# 战斗特写会隐藏 HUD;只有明确的结算/地图/选项信号才退出。 if not state.get('ok') or not active or is_terminal(state):
if not active or is_terminal(state):
break break
# P cycles between Win Rate and Damage in current game versions. # P cycles between Win Rate and Damage in current game versions.
# Only start a turn when its explicit Win Rate control is visible. # Only start a turn when its explicit Win Rate control is visible.
labels = [item['text'].replace(' ', '').lower() items = state.get('items', [])
for item in state.get('items', [])] labels = [item['text'].replace(' ', '').lower() for item in items]
target = next((item['text'] for item in state.get('items', []) target = next((item['text'] for item, label in zip(items, labels)
if item['text'].replace(' ', '').lower() if label in ('win', 'winrate', '胜率')), None)
in ('win', 'winrate', '胜率')), None) # OCR 常把回合数连在一起(如 'WAVE 1' -> 'wave1'), 用包含匹配
if target and any(label in ('turn', 'wave', '回合', '波次') for label in labels): if target and any(m in label for label in labels for m in ('turn', 'wave', '回合', '波次')):
selected = client.call('click_text', {'text': target}) selected = client.call('click_text', {'text': target})
if selected.get('ok'): if selected.get('ok'):
time.sleep(.5) time.sleep(.5)
if cancelled():
raise SessionCancelled('Battle batch stopped between Win Rate and Enter')
client.call('keypress', {'key': 'enter'}) client.call('keypress', {'key': 'enter'})
pairs += 1 pairs += 1
time.sleep(2.5) time.sleep(min(2.5, max(0, deadline - time.monotonic())))
if cancelled():
break
state = client.call('get_state') state = client.call('get_state')
print(json.dumps({'pairs': pairs, 'state': state}, ensure_ascii=False)) 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__': if __name__ == '__main__':
+132
View File
@@ -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': '<same request_id>', 'choice': '<candidate ID>'},
'requires_fresh_observation_before_external_input': True,
'note': 'The caller handles this decision. No game input is sent while handing off.',
},
}
if self.mode in ('auto', 'jev') and configured_model and self.config.get('apiKey'):
request['failed_jev_ms'] = failed_jev_ms
# The request contains observations and candidates, never provider config
# or credentials. Detach it so the callback cannot alter executable actions.
request = json.loads(json.dumps(request, ensure_ascii=False))
if self.executor_decider is None:
raise DecisionRequired(request)
started = time.monotonic()
expected_request_id = request['request_id']
answer = self.executor_decider(request)
if isinstance(answer, dict) and answer.get('request_id') != expected_request_id:
raise ValueError('Execution-model response belongs to a different decision request')
choice, _, confidence, probabilities, returned_model = _answer(answer, options)
latency = round((time.monotonic() - started) * 1000)
return Decision(choice, 'executor', latency, confidence=confidence, probabilities=probabilities,
model=returned_model, fallback_reason=reason, failed_jev_ms=request.get('failed_jev_ms'))
+28
View File
@@ -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))
+12 -3
View File
@@ -54,13 +54,15 @@ def _post(cfg, body):
return json.loads(content) 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'): if not cfg.get('apiKey'):
raise ValueError('Jev API key is required') raise ValueError('Jev API key is required')
if not criteria: if not criteria:
raise ValueError('Jev requires permitted choices') raise ValueError('Jev requires permitted choices')
model = cfg.get('model', 'jev-1.13-free')
body = { body = {
'model': cfg.get('model', 'jev-1.13-free'), 'model': model,
'state': state, 'state': state,
'questions': {'action': {'type': 'choice', 'instructions': instructions, 'questions': {'action': {'type': 'choice', 'instructions': instructions,
'criteria': criteria}}, 'criteria': criteria}},
@@ -82,7 +84,14 @@ def request_decision(cfg, state, criteria, instructions):
choice = answer.get('choice') choice = answer.get('choice')
if answer.get('type') != 'choice' or choice not in criteria: if answer.get('type') != 'choice' or choice not in criteria:
raise ValueError('Jev returned an unsupported candidate') 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(): def main():
+112 -86
View File
@@ -5,12 +5,13 @@ import json
import os import os
import re import re
import time import time
import urllib.error
import urllib.request
from pathlib import Path from pathlib import Path
from mcp_session import Session as Bridge from mcp_session import Session as Bridge, SessionCancelled, SessionTimeout
from jev_client import request_decision 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] REPO_ROOT = Path(__file__).resolve().parents[1]
MIRROR_ASSETS = REPO_ROOT / 'vendor' / 'aalc' / 'assets' / 'images' / 'default' / 'share' / 'mirror' MIRROR_ASSETS = REPO_ROOT / 'vendor' / 'aalc' / 'assets' / 'images' / 'default' / 'share' / 'mirror'
@@ -40,12 +41,6 @@ def text_items(state):
return state.get('items') or [] 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 = {} _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, 'action': {'tool': 'click', 'args': {'x': item['x'] + item['w'] // 2,
'y': item['y'] + item['h'] // 2}}, 'y': item['y'] + item['h'] // 2}},
} }
end_screen = any(t.upper() in ('VICTORY', 'DEFEAT') or any(m in t for m in end_screen = battle_is_terminal(state)
('正在探', '获得E.G.O饰品', '选择E.G.O饰品', '饰品观测', '开始战斗', '主题卡包', '应该让谁', '选择一位罪人', '进行判定', '选择遭遇战奖励卡')) for t in texts) battle = battle_is_visible(state)
battle = any(m in combined.upper() for m in ('WAVE', 'TURN', 'DURANTE')) or any(t in ('胜率', '伤害') for t in texts)
if not end_screen and (battle or previous_battle): if not end_screen and (battle or previous_battle):
options['battle'] = {'description': '仍处于战斗或特写:执行短批次 P→回车,两次后检查结算,不分析拼点。', options['battle'] = {'description': '仍处于战斗或特写:执行短批次 P→回车,两次后检查结算,不分析拼点。',
'action': {'tool': 'battle', 'args': {'rounds': 2}}} 'action': {'tool': 'battle', 'args': {'rounds': 2}}}
@@ -579,7 +573,7 @@ def decide(cfg, state, options, recent):
'\n截图视觉与可用控件观察(不是预先做出的决定):\n' + '\n截图视觉与可用控件观察(不是预先做出的决定):\n' +
'\n'.join(val['description'] for key,val in options.items() if key != 'requires_analysis') + '\n'.join(val['description'] for key,val in options.items() if key != 'requires_analysis') +
'\n最近动作和执行结果:' + json.dumps(recent[-4:], ensure_ascii=False)) '\n最近动作和执行结果:' + json.dumps(recent[-4:], ensure_ascii=False))
return request_decision(cfg, description, return request_answer(cfg, description,
{key: val['description'] for key, val in options.items()}, SYSTEM_RULES) {key: val['description'] for key, val in options.items()}, SYSTEM_RULES)
@@ -632,9 +626,9 @@ def fixed_fallback(options):
return 'requires_analysis' return 'requires_analysis'
def execute(bridge, action): def execute(bridge, action, deadline=None):
def call(tool, args=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 {'ok':False,'stopped':True}
return bridge.call(tool, args) return bridge.call(tool, args)
if action['tool'] == 'claim_final': if action['tool'] == 'claim_final':
@@ -664,9 +658,9 @@ def execute(bridge, action):
time.sleep(0.7) time.sleep(0.7)
return {'ok': True, 'waited': 0.7} return {'ok': True, 'waited': 0.7}
if action['tool'] == 'battle': 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 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 _ in range(2):
for key in ('p', 'enter'): for key in ('p', 'enter'):
result = call('keypress', {'key': key}) result = call('keypress', {'key': key})
@@ -678,13 +672,10 @@ def execute(bridge, action):
state = call('get_state') state = call('get_state')
if not state.get('ok'): if not state.get('ok'):
return state return state
texts = [i['text'].replace(' ', '') for i in text_items(state)] if battle_is_terminal(state):
terminal = death_retry_screen(texts) or any(t.upper() in ('VICTORY', 'DEFEAT') or any(m in t for m in
('正在探', '获得E.G.O饰品', '选择E.G.O饰品', '饰品观测', '开始战斗', '主题卡包',
'应该让谁', '选择一位罪人', '进行判定', '选择遭遇战奖励卡', '选项事件', '选择苦难', '选项', '结果')) for t in texts)
if terminal:
return {'ok': True, 'pairs': pairs, 'terminal': True, 'screen': state.get('screen')} 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')) return call(action['tool'], action.get('args'))
@@ -706,51 +697,55 @@ def acquire_single_instance():
return lambda: kernel.CloseHandle(lease) return lambda: kernel.CloseHandle(lease)
def archive_context(context_path): def main(executor_decider=None):
"""一局结束后归档本局状态。claim_requested 等标记若留给下一局, 新局一启动就会被判定为已完成。"""
if context_path.exists():
context_path.replace(context_path.with_name('jev_shop_context.%s.json' % time.strftime('%Y%m%d_%H%M%S')))
def main():
parser = argparse.ArgumentParser() parser = 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('--steps', type=int, default=250)
parser.add_argument('--seconds', type=int, default=1200) 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() args = parser.parse_args()
if args.steps <= 0 or args.seconds <= 0:
parser.error('--steps and --seconds must be positive')
release = acquire_single_instance() release = acquire_single_instance()
if release is None: if release is None:
print(json.dumps({'state':'already_running'}), flush=True) print(json.dumps({'state':'already_running'}), flush=True)
return 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' log = RUNTIME_HOME / 'jev_mirror_log.jsonl'
status = RUNTIME_HOME / 'jev_mirror_status.json' status = RUNTIME_HOME / 'jev_mirror_status.json'
# 工具失败按 {'ok': False} 返回: 截图暂不可用、按钮已消失等情况观察后继续, 而不是整局退出
bridge = Bridge(raise_on_error=False)
deadline = time.monotonic() + args.seconds deadline = time.monotonic() + args.seconds
bridge = None
run = None
recent = [] recent = []
repeats = {} 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_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() stable_since = time.monotonic()
last_fingerprint = None last_fingerprint = None
unknown_since = None unknown_since = None
decision_fallback_reason = None
try: 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): for step in range(args.steps):
if STOP_FILE.exists() or time.monotonic() > deadline: 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 return
observation_started = time.monotonic() observation_started = time.monotonic()
state = bridge.call('get_state') state = bridge.call('get_state')
@@ -766,13 +761,13 @@ def main():
match = re.search(r'(?:第|选择)([1-5])层', item['text'].replace(' ', '')) match = re.search(r'(?:第|选择)([1-5])层', item['text'].replace(' ', ''))
if match: if match:
context['floor'] = int(match[1]) context['floor'] = int(match[1])
context_path.write_text(json.dumps(context), encoding='utf-8') save_json(context_path, context)
state['floor'] = context.get('floor', 3) state['floor'] = context.get('floor', 1)
state['symbol_upgraded'] = context.get('symbol_upgraded', False) state['symbol_upgraded'] = context.get('symbol_upgraded', False)
state['battery_obtained'] = context.get('battery_obtained', False) state['battery_obtained'] = context.get('battery_obtained', False)
state['thunderbranch_pending'] = context.get('thunderbranch_pending',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['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']) options = candidates(state, previous_battle, context['refresh_used'])
if fingerprint != last_fingerprint: if fingerprint != last_fingerprint:
stable_since = time.monotonic() stable_since = time.monotonic()
@@ -802,6 +797,7 @@ def main():
unknown_since = None unknown_since = None
# User explicitly prescribed the complete battle loop. Only scene # User explicitly prescribed the complete battle loop. Only scene
# transitions return to Jev; combat does not require new decisions. # 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)): if any(re.search(r'CON+ECTING|LOADING', i['text'].upper()) for i in text_items(state)):
choice, latency = 'wait', 0 choice, latency = 'wait', 0
elif len(options)==2 and time.monotonic() - unknown_since < 10: elif len(options)==2 and time.monotonic() - unknown_since < 10:
@@ -814,83 +810,113 @@ def main():
choice, latency = 'event_advance', 0 choice, latency = 'event_advance', 0
elif 'battle' in options: elif 'battle' in options:
choice, latency = 'battle', 0 choice, latency = 'battle', 0
else:
if os.environ.get('LC_FIXED_FALLBACK') == '1' or decision_fallback_reason:
choice, latency = fixed_fallback(options), 0
else: else:
try: try:
choice, latency = decide(cfg, state, options, recent) decision = router.choose(state, options, recent, run['run_id'])
except urllib.error.HTTPError as error: choice, latency = decision.choice, decision.jev_ms
if error.code not in (401,403,429): except DecisionRequired as required:
raise record = {'state': 'requires_decision', 'step': step, 'run_id': run['run_id'],
decision_fallback_reason='Jev HTTP %d; deterministic fallback for this session' % error.code 'decision_engine': 'executor', 'decision_request': required.request,
choice, latency=fixed_fallback(options),0 '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'] 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')} 'ocr_ms':observation_ms,'screen': state.get('screen'), 'at': time.strftime('%Y-%m-%dT%H:%M:%S')}
if decision_fallback_reason: record['decision_engine'] = decision.engine if decision else 'rules'
record['decision_fallback_reason']=decision_fallback_reason 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': if choice == 'run_complete':
complete_run(RUNTIME_HOME, run, context, state.get('screen'))
record['state'] = 'completed' record['state'] = 'completed'
status.write_text(json.dumps(record, ensure_ascii=False), encoding='utf-8') save_json(status, record)
run_path = RUNTIME_HOME / 'mirror_current_run.json' with log.open('a', encoding='utf-8') as output:
if run_path.exists(): output.write(json.dumps(record, ensure_ascii=False) + '\n')
from datetime import datetime, timezone
run = json.loads(run_path.read_text(encoding='utf-8'))
now = datetime.now(timezone.utc)
run.update(status='completed', dungeon_completed=True, final_reward_claimed=True,
end_utc=now.isoformat(), elapsed_seconds=(now-datetime.fromisoformat(run['start_utc'])).total_seconds(),
completion_evidence=state.get('screen'))
run_path.write_text(json.dumps(run, ensure_ascii=False, indent=2), encoding='utf-8')
archive_context(context_path)
print(json.dumps(record, ensure_ascii=False), flush=True) print(json.dumps(record, ensure_ascii=False), flush=True)
return return
if choice == 'requires_analysis': if choice == 'requires_analysis':
record.update(state='requires_analysis', items=text_items(state)) 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) print(json.dumps(record, ensure_ascii=False), flush=True)
return return
action_id = json.dumps(action, sort_keys=True) action_id = json.dumps(action, sort_keys=True)
repeats[(fingerprint, action_id)] = repeats.get((fingerprint, action_id), 0) + 1 repeats[(fingerprint, action_id)] = repeats.get((fingerprint, action_id), 0) + 1
action_started = time.monotonic() action_started = time.monotonic()
result = execute(bridge, action) result = execute(bridge, action, deadline=deadline)
record['action_ms'] = round((time.monotonic()-action_started)*1000) record['action_ms'] = round((time.monotonic()-action_started)*1000)
record['finished_at'] = time.strftime('%Y-%m-%dT%H:%M:%S') record['finished_at'] = time.strftime('%Y-%m-%dT%H:%M:%S')
if result.get('stopped'): if result.get('stopped'):
record.update(result=result,state='stopped',battle_context=previous_battle) record.update(result=result,state='stopped',battle_context=previous_battle)
with log.open('a',encoding='utf-8') as output: with log.open('a',encoding='utf-8') as output:
output.write(json.dumps(record,ensure_ascii=False)+'\n') 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 return
if choice == 'claim_final' and result.get('ok'): if choice == 'claim_final' and result.get('ok'):
context['claim_requested'] = True record_claim(RUNTIME_HOME, run, context, state.get('screen'))
context_path.write_text(json.dumps(context), encoding='utf-8')
if choice in ('confirm_startup_battery','confirm_thunderbranch') and result.get('ok'): 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['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)): 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['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'): if choice == 'shop_refresh' and result.get('ok'):
context['refresh_used'] += 1 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( started_battle = choice.startswith('button_') and bool(result.get('ok')) and any(
i['text'].replace(' ', '') == '开始战斗' for i in text_items(state)) i['text'].replace(' ', '') == '开始战斗' for i in text_items(state))
previous_battle = ((action['tool'] == 'battle' and not result.get('terminal')) or started_battle previous_battle = ((action['tool'] == 'battle' and not result.get('terminal')) or started_battle
or (previous_battle and action['tool'] == 'wait')) 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) record.update(result=result, state='running', battle_context=previous_battle)
with log.open('a', encoding='utf-8') as output: with log.open('a', encoding='utf-8') as output:
output.write(json.dumps(record, ensure_ascii=False) + '\n') 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)]}) 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) print(json.dumps({k:v for k,v in record.items() if k != 'items'}, ensure_ascii=False), flush=True)
time.sleep(0.35) 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: except Exception as error:
record = {'state': 'requires_analysis', 'error': '%s: %s' % (type(error).__name__, str(error))} state = 'stopped' if isinstance(error, SessionCancelled) else 'requires_analysis'
status.write_text(json.dumps(record, ensure_ascii=False), encoding='utf-8') 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) print(json.dumps(record, ensure_ascii=False), flush=True)
finally: finally:
try:
if bridge is not None:
bridge.close() bridge.close()
finally:
release() release()
+133 -15
View File
@@ -1,15 +1,41 @@
"""Reusable client for the installed stdio MCP bridge; no direct game input.""" """Reusable client for the installed stdio MCP bridge; no direct game input."""
import json import json
import math
import os import os
import queue
import subprocess import subprocess
import sys import sys
import threading
import time
from collections import deque
from pathlib import Path 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: 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, ...} 返回, 由调用方观察后继续; 协议层错误仍抛异常 # False: 工具失败按 {'ok': False, ...} 返回, 由调用方观察后继续; 协议层错误仍抛异常
self.raise_on_error = raise_on_error 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] root = Path(__file__).resolve().parents[1]
self.process = subprocess.Popen( self.process = subprocess.Popen(
[sys.executable, '-X', 'utf8', str(root / 'lc_mcp' / 'bridge.py')], [sys.executable, '-X', 'utf8', str(root / 'lc_mcp' / 'bridge.py')],
@@ -18,45 +44,137 @@ class Session:
text=True, encoding='utf-8', bufsize=1, text=True, encoding='utf-8', bufsize=1,
) )
self.sequence = 0 self.sequence = 0
# Windows pipes cannot be polled with select(). Dedicated readers and
# a writer let the caller cancel even if a pipe read/write is blocked.
self._threads = [threading.Thread(target=target, daemon=True) for target in
(self._read_responses, self._write_requests, self._drain_stderr)]
for thread in self._threads:
thread.start()
try:
self.request('initialize', { self.request('initialize', {
'protocolVersion': '2024-11-05', 'capabilities': {}, 'protocolVersion': '2024-11-05', 'capabilities': {},
'clientInfo': {'name': 'lc-mcp-session', 'version': '1'}, 'clientInfo': {'name': 'lc-mcp-session', 'version': '1'},
}) })
self.process.stdin.write(json.dumps({'jsonrpc': '2.0', 'method': 'notifications/initialized'}) + '\n') self._send({'jsonrpc': '2.0', 'method': 'notifications/initialized'})
self.process.stdin.flush() except BaseException:
self._abort()
raise
def request(self, method, params): 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 self.sequence += 1
mid = self.sequence mid = self.sequence
request = {'jsonrpc': '2.0', 'id': mid, 'method': method, 'params': params} self._send({'jsonrpc': '2.0', 'id': mid, 'method': method, 'params': params})
self.process.stdin.write(json.dumps(request, ensure_ascii=False) + '\n') deadline = time.monotonic() + limit
self.process.stdin.flush()
while True: while True:
line = self.process.stdout.readline() if self.cancelled():
if not line: self._abort()
raise ConnectionError('MCP bridge closed') 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) 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 result.get('id') == mid:
if 'error' in result: if 'error' in result:
raise RuntimeError(result['error']['message']) raise RuntimeError(result['error']['message'])
return result['result'] return result['result']
def call(self, name, arguments=None): 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']) data = json.loads(result['content'][0]['text'])
if result.get('isError') and self.raise_on_error: if result.get('isError') and self.raise_on_error:
raise RuntimeError(data) raise RuntimeError(data)
return data return data
def _abort(self):
if self.process.poll() is None:
self.process.kill()
self.close()
def close(self): def close(self):
self.process.stdin.close() if self._closed:
return
self._closed = True
self._outgoing.put(None)
try: try:
self.process.wait(5) self.process.wait(1)
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired:
self.process.kill() self.process.kill()
self.process.wait() self.process.wait()
self.process.stdout.close() for thread in self._threads:
self.process.stderr.close() thread.join(1)
for stream in (self.process.stdin, self.process.stdout, self.process.stderr):
stream.close()
def __enter__(self): def __enter__(self):
return self return self
+99
View File
@@ -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)