"""Standard-library-only stdio transport for one immutable DSH turn capability.""" from __future__ import annotations import json import os import sys from urllib.error import HTTPError from urllib.request import ProxyHandler, Request, build_opener MAX_LINE = 2 * 1024 * 1024 def main(): endpoint = os.environ['QUALITY_DSH_RELAY'] capability = os.environ['QUALITY_DSH_CAPABILITY'] if not endpoint.startswith('http://127.0.0.1:') or endpoint.count('/') != 2: raise ValueError('invalid relay') opener = build_opener(ProxyHandler({})) while True: raw = sys.stdin.readline(MAX_LINE + 1) if not raw: return 0 if len(raw) > MAX_LINE or not raw.endswith('\n'): return 2 request = None try: request = json.loads(raw) outgoing = Request(endpoint + '/mcp', data=raw.encode('utf-8'), headers={'Content-Type': 'application/json', 'Authorization': 'Bearer ' + capability}, method='POST') with opener.open(outgoing, timeout=190) as response: body = response.read(8 * 1024 * 1024 + 1) if len(body) > 8 * 1024 * 1024: raise ValueError('response too large') if body.strip(): result = json.loads(body) print(json.dumps(result, ensure_ascii=False, separators=(',', ':')), flush=True) except Exception: # Neither transport exceptions nor response bodies may expose capabilities. if isinstance(request, dict) and 'id' in request: print(json.dumps({'jsonrpc': '2.0', 'id': request['id'], 'error': { 'code': -32603, 'message': '本轮质量查询未完成;没有返回空数据成功。'}}, ensure_ascii=False), flush=True) if __name__ == '__main__': try: raise SystemExit(main()) except Exception: raise SystemExit('DSH quality bridge unavailable') from None