与 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>
112 lines
4.5 KiB
Python
112 lines
4.5 KiB
Python
"""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_answer(cfg, state, criteria, instructions):
|
|
"""返回 {'choice', 'latency_ms', 'confidence', 'probabilities', 'model'}; 候选之外的结果会被拒绝。"""
|
|
if not cfg.get('apiKey'):
|
|
raise ValueError('Jev API key is required')
|
|
if not criteria:
|
|
raise ValueError('Jev requires permitted choices')
|
|
model = cfg.get('model', 'jev-1.13-free')
|
|
body = {
|
|
'model': model,
|
|
'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': 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():
|
|
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()
|