main
John Lauer
Preserve existing Codex nonce panel identity before activation
4b85a6a
"""Preserve a verified conversation behind an existing Adom nonce editor resource."""
import hashlib
import json
import os
from pathlib import Path
import re
import sqlite3
from urllib.parse import urlsplit, unquote, quote
import uuid
def bind_thread(resource, thread_id=None):
from thread_names import UUID
thread_id = thread_id or os.environ.get('CODEX_THREAD_ID', '')
if not UUID.fullmatch(thread_id): raise ValueError('A conversation UUID is required')
uri = urlsplit(resource)
query = unquote(uri.query)
if uri.scheme != 'openai-codex' or uri.netloc != 'route' or uri.path != '/extension/panel/new' or not re.fullmatch(r'(?:adom|nonce)=[A-Za-z0-9_.:-]{1,128}', query):
raise ValueError('Pass the exact existing Adom nonce editor resource; bare /new cannot be bound safely')
route = uri.path + '?' + query
home = Path(os.environ.get('CODEX_HOME', Path.home() / '.codex')).resolve()
dbs = sorted(home.glob('state_*.sqlite'), key=lambda p: int(re.search(r'state_(\d+)', p.name)[1]))
if not dbs: raise RuntimeError('Codex has no native conversation store')
with sqlite3.connect('file:' + quote(str(dbs[-1])) + '?mode=ro', uri=True, timeout=1) as db:
if not db.execute('select 1 from threads where id=?', (thread_id,)).fetchone():
raise ValueError('That conversation is not present in this Codex home')
base = Path(os.environ.get('ADOM_CODEX_BINDINGS_DIR', Path.home() / '.local/state/adom/codex-integration/panel-bindings'))
directory = base / hashlib.sha256(str(home).encode()).hexdigest()
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
file = directory / (hashlib.sha256(route.encode()).hexdigest() + '.json')
temporary = file.with_name(file.name + '.' + uuid.uuid4().hex + '.tmp')
try:
temporary.write_text(json.dumps({'route': route, 'threadId': thread_id}) + '\n')
temporary.chmod(0o600)
temporary.replace(file)
finally: temporary.unlink(missing_ok=True)
return {'ok': True, 'id': thread_id, 'resource': resource, 'bound': True}