main
John Lauer Publish 0.1.35 a61dd3b
#!/usr/bin/env python3
"""Hold the last good Codex extension while the newest build is known to be broken.

The editor auto-updates Codex. When it installs a build listed in
bad-versions.json (bundled; refreshed hourly from the wiki page so a build can
be listed or cleared without a package release), put back the last good build
and hold it only while Open VSX's newest build on that channel is still listed.
Then release the hold so normal updates resume. Never while a Codex turn runs.

The held build bundles an older engine that does not offer OpenAI's newest models.
While the hold lasts, fetch OpenAI's newest stable engine from npm, check it, and
record it in engine.json; the runtime runs it for the held build from the next
editor reload. Dropped when the hold lifts.
"""
import base64
import hashlib
import json
import os
import re
from pathlib import Path
import shutil
import signal
import subprocess
import tarfile
import tempfile
import time
import urllib.request

import runtime

ROOT = Path(__file__).resolve().parent
LIST_URL = 'https://wiki.adom.inc/api/v1/pages/adom/codex/files/runtime/bad-versions.json'
OPEN_VSX_QUERY = 'https://open-vsx.org/api/-/query?namespaceName=openai&extensionName=chatgpt&includeAllVersions=true'
TARGET = 'linux-arm64' if os.uname().machine == 'aarch64' else 'linux-x64'
ID = 'openai.chatgpt'
REFRESH_S = 3600
ENGINE_URL = 'https://registry.npmjs.org/@openai/codex/' + TARGET
TRIPLE = ('aarch64' if TARGET == 'linux-arm64' else 'x86_64') + '-unknown-linux-musl'
ENGINE_REFRESH_S = 6 * 3600


def fetch_json(url, timeout=15):
    request = urllib.request.Request(url, headers={'User-Agent': 'adom-codex-guard'})
    with urllib.request.urlopen(request, timeout=timeout) as response:
        return json.load(response)


def key(version):
    return tuple(int(p) for p in version.split('.'))


def cli_version(binary):
    """(major, minor, patch) from `codex --version`, or None."""
    try: output = subprocess.run([str(binary), '--version'], capture_output=True, text=True,
                                 timeout=20, stdin=subprocess.DEVNULL).stdout
    except (OSError, subprocess.SubprocessError): return None
    match = re.search(r'(\d+)\.(\d+)\.(\d+)', output)
    return tuple(map(int, match.groups())) if match else None


class Guard:
    def __init__(self, integration):
        self.home = integration.home
        self.extensions = integration.extensions
        self.registry = self.extensions / 'extensions.json'
        self.path = integration.state / 'guard.json'
        self.engine_path = integration.state / 'engine.json'
        self.engines = self.home / '.local/share/adom/codex-engine'
        self.write = integration.write_json
        try: self.state = json.loads(self.path.read_text())
        except (OSError, ValueError): self.state = {}

    def save(self):
        self.write(self.path, self.state)

    def bad_list(self):
        """Wiki copy when fresh, else the last fetched copy, else the bundled one."""
        if time.time() - self.state.get('list_checked', 0) > REFRESH_S:
            self.state['list_checked'] = time.time()
            try: self.state['list'] = fetch_json(LIST_URL)
            except Exception as error: self.state['list_error'] = str(error)
            self.save()
        if isinstance(self.state.get('list'), dict): return self.state['list']
        return json.loads((ROOT / 'bad-versions.json').read_text())

    def bad(self, listing, version):
        return next((b for b in listing.get('builds', []) if version in b.get('versions', [])), None)

    def installed(self):
        try: entries = json.loads(self.registry.read_text())
        except (OSError, ValueError): return None
        return next((e for e in entries if e.get('identifier', {}).get('id') == ID), None)

    def set_metadata(self, **values):
        entries = json.loads(self.registry.read_text())
        for entry in entries:
            if entry.get('identifier', {}).get('id') == ID: entry.setdefault('metadata', {}).update(values)
        temporary = self.registry.with_name(self.registry.name + '.adom-codex.tmp')
        temporary.write_text(json.dumps(entries))
        temporary.replace(self.registry)

    def newest(self, pre_release):
        """Newest Open VSX build on the user's channel (a pre-release user also gets stable).
        OpenAI numbers pre-releases above stable (26.5xxx > 26.9xx), so ask for each
        version's channel instead of trusting the version order."""
        query = fetch_json(f'{OPEN_VSX_QUERY}&targetPlatform={TARGET}')
        versions = [e['version'] for e in query.get('extensions', [])
                    if pre_release or not e.get('preRelease')]
        return max(versions, key=key) if versions else None

    def notify(self, message, level='warning'):
        tool = shutil.which('adom-vscode') or str(self.home / '.local/bin/adom-vscode')
        try: subprocess.run([tool, 'notify', '--level', level, message], timeout=20,
                            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        except Exception: pass

    def codex_idle(self):
        """No Codex turn running. A missing backend is idle."""
        directory = runtime.state_dir()
        try: metadata = json.loads((directory / 'server.json').read_text())
        except (OSError, ValueError): return True, None
        if not runtime.process_matches(metadata): return True, None
        try: return runtime.backend_idle(directory / 'server.sock'), metadata
        except Exception: return False, metadata

    def retire_when_idle(self):
        """Stop a backend a bad build started, once no turn is running (else on a later pass)."""
        idle, backend = self.codex_idle()
        if not idle: return
        self.retire_backend(backend, self.state.pop('retire_from', []))

    def retire_backend(self, metadata, bad_versions):
        """A backend started by a bad build has that build's startup options; the good
        build's views could never attach to it. Stop it while it is idle."""
        if not metadata: return
        running = runtime.extension_version(metadata.get('binary', ''))
        if not running or '.'.join(map(str, running)) not in bad_versions: return
        os.kill(metadata['pid'], signal.SIGTERM)
        deadline = time.monotonic() + 10
        while runtime.process_matches(metadata) and time.monotonic() < deadline: time.sleep(.05)

    def drop_unrunnable_companions(self):
        """Codex Audio (openai.codex-audio, microphone dictation) is a desktop-only ('ui') extension
        with no browser build: code-server can never run it, so it only sits there with a warning
        (AdomLapper 2026-10-31, installed beside the bad 26.1021 build). Remove it whenever it
        shows up (a Codex update can bring it back); a failed removal retries once an hour."""
        try: entries = json.loads(self.registry.read_text())
        except (OSError, ValueError): return
        if not any(e.get('identifier', {}).get('id') == 'openai.codex-audio' for e in entries): return
        if time.time() - self.state.get('companion_attempt', 0) < 3600: return
        self.state['companion_attempt'] = time.time(); self.save()
        code_server = shutil.which('code-server') or '/usr/lib/code-server/bin/code-server'
        env = {k: v for k, v in os.environ.items() if not k.startswith('VSCODE_')}
        r = subprocess.run([code_server, '--uninstall-extension', 'openai.codex-audio'],
                           capture_output=True, text=True, timeout=180, env=env)
        if r.returncode == 0:
            self.state['companions_dropped'] = time.time()
            self.state.pop('companion_attempt', None)
            self.save()

    def check(self):
        self.drop_unrunnable_companions()
        entry = self.installed()
        if not entry: return
        version = entry.get('version', '')
        metadata = entry.get('metadata', {})
        listing = self.bad_list()
        build = self.bad(listing, version)
        if not build:
            if self.state.get('retire_from'): self.retire_when_idle()
            self.state['last_good'] = version
            if self.state.get('held') == version: self.maybe_release(listing, metadata)
            # A fresh install already ON the fallback build (the golden image ships it) never saw
            # the bad build, so it was never held, yet it bundles the same old engine. Linux
            # Hydrogen 2026-11-02: GPT-6.1 Sol missing for that reason. Give it the newest engine too.
            if self.state.get('held') == version or version == listing.get('fallback'): self.newer_engine(version)
            else: self.drop_engine()
            self.save()
            return
        good = self.state.get('last_good') or listing.get('fallback')
        if not good or self.bad(listing, good): return
        # Putting the good build back on disk never touches a running backend (it keeps running
        # from its own files), so do it now even mid-turn. Only stopping a backend the bad build
        # started waits for idle (retire_when_idle). ConfRoomROG 2026-10-31: one Codex thread sat
        # 'active, waitingOnApproval' for days, so 'wait for idle first' never swapped the build.
        code_server = shutil.which('code-server') or '/usr/lib/code-server/bin/code-server'
        # The watcher may have been started from an editor terminal and carry that window's
        # VSCODE_IPC_HOOK_CLI; after a reload the socket is dead and every install fails with
        # ECONNREFUSED (AdomLapper 2026-10-31: the bad build stayed for hours). Install directly.
        env = {k: v for k, v in os.environ.items() if not k.startswith('VSCODE_')}
        result = subprocess.run([code_server, '--install-extension', f'{ID}@{good}', '--force'],
                                capture_output=True, text=True, timeout=600, env=env)
        if result.returncode != 0:
            self.state['last_error'] = (result.stdout + result.stderr)[-500:]
            self.save()
            return
        # Installing an exact version pins it, which is the hold we want until a fix ships.
        self.set_metadata(pinned=True, preRelease=False)
        self.state.pop('last_error', None)
        self.state['retire_from'] = build.get('versions', [])
        self.retire_when_idle()
        self.state.update(held=good, held_since=time.time(), held_from=version,
                          channel_pre_release=bool(metadata.get('preRelease')), release_checked=0)
        self.save()
        # John 2026-10-31: people kept pressing Update because nothing said the update itself is
        # the broken part. Say that first, plainly, and that they have nothing to do.
        self.notify(f'Codex {version} is broken for everyone right now ({build.get("reason", "")}; OpenAI: '
                    f'{build.get("issue", "")}), so Adom kept the working Codex {good}, with the newest models. '
                    'You can skip this update: it comes back by itself once OpenAI fixes it. '
                    'Reload the window if Codex does not load.')

    def maybe_release(self, listing, metadata):
        if not metadata.get('pinned'):
            self.state.pop('held', None)  # someone already released it
            return
        if time.time() - self.state.get('release_checked', 0) < REFRESH_S: return
        self.state['release_checked'] = time.time()
        try: newest = self.newest(self.state.get('channel_pre_release', False))
        except Exception as error:
            self.state['release_error'] = str(error)
            return
        if newest and not self.bad(listing, newest) and key(newest) > key(self.state['held']):
            self.set_metadata(pinned=False)
            self.state.pop('held', None)
            self.notify(f'Codex {newest} is out with the fix; it will install with your next update.', 'info')

    def newer_engine(self, version):
        """Fetch, check and record OpenAI's newest stable engine for the held build."""
        if time.time() - self.state.get('engine_checked', 0) < ENGINE_REFRESH_S: return
        self.state['engine_checked'] = time.time()
        try:
            arch = 'linux-aarch64' if TARGET == 'linux-arm64' else 'linux-x86_64'
            location = (self.installed() or {}).get('location', {}).get('path') \
                or str(self.extensions / f'{ID}-{version}-{TARGET}')
            have = cli_version(Path(location) / 'bin' / arch / 'codex')
            release = fetch_json(ENGINE_URL)
            newest = release['version'].split('-')[0]
            current = self.recorded_engine()
            if not have or key(newest) <= have:
                return self.drop_engine()
            if current.get('version') == newest and current.get('extension') == version: return
            if shutil.disk_usage(self.home).free < 2 * 1024**3:
                raise RuntimeError('less than 2 GB free')
            binary = self.engines / newest / TRIPLE / 'bin' / 'codex'
            if not binary.is_file(): self.download(release, newest)
            if cli_version(binary) != key(newest): raise RuntimeError(f'engine {newest} did not run')
            with tempfile.TemporaryDirectory(prefix='codex-engine-schema-') as temporary:
                subprocess.run([str(binary), 'app-server', 'generate-json-schema', '--experimental',
                                '--out', temporary], check=True, capture_output=True, timeout=30,
                               stdin=subprocess.DEVNULL)
            self.write(self.engine_path, {'binary': str(binary), 'version': newest, 'extension': version,
                                          'bundled': '.'.join(map(str, have)), 'at': time.time()})
            self.state.pop('engine_error', None)
            self.prune_engines(newest)
            self.notify(f'Codex {version} now runs OpenAI\'s newest Codex engine ({newest}), so the newest '
                        'models are in its model picker. Reload the window to use them.', 'info')
        except Exception as error:
            self.state['engine_error'] = str(error)[-300:]
            self.state['engine_checked'] = time.time() - ENGINE_REFRESH_S + REFRESH_S  # retry in an hour

    def recorded_engine(self):
        try: return json.loads(self.engine_path.read_text())
        except (OSError, ValueError): return {}

    def download(self, release, version):
        """npm's platform package, checked against the registry's sha512, unpacked whole."""
        dist = release['dist']
        algorithm, expected = dist['integrity'].split('-', 1)
        if algorithm != 'sha512': raise RuntimeError('unexpected integrity ' + algorithm)
        self.engines.mkdir(parents=True, exist_ok=True)
        with tempfile.TemporaryDirectory(prefix='.fetch-', dir=self.engines) as temporary:
            archive = Path(temporary) / 'engine.tgz'
            digest = hashlib.sha512()
            request = urllib.request.Request(dist['tarball'], headers={'User-Agent': 'adom-codex-guard'})
            with urllib.request.urlopen(request, timeout=60) as response, archive.open('wb') as output:
                while chunk := response.read(1 << 20):
                    digest.update(chunk)
                    output.write(chunk)
            if base64.b64encode(digest.digest()).decode() != expected:
                raise RuntimeError('engine download failed its checksum')
            prefix = f'package/vendor/{TRIPLE}/'
            unpacked = Path(temporary) / 'unpacked'
            with tarfile.open(archive) as bundle:
                members = [m for m in bundle.getmembers() if m.name.startswith(prefix)]
                for member in members: member.name = member.name[len('package/vendor/'):]
                bundle.extractall(unpacked, members=members, filter='data')
            target = self.engines / version
            shutil.rmtree(target, ignore_errors=True)
            unpacked.replace(target)

    def prune_engines(self, keep):
        """Keep the recorded engine and whichever one a running backend still uses."""
        try: running = json.loads((runtime.state_dir() / 'server.json').read_text()).get('binary', '')
        except (OSError, ValueError, RuntimeError): running = ''
        for directory in self.engines.glob('*'):
            if directory.name != keep and not running.startswith(str(directory) + '/'):
                shutil.rmtree(directory, ignore_errors=True)

    def drop_engine(self):
        """No hold, no newer engine: the editor's own build runs its own engine."""
        if not self.engine_path.exists(): return
        self.engine_path.unlink(missing_ok=True)
        self.state.pop('engine_checked', None)
        self.prune_engines(None)