记录 4-48 实测失败与耗时复盘,修复前台输入及 Jev 配置
This commit is contained in:
+16
-8
@@ -1,4 +1,4 @@
|
|||||||
"""Bounded P/Enter batches through MCP; stop when the battle UI disappears."""
|
"""Bounded Win Rate batches through MCP, with a fresh UI check per turn."""
|
||||||
import argparse
|
import argparse
|
||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
@@ -20,7 +20,7 @@ def main():
|
|||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
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:
|
with Session(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', []))
|
texts = ' '.join(item['text'] for item in state.get('items', []))
|
||||||
active = args.battle_confirmed or any(marker in texts.upper() for marker in ('WAVE', 'TURN', 'DURANTE', '胜率', '伤害'))
|
active = args.battle_confirmed or any(marker in texts.upper() for marker in ('WAVE', 'TURN', 'DURANTE', '胜率', '伤害'))
|
||||||
@@ -28,12 +28,20 @@ def main():
|
|||||||
# 战斗特写会隐藏 HUD;只有明确的结算/地图/选项信号才退出。
|
# 战斗特写会隐藏 HUD;只有明确的结算/地图/选项信号才退出。
|
||||||
if 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.
|
||||||
for _ in range(2):
|
# Only start a turn when its explicit Win Rate control is visible.
|
||||||
client.call('keypress', {'key': 'p'})
|
labels = [item['text'].replace(' ', '').lower()
|
||||||
client.call('keypress', {'key': 'enter'})
|
for item in state.get('items', [])]
|
||||||
pairs += 1
|
target = next((item['text'] for item in state.get('items', [])
|
||||||
time.sleep(1.5)
|
if item['text'].replace(' ', '').lower()
|
||||||
|
in ('win', 'winrate', '胜率')), None)
|
||||||
|
if target and any(label in ('turn', 'wave', '回合', '波次') for label in labels):
|
||||||
|
selected = client.call('click_text', {'text': target})
|
||||||
|
if selected.get('ok'):
|
||||||
|
time.sleep(.5)
|
||||||
|
client.call('keypress', {'key': 'enter'})
|
||||||
|
pairs += 1
|
||||||
|
time.sleep(2.5)
|
||||||
state = client.call('get_state')
|
state = client.call('get_state')
|
||||||
print(json.dumps({'pairs': pairs, 'state': state}, ensure_ascii=False))
|
print(json.dumps({'pairs': pairs, 'state': state}, ensure_ascii=False))
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
"""Jev choice API shared by scene agents; credentials never enter curl argv."""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
DEFAULT_BASE_URL = 'https://opencode.ai/zen/v1'
|
||||||
|
|
||||||
|
|
||||||
|
def _post(cfg, body):
|
||||||
|
url = cfg.get('baseUrl', DEFAULT_BASE_URL).rstrip('/') + '/systemone'
|
||||||
|
headers = {
|
||||||
|
'Authorization': 'Bearer ' + cfg['apiKey'],
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'User-Agent': 'lc-mcp/0.1',
|
||||||
|
'x-opencode-session': cfg.setdefault('sessionId', str(uuid.uuid4())),
|
||||||
|
}
|
||||||
|
payload = json.dumps(body, ensure_ascii=False)
|
||||||
|
timeout = float(cfg.get('timeoutSeconds', 7))
|
||||||
|
transport = cfg.get('transport', 'urllib')
|
||||||
|
if transport == 'urllib':
|
||||||
|
request = urllib.request.Request(url, data=payload.encode('utf-8'),
|
||||||
|
headers=headers, method='POST')
|
||||||
|
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||||
|
return json.load(response)
|
||||||
|
if transport != 'curl':
|
||||||
|
raise ValueError('Unsupported Jev transport')
|
||||||
|
if any('\r' in value or '\n' in value for value in headers.values()):
|
||||||
|
raise ValueError('Jev headers must be single-line values')
|
||||||
|
config = '\n'.join('header = ' + json.dumps(key + ': ' + value)
|
||||||
|
for key, value in headers.items()) + '\n'
|
||||||
|
result = subprocess.run(
|
||||||
|
['curl.exe' if os.name == 'nt' else 'curl', '-sS', '--config', '-',
|
||||||
|
'--connect-timeout', str(min(timeout, 10)), '--max-time', str(timeout),
|
||||||
|
'--data-raw', payload, '--write-out', '\n%{http_code}', url],
|
||||||
|
input=config, capture_output=True, text=True, encoding='utf-8',
|
||||||
|
timeout=timeout + 2,
|
||||||
|
)
|
||||||
|
if result.returncode:
|
||||||
|
# Curl diagnostics may contain request details; expose only its exit code.
|
||||||
|
raise OSError('Jev transport failed (curl exit %d)' % result.returncode)
|
||||||
|
content, separator, status = result.stdout.rpartition('\n')
|
||||||
|
if not separator or not status.isdigit():
|
||||||
|
raise ValueError('Invalid Jev HTTP response')
|
||||||
|
code = int(status)
|
||||||
|
if not 200 <= code < 300:
|
||||||
|
raise urllib.error.HTTPError(url, code, 'Jev HTTP %d' % code, {}, None)
|
||||||
|
return json.loads(content)
|
||||||
|
|
||||||
|
|
||||||
|
def request_decision(cfg, state, criteria, instructions):
|
||||||
|
if not cfg.get('apiKey'):
|
||||||
|
raise ValueError('Jev API key is required')
|
||||||
|
if not criteria:
|
||||||
|
raise ValueError('Jev requires permitted choices')
|
||||||
|
body = {
|
||||||
|
'model': cfg.get('model', 'jev-1.13-free'),
|
||||||
|
'state': state,
|
||||||
|
'questions': {'action': {'type': 'choice', 'instructions': instructions,
|
||||||
|
'criteria': criteria}},
|
||||||
|
}
|
||||||
|
started = time.monotonic()
|
||||||
|
for attempt in range(2):
|
||||||
|
try:
|
||||||
|
result = _post(cfg, body)
|
||||||
|
break
|
||||||
|
except urllib.error.HTTPError as error:
|
||||||
|
if error.code in (401, 403, 429) or attempt:
|
||||||
|
raise
|
||||||
|
time.sleep(.3)
|
||||||
|
except (OSError, TimeoutError):
|
||||||
|
if attempt:
|
||||||
|
raise
|
||||||
|
time.sleep(.3)
|
||||||
|
answer = result.get('answers', {}).get('action', {})
|
||||||
|
choice = answer.get('choice')
|
||||||
|
if answer.get('type') != 'choice' or choice not in criteria:
|
||||||
|
raise ValueError('Jev returned an unsupported candidate')
|
||||||
|
return choice, round((time.monotonic() - started) * 1000)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description='Choose from an observed game scene; sends no game input.')
|
||||||
|
parser.add_argument('config', type=Path)
|
||||||
|
parser.add_argument('observation', type=Path)
|
||||||
|
args = parser.parse_args()
|
||||||
|
cfg = json.loads(args.config.read_text(encoding='utf-8-sig'))
|
||||||
|
cfg['apiKey'] = os.environ.get('OPENCODE_API_KEY') or cfg.get('apiKey')
|
||||||
|
observation = json.loads(args.observation.read_text(encoding='utf-8-sig'))
|
||||||
|
choice, latency = request_decision(cfg, observation['state'], observation['criteria'],
|
||||||
|
observation['instructions'])
|
||||||
|
print(json.dumps({'choice': choice, 'jev_ms': latency}, ensure_ascii=False))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
{
|
{
|
||||||
"decisionEngine": "jev",
|
"decisionEngine": "jev",
|
||||||
"model": "jev-1.13-free"
|
"model": "jev-1.13-free",
|
||||||
|
"baseUrl": "https://opencode.ai/zen/v1",
|
||||||
|
"transport": "urllib",
|
||||||
|
"timeoutSeconds": 7
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ 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
|
||||||
|
from jev_client import request_decision
|
||||||
|
|
||||||
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'
|
||||||
@@ -572,39 +573,14 @@ def candidates(state, previous_battle=False, refresh_used=0):
|
|||||||
|
|
||||||
|
|
||||||
def decide(cfg, state, options, recent):
|
def decide(cfg, state, options, recent):
|
||||||
body = {'model': 'jev-1.13-free',
|
description = ('目标:按用户已配置的队伍和速通规则推进当前镜牢。当前楼层:%s\n当前游戏 OCR(坐标仅供辨识):\n' % state.get('floor', '尚未识别') +
|
||||||
'state': '目标:按用户已配置的队伍和速通规则推进当前镜牢。当前楼层:%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))
|
||||||
'questions': {'action': {'type': 'choice', 'instructions': SYSTEM_RULES,
|
return request_decision(cfg, description,
|
||||||
'criteria': {key: val['description'] for key, val in options.items()}}}}
|
{key: val['description'] for key, val in options.items()}, SYSTEM_RULES)
|
||||||
request = urllib.request.Request(
|
|
||||||
'https://opencode.ai/zen/v1/systemone',
|
|
||||||
data=json.dumps(body, ensure_ascii=False).encode('utf-8'),
|
|
||||||
headers={'Authorization': 'Bearer ' + cfg['apiKey'], 'Content-Type': 'application/json',
|
|
||||||
'User-Agent': 'Mozilla/5.0'}, method='POST')
|
|
||||||
start = time.monotonic()
|
|
||||||
for attempt in range(2):
|
|
||||||
try:
|
|
||||||
with urllib.request.urlopen(request, timeout=7) as response:
|
|
||||||
result = json.load(response)
|
|
||||||
break
|
|
||||||
except urllib.error.HTTPError as error:
|
|
||||||
if error.code in (401,403,429) or attempt:
|
|
||||||
raise
|
|
||||||
time.sleep(.3)
|
|
||||||
except (OSError, TimeoutError):
|
|
||||||
if attempt:
|
|
||||||
raise
|
|
||||||
time.sleep(.3)
|
|
||||||
answer = result.get('answers', {}).get('action', {})
|
|
||||||
choice = answer.get('choice')
|
|
||||||
if answer.get('type') != 'choice' or choice not in options:
|
|
||||||
raise ValueError('Jev returned an unsupported candidate')
|
|
||||||
return choice, round((time.monotonic() - start) * 1000)
|
|
||||||
|
|
||||||
|
|
||||||
def fixed_fallback(options):
|
def fixed_fallback(options):
|
||||||
|
|||||||
Reference in New Issue
Block a user