Files
2026-11-10 19:04:27 +08:00

276 lines
17 KiB
Python

"""Codex app-server adapter: personal R&D login or independent OpenAI API key."""
import asyncio
import hashlib
import json
import os
from pathlib import Path
import shutil
import time
from urllib.parse import urlsplit
from jsonschema import Draft202012Validator, ValidationError
from .errors import ModelError, provider_failure
from .storage import write_json
from .config import CODEX_MODEL, CODEX_EFFORT
from .schema import strict_schema, ADAPTER_VERSION
PROVIDER_ID = 'vibemake_openai'
def resolve_codex(explicit=None):
value = explicit or os.getenv('AI_PCB_CODEX_EXECUTABLE')
cached = str(Path(__file__).resolve().parents[1] / '.cache/codex-cli/node_modules/.bin/codex')
candidates = [value] if value else [cached, 'codex', str(Path.home() / '.codex/plugins/.plugin-appserver/codex')]
for candidate in candidates:
found = shutil.which(os.path.expanduser(candidate))
if found:
return found
raise ModelError('Codex executable is missing; configure AI_PCB_CODEX_EXECUTABLE')
def settings(require_key=True):
mode = os.getenv('AI_PCB_CODEX_AUTH', 'apikey')
if mode not in {'apikey', 'chatgpt'}:
raise ModelError('AI_PCB_CODEX_AUTH must be apikey or chatgpt')
key = os.getenv('OPENAI_API_KEY', '')
key_file = os.getenv('OPENAI_API_KEY_FILE')
if not key and key_file:
path = Path(key_file).expanduser()
if path.stat().st_size > 16384:
raise ModelError('OpenAI key file is invalid')
key = path.read_text().strip()
if mode == 'apikey' and require_key and not key:
raise ModelError('Codex website backend requires OPENAI_API_KEY or OPENAI_API_KEY_FILE; personal ChatGPT login is not used for hosted workloads')
endpoint = os.getenv('OPENAI_BASE_URL', 'https://api.openai.com/v1').rstrip('/')
parsed = urlsplit(endpoint)
if parsed.scheme != 'https' or parsed.username or parsed.password or parsed.query or parsed.fragment:
raise ModelError('OpenAI provider requires an HTTPS base URL without credentials or query parameters')
executable = resolve_codex()
root = Path(os.getenv('AI_PCB_API_DATA', str(Path.home() / '.local/share/vibemake-pcb'))).expanduser()
default_home = Path.home() / '.codex' if mode == 'chatgpt' else root / 'codex-runtime'
home_variable = 'AI_PCB_CODEX_LOGIN_HOME' if mode == 'chatgpt' else 'AI_PCB_OPENAI_CODEX_HOME'
home = Path(os.getenv(home_variable, str(default_home))).expanduser().resolve()
if mode == 'chatgpt' and require_key:
auth = home / 'auth.json'
if not auth.is_file() or not json.loads(auth.read_text()).get('tokens'):
raise ModelError('Log into Codex on the backend host before enabling personal R&D mode')
home.mkdir(parents=True, exist_ok=True, mode=0o700)
return executable, home, endpoint, key, mode
def process_config(require_key=True):
executable, home, endpoint, key, mode = settings(require_key)
config = {
'model_provider': 'openai' if mode == 'chatgpt' else PROVIDER_ID,
'model': CODEX_MODEL, 'model_reasoning_effort': CODEX_EFFORT,
'approval_policy': 'never', 'sandbox_mode': 'read-only', 'web_search': 'disabled',
'project_doc_max_bytes': 0, 'mcp_servers': {},
'model_providers.' + PROVIDER_ID + '.name': 'VibeMake OpenAI API',
'model_providers.' + PROVIDER_ID + '.base_url': endpoint,
'model_providers.' + PROVIDER_ID + '.wire_api': 'responses',
'model_providers.' + PROVIDER_ID + '.env_key': 'OPENAI_API_KEY',
'model_providers.' + PROVIDER_ID + '.requires_openai_auth': False,
'model_providers.' + PROVIDER_ID + '.request_max_retries': 0,
'model_providers.' + PROVIDER_ID + '.stream_max_retries': 0,
'model_providers.' + PROVIDER_ID + '.stream_idle_timeout_ms': 300000,
}
if mode == 'chatgpt':
config = {name: value for name, value in config.items() if not name.startswith('model_providers.')}
for feature in ['shell_tool', 'apps', 'plugins', 'multi_agent', 'multi_agent_v2',
'browser_use', 'browser_use_external', 'computer_use', 'in_app_browser', 'code_mode_host']:
config['features.' + feature] = False
argv = [executable, 'app-server', '--listen', 'stdio://']
for name, value in config.items():
encoded = '{}' if value == {} else json.dumps(value)
argv.extend(['-c', name + '=' + encoded])
env = dict(os.environ)
env.pop('DEEPSEEK_API_KEY', None)
env.pop('CODEX_API_KEY', None)
env['CODEX_HOME'] = str(home)
if key and mode == 'apikey':
env['OPENAI_API_KEY'] = key
else:
env.pop('OPENAI_API_KEY', None)
return argv, env
def restore_optional(value, schema):
if isinstance(value, dict):
properties, required = schema.get('properties', {}), set(schema.get('required', []))
result = {}
for name, child in value.items():
child_schema = properties.get(name, {})
if child is None and name not in required and not Draft202012Validator(child_schema).is_valid(None):
continue
result[name] = restore_optional(child, child_schema)
return result
if isinstance(value, list):
return [restore_optional(child, schema.get('items', {})) for child in value]
return value
async def probe(require_key=True):
"""Check auth and exact settings on an ephemeral thread, without a turn."""
from .transport import AppServer
argv, env = process_config(require_key)
async with AppServer(command=argv, env=env) as client:
account = await client.request('account/read', {'refreshToken': False})
mode = os.getenv('AI_PCB_CODEX_AUTH', 'apikey')
if mode == 'chatgpt' and require_key and (account.get('account') or {}).get('type') != 'chatgpt':
raise ModelError('The Codex process did not load the expected personal R&D login')
result = await client.request('model/list', {'limit': 100, 'includeHidden': True})
match = next((item for item in result.get('data', []) if item.get('model') == CODEX_MODEL), None)
efforts = [item.get('reasoningEffort') for item in (match or {}).get('supportedReasoningEfforts', [])]
if match and CODEX_EFFORT not in efforts:
raise ModelError('Installed Codex catalog does not support gpt-6.1-sol / medium')
# A local catalog can lag a newly released, explicitly requested model.
# It is neither an entitlement check nor grounds to substitute the model.
provider_id = 'openai' if mode == 'chatgpt' else PROVIDER_ID
reply = await client.request('thread/start', {'model': CODEX_MODEL, 'modelProvider': provider_id,
'cwd': str(Path(env['CODEX_HOME']).resolve()), 'approvalPolicy': 'never', 'sandbox': 'read-only',
'serviceTier': 'default', 'ephemeral': True,
'baseInstructions': 'Configuration check only. No inference turn will be started.'})
if reply.get('model') != CODEX_MODEL or reply.get('reasoningEffort') not in {None, CODEX_EFFORT}:
raise ModelError('Codex did not retain the requested model and medium effort')
return {'provider': 'codex', 'model': CODEX_MODEL, 'reasoning_effort': CODEX_EFFORT,
'transport_ready': True, 'api_key_configured': bool(env.get('OPENAI_API_KEY')),
'auth_mode': mode, 'inference_verified': False,
'catalog_match': bool(match), 'model_request_confirmed': True,
'uses_personal_login': (account.get('account') or {}).get('type') == 'chatgpt'}
class Codex:
def __init__(self, directory, event=None, cancel=None, *, guidance=None):
self.directory = Path(directory)
self.event, self.cancel = event or (lambda *args: None), cancel or (lambda: None)
self.guidance = guidance if guidance is not None else (Path(__file__).resolve().parents[1] / 'kicad_backend/guidance.md').read_text()
self.timeout = min(7200, max(30, int(os.getenv('AI_PCB_MODEL_TIMEOUT', '1800'))))
def call(self, role, payload, schema, *, images=(), retry=1):
from .transport import ProtocolError
fingerprint = hashlib.sha256(json.dumps(['codex', CODEX_MODEL, CODEX_EFFORT, ADAPTER_VERSION, role, payload, schema, self.guidance], sort_keys=True, ensure_ascii=False).encode()).hexdigest()
directory = self.directory / (role + '-' + fingerprint[:12])
response = directory / 'response.json'
validator = Draft202012Validator(schema)
deferred = []
wire_schema = strict_schema(schema, deferred=deferred)
if response.is_file():
value = json.loads(response.read_text())
validator.validate(value)
self.event('agent.cache_hit', {'role': role, 'provider': 'codex'})
return value
write_json(directory / 'schema-compatibility.json', {'adapter_version': ADAPTER_VERSION, 'server_validation_retained': True, 'deferred_constraints': deferred})
write_json(directory / 'input.json', {'role': role, 'payload': payload, 'schema': schema, 'wire_schema': wire_schema,
'provider': 'codex', 'model': CODEX_MODEL, 'reasoning_effort': CODEX_EFFORT, 'fingerprint': fingerprint})
started = time.monotonic()
request = dict(payload)
self.event('agent.started', {'role': role, 'provider': 'codex', 'model': CODEX_MODEL,
'reasoning_effort': CODEX_EFFORT, 'attempt_timeout_seconds': self.timeout})
for attempt in range(retry + 1):
self.cancel()
try:
text, usage = asyncio.run(self._turn(role, request, wire_schema, directory, images, attempt))
value = restore_optional(json.loads(text), schema)
validator.validate(value)
write_json(response, value)
metrics = {'provider': 'codex', 'model': CODEX_MODEL, 'reasoning_effort': CODEX_EFFORT,
'seconds': round(time.monotonic() - started, 2), 'usage': usage,
'attempts': attempt + 1, 'request_chars': len(json.dumps(request, ensure_ascii=False))}
write_json(directory / 'metrics.json', metrics)
self.event('agent.completed', {'role': role, **metrics})
return value
except (ValidationError, json.JSONDecodeError) as exc:
error = exc.message[:700] if isinstance(exc, ValidationError) else 'Output is not valid JSON'
write_json(directory / f'attempt-{attempt+1}-failure.json', {'error': error, 'type': type(exc).__name__})
if attempt == retry:
raise ModelError('Codex 结构化输出未通过检查:' + error) from None
request = {**payload, 'previous_answer': text, 'correction_required': error}
except (TimeoutError, ConnectionError) as exc:
write_json(directory / f'attempt-{attempt+1}-failure.json', {'type': type(exc).__name__})
if attempt == retry:
raise ModelError('Codex request timed out or disconnected after bounded retries') from None
except (ModelError, ProtocolError) as exc:
write_json(directory / 'failure.json', {'type': type(exc).__name__, 'message': str(exc)[:1000],
'provider': 'codex', 'model': CODEX_MODEL, 'reasoning_effort': CODEX_EFFORT,
'permanent': getattr(exc, 'permanent', False), 'code': getattr(exc, 'code', None)})
if isinstance(exc, ModelError):
raise
raise ModelError(str(exc)) from None
self.event('agent.retry', {'role': role, 'provider': 'codex', 'attempt': attempt + 2})
raise ModelError('Codex call exhausted retries')
async def _turn(self, role, payload, schema, directory, images, attempt):
from .transport import AppServer, ProtocolError
argv, env = process_config()
guidance = (self.guidance + '\nYou are a structured PCB planning role. All facts and API signatures are supplied. '
'Do not use tools, run commands, modify files, ask interactive questions, or operate EDA. '
'Return exactly the required JSON. The server handles execution and approval.')
async with AppServer(command=argv, env=env) as client:
self.cancel()
provider_id = 'openai' if os.getenv('AI_PCB_CODEX_AUTH', 'apikey') == 'chatgpt' else PROVIDER_ID
reply = await client.request('thread/start', {'model': CODEX_MODEL, 'modelProvider': provider_id,
'cwd': str(directory.resolve()), 'approvalPolicy': 'never', 'sandbox': 'read-only',
'serviceTier': 'default', 'baseInstructions': guidance, 'ephemeral': True, 'serviceName': 'vibemake-pcb'})
thread_id = reply['thread']['id']
if reply.get('model') not in {None, CODEX_MODEL}:
raise ModelError('Codex returned a different model; automatic substitution is disabled')
if reply.get('reasoningEffort') not in {None, CODEX_EFFORT}:
raise ModelError('Codex returned a different reasoning effort')
with client.subscribe() as events:
inputs = [{'type': 'text', 'text': json.dumps(payload, ensure_ascii=False)}]
inputs += [{'type': 'localImage', 'path': str(Path(path).resolve(strict=True))} for path in list(images)[:3]]
reply = await client.request('turn/start', {'threadId': thread_id, 'input': inputs,
'model': CODEX_MODEL, 'effort': CODEX_EFFORT, 'outputSchema': schema, 'approvalPolicy': 'never'})
turn_id = reply['turn']['id']
write_json(directory / f'attempt-{attempt+1}-session.json', {'thread_id': thread_id, 'turn_id': turn_id, 'status': 'running'})
started = last = time.monotonic()
messages, usage, completed = {}, {}, False
try:
while True:
self.cancel()
now = time.monotonic()
if now - started >= self.timeout:
raise TimeoutError('Codex turn deadline reached')
if now - last >= 10:
self.event('agent.progress', {'role': role, 'provider': 'codex', 'seconds': round(now-started)})
last = now
try:
event = await events.get(min(1, self.timeout - (now-started)))
except asyncio.TimeoutError:
continue
params, method = event.get('params', {}), event.get('method')
if method == 'client/serverRequest':
raise ModelError('Codex attempted an interactive request; no user intervention or permission is granted')
if params.get('threadId') != thread_id:
continue
if params.get('turnId') and params['turnId'] != turn_id:
continue
if method == 'thread/tokenUsage/updated':
raw = (params.get('tokenUsage') or {}).get('total', {})
usage = {'input_tokens': raw.get('inputTokens', 0), 'output_tokens': raw.get('outputTokens', 0),
'cached_input_tokens': raw.get('cachedInputTokens', 0),
'reasoning_output_tokens': raw.get('reasoningOutputTokens', 0)}
item = params.get('item', {})
if method in {'item/started', 'item/completed'} and item.get('type') not in {None, 'agentMessage', 'userMessage', 'reasoning'}:
raise ModelError('Codex attempted a tool operation; this provider only returns design data')
if method == 'item/completed' and item.get('type') == 'agentMessage':
messages[item['id']] = item
if method == 'turn/completed':
turn = params['turn']
completed = True
write_json(directory / f'attempt-{attempt+1}-session.json', {'thread_id': thread_id, 'turn_id': turn_id, 'status': turn['status'], 'error': turn.get('error')})
if turn['status'] != 'completed':
raise provider_failure(turn.get('error') or {'message': turn['status']})
for item in turn.get('items', []):
if item.get('type') == 'agentMessage':
messages[item['id']] = item
text = '\n'.join(item.get('text', '') for item in messages.values() if item.get('phase') in {None, 'final_answer'})
return text, usage
except ProtocolError:
raise ConnectionError('Codex transport disconnected') from None
finally:
if not completed:
try:
await client.request('turn/interrupt', {'threadId': thread_id, 'turnId': turn_id}, timeout=5)
except Exception:
pass