Fix MCP cancellation, mirror run state, and battle boundaries

Browse Source
This commit is contained in:
Codex
2026-10-03 01:21:51 +08:00
parent 97eca204c2
commit 7188b4ac0f
12 changed files with 926 additions and 117 deletions
+37 -21
View File
@@ -1,16 +1,18 @@
"""Bounded P/Enter batches through MCP; stop when the battle UI disappears.""" """Bounded P/Enter batches through MCP; stop when the battle UI disappears."""
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,24 +20,38 @@ 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() as client: state = {}
state = client.call('get_state') def cancelled():
texts = ' '.join(item['text'] for item in state.get('items', [])) return STOP_FILE.exists() or time.monotonic() >= deadline
active = args.battle_confirmed or any(marker in texts.upper() for marker in ('WAVE', 'TURN', 'DURANTE', '胜率', '伤害')) try:
while time.monotonic() < deadline: if cancelled():
# 战斗特写会隐藏 HUD;只有明确的结算/地图/选项信号才退出。 raise SessionCancelled('Battle batch stopped before connecting')
if not active or is_terminal(state): with Session(cancelled=cancelled) as client:
break
# 短批次,批次末只检查界面是否仍为战斗,不分析拼点。
for _ in range(2):
client.call('keypress', {'key': 'p'})
client.call('keypress', {'key': 'enter'})
pairs += 1
time.sleep(1.5)
state = client.call('get_state') 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
for _ in range(2):
for key in ('p', 'enter'):
if cancelled():
raise SessionCancelled('Battle batch stopped between keys')
client.call('keypress', {'key': key})
pairs += 1
time.sleep(min(1.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__': if __name__ == '__main__':
+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))
+77 -62
View File
@@ -11,7 +11,9 @@ import urllib.error
import urllib.request 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 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
REPO_ROOT = Path(__file__).resolve().parents[1] REPO_ROOT = Path(__file__).resolve().parents[1]
RUNTIME_HOME = Path(os.environ.get('LC_JEV_HOME', str(Path.home() / 'lc_mcp' / 'jev'))) RUNTIME_HOME = Path(os.environ.get('LC_JEV_HOME', str(Path.home() / 'lc_mcp' / 'jev')))
@@ -40,12 +42,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)
def button_enabled(state, item): def button_enabled(state, item):
try: try:
from PIL import Image from PIL import Image
@@ -478,9 +474,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}}}
@@ -629,9 +624,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':
@@ -661,9 +656,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})
@@ -675,13 +670,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'))
@@ -690,7 +682,12 @@ def main():
parser.add_argument('config') parser.add_argument('config')
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')
# 防止另一个终端重复启动同一个游戏的执行器。 # 防止另一个终端重复启动同一个游戏的执行器。
import ctypes import ctypes
kernel = ctypes.windll.kernel32 kernel = ctypes.windll.kernel32
@@ -702,34 +699,35 @@ def main():
if lease: if lease:
kernel.CloseHandle(ctypes.c_void_p(lease)) kernel.CloseHandle(ctypes.c_void_p(lease))
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']:
kernel.CloseHandle(ctypes.c_void_p(lease))
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'
bridge = Bridge()
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 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'))
cfg['apiKey'] = os.environ.get('OPENCODE_API_KEY') or cfg.get('apiKey')
if not cfg['apiKey'] and os.environ.get('LC_FIXED_FALLBACK') != '1':
raise RuntimeError('Set OPENCODE_API_KEY or enable 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)
bridge = Bridge(cancelled=lambda: STOP_FILE.exists() or time.monotonic() >= deadline)
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')
@@ -745,13 +743,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()
@@ -805,71 +803,88 @@ def main():
decision_fallback_reason='Jev HTTP %d; deterministic fallback for this session' % error.code decision_fallback_reason='Jev HTTP %d; deterministic fallback for this session' % error.code
choice, latency=fixed_fallback(options),0 choice, latency=fixed_fallback(options),0
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: if decision_fallback_reason:
record['decision_fallback_reason']=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')
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': if choice == 'shop_refresh':
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 any( started_battle = choice.startswith('button_') 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:
bridge.close() try:
kernel.CloseHandle(ctypes.c_void_p(lease)) if bridge is not None:
bridge.close()
finally:
kernel.CloseHandle(ctypes.c_void_p(lease))
if __name__ == '__main__': if __name__ == '__main__':
+145 -27
View File
@@ -1,13 +1,39 @@
"""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): def __init__(self, timeout=30, cancelled=None):
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)
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')],
@@ -16,45 +42,137 @@ class Session:
text=True, encoding='utf-8', bufsize=1, text=True, encoding='utf-8', bufsize=1,
) )
self.sequence = 0 self.sequence = 0
self.request('initialize', { # Windows pipes cannot be polled with select(). Dedicated readers and
'protocolVersion': '2024-11-05', 'capabilities': {}, # a writer let the caller cancel even if a pipe read/write is blocked.
'clientInfo': {'name': 'lc-mcp-session', 'version': '1'}, self._threads = [threading.Thread(target=target, daemon=True) for target in
}) (self._read_responses, self._write_requests, self._drain_stderr)]
self.process.stdin.write(json.dumps({'jsonrpc': '2.0', 'method': 'notifications/initialized'}) + '\n') for thread in self._threads:
self.process.stdin.flush() 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): def _read_responses(self):
self.sequence += 1 try:
mid = self.sequence for line in self.process.stdout:
request = {'jsonrpc': '2.0', 'id': mid, 'method': method, 'params': params} self._responses.put(line)
self.process.stdin.write(json.dumps(request, ensure_ascii=False) + '\n') except (OSError, ValueError, UnicodeError) as error:
self.process.stdin.flush() self._responses.put(error)
while True: finally:
line = self.process.stdout.readline() self._responses.put(None)
if not line:
raise ConnectionError('MCP bridge closed') def _write_requests(self):
result = json.loads(line) try:
if result.get('id') == mid: while True:
if 'error' in result: line = self._outgoing.get()
raise RuntimeError(result['error']['message']) if line is None:
return result['result'] 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): 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'): if result.get('isError'):
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', '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)