Fix MCP cancellation, mirror run state, and battle boundaries
This commit is contained in:
+77
-62
@@ -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__':
|
||||||
|
|||||||
Reference in New Issue
Block a user