#!/usr/bin/env python3 """Install automatic managed model switching and the native console picker.""" import argparse import ast import hashlib import os from pathlib import Path import tempfile MARKER = '# Strata Next native picker integration v1' PROFILE_MARKER = '# Strata Next native picker profile integration v1' HELPER_MARKER = '# Strata Next native picker profile v1' NATIVE = '''STRATA_SWITCH_HELPER = '/home/para/.cache/strata-next/model-switch.py' STRATA_NATIVE_MODEL = dict(id='strata-native', label='Flash-Next IQ3_S · Native Responses · автоматичне перемикання', backend='strata-native', maxContext=262144, bytes=84525205664) def start_strata_native(args): if args.layout not in (None, '1x256') or args.kv_cache not in (None, 'q8_0') or args.kv_mode != 'with-key': raise RuntimeError('strata-native: чинний профіль 1x256 · INT8 K+V; для іншого режиму вибери відповідний профіль') target = dict(backend='strata-native', url='http://127.0.0.1:18084', key_file=None, managed=False) validate_connection(target) import socket with socket.socket() as probe: probe.settimeout(1) listening = probe.connect_ex(('127.0.0.1', 18084)) == 0 if not listening: subprocess.run(['ssh', '-fN', '-o', 'BatchMode=yes', '-o', 'ExitOnForwardFailure=yes', '-o', 'ConnectTimeout=8', '-L', '127.0.0.1:18084:127.0.0.1:18082', HOST], check=True, timeout=15) remote('start', {'backend': 'native', 'waitSeconds': args.wait_seconds}, stream=True, helper=STRATA_SWITCH_HELPER) try: state = discover(target) except (OSError, ValueError, KeyError, RuntimeError): raise RuntimeError('Native runtime недоступний або не готовий на 127.0.0.1:18084. Перевір endpoint і SSH tunnel; профіль harness не змінено.') from None if state.get('model') != 'strata-native-iq3-s': raise RuntimeError('Native endpoint має іншу модель; скористайся connect strata-native з явним URL') configure(state) atomic(PROFILE / 'connection.json', json.dumps(target, indent=2) + '\\n') print('Готово: strata-native · 1 × 256К · INT8 K+V · Responses API. Запускай codex-qwen.') ''' def profile_patch(text): if PROFILE_MARKER in text: return text anchor = " target = dict(backend='strata-native', url='http://127.0.0.1:18084', key_file=None, managed=False)\n" if text.count(anchor) != 1: raise RuntimeError('Launcher changed: native profile anchor mismatch') text = text.replace(anchor, " from qwen_native_profile import attach\n" " if attach(PROFILE, validate=validate_connection, discover=discover,\n" " configure=configure, atomic=atomic):\n" " return\n" + anchor) text = text.replace('Flash-Next IQ3_S · Native Responses · автоматичне перемикання', 'Flash-Next IQ3_S · Native Responses · вибір підключення') text = text.replace('native endpoint 127.0.0.1:18084; автоматичне перемикання', 'налаштоване native-підключення або кероване перемикання') text = text.replace('Native використовує підготовлений IQ3_S pack; start strata-native автоматично перемикає runtime.', 'Native використовує підготовлений IQ3_S pack; start strata-native обирає налаштоване підключення.') text += '\n' + PROFILE_MARKER + '\n' ast.parse(text) return text def patched(original): if MARKER in original: return profile_patch(original) if '# Strata Next native bearer file integration v1' not in original: raise RuntimeError('Install native Responses integration first') text = original def replace(old, new, count=1): nonlocal text if text.count(old) != count: raise RuntimeError('Launcher changed: native picker anchor mismatch') text = text.replace(old, new) replace('def start_strata(args):\n', NATIVE + 'def start_strata(args):\n') replace('[*registry(), STRATA_MODEL, *STRATA_AGENT_MODELS]', '[*registry(), STRATA_MODEL, *STRATA_AGENT_MODELS, STRATA_NATIVE_MODEL]', count=2) replace(" if model.get('backend') == 'strata': modes = '1x256 · KV int8 · окремий рушій Strata'", " if model.get('backend') == 'strata-native': modes = '1x256 · INT8 K+V · native endpoint 127.0.0.1:18084; автоматичне перемикання'\n" " if model.get('backend') == 'strata': modes = '1x256 · KV int8 · окремий рушій Strata'") replace(" if model.get('backend') == 'strata-agent': return start_strata_agent(args, model)", " if model.get('backend') == 'strata-native': return start_strata_native(args)\n" " if model.get('backend') == 'strata-agent': return start_strata_agent(args, model)") replace(" if model.get('backend') == 'strata-agent':\n", " if model.get('backend') == 'strata-native':\n" " print('Native використовує підготовлений IQ3_S pack; start strata-native автоматично перемикає runtime.')\n" " return\n" " if model.get('backend') == 'strata-agent':\n") replace(" proc = subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=8', HOST,", " switches = {REMOTE: 'llama', '/home/para/inference/codex-qwen/strata_remote.py': 'strata', STRATA_AGENT_HELPER: 'agent'}\n" " if action == 'start' and helper in switches:\n" " return remote('start', dict(payload or {}, backend=switches[helper]), stream=True, helper=STRATA_SWITCH_HELPER)\n" " proc = subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=8', HOST,") replace("strata_remote('start', {'days': args.days})", "strata_remote('start', {'days': args.days, 'waitSeconds': args.wait_seconds})", count=2) replace("strata_agent_remote('start', {'profile': model['id']})", "strata_agent_remote('start', {'profile': model['id'], 'waitSeconds': args.wait_seconds})") replace("days=args.days, kvCache=kv_cache)", "days=args.days, kvCache=kv_cache, waitSeconds=args.wait_seconds)") replace("if not 0 <= args.wait_seconds <= 7200: raise RuntimeError('wait-seconds must be 0..7200')", "if not 1 <= args.wait_seconds <= 7200: raise RuntimeError('wait-seconds must be 1..7200 for managed switching')") text += '\n' + MARKER + '\n' ast.parse(text) return profile_patch(text) def install(path): original = path.read_text() text = patched(original) source = Path(__file__).with_name('qwen_native_profile.py').read_text() ast.parse(source) helper = path.with_name('qwen_native_profile.py') if helper.exists() and HELPER_MARKER not in helper.read_text(): raise RuntimeError('Refusing to overwrite unrelated qwen_native_profile.py') helper_changed = not helper.exists() or helper.read_text() != source if text == original and not helper_changed: return False backup = path.with_name(path.name + '.before-native-picker-' + hashlib.sha256(original.encode()).hexdigest()[:12]) if not backup.exists(): fd = os.open(backup, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) with os.fdopen(fd, 'w') as out: out.write(original) # Publish the helper first so an interrupted upgrade cannot leave the new # launcher importing a module that was not installed. Keep the launcher fd # scoped separately so helper installation failures cannot leak it. if helper_changed: helper_fd, helper_name = tempfile.mkstemp(prefix='native-profile-', dir=path.parent) try: with os.fdopen(helper_fd, 'w') as out: out.write(source) os.chmod(helper_name, 0o600) os.replace(helper_name, helper) finally: if os.path.exists(helper_name): os.unlink(helper_name) fd, name = tempfile.mkstemp(prefix='native-picker-', dir=path.parent) try: with os.fdopen(fd, 'w') as out: out.write(text) os.chmod(name, path.stat().st_mode & 0o777) if path.read_text() != original: raise RuntimeError('Launcher changed during installation') os.replace(name, path) finally: if os.path.exists(name): os.unlink(name) return True if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--path', type=Path, default=Path.home()/'.local/share/codex-qwen/qwen_local.py') changed = install(parser.parse_args().path) print('Native menu installed; selected connection unchanged' if changed else 'Native menu already installed')