#!/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' if marker in original: print('Native integration already installed') raise SystemExit(0) text = original def replace(old, new): global text 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. text += '\n' + marker + '\nif os.environ.get("QWEN_CODEX_PROFILE"):\n PROFILE = Path(os.environ["QWEN_CODEX_PROFILE"]).expanduser().resolve()\n' ast.parse(text) 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)