main
Colby Knox
Publish 0.1.42
8f19c53
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
"""Codex owns conversation names. Read its store; mutate only through its RPC API."""
import json
import os
from pathlib import Path
import re
import sqlite3
import time
from urllib.parse import quote
from contextlib import contextmanager
import selectors
import subprocess
UUID = re.compile(r'^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$', re.I)
def name_binary():
from runtime import native_binary, newer_engine
try: return native_binary()
except RuntimeError:
if os.environ.get('ADOM_CODEX_NATIVE'): raise
# Outside an IDE child PATH, several VSIX versions can be on disk. Use
# the registered build, not an arbitrary newest directory.
directory = Path.home() / '.local/share/code-server/extensions'
entries = json.loads((directory / 'extensions.json').read_text())
entry = next(e for e in entries if e.get('identifier', {}).get('id') == 'openai.chatgpt')
location = entry.get('relativeLocation')
package = directory / location if location else Path(entry['location']['path'])
if package.resolve().parent != directory.resolve(): raise RuntimeError('Registered Codex path is outside the extension directory')
arch = 'linux-aarch64' if os.uname().machine == 'aarch64' else 'linux-x86_64'
binary = package / 'bin' / arch / 'codex'
if not binary.is_file(): raise RuntimeError('The registered Codex executable is unavailable')
return newer_engine(binary)
@contextmanager
def name_connection():
from runtime import state_dir, process_matches, unix_connect
try: metadata = json.loads((state_dir() / 'server.json').read_text())
except (OSError, ValueError): metadata = None
if metadata and process_matches(metadata):
with unix_connect(metadata['socket'], compression=None, open_timeout=5,
close_timeout=1, max_size=None) as connection:
yield connection
return
# A native/custom engine need not keep an Adom backend alive. This metadata-
# only client starts no chat/model turn and leaves no daemon behind.
process = subprocess.Popen([str(name_binary()), 'app-server'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=0)
selector = selectors.DefaultSelector()
selector.register(process.stdout, selectors.EVENT_READ)
class Stdio:
buffer = b''
def send(self, message):
process.stdin.write(message.encode() + b'\n')
def recv(self, timeout):
deadline = time.monotonic() + timeout
while b'\n' not in self.buffer:
if not selector.select(max(0, deadline-time.monotonic())):
raise TimeoutError('Codex metadata request timed out')
chunk = os.read(process.stdout.fileno(), 65536)
if not chunk: raise RuntimeError('Codex metadata process closed unexpectedly')
self.buffer += chunk
if len(self.buffer) > 16 * 1024 * 1024: raise RuntimeError('Codex metadata response exceeded its size limit')
line, self.buffer = self.buffer.split(b'\n', 1)
return line.decode()
try: yield Stdio()
finally:
selector.close()
process.stdin.close()
if process.poll() is None: process.terminate()
try: process.wait(timeout=3)
except subprocess.TimeoutExpired: process.kill(); process.wait(timeout=3)
process.stdout.close()
def list_threads(home=None, limit=300):
home = Path(home or os.environ.get('CODEX_HOME', Path.home() / '.codex'))
# Numeric schema order (state_10 must outrank state_9). Never create or write a DB.
dbs = sorted(home.glob('state_*.sqlite'),
key=lambda p: int(re.search(r'state_(\d+)', p.name)[1]))
if not dbs:
return []
with sqlite3.connect('file:' + quote(str(dbs[-1].resolve())) + '?mode=ro',
uri=True, timeout=1) as db:
cols = {r[1] for r in db.execute('pragma table_info(threads)')}
title = "coalesce(nullif(trim(name),''),title)" if 'name' in cols else 'title'
# Only the person's own conversations. Codex also stores the threads it starts
# for itself: Guardian reviews of a tool action (thread_source guardian_review)
# and other sub-agents, whose `source` is a JSON object naming the subagent.
# Codex's own UI leaves them out of its list; so does this one. They stay on
# disk untouched, and an open panel still names them (native_names).
where = ['archived=0']
if 'thread_source' in cols:
where.append("coalesce(thread_source,'user') != 'guardian_review'")
if 'source' in cols:
where.append("coalesce(source,'') NOT LIKE '%subagent%'")
rows = db.execute(f'SELECT id,{title},cwd,updated_at FROM threads '
f'WHERE {" AND ".join(where)} ORDER BY updated_at DESC LIMIT ?', (limit,))
return [{'id': r[0], 'title': r[1], 'cwd': r[2],
'when': r[3] * 1000 if r[3] < 10**12 else r[3]} for r in rows]
def native_names(thread_ids, home=None):
"""Small metadata-only query for open panels, including old/archived conversations."""
ids = [value for value in thread_ids if isinstance(value, str) and UUID.fullmatch(value)]
if not ids: return {}
home = Path(home or os.environ.get('CODEX_HOME', Path.home() / '.codex'))
dbs = sorted(home.glob('state_*.sqlite'), key=lambda p: int(re.search(r'state_(\d+)', p.name)[1]))
if not dbs: return {}
with sqlite3.connect('file:' + quote(str(dbs[-1].resolve())) + '?mode=ro', uri=True, timeout=1) as db:
columns = {row[1] for row in db.execute('pragma table_info(threads)')}
name_column = 'name' if 'name' in columns else 'NULL'
title_column = 'title' if 'title' in columns else 'NULL'
rows = db.execute(f'select id,{name_column},{title_column} from threads where id in (' + ','.join('?' for _ in ids) + ')', ids)
result = {}
for sid, name, title in rows:
if isinstance(name, str) and name.strip(): result[sid] = name
# Current Codex writes automatic titles into `title`, explicit renames
# into `name`. Do not promote a huge raw prompt while naming is pending.
elif isinstance(title, str) and title.strip() and len(title.strip()) <= 80 and '\n' not in title:
result[sid] = title.strip()
return result
def rename_thread(name, thread_id=None):
thread_id = thread_id or os.environ.get('CODEX_THREAD_ID', '')
if not UUID.fullmatch(thread_id):
raise ValueError('Pass --id <conversation UUID>, or run inside a Codex thread (CODEX_THREAD_ID).')
name = name.strip()
if not name or len(name) > 200 or any(ord(c) < 32 for c in name):
raise ValueError('Use a nonempty, single-line name of at most 200 characters.')
with name_connection() as connection:
seq = 0
def rpc(method, params):
nonlocal seq
seq += 1
connection.send(json.dumps({'id': seq, 'method': method, 'params': params}))
deadline = time.monotonic() + 15
while time.monotonic() < deadline:
reply = json.loads(connection.recv(timeout=max(.01, deadline-time.monotonic())))
if reply.get('id') == seq and ('result' in reply or 'error' in reply):
if 'error' in reply:
raise RuntimeError(str(reply['error']))
return reply['result']
raise TimeoutError('Codex did not confirm the rename; read back before retrying.')
rpc('initialize', {'clientInfo': {'name': 'adom-thread-names', 'version': '1'},
'capabilities': {'experimentalApi': True}})
connection.send(json.dumps({'method': 'initialized'}))
rpc('thread/name/set', {'threadId': thread_id, 'name': name})
thread = rpc('thread/read', {'threadId': thread_id, 'includeTurns': False})['thread']
if thread.get('name') != name:
raise RuntimeError('Codex accepted the request but did not confirm the saved name.')
return {'ok': True, 'id': thread_id, 'name': name, 'persisted': True,
'source': 'codex', 'tab_verified': False}
if __name__ == '__main__':
import sys
print(json.dumps(native_names(json.loads(sys.argv[1]))))