#!/usr/bin/env python3 """Add opt-in direct native Responses support to the installed qwen launcher. The existing launcher remains the source of model selection and MCP settings. Patch only known anchors, keep a private backup, and never change its selected connection. Run with --path to target a non-default installation. """ import argparse import ast import hashlib import os from pathlib import Path import tempfile parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--path', type=Path, default=Path.home()/'.local/share/codex-qwen/qwen_local.py') args = parser.parse_args() os.umask(0o077) original = args.path.read_text() marker = '# Strata Next native Responses integration v1' text = original applying_base = True def replace(old, new): global text if applying_base and marker in original: return if text.count(old) != 1: raise RuntimeError('Launcher changed: expected one anchor: ' + old[:100]) text = text.replace(old, new) replace("if target['backend'] not in {'llama', 'strata'}", "if target['backend'] not in {'llama', 'strata', 'strata-native'}") replace("def validate_connection(target):\n", '''def validate_connection(target): if target['backend'] == 'strata-native': from urllib.parse import urlsplit parsed = urlsplit(target['url']) if (parsed.scheme != 'http' or parsed.hostname not in {'127.0.0.1', 'localhost', '::1'} or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path): raise RuntimeError('Native preview needs a plain loopback HTTP URL, without credentials or path') if target.get('key_file'): raise RuntimeError('Native loopback preview uses --no-auth; protect remote access with SSH') return ''') replace("if state.get('backend') != 'strata': return metadata(state['model'])", "if state.get('backend') not in {'strata', 'strata-native'}: return metadata(state['model'])") replace(" models = read('/v1/models')['data']", ''' if selected['backend'] == 'strata-native': from urllib.parse import urlsplit parsed = urlsplit(selected['url']) if parsed.hostname not in {'127.0.0.1', 'localhost', '::1'}: raise RuntimeError('Native preview requires a loopback URL; use an SSH tunnel for the GPU server') observed = read('/status') if observed.get('service') != 'strata-control' or not observed.get('ready'): raise RuntimeError('Native Strata runtime is not ready') model = observed.get('model', '') if not isinstance(model, str) or not re.fullmatch(r'[A-Za-z0-9_.-]{1,180}', model): raise RuntimeError('Native runtime must configure its model ID') context = observed.get('max_context') if type(context) is not int or context != 262144: raise RuntimeError('Native preview currently qualifies one 256K context') if read('/status') != observed: raise RuntimeError('Native runtime changed during discovery') return dict(backend='strata-native', model=model, context=context, parallel=1, busy=None, vision=False, upstream=selected['url']) models = read('/v1/models')['data']''') replace("def status():\n", """def status(): if connection()['backend'] == 'strata-native': live = discover() print(f"Strata Native: {live['model']} · 1 × 256К · Responses API ready") return {}, live """) replace("choices=['strata', 'llama']", "choices=['strata', 'llama', 'strata-native']") replace("target = dict(backend='strata', url=url,", "target = dict(backend=args.backend, url=url,") replace(" elif args.command == 'stop':\n", """ elif args.command == 'stop': if connection()['backend'] == 'strata-native': raise RuntimeError('Native endpoint is externally managed; stop its owning service on the GPU host') """) replace(" elif args.command == 'logs':\n", """ elif args.command == 'logs': if connection()['backend'] == 'strata-native': print('Native runtime logs are on the GPU host; there is no Responses bridge') return """) replace(" if state.get('backend') == 'strata':\n", ''' if state.get('backend') == 'strata-native': overrides = ['--config', 'model_provider="qwen_native"', '--config', 'model_providers.qwen_native.name="Strata Native"', '--config', 'model_providers.qwen_native.wire_api="responses"', '--config', 'model_providers.qwen_native.base_url=' + json.dumps(selected['url'] + '/v1'), '--config', 'model_providers.qwen_native.stream_idle_timeout_ms=900000', '--config', 'web_search="disabled"'] offset = len(command) - len(args) if args else len(command) command[offset:offset] = overrides print('Strata Native Responses · direct connection', flush=True) os.execvpe(binary, command, env) if state.get('backend') == 'strata': ''') # Environment override keeps test sessions independent of the user's selection. if marker not in original: text += '\n' + marker + '\nif os.environ.get("QWEN_CODEX_PROFILE"):\n PROFILE = Path(os.environ["QWEN_CODEX_PROFILE"]).expanduser().resolve()\n' applying_base = False auth_marker = '# Strata Next native bearer file integration v1' if auth_marker not in original: replace(" if target.get('key_file'):\n raise RuntimeError('Native loopback preview uses --no-auth; protect remote access with SSH')\n", " if target.get('key_file'): native_key(target)\n") replace("def connection_key(target):\n", """def native_key(target): import stat path = Path(target['key_file']).expanduser().resolve() fd = os.open(path, os.O_RDONLY | getattr(os, 'O_NONBLOCK', 0)) with os.fdopen(fd, 'rb') as source: info = os.fstat(source.fileno()) if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077: raise RuntimeError('Native API key needs a private regular file (chmod 600)') data = source.read(515) token = data.rstrip(b'\\r\\n') if len(data) > 514 or not 32 <= len(token) <= 512 or not all(33 <= b <= 126 for b in token): raise RuntimeError('Native API key requires 32..512 printable ASCII bytes without whitespace') return token.decode('ascii') def connection_key(target): if target.get('backend') == 'strata-native' and target.get('key_file'): return native_key(target) """) replace(" '--config', 'web_search=\"disabled\"']\n offset = len(command) - len(args) if args else len(command)\n", """ '--config', 'web_search="disabled"'] if selected.get('key_file'): native_key(selected) overrides += ['--config', 'model_providers.qwen_native.auth.command="/bin/cat"', '--config', 'model_providers.qwen_native.auth.args=' + json.dumps([str(Path(selected['key_file']).expanduser().resolve())])] offset = len(command) - len(args) if args else len(command) """) text += '\n' + auth_marker + '\n' ast.parse(text) if text == original: print('Native integration already installed') raise SystemExit(0) backup = args.path.with_name(args.path.name + '.before-native-' + hashlib.sha256(original.encode()).hexdigest()[:12]) if not backup.exists(): backup.write_text(original) backup.chmod(0o600) fd, temporary = tempfile.mkstemp(prefix='qwen-native-', dir=args.path.parent) try: with os.fdopen(fd, 'w') as out: out.write(text) os.chmod(temporary, args.path.stat().st_mode & 0o777) os.replace(temporary, args.path) finally: if os.path.exists(temporary): os.unlink(temporary) print('Native launcher installed; previous connection unchanged; backup:', backup)