合并 codex/mcp-runtime-reliability: 运行可靠性、局状态与决策交接
与 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:
+121
-95
@@ -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}}}
|
||||||
@@ -574,13 +568,13 @@ def candidates(state, previous_battle=False, refresh_used=0):
|
|||||||
|
|
||||||
def decide(cfg, state, options, recent):
|
def decide(cfg, state, options, recent):
|
||||||
description = ('目标:按用户已配置的队伍和速通规则推进当前镜牢。当前楼层:%s\n当前游戏 OCR(坐标仅供辨识):\n' % state.get('floor', '尚未识别') +
|
description = ('目标:按用户已配置的队伍和速通规则推进当前镜牢。当前楼层:%s\n当前游戏 OCR(坐标仅供辨识):\n' % state.get('floor', '尚未识别') +
|
||||||
'\n'.join('%s @%d,%d' % (i['text'], i['x'], i['y']) for i in text_items(state)
|
'\n'.join('%s @%d,%d' % (i['text'], i['x'], i['y']) for i in text_items(state)
|
||||||
if not i['text'].upper().startswith('STEAM')) +
|
if not i['text'].upper().startswith('STEAM')) +
|
||||||
'\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)
|
||||||
|
|
||||||
|
|
||||||
def fixed_fallback(options):
|
def fixed_fallback(options):
|
||||||
@@ -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:
|
||||||
@@ -815,83 +811,113 @@ def main():
|
|||||||
elif 'battle' in options:
|
elif 'battle' in options:
|
||||||
choice, latency = 'battle', 0
|
choice, latency = 'battle', 0
|
||||||
else:
|
else:
|
||||||
if os.environ.get('LC_FIXED_FALLBACK') == '1' or decision_fallback_reason:
|
try:
|
||||||
choice, latency = fixed_fallback(options), 0
|
decision = router.choose(state, options, recent, run['run_id'])
|
||||||
else:
|
choice, latency = decision.choice, decision.jev_ms
|
||||||
try:
|
except DecisionRequired as required:
|
||||||
choice, latency = decide(cfg, state, options, recent)
|
record = {'state': 'requires_decision', 'step': step, 'run_id': run['run_id'],
|
||||||
except urllib.error.HTTPError as error:
|
'decision_engine': 'executor', 'decision_request': required.request,
|
||||||
if error.code not in (401,403,429):
|
'ocr_ms': observation_ms, 'screen': state.get('screen'),
|
||||||
raise
|
'at': time.strftime('%Y-%m-%dT%H:%M:%S')}
|
||||||
decision_fallback_reason='Jev HTTP %d; deterministic fallback for this session' % error.code
|
if 'failed_jev_ms' in required.request:
|
||||||
choice, latency=fixed_fallback(options),0
|
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:
|
||||||
bridge.close()
|
try:
|
||||||
release()
|
if bridge is not None:
|
||||||
|
bridge.close()
|
||||||
|
finally:
|
||||||
|
release()
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
Reference in New Issue
Block a user