diff --git a/AGENTS.md b/AGENTS.md index 595ac10..dd366f0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,6 +38,7 @@ PYTHONPATH=bridge ./.runtime/notion-agent-cli-venv/bin/python -m unittest discov npm --prefix runtime test npm --prefix runtime run check npm --prefix notion-private-api-mcp run check +npm --prefix notion-private-api-mcp test node --test scripts/install-codex-config.test.mjs node --test scripts/patch-codex-webview.test.mjs node --test scripts/render-config.test.mjs diff --git a/README.md b/README.md index 607c2de..4d4ef84 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,15 @@ Set-Location .\notioncode_mcp powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\install.ps1 ``` +Интенсивность рассуждений можно свободно выбрать при установке. Поддерживаются +`low`, `medium`, `high`, `xhigh`, `max` и `ultra`. Если параметр не указан, +installer сохраняет уже выбранное пользователем значение: + +```powershell +powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\install.ps1 ` + -ReasoningEffort high +``` + Чтобы ограничить доступ tools отдельным каталогом: ```powershell @@ -192,6 +201,29 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\install.ps1 Успех: `verify.ps1` возвращает JSON с `"ok": true`. +### Опциональный MCP для внешнего inference + +Installer также регистрирует выключенный по умолчанию `external-inference` MCP. Он не ускоряет Notion AI, +не переносит лимиты Notion и не создаёт фиктивный Fast/Ultrafast tier. Инструмент +делает отдельный, оплачиваемый у выбранного провайдера запрос и возвращает +фактическое время выполнения. Поддерживаются только явно перечисленные модели +OpenRouter, Vivgrid и Cerebras; несуществующие GPT-6/Ultrafast aliases запрещены. + +Пока MCP выключен, он не может сделать платный запрос. Если пользователь позднее +явно решит оплачивать отдельный API, ключ вводится локально с маскировкой и не +записывается в Codex config или логи: + +```powershell +.\configure-external-provider.ps1 -Provider openrouter +``` + +Допустимые значения `-Provider`: `openrouter`, `vivgrid`, `cerebras`. После ввода +перезапустите Codex. Tool `external_provider_status` сообщает только наличие +ключа, никогда его значение. Tool `external_generate` требует явного признака, +что пользователь разрешил отдельно оплачиваемый внешний запрос. Скорость нужно +сравнивать по возвращаемому `elapsed_ms`; название провайдера само по себе не +гарантирует ускорение. + ## Codex в VS Code 1. Установите официальное расширение `openai.chatgpt`. @@ -212,6 +244,32 @@ auto-compaction запускается на 200 000 total tokens, а output tool 12 000 токенов. Bridge поддерживает и обычный compaction-turn, и `POST /v1/responses/compact`. +## Опциональный Fast mode в Codex Desktop на Windows + +Если пользовательская копия Codex Desktop уже подготовлена в +`%LOCALAPPDATA%\NotionCode\CodexDesktop\\app`, Windows-installer +запускает строгий compatibility patch для встроенного переключателя +`Standard` / `Fast`. Защищённые файлы в `C:\Program Files\WindowsApps` никогда +не изменяются. + +Patcher поддерживает только явно проверенные версии, требует ровно по одному +известному UI- и request-gate, сохраняет исходный `app.asar` рядом как +`app.asar.notioncode-original.bak`, пересчитывает SHA-256 и block-integrity +целевого renderer-файла и сохраняет точный размер архива. Неизвестная версия, +неоднозначный pattern или несовпадение integrity завершают операцию без +частичного обновления. Повторный запуск идемпотентен. + +Для проверки без записи: + +```powershell +node .\scripts\patch-codex-desktop.mjs --dry-run +``` + +После обновления официального Codex Desktop сначала подготовьте новую +пользовательскую копию, затем обновите список проверенных версий patcher-а и +повторите installer. Скрипт не придумывает Ultrafast-модели и показывает Fast +только для моделей, которые действительно публикуют tier `priority`. + ## Лимиты контекста и токенов Эти значения являются локальными настройками Codex/OpenCode и metadata моделей. @@ -514,6 +572,7 @@ npm --prefix runtime test npm --prefix runtime run check npm --prefix notion-private-api-mcp run check node --test scripts/install-codex-config.test.mjs +node --test scripts/patch-codex-desktop.test.mjs node --test scripts/patch-codex-webview.test.mjs node --test scripts/render-config.test.mjs node scripts/check-layout.mjs diff --git a/bridge/account_pool.py b/bridge/account_pool.py index 3e916af..8fb55aa 100644 --- a/bridge/account_pool.py +++ b/bridge/account_pool.py @@ -8,7 +8,8 @@ import time from collections import deque from collections.abc import Awaitable, Callable -from dataclasses import dataclass +from contextvars import ContextVar +from dataclasses import dataclass, field, replace from pathlib import Path from typing import Any, TypeVar @@ -18,21 +19,79 @@ NotionAgentError, retry_policy_for, ) -from notion_agent_cli.provider import NotionAgentClient +from notion_agent_cli.provider import NotionAgentClient, fetch_live_client_version from diagnostics import exception_fields, log_event MAX_ACCOUNTS = 10 -MAX_REASONING_EFFORT = "high" +MAX_REASONING_EFFORT = "ultra" +SUPPORTED_REASONING_EFFORTS = frozenset( + {"none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"} +) +_REQUEST_REASONING_EFFORT: ContextVar[str | None] = ContextVar( + "notion_request_reasoning_effort", + default=None, +) +_REQUEST_SERVICE_TIER: ContextVar[str | None] = ContextVar( + "notion_request_service_tier", + default=None, +) INFERENCE_TIMEOUT_SECONDS = max( 1.0, float(os.getenv("NOTION_INFERENCE_TIMEOUT_SECONDS", "180")), ) +# Keep one short retry inside the bridge for ordinary transient failures. +# A 180-second recovery window made a one-account setup wait in repeated +# 30-second cooldowns, so even a trivial prompt could take several minutes. +POOL_RECOVERY_WAIT_SECONDS = max( + 1.0, + float(os.getenv("NOTION_POOL_RECOVERY_WAIT_SECONDS", "8")), +) +MAX_RECOVERY_CYCLES = max( + 0, + int(os.getenv("NOTION_MAX_RECOVERY_CYCLES", "1")), +) +SINGLE_ACCOUNT_TRANSIENT_COOLDOWN = max( + 0.1, + float(os.getenv("NOTION_SINGLE_ACCOUNT_TRANSIENT_COOLDOWN_SECONDS", "1")), +) DEFAULT_TRANSIENT_COOLDOWN = 30 DEFAULT_DENIAL_COOLDOWN = 300 +EMPTY_TEXT_COOLDOWN = 60 +# A provider-side model substitution is not an account credential failure. Keep +# the affected model unavailable long enough to prevent every new request from +# repeating the same slow, doomed failover, while preserving every other +# advertised model (for example, Terra after a Sol mismatch). +MODEL_INTEGRITY_COOLDOWN = max( + 1.0, + float(os.getenv("NOTION_MODEL_INTEGRITY_COOLDOWN_SECONDS", "21600")), +) +# The upstream library's generic retry advice is 30 seconds. That is too long +# for a multi-account interactive pool: one short retryable error on each slot +# leaves every account cooling down and turns later requests into avoidable +# 503s. Live Sol probes showed the same accounts succeeding again within a few +# seconds. Keep hard denials and EMPTY_TEXT quarantine unchanged, but allow +# ordinary retryable transport/HTTP/Notion errors to fail over and recover +# inside the bridge's bounded recovery window. +TRANSIENT_FAILOVER_COOLDOWN = max( + 0.1, + float(os.getenv("NOTION_TRANSIENT_FAILOVER_COOLDOWN_SECONDS", "2")), +) +# Accounts that repeatedly pass credential validation but fail real inference +# are worse than having fewer accounts: they add a failed attempt to nearly +# every request and can push the whole pool into a visible 503/cooldown loop. +# Quarantine those accounts for several hours, while allowing an updated +# credential file to clear the quarantine on restart. +UNHEALTHY_ACCOUNT_MIN_OUTCOMES = 10 +UNHEALTHY_ACCOUNT_FAILURE_RATIO = 0.60 +UNHEALTHY_ACCOUNT_COOLDOWN = 6 * 60 * 60 GLOBAL_FAILURE_WINDOW = 30 GLOBAL_FAILURE_THRESHOLD = 3 +CLIENT_VERSION_REFRESH_SECONDS = max( + 300.0, + float(os.getenv("NOTION_CLIENT_VERSION_REFRESH_SECONDS", "21600")), +) log = logging.getLogger("uvicorn.error.notion_pool") _LOCAL_ERROR_CODES = { @@ -50,9 +109,103 @@ T = TypeVar("T") +def normalize_reasoning_effort(value: Any) -> str: + if isinstance(value, str): + normalized = value.strip().lower() + if normalized in SUPPORTED_REASONING_EFFORTS: + return normalized + return MAX_REASONING_EFFORT + + +def normalize_service_tier(value: Any) -> str: + if isinstance(value, str): + normalized = value.strip().lower() + if normalized in {"priority", "fast"}: + return "priority" + if normalized == "ultrafast": + return "ultrafast" + return "default" + + +def latency_profile_key(service_tier: Any, reasoning_effort: Any) -> str: + return ( + f"{normalize_service_tier(service_tier)}:" + f"{normalize_reasoning_effort(reasoning_effort)}" + ) + + class MaxEffortNotionAgentClient(NotionAgentClient): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self._client_version_checked_at = 0.0 + + async def _refresh_client_version_if_needed(self) -> None: + now = time.monotonic() + if ( + self._client_version_checked_at > 0 + and now - self._client_version_checked_at < CLIENT_VERSION_REFRESH_SECONDS + ): + return + self._client_version_checked_at = now + try: + live_version = await fetch_live_client_version() + except Exception as error: + log_event( + log, + "client_version_refresh_failed", + level=logging.WARNING, + **exception_fields(error), + ) + return + account = self.load_account() + if account.client_version == live_version: + return + previous_version = account.client_version + self._account = replace(account, client_version=live_version) + log_event( + log, + "client_version_refreshed", + previous_version=previous_version, + live_version=live_version, + ) + + async def complete(self, *args: Any, **kwargs: Any): + reasoning_effort = kwargs.pop("reasoning_effort", None) + service_tier = kwargs.pop("service_tier", None) + request_effort = ( + normalize_reasoning_effort(reasoning_effort) + if reasoning_effort is not None + else None + ) + token = _REQUEST_REASONING_EFFORT.set( + request_effort + ) + tier_token = _REQUEST_SERVICE_TIER.set( + service_tier.strip().lower() + if isinstance(service_tier, str) and service_tier.strip() + else None + ) + await self._refresh_client_version_if_needed() + try: + # Never retry in legacy cumulative mode. Live probes proved that + # legacy mode can reject or substitute an explicitly selected + # model, including gpt-5.6-sol. Propagate EMPTY_TEXT so the account + # pool can fail over to another patch-mode account without silently + # changing model, reasoning effort, or service tier. + return await super().complete(*args, **kwargs) + finally: + _REQUEST_REASONING_EFFORT.reset(token) + _REQUEST_SERVICE_TIER.reset(tier_token) + def _prepare_call(self, *args: Any, **kwargs: Any): + explicit_effort = kwargs.pop("reasoning_effort", None) + explicit_service_tier = kwargs.pop("service_tier", None) prep = super()._prepare_call(*args, **kwargs) + reasoning_effort = normalize_reasoning_effort( + explicit_effort + if explicit_effort is not None + else _REQUEST_REASONING_EFFORT.get() + ) transcript = prep.body.get("transcript") if not isinstance(transcript, list): raise RuntimeError("Notion inference request has no transcript") @@ -62,7 +215,17 @@ def _prepare_call(self, *args: Any, **kwargs: Any): config = item.get("value") if not isinstance(config, dict): raise RuntimeError("Notion inference request has no config value") - config["reasoningEffort"] = MAX_REASONING_EFFORT + config["reasoningEffort"] = reasoning_effort + service_tier = ( + explicit_service_tier + if explicit_service_tier is not None + else _REQUEST_SERVICE_TIER.get() + ) + if isinstance(service_tier, str) and service_tier.strip(): + # Best-effort provider config field. Older Notion backends may + # ignore it, but preserving it lets compatible providers use + # Fast/Ultrafast without changing the selected base model. + config["serviceTier"] = service_tier.strip().lower() return prep raise RuntimeError("Notion inference request has no config block") @@ -71,6 +234,14 @@ class AccountPoolExhausted(RuntimeError): """Every configured Notion account failed for one operation.""" +class ModelIntegrityError(RuntimeError): + """The provider returned a model other than the explicitly selected one.""" + + def __init__(self, message: str, *, requested_model: str | None = None) -> None: + super().__init__(message) + self.requested_model = requested_model + + class AccountPoolCoolingDown(AccountPoolExhausted): def __init__(self, retry_after: int) -> None: super().__init__(f"All Notion accounts are cooling down; retry after {retry_after}s") @@ -91,9 +262,18 @@ class _AccountSlot: successes: int = 0 failures: int = 0 last_error_code: str = "" + latency_ewma_ms: float = 0 + latency_samples: int = 0 + tier_latency_ewma_ms: dict[str, float] = field(default_factory=dict) + tier_latency_samples: dict[str, int] = field(default_factory=dict) + profile_latency_ewma_ms: dict[str, float] = field(default_factory=dict) + profile_latency_samples: dict[str, int] = field(default_factory=dict) + model_cooldown_until: dict[str, float] = field(default_factory=dict) def is_failover_error(error: Exception) -> bool: + if isinstance(error, ModelIntegrityError): + return True if isinstance(error, httpx.HTTPError): return True if isinstance(error, NotionAgentError): @@ -128,6 +308,12 @@ def build_account_pool(account_home: Path) -> NotionAccountPool: client = MaxEffortNotionAgentClient( account_path, thread_state_dir=thread_state_dir, + # Patch responses preserve the explicitly selected Notion model. + # Live cross-account probes proved that legacy cumulative mode + # rejects or substitutes gpt-5.6-sol, while patch mode executes its + # resolved orange-mousse model correctly on every configured + # account. Never choose response mode by account filename or speed. + as_patch_response=True, ) try: account = client.load_account() @@ -213,8 +399,32 @@ def __init__( def size(self) -> int: return len(self._slots) - def lease(self, preferred_account_id: str | None = None) -> AccountLease: - return AccountLease(self, preferred_account_id=preferred_account_id) + @property + def clients(self) -> tuple[NotionAgentClient, ...]: + """Return configured clients without exposing account contents.""" + return tuple(slot.client for slot in self._slots) + + async def eligible_clients(self) -> tuple[NotionAgentClient, ...]: + """Return clients eligible to attest the currently available model catalog.""" + async with self._condition: + return tuple(slot.client for slot in self._slots if not slot.disabled) + + def lease( + self, + preferred_account_id: str | None = None, + avoid_account_id: str | None = None, + service_tier: str | None = None, + reasoning_effort: str | None = None, + required_model: str | None = None, + ) -> AccountLease: + return AccountLease( + self, + preferred_account_id=preferred_account_id, + avoid_account_id=avoid_account_id, + service_tier=normalize_service_tier(service_tier), + reasoning_effort=normalize_reasoning_effort(reasoning_effort), + required_model=required_model, + ) async def status(self) -> dict[str, Any]: async with self._condition: @@ -254,6 +464,18 @@ async def status(self) -> dict[str, Any]: "successes": slot.successes, "failures": slot.failures, "last_error": slot.last_error_code or None, + "latency_ewma_ms": round(slot.latency_ewma_ms) if slot.latency_samples else None, + "latency_samples": slot.latency_samples, + "tier_latency_ewma_ms": { + tier: round(value) + for tier, value in slot.tier_latency_ewma_ms.items() + }, + "tier_latency_samples": dict(slot.tier_latency_samples), + "profile_latency_ewma_ms": { + profile: round(value) + for profile, value in slot.profile_latency_ewma_ms.items() + }, + "profile_latency_samples": dict(slot.profile_latency_samples), } for slot in self._slots ], @@ -265,6 +487,72 @@ async def aclose(self) -> None: return_exceptions=True, ) + async def revalidate_stale_disabled_accounts(self) -> int: + """Restore only accounts disabled by a stale auth or entitlement result. + + Model-integrity failures remain disabled until the credential file changes, + because accepting a substituted model would violate the selected model. + """ + async with self._condition: + candidates = [ + slot for slot in self._slots + if slot.disabled + and slot.last_error_code in { + str(ErrorCode.AUTH_INVALID), + str(ErrorCode.PREMIUM_REQUIRED), + } + ] + restored = 0 + for slot in candidates: + try: + result = await asyncio.wait_for( + slot.client.complete( + prompt="Reply with exactly OK.", + model="gpt-5.6-sol", + web_search=False, + workspace_search=False, + ask_mode=True, + reasoning_effort="low", + ), + timeout=INFERENCE_TIMEOUT_SECONDS, + ) + if not isinstance(getattr(result, "text", None), str) or not result.text.strip(): + raise RuntimeError("empty validation response") + raw = getattr(result, "raw", None) + reported = raw.get("reported_notion_model") if isinstance(raw, dict) else None + actual_model = getattr(result, "model", None) or reported + if actual_model != "orange-mousse": + raise ModelIntegrityError( + "stale-account validation requested gpt-5.6-sol but received " + f"{actual_model!r}" + ) + except Exception as error: + log_event( + log, + "account_revalidation_failed", + level=logging.WARNING, + account_number=slot.number, + account_id=slot.account_id, + account_file=self._account_file(slot), + **exception_fields(error), + ) + continue + async with self._condition: + slot.disabled = False + slot.cooldown_until = 0 + slot.last_error_code = "" + self._save_state() + self._condition.notify_all() + restored += 1 + log_event( + log, + "account_revalidated", + account_number=slot.number, + account_id=slot.account_id, + account_file=self._account_file(slot), + ) + return restored + def _load_state(self) -> None: if self._state_path is None or not self._state_path.is_file(): return @@ -276,6 +564,7 @@ def _load_state(self) -> None: saved_accounts = state.get("accounts", {}) if isinstance(state, dict) else {} if not isinstance(saved_accounts, dict): return + migrated_legacy_model_integrity = False for slot in self._slots: saved = saved_accounts.get(slot.account_id) if not isinstance(saved, dict): @@ -284,11 +573,62 @@ def _load_state(self) -> None: slot.assignments = int(saved.get("assignments", 0) or 0) slot.successes = int(saved.get("successes", 0) or 0) slot.failures = int(saved.get("failures", 0) or 0) + slot.latency_ewma_ms = float(saved.get("latency_ewma_ms", 0) or 0) + slot.latency_samples = int(saved.get("latency_samples", 0) or 0) + saved_tier_ewma = saved.get("tier_latency_ewma_ms", {}) + saved_tier_samples = saved.get("tier_latency_samples", {}) + saved_profile_ewma = saved.get("profile_latency_ewma_ms", {}) + saved_profile_samples = saved.get("profile_latency_samples", {}) + if isinstance(saved_tier_ewma, dict): + slot.tier_latency_ewma_ms = { + normalize_service_tier(tier): float(value) + for tier, value in saved_tier_ewma.items() + if isinstance(tier, str) and isinstance(value, (int, float)) + } + if isinstance(saved_tier_samples, dict): + slot.tier_latency_samples = { + normalize_service_tier(tier): int(value) + for tier, value in saved_tier_samples.items() + if isinstance(tier, str) and isinstance(value, (int, float)) + } + if isinstance(saved_profile_ewma, dict): + slot.profile_latency_ewma_ms = { + profile: float(value) + for profile, value in saved_profile_ewma.items() + if isinstance(profile, str) + and ":" in profile + and isinstance(value, (int, float)) + } + if isinstance(saved_profile_samples, dict): + slot.profile_latency_samples = { + profile: int(value) + for profile, value in saved_profile_samples.items() + if isinstance(profile, str) + and ":" in profile + and isinstance(value, (int, float)) + } credential_unchanged = float(saved.get("credential_mtime", 0) or 0) == slot.credential_mtime if credential_unchanged: slot.cooldown_until = float(saved.get("cooldown_until", 0) or 0) slot.disabled = bool(saved.get("disabled", False)) + saved_model_cooldowns = saved.get("model_cooldown_until", {}) + if isinstance(saved_model_cooldowns, dict): + slot.model_cooldown_until = { + model: float(until) + for model, until in saved_model_cooldowns.items() + if isinstance(model, str) and isinstance(until, (int, float)) + } slot.last_error_code = str(saved.get("last_error_code", "") or "") + # Versions before model-scoped cooldowns persisted a model mismatch as + # a disabled account. That state is safe to undo: token/auth failures + # retain their disabled state and still require explicit validation. + if slot.disabled and slot.last_error_code.startswith("ModelIntegrityError"): + slot.disabled = False + slot.cooldown_until = 0 + slot.last_error_code = "" + migrated_legacy_model_integrity = True + if migrated_legacy_model_integrity: + self._save_state() def _save_state(self) -> None: if self._state_path is None: @@ -304,6 +644,13 @@ def _save_state(self) -> None: "cooldown_until": slot.cooldown_until, "disabled": slot.disabled, "last_error_code": slot.last_error_code, + "latency_ewma_ms": slot.latency_ewma_ms, + "latency_samples": slot.latency_samples, + "tier_latency_ewma_ms": slot.tier_latency_ewma_ms, + "tier_latency_samples": slot.tier_latency_samples, + "profile_latency_ewma_ms": slot.profile_latency_ewma_ms, + "profile_latency_samples": slot.profile_latency_samples, + "model_cooldown_until": slot.model_cooldown_until, "credential_mtime": slot.credential_mtime, } for slot in self._slots @@ -312,10 +659,14 @@ def _save_state(self) -> None: temporary = self._state_path.with_suffix(".tmp") try: self._state_path.parent.mkdir(parents=True, exist_ok=True) - temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8") + with temporary.open("w", encoding="utf-8") as handle: + json.dump(state, handle, indent=2) + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) if os.name != "nt": temporary.chmod(0o600) - temporary.replace(self._state_path) + os.replace(temporary, self._state_path) except OSError as error: log.warning("Could not persist account scheduler state: %s", error) @@ -323,6 +674,11 @@ async def _acquire( self, excluded: set[int], preferred_account_id: str | None = None, + avoid_account_id: str | None = None, + recovery_deadline: float | None = None, + service_tier: str = "default", + reasoning_effort: str = MAX_REASONING_EFFORT, + required_model: str | None = None, ) -> _AccountSlot: if not self._slots: raise AccountPoolExhausted("No valid Notion accounts are configured") @@ -332,8 +688,48 @@ async def _acquire( async with self._condition: while True: now = time.time() - if self._global_cooldown_until > now: + ready_failover_accounts = [ + slot for index, slot in enumerate(self._slots) + if index not in excluded + and not slot.busy + and not slot.disabled + and slot.cooldown_until <= now + and self._model_is_ready(slot, required_model, now) + and self._advertises_model(slot, required_model) + ] + # The global breaker protects a new request when recent failures + # indicate a provider-wide outage. It must not pause an in-flight + # request before trying a distinct account that is already ready. + # Previously, historical failures from three accounts caused each + # ordinary failover to sleep for two seconds and could exhaust the + # whole recovery budget before the final healthy account ran. + bypass_global_cooldown = bool(excluded and ready_failover_accounts) + if self._global_cooldown_until > now and not bypass_global_cooldown: retry_after = max(1, round(self._global_cooldown_until - now)) + remaining = ( + recovery_deadline - time.monotonic() + if recovery_deadline is not None else 0 + ) + if remaining > 0: + wait_seconds = min( + self._global_cooldown_until - now, + remaining, + ) + log_event( + log, + "account_pool_recovery_wait", + level=logging.WARNING, + reason="global_cooldown", + wait_seconds=round(wait_seconds, 3), + ) + try: + await asyncio.wait_for( + self._condition.wait(), + timeout=max(0.001, wait_seconds), + ) + except asyncio.TimeoutError: + pass + continue log_event( log, "circuit_breaker_active", @@ -341,29 +737,105 @@ async def _acquire( retry_after=retry_after, ) raise AccountPoolCoolingDown(retry_after) - eligible = [ - slot for index, slot in enumerate(self._slots) - if index not in excluded - and not slot.busy - and not slot.disabled - and slot.cooldown_until <= now - ] + eligible = ready_failover_accounts selected = next( (slot for slot in eligible if slot.account_id == preferred_account_id), None, ) - if selected is None and eligible: - selected = min( - eligible, - key=lambda slot: (slot.last_assigned_at, slot.assignments, slot.number), + selection_pool = eligible + if selected is None and avoid_account_id is not None: + alternatives = [ + slot for slot in eligible + if slot.account_id != avoid_account_id + ] + if alternatives: + selection_pool = alternatives + if selected is None and selection_pool: + # Explore every account once, then route new conversations to + # the account with the lowest measured end-to-end latency. + # Existing conversations still use preferred_account_id so + # Notion thread continuity is never sacrificed for speed. + # Only explore accounts that have never produced either a + # success or a failure. An account returning empty output + # must not remain "unmeasured" forever and win every new + # selection merely because it has no successful latency. + # Provider scheduling can differ substantially by tier. A + # single all-tier EWMA allowed slow Priority requests to be + # routed using Standard measurements (and vice versa). + # Explore each healthy account once per tier, then use that + # tier's measured latency. The selected model and reasoning + # effort are untouched. + tier = normalize_service_tier(service_tier) + effort = normalize_reasoning_effort(reasoning_effort) + profile = latency_profile_key(tier, effort) + # A newly introduced tier+effort profile has no historical + # samples after migration. Bootstrap its first selection + # from the existing tier/overall latency data instead of + # treating every account as equally unmeasured. Once one + # account has produced a profile sample, explore the other + # healthy accounts once for that profile before preferring + # the lowest profile EWMA. + profile_learning_started = any( + slot.profile_latency_samples.get(profile, 0) > 0 + for slot in selection_pool ) + unmeasured = [ + slot for slot in selection_pool + if profile_learning_started + and slot.profile_latency_samples.get(profile, 0) == 0 + and not ( + slot.successes + slot.failures >= UNHEALTHY_ACCOUNT_MIN_OUTCOMES + and slot.failures / max(1, slot.successes + slot.failures) + >= UNHEALTHY_ACCOUNT_FAILURE_RATIO + ) + ] + if unmeasured: + selected = min( + unmeasured, + key=lambda slot: (slot.last_assigned_at, slot.assignments, slot.number), + ) + else: + selected = min( + selection_pool, + key=lambda slot: ( + # Quarantine-grade reliability problems must + # beat raw speed, but small historical failure + # differences between healthy accounts must not + # route every new turn to a much slower account. + # The previous ordering put failure ratio first, + # so an account with 0 failures and 17 s latency + # beat a healthy account averaging 8 s forever. + ( + slot.successes + slot.failures >= UNHEALTHY_ACCOUNT_MIN_OUTCOMES + and slot.failures / max(1, slot.successes + slot.failures) + >= UNHEALTHY_ACCOUNT_FAILURE_RATIO + ), + ( + slot.profile_latency_ewma_ms.get(profile, 0) + or slot.tier_latency_ewma_ms.get(tier, 0) + or ( + slot.latency_ewma_ms + if slot.latency_samples else float("inf") + ) + ), + slot.failures / max(1, slot.successes + slot.failures), + slot.last_assigned_at, + slot.assignments, + slot.number, + ), + ) if selected is not None: selected.busy = True selected.last_assigned_at = now selected.assignments += 1 self._save_state() selection = "affinity" if selected.account_id == preferred_account_id else ( - "failover" if excluded else "balanced" + "failover" if excluded else + "tier_latency" if selected.tier_latency_samples.get( + normalize_service_tier(service_tier), 0 + ) else + "latency" if selected.latency_samples else + "balanced" ) log_event( log, @@ -372,23 +844,76 @@ async def _acquire( account_id=selected.account_id, account_file=self._account_file(selected), selection=selection, + avoided_account_id=avoid_account_id, attempt=len(excluded) + 1, assignments=selected.assignments, + latency_ewma_ms=( + round(selected.latency_ewma_ms) + if selected.latency_samples else None + ), + service_tier=normalize_service_tier(service_tier), + reasoning_effort=normalize_reasoning_effort(reasoning_effort), + required_model=required_model, + tier_latency_ewma_ms=( + round(selected.tier_latency_ewma_ms[ + normalize_service_tier(service_tier) + ]) + if selected.tier_latency_samples.get( + normalize_service_tier(service_tier), 0 + ) else None + ), + profile_latency_ewma_ms=( + round(selected.profile_latency_ewma_ms[ + latency_profile_key(service_tier, reasoning_effort) + ]) + if selected.profile_latency_samples.get( + latency_profile_key(service_tier, reasoning_effort), 0 + ) else None + ), ) return selected waiting_busy = any( - index not in excluded and slot.busy and not slot.disabled + index not in excluded + and slot.busy + and not slot.disabled + and self._model_is_ready(slot, required_model, now) + and self._advertises_model(slot, required_model) for index, slot in enumerate(self._slots) ) if waiting_busy: await self._condition.wait() continue retry_times = [ - slot.cooldown_until for index, slot in enumerate(self._slots) - if index not in excluded and not slot.disabled and slot.cooldown_until > now + max(slot.cooldown_until, self._model_cooldown_until(slot, required_model)) + for index, slot in enumerate(self._slots) + if index not in excluded + and not slot.disabled + and self._advertises_model(slot, required_model) + and max(slot.cooldown_until, self._model_cooldown_until(slot, required_model)) > now ] if retry_times: retry_after = max(1, round(min(retry_times) - now)) + remaining = ( + recovery_deadline - time.monotonic() + if recovery_deadline is not None else 0 + ) + if remaining > 0: + wait_seconds = min(min(retry_times) - now, remaining) + log_event( + log, + "account_pool_recovery_wait", + level=logging.WARNING, + reason="account_cooldown", + wait_seconds=round(wait_seconds, 3), + ) + try: + await asyncio.wait_for( + self._condition.wait(), + timeout=max(0.001, wait_seconds), + ) + except asyncio.TimeoutError: + pass + continue log_event( log, "account_pool_cooling_down", @@ -399,6 +924,30 @@ async def _acquire( log_event(log, "account_pool_exhausted", level=logging.ERROR) raise AccountPoolExhausted("No usable Notion accounts are available") + @staticmethod + def _advertises_model(slot: _AccountSlot, required_model: str | None) -> bool: + if not required_model: + return True + advertised = getattr(slot.client, "_notion_available_model_aliases", None) + # Before the first successful catalog refresh, retain the old behavior + # rather than making the whole bridge unavailable. Once discovery has + # run, route only to accounts that advertised the selected alias. + return advertised is None or required_model in advertised + + @staticmethod + def _model_cooldown_until(slot: _AccountSlot, required_model: str | None) -> float: + return slot.model_cooldown_until.get(required_model, 0) if required_model else 0 + + @classmethod + def _model_is_ready(cls, slot: _AccountSlot, required_model: str | None, now: float) -> bool: + return cls._model_cooldown_until(slot, required_model) <= now + + @classmethod + def _supports_model(cls, slot: _AccountSlot, required_model: str | None) -> bool: + return cls._advertises_model(slot, required_model) and cls._model_is_ready( + slot, required_model, time.time() + ) + @staticmethod def _account_file(slot: _AccountSlot) -> str: account_path = getattr(slot.client, "account_path", None) @@ -409,10 +958,49 @@ async def _release(self, slot: _AccountSlot) -> None: slot.busy = False self._condition.notify_all() - async def _record_success(self, slot: _AccountSlot, duration_ms: int) -> None: + async def _record_success( + self, + slot: _AccountSlot, + duration_ms: int, + service_tier: str = "default", + reasoning_effort: str = MAX_REASONING_EFFORT, + required_model: str | None = None, + ) -> None: async with self._condition: slot.successes += 1 slot.last_error_code = "" + if required_model: + slot.model_cooldown_until.pop(required_model, None) + # EWMA reacts to sustained speed differences without allowing one + # unusually slow or fast request to permanently bias routing. + if slot.latency_samples == 0: + slot.latency_ewma_ms = float(duration_ms) + else: + slot.latency_ewma_ms = ( + 0.25 * duration_ms + 0.75 * slot.latency_ewma_ms + ) + slot.latency_samples += 1 + tier = normalize_service_tier(service_tier) + tier_samples = slot.tier_latency_samples.get(tier, 0) + if tier_samples == 0: + slot.tier_latency_ewma_ms[tier] = float(duration_ms) + else: + slot.tier_latency_ewma_ms[tier] = ( + 0.25 * duration_ms + + 0.75 * slot.tier_latency_ewma_ms[tier] + ) + slot.tier_latency_samples[tier] = tier_samples + 1 + effort = normalize_reasoning_effort(reasoning_effort) + profile = latency_profile_key(tier, effort) + profile_samples = slot.profile_latency_samples.get(profile, 0) + if profile_samples == 0: + slot.profile_latency_ewma_ms[profile] = float(duration_ms) + else: + slot.profile_latency_ewma_ms[profile] = ( + 0.25 * duration_ms + + 0.75 * slot.profile_latency_ewma_ms[profile] + ) + slot.profile_latency_samples[profile] = profile_samples + 1 self._save_state() log_event( log, @@ -421,6 +1009,14 @@ async def _record_success(self, slot: _AccountSlot, duration_ms: int) -> None: account_id=slot.account_id, account_file=self._account_file(slot), duration_ms=duration_ms, + latency_ewma_ms=round(slot.latency_ewma_ms), + latency_samples=slot.latency_samples, + service_tier=tier, + reasoning_effort=effort, + tier_latency_ewma_ms=round(slot.tier_latency_ewma_ms[tier]), + tier_latency_samples=slot.tier_latency_samples[tier], + profile_latency_ewma_ms=round(slot.profile_latency_ewma_ms[profile]), + profile_latency_samples=slot.profile_latency_samples[profile], successes=slot.successes, ) @@ -429,6 +1025,7 @@ async def _record_failure( slot: _AccountSlot, error: Exception, duration_ms: int, + required_model: str | None = None, ) -> None: now = time.time() code = error.code if isinstance(error, NotionAgentError) else type(error).__name__ @@ -444,16 +1041,64 @@ async def _record_failure( subtype = error.subtype or "" if isinstance(error, httpx.HTTPError): retryable, retry_after = True, DEFAULT_TRANSIENT_COOLDOWN + if retryable is True and code in { + ErrorCode.TRANSPORT, + ErrorCode.HTTP_ERROR, + ErrorCode.NOTION_ERROR, + "ConnectError", + "ReadError", + "WriteError", + "PoolTimeout", + }: + retry_after = min( + retry_after if retry_after is not None else DEFAULT_TRANSIENT_COOLDOWN, + TRANSIENT_FAILOVER_COOLDOWN, + ) async with self._condition: slot.failures += 1 slot.last_error_code = f"{code}:{subtype}" if subtype else str(code) - if code in {ErrorCode.AUTH_INVALID, ErrorCode.PREMIUM_REQUIRED}: + outcomes = slot.successes + slot.failures + failure_ratio = slot.failures / max(1, outcomes) + health_quarantined = ( + code in {ErrorCode.EMPTY_TEXT, ErrorCode.NOTION_ERROR} + and outcomes >= UNHEALTHY_ACCOUNT_MIN_OUTCOMES + and failure_ratio >= UNHEALTHY_ACCOUNT_FAILURE_RATIO + ) + if isinstance(error, ModelIntegrityError): + affected_model = error.requested_model or required_model + if affected_model: + slot.model_cooldown_until[affected_model] = max( + slot.model_cooldown_until.get(affected_model, 0), + now + MODEL_INTEGRITY_COOLDOWN, + ) + # A substituted/unsupported model proves nothing about token + # validity. Keep the account usable for every other model. + slot.disabled = False + applied_delay = 0 + elif code in {ErrorCode.AUTH_INVALID, ErrorCode.PREMIUM_REQUIRED}: slot.disabled = True applied_delay = 0 else: delay = retry_after + if code == ErrorCode.EMPTY_TEXT: + # The upstream library recommends one immediate retry, but + # failover already performs that retry on another account. + # Re-selecting the same persistently empty account on the + # next request caused the visible cooldown/503 loop. + delay = max(delay or 0, EMPTY_TEXT_COOLDOWN) + if health_quarantined: + delay = max(delay or 0, UNHEALTHY_ACCOUNT_COOLDOWN) if delay is None: delay = DEFAULT_DENIAL_COOLDOWN if retryable is False else DEFAULT_TRANSIENT_COOLDOWN + if ( + len(self._slots) == 1 + and retryable is not False + and code in {ErrorCode.HTTP_ERROR, ErrorCode.NOTION_ERROR} + ): + # There is no alternate account to protect with a long + # cooldown. Retry once quickly, then fail promptly instead + # of keeping the Codex turn open for several minutes. + delay = min(delay, SINGLE_ACCOUNT_TRANSIENT_COOLDOWN) applied_delay = max(0, delay) slot.cooldown_until = max(slot.cooldown_until, now + applied_delay) signature = slot.last_error_code @@ -469,7 +1114,11 @@ async def _record_failure( if circuit_opened: self._global_cooldown_until = max( self._global_cooldown_until, - now + (retry_after or DEFAULT_TRANSIENT_COOLDOWN), + now + ( + retry_after + if retry_after is not None + else DEFAULT_TRANSIENT_COOLDOWN + ), ) self._save_state() log_event( @@ -481,6 +1130,8 @@ async def _record_failure( account_file=self._account_file(slot), duration_ms=duration_ms, failures=slot.failures, + failure_ratio=round(failure_ratio, 3), + health_quarantined=health_quarantined, disabled=slot.disabled, cooldown_seconds=applied_delay, **exception_fields(error), @@ -502,12 +1153,22 @@ def __init__( pool: NotionAccountPool, *, preferred_account_id: str | None = None, + avoid_account_id: str | None = None, + service_tier: str = "default", + reasoning_effort: str = MAX_REASONING_EFFORT, + required_model: str | None = None, ) -> None: self._pool = pool self._preferred_account_id = preferred_account_id + self._avoid_account_id = avoid_account_id + self._service_tier = normalize_service_tier(service_tier) + self._reasoning_effort = normalize_reasoning_effort(reasoning_effort) + self._required_model = required_model self._slot: _AccountSlot | None = None self._attempted: set[int] = set() self._failures: list[str] = [] + self._recovery_deadline = 0.0 + self._recovery_cycles = 0 @property def client(self) -> NotionAgentClient: @@ -522,9 +1183,15 @@ def account_id(self) -> str: return self._slot.account_id async def __aenter__(self) -> AccountLease: + self._recovery_deadline = time.monotonic() + POOL_RECOVERY_WAIT_SECONDS self._slot = await self._pool._acquire( self._attempted, preferred_account_id=self._preferred_account_id, + avoid_account_id=self._avoid_account_id, + recovery_deadline=self._recovery_deadline, + service_tier=self._service_tier, + reasoning_effort=self._reasoning_effort, + required_model=self._required_model, ) self._attempted.add(self._slot.number - 1) return self @@ -552,6 +1219,9 @@ async def run( await self._pool._record_success( self._slot, round((time.monotonic() - started_at) * 1000), + self._service_tier, + self._reasoning_effort, + self._required_model, ) return result except asyncio.CancelledError: @@ -609,23 +1279,81 @@ async def _switch_account(self, error: Exception, *, duration_ms: int) -> None: previous_number = self._slot.number previous_id = self._slot.account_id previous_file = self._pool._account_file(self._slot) - await self._pool._record_failure(self._slot, error, duration_ms) + await self._pool._record_failure( + self._slot, error, duration_ms, required_model=self._required_model + ) await self._pool._release(self._slot) self._slot = None - if len(self._attempted) >= self._pool.size: + # Compare attempts with accounts that can actually serve this request, + # not the configured pool size. A persistently disabled account (for + # example, one quarantined after a model-integrity violation) can never + # be attempted. Counting it previously prevented the retry cycle after + # every eligible account had transiently failed, causing an avoidable + # 503 after only two attempts in a three-account pool with one disabled. + eligible_account_count = sum( + not slot.disabled + and self._pool._advertises_model(slot, self._required_model) + for slot in self._pool._slots + ) + if len(self._attempted) >= eligible_account_count: + if ( + self._recovery_cycles < MAX_RECOVERY_CYCLES + and time.monotonic() < self._recovery_deadline + ): + self._recovery_cycles += 1 + log_event( + log, + "account_pool_retry_cycle", + level=logging.WARNING, + attempted=len(self._attempted), + retry_cycle=self._recovery_cycles, + recovery_seconds_remaining=round( + self._recovery_deadline - time.monotonic(), + 3, + ), + ) + self._attempted.clear() + self._slot = await self._pool._acquire( + self._attempted, + recovery_deadline=self._recovery_deadline, + service_tier=self._service_tier, + reasoning_effort=self._reasoning_effort, + required_model=self._required_model, + ) + self._attempted.add(self._slot.number - 1) + log_event( + log, + "account_failover", + level=logging.WARNING, + from_account_number=previous_number, + from_account_id=previous_id, + from_account_file=previous_file, + to_account_number=self._slot.number, + to_account_id=self._slot.account_id, + to_account_file=self._pool._account_file(self._slot), + retry_cycle=True, + ) + return failures = ", ".join(self._failures) log_event( log, "account_pool_exhausted", level=logging.ERROR, attempted=len(self._attempted), + eligible_accounts=eligible_account_count, last_account_id=previous_id, last_account_file=previous_file, ) raise AccountPoolExhausted( - f"All {self._pool.size} Notion accounts failed ({failures})" + f"All {eligible_account_count} Notion accounts failed ({failures})" ) from error - self._slot = await self._pool._acquire(self._attempted) + self._slot = await self._pool._acquire( + self._attempted, + recovery_deadline=self._recovery_deadline, + service_tier=self._service_tier, + reasoning_effort=self._reasoning_effort, + required_model=self._required_model, + ) self._attempted.add(self._slot.number - 1) log_event( log, diff --git a/bridge/conversation_segments.py b/bridge/conversation_segments.py index 3da0245..4dc89d5 100644 --- a/bridge/conversation_segments.py +++ b/bridge/conversation_segments.py @@ -13,8 +13,9 @@ CONVERSATION_TTL = 30 * 24 * 60 * 60 MAX_CONVERSATIONS = 500 -# Version 2 invalidates bindings created while Notion recorded the thread as Auto. -STATE_VERSION = 2 +# Version 3 normalizes assistant message fingerprints so Codex-side rewrites do +# not spuriously force a new Notion thread mid-conversation. +STATE_VERSION = 3 def conversation_storage_key(key: str) -> str: @@ -22,12 +23,45 @@ def conversation_storage_key(key: str) -> str: return hashlib.sha256(key.encode()).hexdigest() +def _normalized_segment_input_item(item: Any) -> Any: + """Return a stable per-item shape for conversation continuation checks. + + Codex may rewrite previously generated assistant message text while keeping + the logical conversation unchanged. Using the raw assistant content makes + append-only history look like a rewrite, which incorrectly rolls the bridge + onto a fresh Notion thread and loses continuity. Preserve user and tool + payloads exactly, but collapse assistant message bodies to a stable summary. + """ + if not isinstance(item, dict): + return item + if item.get("type") == "message" and item.get("role") == "assistant": + normalized: dict[str, Any] = { + "type": item.get("type"), + "role": item.get("role"), + } + content = item.get("content") + if isinstance(content, list): + normalized["content_types"] = [ + part.get("type") if isinstance(part, dict) else type(part).__name__ + for part in content + ] + elif content is not None: + normalized["content_type"] = type(content).__name__ + return normalized + return item + + def response_input_fingerprints(body: dict[str, Any]) -> tuple[str, ...]: value = body.get("input") items = value if isinstance(value, list) else [value] if isinstance(value, str) else [] return tuple( hashlib.sha256( - json.dumps(item, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() + json.dumps( + _normalized_segment_input_item(item), + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + ).encode() ).hexdigest() for item in items ) diff --git a/bridge/model_catalog.py b/bridge/model_catalog.py new file mode 100644 index 0000000..3261af7 --- /dev/null +++ b/bridge/model_catalog.py @@ -0,0 +1,432 @@ +from __future__ import annotations + +import asyncio +import copy +import json +import os +from datetime import UTC, datetime +from pathlib import Path +from typing import Any, Iterable + +BASE_MODEL_IDS = ("fable-5", "gpt-5.6-sol", "opus-5") +BASE_DISPLAY_NAMES = { + "fable-5": "Fable 5 (Notion)", + "gpt-5.6-sol": "GPT-5.6 Sol (Notion)", + "opus-5": "Opus 5 (Notion)", +} + + +def _alias_from_model_message(message: str) -> str: + return message.strip().lower().replace(" ", "-") + + +def _parse_available_model_details(response: dict[str, Any]) -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + for entry in response.get("models") or []: + if not isinstance(entry, dict) or entry.get("isDisabled"): + continue + message = entry.get("modelMessage") + internal_id = entry.get("model") + if not isinstance(message, str) or not isinstance(internal_id, str): + continue + alias = _alias_from_model_message(message) + if not alias: + continue + details: dict[str, Any] = {"internal_id": internal_id} + display_group = entry.get("displayGroup") + if isinstance(display_group, str) and display_group.strip(): + details["display_group"] = display_group.strip().lower() + model_card_attributes = entry.get("modelCardAttributes") + if isinstance(model_card_attributes, dict): + speed = model_card_attributes.get("speed") + if isinstance(speed, int): + details["speed"] = speed + advertised_tiers: set[str] = set() + for key in ( + "serviceTiers", + "service_tiers", + "supportedServiceTiers", + "supported_service_tiers", + ): + value = entry.get(key) + if not isinstance(value, list): + continue + for tier in value: + tier_id = tier.get("id") if isinstance(tier, dict) else tier + if not isinstance(tier_id, str): + continue + normalized = tier_id.strip().lower() + if normalized == "fast": + normalized = "priority" + if normalized in {"priority", "ultrafast"}: + advertised_tiers.add(normalized) + if advertised_tiers: + details["service_tiers"] = tuple(sorted(advertised_tiers)) + out[alias] = details + return out + + +def _same_model_signature(left: dict[str, Any] | None, right: dict[str, Any]) -> bool: + return ( + isinstance(left, dict) + and left.get("internal_id") == right.get("internal_id") + ) + + +def _fast_group_prefix(alias: str) -> str: + head, _, _tail = alias.rpartition("-") + return head or alias + + +def _display_name(alias: str) -> str: + rendered: list[str] = [] + for word in alias.replace("_", "-").split("-"): + lower = word.lower() + if lower == "gpt": + rendered.append("GPT") + elif lower in {"ai", "oss"}: + rendered.append(lower.upper()) + elif word: + rendered.append(word[:1].upper() + word[1:]) + return " ".join(rendered) + " (Notion)" + + +def _atomic_json_write(path: Path, payload: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text( + json.dumps(payload, indent=2, ensure_ascii=False) + "\n", + encoding="utf-8", + ) + if os.name != "nt": + temporary.chmod(0o600) + os.replace(temporary, path) + + +class VerifiedModelCatalog: + """Expose models authoritatively returned by at least one eligible account. + + New models are often enabled gradually. Requiring every configured account + to report a model hid legitimate rollouts until the slowest account gained + access. Conflicting internal IDs are still rejected, and each client is + annotated with its own advertised aliases so the account pool can route a + selected model only to accounts that actually support it. + """ + + def __init__( + self, + account_home: Path, + base_catalog_path: Path, + *, + base_alias_path: Path | None = None, + base_model_ids: tuple[str, ...] = BASE_MODEL_IDS, + base_display_names: dict[str, str] | None = None, + ) -> None: + self.account_home = account_home + self.alias_path = account_home / "models.json" + self.codex_catalog_path = account_home / "codex-models.json" + self.base_catalog_path = base_catalog_path + self.base_alias_path = base_alias_path + self.base_model_ids = base_model_ids + self.base_display_names = dict(base_display_names or BASE_DISPLAY_NAMES) + self._dynamic_aliases: dict[str, str] = {} + self._verified_model_details: dict[str, dict[str, Any]] = {} + self._lock = asyncio.Lock() + self._status: dict[str, Any] = { + "state": "pending", + "verified_accounts": 0, + "dynamic_models": 0, + "last_success_at": None, + "last_error": None, + } + + def model_ids(self) -> tuple[str, ...]: + dynamic = sorted( + alias for alias in self._dynamic_aliases if alias not in self.base_model_ids + ) + return (*self.base_model_ids, *dynamic) + + def display_name(self, model_id: str) -> str: + return self.base_display_names.get(model_id, _display_name(model_id)) + + def notion_model_for(self, model_id: str) -> str | None: + dynamic = self._dynamic_aliases.get(model_id) + if isinstance(dynamic, str) and dynamic: + return dynamic + verified = self._verified_model_details.get(model_id) + internal_id = verified.get("internal_id") if isinstance(verified, dict) else None + if isinstance(internal_id, str) and internal_id: + return internal_id + base = self._base_aliases().get(model_id) + if isinstance(base, str) and base: + return base + return None + + def model_entries(self) -> list[dict[str, Any]]: + for path in (self.codex_catalog_path, self.base_catalog_path): + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + continue + models = payload.get("models") + if not isinstance(models, list): + continue + entries = [copy.deepcopy(item) for item in models if isinstance(item, dict)] + if entries: + # Generated catalogs can outlive a bridge upgrade. Re-apply the + # currently verified tier capabilities when reading so stale + # metadata cannot keep an unreleased Ultrafast option visible. + for item in entries: + slug = item.get("slug") + if isinstance(slug, str): + self._apply_verified_service_tiers(slug, item) + return entries + return [ + { + "slug": model_id, + "model": model_id, + "display_name": self.display_name(model_id), + "displayName": self.display_name(model_id), + } + for model_id in self.model_ids() + ] + + def status(self) -> dict[str, Any]: + return dict(self._status) + + async def refresh(self, clients: Iterable[Any]) -> bool: + client_list = list(clients) + if not client_list: + self._status.update( + state="no_accounts", verified_accounts=0, last_error="no_accounts" + ) + return False + + async with self._lock: + results = await asyncio.gather( + *(client.fetch_available_models() for client in client_list), + return_exceptions=True, + ) + successful: list[tuple[Any, dict[str, dict[str, Any]]]] = [] + failures = 0 + for client, result in zip(client_list, results, strict=True): + if isinstance(result, BaseException): + failures += 1 + client._notion_available_model_aliases = frozenset() + else: + successful.append((client, _parse_available_model_details(result))) + + if not successful: + self._status.update( + state="degraded", + verified_accounts=0, + last_error="account_refresh_failed", + ) + return False + + parsed = [mapping for _client, mapping in successful] + + verified_details: dict[str, dict[str, Any]] = {} + support_counts: dict[str, int] = {} + candidate_aliases = set().union(*(mapping.keys() for mapping in parsed)) + for alias in candidate_aliases: + advertised = [mapping[alias] for mapping in parsed if alias in mapping] + if not advertised: + continue + # A model may be absent from accounts that have not received the + # rollout yet, but two accounts must never disagree about what a + # friendly alias means. + if all(_same_model_signature(details, advertised[0]) for details in advertised[1:]): + merged = copy.deepcopy(advertised[0]) + service_tiers = sorted( + { + tier + for details in advertised + for tier in details.get("service_tiers", ()) + } + ) + if service_tiers: + merged["service_tiers"] = tuple(service_tiers) + verified_details[alias] = merged + support_counts[alias] = len(advertised) + aliases = { + alias: str(details["internal_id"]) + for alias, details in verified_details.items() + } + aliases_to_write = {**self._base_aliases(), **aliases} + self._verified_model_details = verified_details + self._write_aliases(aliases_to_write) + self._write_codex_catalog(aliases) + self._dynamic_aliases = aliases_to_write + for client, mapping in successful: + client._notion_available_model_aliases = frozenset(mapping) + # The provider caches the per-user alias map. Refreshing the + # verified catalog must invalidate it so newly advertised + # models and internal IDs are used on later requests. + if hasattr(client, "_user_map_cache"): + client._user_map_cache = None + self._status.update( + state="degraded" if failures else "ok", + verified_accounts=len(parsed), + dynamic_models=sum( + alias not in self.base_model_ids for alias in aliases + ), + partially_available_models=sum( + count < len(client_list) for count in support_counts.values() + ), + last_success_at=datetime.now(UTC).isoformat(timespec="seconds"), + last_error="account_refresh_failed" if failures else None, + ) + return failures == 0 + + def fast_model_for(self, model_id: str) -> str | None: + prefix = _fast_group_prefix(model_id) + candidates: list[tuple[int, str]] = [] + for alias, details in self._verified_model_details.items(): + if alias == model_id or details.get("display_group") != "fast": + continue + if not alias.startswith(prefix): + continue + haystack = alias.replace("_", "").replace("-", "").lower() + if "ultrafast" in haystack: + continue + speed = details.get("speed") + candidates.append((speed if isinstance(speed, int) else -1, alias)) + if not candidates: + return None + candidates.sort(key=lambda item: (item[0], item[1]), reverse=True) + return candidates[0][1] + + def tier_model_for(self, model_id: str, service_tier: str | None) -> str | None: + if not isinstance(service_tier, str) or not service_tier.strip(): + return None + tier = service_tier.strip().lower() + if tier in {"priority", "fast", "ultrafast"}: + # Speed tiers must stay on the model the user explicitly selected. + # Verified sibling models such as Luna, Terra, or a future + # "...-ultrafast" alias may still appear as separate explicit model + # choices in the catalog, but choosing a speed tier must not swap the + # model behind the user's back. + return None + return None + + def supports_service_tier(self, model_id: str, service_tier: str | None) -> bool: + if not isinstance(service_tier, str): + return False + tier = service_tier.strip().lower() + if tier == "fast": + tier = "priority" + if tier == "priority": + return True + details = self._verified_model_details.get(model_id) + return ( + tier == "ultrafast" + and isinstance(details, dict) + and tier in details.get("service_tiers", ()) + ) + + def _apply_verified_service_tiers( + self, model_id: str, item: dict[str, Any] + ) -> None: + tiers = item.get("service_tiers") + if isinstance(tiers, list): + tiers = [ + tier + for tier in tiers + if not isinstance(tier, dict) or tier.get("id") != "ultrafast" + ] + if self.supports_service_tier(model_id, "ultrafast"): + tiers.append( + { + "id": "ultrafast", + "name": "Ultrafast", + "description": ( + "Keeps the selected model and requests the provider " + "ultrafast tier verified in live model metadata" + ), + } + ) + item["service_tiers"] = tiers + additional = item.get("additional_speed_tiers") + if isinstance(additional, list): + additional = [tier for tier in additional if tier != "ultrafast"] + if self.supports_service_tier(model_id, "ultrafast"): + additional.append("ultrafast") + item["additional_speed_tiers"] = additional + + def _base_aliases(self) -> dict[str, str]: + if self.base_alias_path is None or not self.base_alias_path.is_file(): + return {} + try: + payload = json.loads(self.base_alias_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return {} + aliases = payload.get("friendly_aliases") + if not isinstance(aliases, dict): + return {} + return { + alias: internal_id + for alias, internal_id in aliases.items() + if alias in self.base_model_ids + and isinstance(internal_id, str) + and internal_id + } + + def _write_aliases(self, aliases: dict[str, str]) -> None: + _atomic_json_write( + self.alias_path, + { + "friendly_aliases": dict(sorted(aliases.items())), + "updated_at": datetime.now(UTC).isoformat(timespec="seconds"), + }, + ) + + def _write_codex_catalog(self, aliases: dict[str, str]) -> None: + base = json.loads(self.base_catalog_path.read_text(encoding="utf-8")) + models = base.get("models") + if not isinstance(models, list): + raise ValueError("base Codex model catalog has no models array") + by_slug = { + item.get("slug"): item for item in models if isinstance(item, dict) + } + for slug, item in by_slug.items(): + if isinstance(slug, str): + self._apply_verified_service_tiers(slug, item) + next_priority = max( + (int(item.get("priority", 0)) for item in models if isinstance(item, dict)), + default=0, + ) + 1 + for alias in sorted(aliases): + if alias in self.base_model_ids or alias in by_slug: + continue + if alias.startswith("gpt-"): + template_slug = "gpt-5.6-sol" + elif "opus" in alias: + template_slug = "opus-5" + else: + template_slug = "gpt-5.5" + template = by_slug.get(template_slug) + if not isinstance(template, dict): + continue + item = copy.deepcopy(template) + name = _display_name(alias) + item.update( + slug=alias, + model=alias, + display_name=name, + displayName=name, + description=( + f"Notion {name.removesuffix(' (Notion)')} through the local bridge." + ), + priority=next_priority, + ) + next_priority += 1 + details = self._verified_model_details.get(alias, {}) + keep_speed_tiers = alias.startswith("gpt-") or details.get("display_group") == "fast" + if not keep_speed_tiers: + item.pop("additional_speed_tiers", None) + item.pop("service_tiers", None) + else: + self._apply_verified_service_tiers(alias, item) + models.append(item) + _atomic_json_write(self.codex_catalog_path, base) diff --git a/bridge/notion_images.py b/bridge/notion_images.py index 0762fff..3f74fc3 100644 --- a/bridge/notion_images.py +++ b/bridge/notion_images.py @@ -310,6 +310,8 @@ async def complete_with_images( workspace_search: bool = False, ask_mode: bool = True, thread_id: str | None = None, + reasoning_effort: str | None = None, + service_tier: str | None = None, on_thinking_delta_async: Callable[[str], Awaitable[None]] | None = None, ) -> ChatResponse: """Complete a request with native images and optional thinking deltas. @@ -326,6 +328,8 @@ async def complete_with_images( workspace_search=workspace_search, ask_mode=ask_mode, thread_id=thread_id, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ) prep = notion._prepare_call( prompt=prompt, @@ -336,6 +340,8 @@ async def complete_with_images( ask_mode=ask_mode, thread_id=thread_id, workflow_id=None, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ) if images: attachments = [ diff --git a/bridge/server.py b/bridge/server.py index f3aa4d9..89e5f9a 100644 --- a/bridge/server.py +++ b/bridge/server.py @@ -19,9 +19,11 @@ from account_pool import ( MAX_REASONING_EFFORT, + SUPPORTED_REASONING_EFFORTS, AccountLease, AccountPoolCoolingDown, AccountPoolExhausted, + ModelIntegrityError, NotionAccountPool, build_account_pool, ) @@ -43,6 +45,7 @@ estimated_image_tokens, extract_response_images, ) +from model_catalog import BASE_DISPLAY_NAMES, BASE_MODEL_IDS, VerifiedModelCatalog from turn_affinity import ( TurnAffinityStore, codex_conversation_key, @@ -56,15 +59,27 @@ PROJECT_ROOT = Path(__file__).resolve().parents[1] ACCOUNT_HOME = Path(os.getenv("NOTION_AGENT_HOME", str(Path.home() / ".notionagents"))).expanduser() MODEL_ID = "opus-5" -SUPPORTED_MODELS = ("fable-5", "gpt-5.6-sol", "opus-5") -MODEL_DISPLAY_NAMES = { - "fable-5": "Fable 5 (Notion)", - "gpt-5.6-sol": "GPT-5.6 Sol (Notion)", - "opus-5": "Opus 5 (Notion)", -} +SUPPORTED_MODELS = BASE_MODEL_IDS +MODEL_DISPLAY_NAMES = BASE_DISPLAY_NAMES CODEX_FABLE_MODEL_ID = "gpt-5.5" FORCED_MODEL_ID = os.getenv("NOTION_FORCE_MODEL", "").strip().lower() REASONING_HEARTBEAT_SECONDS = 10 +MODEL_REFRESH_SECONDS = max( + 30.0, + float(os.getenv("NOTION_MODEL_REFRESH_SECONDS", "60")), +) +# The Notion provider retains the full server-side thread even when the bridge +# sends only incremental events. Roll over before that retained context grows +# near Codex's 210k-token window. The fresh segment receives a bounded recent +# transcript; normal Codex compaction summaries remain preferred when present. +SEGMENT_ROLLOVER_INPUT_TOKENS = max( + 12_000, + int(os.getenv("NOTION_SEGMENT_ROLLOVER_INPUT_TOKENS", "120000")), +) +SEGMENT_ROLLOVER_PROMPT_CHARS = max( + 4_000, + int(os.getenv("NOTION_SEGMENT_ROLLOVER_PROMPT_CHARS", "48000")), +) WORKFLOW_ID = os.getenv("NOTION_WORKFLOW_ID", "") RUNTIME_ENV = Path(os.getenv("NOTION_RUNTIME_ENV", str(PROJECT_ROOT / "runtime" / ".env"))).expanduser() CODE_ROOT = Path(os.getenv("CODE_ROOT", str(Path.home()))).expanduser().resolve() @@ -86,6 +101,100 @@ def _build_explicit_model_config(*args: Any, **kwargs: Any) -> dict[str, Any]: turn_affinities = TurnAffinityStore() conversation_segments = ConversationSegmentStore(ACCOUNT_HOME / "conversation-state.json") log = logging.getLogger("uvicorn.error.notion_bridge") +model_catalog = VerifiedModelCatalog( + ACCOUNT_HOME, + PROJECT_ROOT / "config" / "codex-models.json", + base_alias_path=PROJECT_ROOT / "state-template" / ".notionagents" / "models.json", +) +model_refresh_task: asyncio.Task[None] | None = None + +def validate_selected_model( + result: Any, + *, + requested_model: str, + resolved_model: str, + reused_thread: bool, +) -> Any: + """Reject provider-side model substitution before the lease records success.""" + raw = getattr(result, "raw", None) + reported = raw.get("reported_notion_model") if isinstance(raw, dict) else None + actual = getattr(result, "model", None) or reported + actual = actual if isinstance(actual, str) and actual else None + expected = model_catalog.notion_model_for(resolved_model) + log_event( + log, + "notion_model_selected", + resolved_model=resolved_model, + notion_model=getattr(result, "model", None), + reported_notion_model=reported, + ) + if isinstance(expected, str) and expected and actual and actual != expected: + log_event( + log, + "notion_model_mismatch", + level=logging.ERROR, + requested_model=requested_model, + resolved_model=resolved_model, + expected_notion_model=expected, + actual_notion_model=actual, + reused_thread=reused_thread, + notion_thread_id=( + correlation_id(result.thread_id) + if getattr(result, "thread_id", None) + else None + ), + ) + raise ModelIntegrityError( + f'Explicit model "{resolved_model}" resolved to unexpected Notion model ' + f'"{actual}" (expected "{expected}")', + requested_model=resolved_model, + ) + return result + + +async def complete_selected_model( + notion: NotionAgentClient, + *, + requested_model: str, + resolved_model: str, + **kwargs: Any, +) -> Any: + """Run one provider completion and reject silent model substitution.""" + result = await notion.complete(**kwargs) + return validate_selected_model( + result, + requested_model=requested_model, + resolved_model=resolved_model, + reused_thread=bool(kwargs.get("thread_id")), + ) + +async def refresh_model_catalog_forever() -> None: + while True: + refresh_started_at = time.monotonic() + try: + clients = await account_pool.eligible_clients() if account_pool is not None else () + refreshed = await model_catalog.refresh(clients) + status = model_catalog.status() + log_event( + log, + "model_catalog_refreshed" if refreshed else "model_catalog_refresh_degraded", + level=logging.INFO if refreshed else logging.WARNING, + state=status["state"], + verified_accounts=status["verified_accounts"], + dynamic_models=status["dynamic_models"], + duration_ms=round((time.monotonic() - refresh_started_at) * 1000), + ) + except asyncio.CancelledError: + raise + except Exception as error: + log_event( + log, + "model_catalog_refresh_failed", + level=logging.WARNING, + error_type=type(error).__name__, + duration_ms=round((time.monotonic() - refresh_started_at) * 1000), + ) + await asyncio.sleep(MODEL_REFRESH_SECONDS) @app.middleware("http") @@ -304,16 +413,20 @@ async def complete_agent( system: str | None = None, planner_mode: bool = False, model_id: str = MODEL_ID, + reasoning_effort: str = MAX_REASONING_EFFORT, + service_tier: str | None = None, ): if planner_mode and not WORKFLOW_ID: first_prompt = planner_prompt(prompt, system) response = await lease.run( - lambda notion: notion.complete( + lambda notion: complete_selected_model(notion, requested_model=model_id, resolved_model=model_id, prompt=first_prompt, model=model_id, web_search=False, workspace_search=False, ask_mode=True, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ) ) completed_actions: list[str] = [] @@ -349,25 +462,29 @@ async def complete_agent( ) thread_id = response.thread_id response = await lease.run( - lambda notion: notion.complete( + lambda notion: complete_selected_model(notion, requested_model=model_id, resolved_model=model_id, prompt=continuation_prompt, model=model_id, web_search=False, workspace_search=False, ask_mode=True, thread_id=thread_id, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ), - retry_operation=lambda notion: notion.complete( + retry_operation=lambda notion: complete_selected_model(notion, requested_model=model_id, resolved_model=model_id, prompt=planner_prompt(recovery_task, system), model=model_id, web_search=False, workspace_search=False, ask_mode=True, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ), ) raise RuntimeError("The planner exceeded the maximum action-loop depth") response = await lease.run( - lambda notion: notion.complete( + lambda notion: complete_selected_model(notion, requested_model=model_id, resolved_model=model_id, prompt=prompt, system=system, model=model_id, @@ -375,6 +492,8 @@ async def complete_agent( workspace_search=True, ask_mode=not bool(WORKFLOW_ID), workflow_id=WORKFLOW_ID or None, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ) ) if not WORKFLOW_ID: @@ -403,14 +522,16 @@ async def complete_agent( ) thread_id = response.thread_id response = await lease.run( - lambda notion: notion.complete( + lambda notion: complete_selected_model(notion, requested_model=model_id, resolved_model=model_id, prompt=continuation_prompt, model=model_id, ask_mode=False, workflow_id=WORKFLOW_ID, thread_id=thread_id, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ), - retry_operation=lambda notion: notion.complete( + retry_operation=lambda notion: complete_selected_model(notion, requested_model=model_id, resolved_model=model_id, prompt=recovery_prompt, system=system, model=model_id, @@ -418,6 +539,8 @@ async def complete_agent( workspace_search=True, ask_mode=False, workflow_id=WORKFLOW_ID, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ), ) raise RuntimeError("The agent exceeded the maximum tool-call loop depth") @@ -425,8 +548,9 @@ async def complete_agent( @app.on_event("startup") async def startup() -> None: - global account_pool + global account_pool, model_refresh_task account_pool = build_account_pool(ACCOUNT_HOME) + restored = await account_pool.revalidate_stale_disabled_accounts() status = await account_pool.status() log_event( log, @@ -436,11 +560,21 @@ async def startup() -> None: invalid=status["invalid"], duplicates=status["duplicates"], maximum=status["maximum"], + restored_stale_accounts=restored, ) + model_refresh_task = asyncio.create_task(refresh_model_catalog_forever()) @app.on_event("shutdown") async def shutdown() -> None: + global model_refresh_task + if model_refresh_task is not None: + model_refresh_task.cancel() + try: + await model_refresh_task + except asyncio.CancelledError: + pass + model_refresh_task = None if account_pool is not None: await account_pool.aclose() @@ -461,15 +595,43 @@ def text_content(value: Any) -> str: return str(value or "") +def request_reasoning_effort(body: dict[str, Any]) -> str: + reasoning = body.get("reasoning") + candidate = reasoning.get("effort") if isinstance(reasoning, dict) else None + if candidate is None: + candidate = body.get("reasoning_effort", body.get("effort")) + if isinstance(candidate, str) and candidate.strip(): + normalized = candidate.strip().lower() + if normalized not in SUPPORTED_REASONING_EFFORTS: + raise ValueError(f"unsupported reasoning effort: {candidate}") + return normalized + return MAX_REASONING_EFFORT + + +def request_service_tier(body: dict[str, Any]) -> str | None: + candidate = body.get("service_tier", body.get("serviceTier")) + if isinstance(candidate, str) and candidate.strip(): + normalized = candidate.strip().lower() + if normalized in {"default", "standard"}: + return None + if normalized == "fast": + return "priority" + if normalized in {"priority", "ultrafast"}: + return normalized + raise ValueError(f"unsupported service tier: {candidate}") + return None + + def resolve_model(model: str | None) -> str: requested = (model or MODEL_ID).lower() + supported_models = model_catalog.model_ids() if FORCED_MODEL_ID: - if FORCED_MODEL_ID not in SUPPORTED_MODELS: + if FORCED_MODEL_ID not in supported_models: raise ValueError(f"unsupported forced model: {FORCED_MODEL_ID}") return FORCED_MODEL_ID if requested == CODEX_FABLE_MODEL_ID: return "fable-5" - if requested in SUPPORTED_MODELS: + if requested in supported_models: return requested if requested in {"opus", "best"} or "opus" in requested: return "opus-5" @@ -480,6 +642,21 @@ def resolve_model(model: str | None) -> str: raise ValueError(f"unsupported model: {model}") +def resolve_requested_model(model: str | None, service_tier: str | None) -> str: + resolved = resolve_model(model) + if service_tier == "ultrafast" and not model_catalog.supports_service_tier( + resolved, service_tier + ): + raise ValueError( + "ultrafast is not currently advertised for the selected model; " + "it will be enabled automatically after live model metadata exposes it" + ) + tier_variant = model_catalog.tier_model_for(resolved, service_tier) + if tier_variant: + return tier_variant + return resolved + + def anthropic_system_text(value: Any) -> str: if isinstance(value, str): return value @@ -707,6 +884,45 @@ def responses_planner_prompt(body: dict[str, Any]) -> str: {conversation}""" +def responses_rollover_prompt(body: dict[str, Any]) -> str: + """Build a bounded fresh-segment prompt without replaying old tool logs. + + The retained Notion thread is intentionally abandoned at the segment + threshold. Keep the newest events (including a Codex compaction summary + when one is present), while bounding any individual oversized event too. + """ + request_input = body.get("input", []) + if isinstance(request_input, str): + request_input = [{"type": "message", "role": "user", "content": request_input}] + if not isinstance(request_input, list): + request_input = [] + remaining = SEGMENT_ROLLOVER_PROMPT_CHARS + selected: list[dict[str, Any]] = [] + for item in reversed(request_input): + if not isinstance(item, dict): + continue + rendered = responses_message_text(item) + if not rendered: + continue + if len(rendered) > remaining: + if not selected: + selected.append({"type": "message", "role": "user", "content": rendered[-remaining:]}) + break + selected.append(item) + remaining -= len(rendered) + if remaining <= 0: + break + selected.reverse() + bounded_body = {**body, "input": selected} + return ( + "This is a fresh provider conversation segment. Earlier provider-side " + "history was deliberately rolled over to keep latency and context bounded. " + "Use the retained recent events below; if a compaction checkpoint is present, " + "treat it as the authoritative handoff. Do not claim access to omitted history.\n\n" + + responses_planner_prompt(bounded_body) + ) + + def responses_incremental_body( body: dict[str, Any], previous_input_count: int, @@ -1469,7 +1685,8 @@ async def healthz() -> dict[str, Any]: return { "ok": pool_status["configured"] > 0, "model": MODEL_ID, - "models": list(SUPPORTED_MODELS), + "models": list(model_catalog.model_ids()), + "model_refresh": model_catalog.status(), "reasoning_effort": MAX_REASONING_EFFORT, "account_pool": pool_status, "turn_affinity": await turn_affinities.status(), @@ -1481,23 +1698,44 @@ async def healthz() -> dict[str, Any]: @app.get("/v1/models") async def models() -> dict[str, Any]: + supported_models = set(model_catalog.model_ids()) + now = int(time.time()) + data: list[dict[str, Any]] = [] + for item in model_catalog.model_entries(): + model_id = item.get("model") or item.get("id") or item.get("slug") + if not isinstance(model_id, str) or model_id not in supported_models: + continue + entry = dict(item) + display_name = entry.get("displayName") or entry.get("display_name") or model_catalog.display_name(model_id) + entry["id"] = model_id + entry.setdefault("object", "model") + entry.setdefault("type", "model") + entry["display_name"] = str(display_name) + entry["displayName"] = str(display_name) + entry.setdefault("created", now) + entry.setdefault("created_at", "2026-01-01T00:00:00Z") + entry.setdefault("owned_by", "notion") + data.append(entry) + if not data: + for model_id in model_catalog.model_ids(): + data.append( + { + "id": model_id, + "object": "model", + "type": "model", + "display_name": model_catalog.display_name(model_id), + "displayName": model_catalog.display_name(model_id), + "created": now, + "created_at": "2026-01-01T00:00:00Z", + "owned_by": "notion", + } + ) return { "object": "list", - "data": [ - { - "id": model_id, - "object": "model", - "type": "model", - "display_name": MODEL_DISPLAY_NAMES[model_id], - "created": int(time.time()), - "created_at": "2026-01-01T00:00:00Z", - "owned_by": "notion", - } - for model_id in SUPPORTED_MODELS - ], + "data": data, "has_more": False, - "first_id": SUPPORTED_MODELS[0], - "last_id": SUPPORTED_MODELS[-1], + "first_id": data[0]["id"], + "last_id": data[-1]["id"], } @@ -1550,12 +1788,15 @@ async def handle_openai_responses( on_thinking_delta_async: Callable[[str], Awaitable[None]] | None = None, response_id: str | None = None, ): + bridge_started_at = time.monotonic() conversation_key = conversation_key or codex_conversation_key(body) request_kind = request_kind or codex_request_kind(body) is_compaction = request_kind == "compaction" requested_model = str(body.get("model") or MODEL_ID).lower() try: - model = resolve_model(requested_model) + service_tier = request_service_tier(body) + model = resolve_requested_model(requested_model, service_tier) + reasoning_effort = request_reasoning_effort(body) except ValueError as exc: return JSONResponse({"error": {"message": str(exc), "type": "invalid_request_error"}}, status_code=400) log_event( @@ -1567,6 +1808,12 @@ async def handle_openai_responses( ) if account_pool is None or account_pool.size == 0: return JSONResponse({"error": {"message": "No valid Notion accounts are configured", "type": "api_error"}}, status_code=503) + log_event( + log, + "request_execution_settings", + reasoning_effort=reasoning_effort, + service_tier=service_tier, + ) raw_tools = body.get("tools") or [] tools = [] if is_compaction else responses_tool_catalog(raw_tools) web_search_requested = any( @@ -1603,12 +1850,20 @@ async def handle_openai_responses( rollover_reason = "model_changed" elif segment is not None and segment_prefix is None: rollover_reason = "history_rewritten" + elif ( + segment is not None + and not is_compaction + and segment.input_tokens >= SEGMENT_ROLLOVER_INPUT_TOKENS + ): + rollover_reason = "provider_context_limit" log_event( log, "conversation_segment_checked", state="new" if segment is None else "rollover" if rollover_reason else "continued", segment_index=segment.segment_index if segment is not None else 0, rollover_reason=rollover_reason, + retained_input_tokens=segment.input_tokens if segment is not None else 0, + rollover_input_token_limit=SEGMENT_ROLLOVER_INPUT_TOKENS, preferred_account_id=( segment.account_id if segment is not None and rollover_reason is None else None ), @@ -1658,6 +1913,8 @@ async def cached_stream(): responses_compaction_prompt(body, continuing=False) if is_compaction else responses_planner_prompt(body) ) + if rollover_reason == "provider_context_limit": + full_prompt = responses_rollover_prompt(body) incremental_prompt = None if anchor is not None: if is_compaction: @@ -1686,12 +1943,21 @@ async def cached_stream(): log_event( log, "responses_context", - mode="continuation" if incremental_prompt is not None else "full", + mode=( + "continuation" if incremental_prompt is not None else + "bounded_rollover" if rollover_reason == "provider_context_limit" else + "full" + ), input_items=response_input_count(body), delta_items=(response_input_count(incremental_body) if incremental_body else 0), image_count=len(active_images), image_bytes=sum(len(image.data) for image in active_images), estimated_prompt_tokens=max(1, len(active_prompt) // 4) + estimated_image_tokens(active_images), + rollover_prompt_char_limit=( + SEGMENT_ROLLOVER_PROMPT_CHARS + if rollover_reason == "provider_context_limit" else None + ), + bridge_context_prepare_ms=round((time.monotonic() - bridge_started_at) * 1000), ) async def initial_completion(notion: NotionAgentClient): @@ -1708,6 +1974,8 @@ async def initial_completion(notion: NotionAgentClient): workspace_search=False, ask_mode=True, on_thinking_delta_async=on_thinking_delta_async, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ) return await notion.complete( prompt=full_prompt, @@ -1715,6 +1983,8 @@ async def initial_completion(notion: NotionAgentClient): web_search=web_search_requested, workspace_search=False, ask_mode=True, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ) async def continuation_completion(notion: NotionAgentClient): @@ -1731,6 +2001,8 @@ async def continuation_completion(notion: NotionAgentClient): ask_mode=True, thread_id=anchor.notion_thread_id, on_thinking_delta_async=on_thinking_delta_async, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ) return await notion.complete( prompt=incremental_prompt, @@ -1739,38 +2011,77 @@ async def continuation_completion(notion: NotionAgentClient): workspace_search=False, ask_mode=True, thread_id=anchor.notion_thread_id, + reasoning_effort=reasoning_effort, + service_tier=service_tier, + ) + + async def checked_initial_completion(notion: NotionAgentClient): + return validate_selected_model( + await initial_completion(notion), + requested_model=requested_model, + resolved_model=model, + reused_thread=False, ) + async def checked_continuation_completion(notion: NotionAgentClient): + return validate_selected_model( + await continuation_completion(notion), + requested_model=requested_model, + resolved_model=model, + reused_thread=True, + ) + lease_options: dict[str, str] = { + "service_tier": service_tier, + "reasoning_effort": reasoning_effort, + "required_model": model, + } + if anchor is not None and (affinity_matches_model or is_compaction): + # Tool-loop calls inside one Codex turn and compaction must stay on the + # same Notion thread. Rotating here would break an in-flight tool loop. + lease_options["preferred_account_id"] = anchor.account_id + # New user turns deliberately have no account preference. The pool can + # therefore choose the lowest-latency healthy account instead of forcing a + # round-robin hop to a slower account. Same-turn tool calls and compaction + # remain pinned above, while ordinary failures still fail over immediately. try: - async with account_pool.lease( - preferred_account_id=(anchor.account_id if anchor is not None else None), - ) as lease: + inference_started_at = time.monotonic() + async with account_pool.lease(**lease_options) as lease: can_continue = ( anchor is not None and incremental_prompt is not None and lease.account_id == anchor.account_id ) completion = await lease.run( - continuation_completion if can_continue else initial_completion, - retry_operation=initial_completion, + checked_continuation_completion if can_continue else checked_initial_completion, + retry_operation=checked_initial_completion, ) log_event( log, - "notion_model_selected", - resolved_model=model, - notion_model=getattr(completion, "model", None), - reported_notion_model=( - completion.raw.get("reported_notion_model") - if isinstance(getattr(completion, "raw", None), dict) - else None - ), + "notion_inference_completed", + account_id=lease.account_id, + duration_ms=round((time.monotonic() - inference_started_at) * 1000), + retries_bounded=True, ) for correction_attempt in range(3): valid_call = extract_responses_tool_call(completion.text, tools) malformed_tool = extract_malformed_responses_tool(completion.text, tools) unavailable_tool = extract_unavailable_responses_tool(completion.text, tools) - needs_correction = ( + # Speed optimization: avoid extra correction round-trips for vague refusals, + # but keep the correction loop for the specific case we care about: + # when tools are available and the model incorrectly claims it cannot use them. + refusal_about_tools = ( looks_like_agent_refusal(completion.text) + and isinstance(tools, list) + and len(tools) > 0 + and ( + "don't have access" in completion.text.lower() + or "do not have access" in completion.text.lower() + or "can't access" in completion.text.lower() + or "cannot access" in completion.text.lower() + ) + ) + needs_correction = ( + refusal_about_tools or malformed_tool is not None or unavailable_tool is not None ) @@ -1815,6 +2126,8 @@ async def continuation_completion(notion: NotionAgentClient): ask_mode=True, thread_id=thread_id, on_thinking_delta_async=on_thinking_delta_async, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ), retry_operation=initial_completion, ) @@ -1939,7 +2252,9 @@ async def handle_openai_compaction( ): requested_model = str(body.get("model") or MODEL_ID).lower() try: - model = resolve_model(requested_model) + service_tier = request_service_tier(body) + model = resolve_requested_model(requested_model, service_tier) + reasoning_effort = request_reasoning_effort(body) except ValueError as exc: return JSONResponse( {"error": {"message": str(exc), "type": "invalid_request_error"}}, @@ -1950,6 +2265,12 @@ async def handle_openai_compaction( {"error": {"message": "No valid Notion accounts are configured", "type": "api_error"}}, status_code=503, ) + log_event( + log, + "request_execution_settings", + service_tier=service_tier, + reasoning_effort=reasoning_effort, + ) input_fingerprint = response_input_fingerprint(body) affinity = await turn_affinities.get(turn_key) if ( @@ -1990,29 +2311,36 @@ async def handle_openai_compaction( ) async def initial_completion(notion: NotionAgentClient): - return await notion.complete( + return await complete_selected_model(notion, requested_model=requested_model, resolved_model=model, prompt=responses_compaction_prompt(body, continuing=False), model=model, web_search=False, workspace_search=False, ask_mode=True, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ) async def continuation_completion(notion: NotionAgentClient): if segment is None: return await initial_completion(notion) - return await notion.complete( + return await complete_selected_model(notion, requested_model=requested_model, resolved_model=model, prompt=prompt, model=model, web_search=False, workspace_search=False, ask_mode=True, thread_id=segment.notion_thread_id, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ) try: async with account_pool.lease( preferred_account_id=segment.account_id if continuing else None, + service_tier=service_tier, + reasoning_effort=reasoning_effort, + required_model=model, ) as lease: can_continue = continuing and segment is not None and lease.account_id == segment.account_id completion = await lease.run( @@ -2078,18 +2406,22 @@ async def anthropic_messages(request: Request): body = await request.json() requested_model = str(body.get("model") or MODEL_ID).lower() set_log_context(model=requested_model, stream=bool(body.get("stream", False))) - log_event( - log, - "request_details", - tool_count=len(body.get("tools") or []) if isinstance(body.get("tools") or [], list) else 0, - ) try: - model = resolve_model(requested_model) + service_tier = request_service_tier(body) + reasoning_effort = request_reasoning_effort(body) + model = resolve_requested_model(requested_model, service_tier) except ValueError as exc: return JSONResponse( {"type": "error", "error": {"type": "invalid_request_error", "message": str(exc)}}, status_code=400, ) + log_event( + log, + "request_details", + tool_count=len(body.get("tools") or []) if isinstance(body.get("tools") or [], list) else 0, + reasoning_effort=reasoning_effort, + service_tier=service_tier, + ) if account_pool is None or account_pool.size == 0: return JSONResponse( {"type": "error", "error": {"type": "api_error", "message": "No valid Notion accounts are configured"}}, @@ -2098,16 +2430,22 @@ async def anthropic_messages(request: Request): prompt = anthropic_planner_prompt(body) async def initial_completion(notion: NotionAgentClient): - return await notion.complete( + return await complete_selected_model(notion, requested_model=requested_model, resolved_model=model, prompt=prompt, model=model, web_search=False, workspace_search=False, ask_mode=True, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ) try: - async with account_pool.lease() as lease: + async with account_pool.lease( + service_tier=service_tier, + reasoning_effort=reasoning_effort, + required_model=model, + ) as lease: response = await lease.run(initial_completion) tools = body.get("tools") or [] if ( @@ -2117,7 +2455,7 @@ async def initial_completion(notion: NotionAgentClient): ): thread_id = response.thread_id response = await lease.run( - lambda notion: notion.complete( + lambda notion: complete_selected_model(notion, requested_model=requested_model, resolved_model=model, prompt=( "Your previous answer was not a valid planner recommendation. " "The local operator and the listed tools are available outside the model. " @@ -2131,6 +2469,8 @@ async def initial_completion(notion: NotionAgentClient): workspace_search=False, ask_mode=True, thread_id=thread_id, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ), retry_operation=initial_completion, ) @@ -2171,15 +2511,19 @@ async def completions(request: Request): system, prompt = build_prompt(messages, tools) requested_model = str(body.get("model") or MODEL_ID).lower() set_log_context(model=requested_model, stream=bool(body.get("stream", False))) + try: + reasoning_effort = request_reasoning_effort(body) + service_tier = request_service_tier(body) + model = resolve_requested_model(requested_model, service_tier) + except ValueError as exc: + return JSONResponse({"error": {"message": str(exc)}}, status_code=400) log_event( log, "request_details", tool_count=len(tools) if isinstance(tools, list) else 0, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ) - try: - model = resolve_model(requested_model) - except ValueError as exc: - return JSONResponse({"error": {"message": str(exc)}}, status_code=400) stream = bool(body.get("stream")) planner_mode = bool(tools) and not WORKFLOW_ID @@ -2190,13 +2534,19 @@ async def completions(request: Request): if not stream: try: - async with account_pool.lease() as lease: + async with account_pool.lease( + service_tier=service_tier, + reasoning_effort=reasoning_effort, + required_model=model, + ) as lease: response = await complete_agent( lease, prompt, system, planner_mode=planner_mode, model_id=model, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ) except Exception as exc: log_event( @@ -2259,7 +2609,11 @@ async def completions(request: Request): async def run() -> None: try: - async with account_pool.lease() as lease: + async with account_pool.lease( + service_tier=service_tier, + reasoning_effort=reasoning_effort, + required_model=model, + ) as lease: if WORKFLOW_ID or planner_mode: response = await complete_agent( lease, @@ -2267,16 +2621,20 @@ async def run() -> None: system, planner_mode=planner_mode, model_id=model, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ) else: response = await lease.run( - lambda notion: notion.complete( + lambda notion: complete_selected_model(notion, requested_model=requested_model, resolved_model=model, prompt=prompt, system=system, model=model, web_search=False, workspace_search=True, ask_mode=True, + reasoning_effort=reasoning_effort, + service_tier=service_tier, ) ) full_text.append(response.text) diff --git a/bridge/tests/test_account_pool.py b/bridge/tests/test_account_pool.py index bde2ee4..6929d3b 100644 --- a/bridge/tests/test_account_pool.py +++ b/bridge/tests/test_account_pool.py @@ -5,15 +5,21 @@ import tempfile import time import unittest +from dataclasses import dataclass from pathlib import Path -from unittest.mock import patch +from types import SimpleNamespace +from unittest.mock import AsyncMock, patch +import httpx from notion_agent_cli.exceptions import ErrorCode, NotionAgentError +import account_pool from account_pool import ( MAX_REASONING_EFFORT, + UNHEALTHY_ACCOUNT_COOLDOWN, AccountPoolExhausted, NotionAccountPool, + MaxEffortNotionAgentClient, build_account_pool, discover_account_paths, ) @@ -28,7 +34,184 @@ async def aclose(self) -> None: self.closed = True +class RevalidationClient(FakeClient): + def __init__(self, name: str, result: object | Exception) -> None: + super().__init__(name) + self.result = result + self.calls: list[dict[str, object]] = [] + + async def complete(self, **kwargs: object) -> object: + self.calls.append(kwargs) + if isinstance(self.result, Exception): + raise self.result + return self.result + + +@dataclass +class FakeAccount: + client_version: str + + class AccountPoolTests(unittest.IsolatedAsyncioTestCase): + async def test_required_model_routes_only_to_an_account_that_advertised_it(self) -> None: + old = FakeClient("old") + future = FakeClient("future") + old._notion_available_model_aliases = frozenset({"gpt-5.6-sol"}) + future._notion_available_model_aliases = frozenset({"gpt-5.6-sol", "gpt-6.0-pro"}) + pool = NotionAccountPool([old, future], account_ids=["old", "future"]) + + async with pool.lease(required_model="gpt-6.0-pro") as lease: + self.assertEqual(lease.account_id, "future") + + async def test_pre_refresh_pool_does_not_reject_a_selected_model(self) -> None: + pool = NotionAccountPool([FakeClient("one")], account_ids=["one"]) + async with pool.lease(required_model="gpt-6.0-pro") as lease: + self.assertEqual(lease.account_id, "one") + + def test_prepare_call_writes_request_reasoning_effort(self) -> None: + client = object.__new__(MaxEffortNotionAgentClient) + prepared = SimpleNamespace( + body={"transcript": [{"type": "config", "value": {}}]}, + ) + with patch.object( + account_pool.NotionAgentClient, + "_prepare_call", + return_value=prepared, + ): + result = client._prepare_call( + reasoning_effort="max", + service_tier="PRIORITY", + ) + + self.assertIs(result, prepared) + self.assertEqual( + prepared.body["transcript"][0]["value"]["reasoningEffort"], + "max", + ) + self.assertEqual( + prepared.body["transcript"][0]["value"]["serviceTier"], + "priority", + ) + + def test_prepare_call_invalid_or_missing_effort_falls_back_safely(self) -> None: + client = object.__new__(MaxEffortNotionAgentClient) + for effort in (None, "unsupported", ""): + prepared = SimpleNamespace( + body={"transcript": [{"type": "config", "value": {}}]}, + ) + with patch.object( + account_pool.NotionAgentClient, + "_prepare_call", + return_value=prepared, + ): + kwargs = {} if effort is None else {"reasoning_effort": effort} + client._prepare_call(**kwargs) + self.assertEqual( + prepared.body["transcript"][0]["value"]["reasoningEffort"], + MAX_REASONING_EFFORT, + ) + + async def test_concurrent_request_efforts_do_not_leak(self) -> None: + client = object.__new__(MaxEffortNotionAgentClient) + client._client_version_checked_at = time.monotonic() + entered = 0 + both_entered = asyncio.Event() + + async def fake_complete(_client, *args, **kwargs): + nonlocal entered + entered += 1 + if entered == 2: + both_entered.set() + await asyncio.wait_for(both_entered.wait(), timeout=1) + await asyncio.sleep(0) + return account_pool._REQUEST_REASONING_EFFORT.get() + + with patch.object( + account_pool.NotionAgentClient, + "complete", + new=fake_complete, + ): + low, maximum = await asyncio.gather( + client.complete(reasoning_effort="low"), + client.complete(reasoning_effort="max"), + ) + + self.assertEqual((low, maximum), ("low", "max")) + self.assertIsNone(account_pool._REQUEST_REASONING_EFFORT.get()) + + async def test_empty_patch_response_does_not_use_model_substituting_legacy_mode(self) -> None: + client = MaxEffortNotionAgentClient( + None, + account=FakeAccount(client_version="23.13.20260729.0607"), + ) + client._client_version_checked_at = time.monotonic() + modes = [] + + async def fake_complete(current, *args, **kwargs): + modes.append((current.as_patch_response, account_pool._REQUEST_REASONING_EFFORT.get())) + raise NotionAgentError("empty patch response", code=ErrorCode.EMPTY_TEXT) + + with patch.object(account_pool.NotionAgentClient, "complete", new=fake_complete): + with self.assertRaises(NotionAgentError): + await client.complete(reasoning_effort="high") + + self.assertEqual(modes, [(True, "high")]) + self.assertIsNone(account_pool._REQUEST_REASONING_EFFORT.get()) + await client.aclose() + + async def test_non_empty_error_does_not_use_legacy_mode(self) -> None: + client = MaxEffortNotionAgentClient( + None, + account=FakeAccount(client_version="23.13.20260729.0607"), + ) + client._client_version_checked_at = time.monotonic() + modes = [] + + async def fake_complete(current, *args, **kwargs): + modes.append(current.as_patch_response) + raise NotionAgentError("HTTP 403", code=ErrorCode.HTTP_ERROR) + + with patch.object(account_pool.NotionAgentClient, "complete", new=fake_complete): + with self.assertRaises(NotionAgentError): + await client.complete(reasoning_effort="low") + + self.assertEqual(modes, [True]) + await client.aclose() + + async def test_explicit_legacy_client_is_not_retried(self) -> None: + client = MaxEffortNotionAgentClient( + None, + account=FakeAccount(client_version="23.13.20260729.0607"), + as_patch_response=False, + ) + client._client_version_checked_at = time.monotonic() + modes = [] + + async def fake_complete(current, *args, **kwargs): + modes.append(current.as_patch_response) + raise NotionAgentError("empty response", code=ErrorCode.EMPTY_TEXT) + + with patch.object(account_pool.NotionAgentClient, "complete", new=fake_complete): + with self.assertRaises(NotionAgentError): + await client.complete(reasoning_effort="max") + + self.assertEqual(modes, [False]) + await client.aclose() + + async def test_refreshes_stale_client_version_before_inference(self) -> None: + client = MaxEffortNotionAgentClient( + None, + account=FakeAccount(client_version="23.13.20260101.0000"), + ) + with patch( + "account_pool.fetch_live_client_version", + new=AsyncMock(return_value="23.13.20260724.2104"), + ): + await client._refresh_client_version_if_needed() + + self.assertEqual(client.load_account().client_version, "23.13.20260724.2104") + await client.aclose() + async def test_times_out_runaway_inference_and_releases_account(self) -> None: pool = NotionAccountPool([FakeClient("one")], account_ids=["one"]) @@ -193,6 +376,19 @@ async def test_cooldown_account_is_skipped(self) -> None: async with pool.lease() as lease: self.assertEqual(lease.account_id, "two") + async def test_new_turn_avoidance_rotates_but_keeps_a_ready_fallback(self) -> None: + pool = NotionAccountPool( + [FakeClient("one"), FakeClient("two")], + account_ids=["one", "two"], + ) + + async with pool.lease(avoid_account_id="one") as rotated: + self.assertEqual(rotated.account_id, "two") + + pool._slots[1].cooldown_until = time.time() + 60 + async with pool.lease(avoid_account_id="one") as fallback: + self.assertEqual(fallback.account_id, "one") + async def test_retries_on_next_account_after_notion_failure(self) -> None: pool = NotionAccountPool([FakeClient("one"), FakeClient("two")]) attempts = [] @@ -209,6 +405,129 @@ async def operation(client: FakeClient) -> str: self.assertEqual(result, "ok") self.assertEqual(attempts, ["one", "two"]) + async def test_open_global_breaker_does_not_delay_ready_failover(self) -> None: + pool = NotionAccountPool( + [FakeClient("one"), FakeClient("two"), FakeClient("three")], + account_ids=["one", "two", "three"], + ) + now = time.time() + pool._recent_failures.extend([ + (now, "two", "notion_error:error"), + (now, "three", "notion_error:error"), + ]) + attempts = [] + + async def operation(client: FakeClient) -> str: + attempts.append(client.name) + if client.name == "one": + raise NotionAgentError( + "temporary Notion failure", + code=ErrorCode.NOTION_ERROR, + subtype="error", + retryable=True, + ) + return "ok" + + started = time.monotonic() + with patch("account_pool.TRANSIENT_FAILOVER_COOLDOWN", 2): + async with pool.lease() as lease: + result = await lease.run(operation) + + self.assertEqual(result, "ok") + self.assertEqual(attempts, ["one", "two"]) + self.assertLess(time.monotonic() - started, 0.5) + + async def test_empty_text_fails_over_and_quarantines_bad_account(self) -> None: + pool = NotionAccountPool( + [FakeClient("empty"), FakeClient("healthy")], + account_ids=["empty", "healthy"], + ) + attempts = [] + + async def operation(client: FakeClient) -> str: + attempts.append(client.name) + if client.name == "empty": + raise NotionAgentError("empty response", code=ErrorCode.EMPTY_TEXT) + return "ok" + + async with pool.lease() as lease: + self.assertEqual(await lease.run(operation), "ok") + + self.assertEqual(attempts, ["empty", "healthy"]) + self.assertGreaterEqual(pool._slots[0].cooldown_until - time.time(), 59) + async with pool.lease() as lease: + self.assertEqual(lease.account_id, "healthy") + + async def test_persistently_unhealthy_account_gets_long_quarantine(self) -> None: + with tempfile.TemporaryDirectory() as temporary_directory: + state = Path(temporary_directory) / "pool-state.json" + pool = NotionAccountPool( + [FakeClient("unhealthy"), FakeClient("healthy")], + account_ids=["unhealthy", "healthy"], + state_path=state, + ) + unhealthy = pool._slots[0] + unhealthy.successes = 2 + unhealthy.failures = 7 + + async def operation(client: FakeClient) -> str: + if client.name == "unhealthy": + raise NotionAgentError("empty response", code=ErrorCode.EMPTY_TEXT) + return "ok" + + async with pool.lease(preferred_account_id="unhealthy") as lease: + self.assertEqual(await lease.run(operation), "ok") + + self.assertGreaterEqual( + unhealthy.cooldown_until - time.time(), + UNHEALTHY_ACCOUNT_COOLDOWN - 1, + ) + restarted = NotionAccountPool( + [FakeClient("unhealthy"), FakeClient("healthy")], + account_ids=["unhealthy", "healthy"], + state_path=state, + ) + self.assertGreaterEqual( + restarted._slots[0].cooldown_until - time.time(), + UNHEALTHY_ACCOUNT_COOLDOWN - 1, + ) + + async def test_reliability_beats_raw_latency_for_new_turns(self) -> None: + pool = NotionAccountPool( + [FakeClient("unreliable-fast"), FakeClient("healthy")], + account_ids=["unreliable-fast", "healthy"], + ) + unreliable, healthy = pool._slots + unreliable.latency_ewma_ms = 1000 + unreliable.latency_samples = 5 + unreliable.successes = 5 + unreliable.failures = 20 + healthy.latency_ewma_ms = 10000 + healthy.latency_samples = 5 + healthy.successes = 20 + healthy.failures = 1 + + async with pool.lease() as lease: + self.assertEqual(lease.account_id, "healthy") + + async def test_latency_beats_small_failure_difference_between_healthy_accounts(self) -> None: + pool = NotionAccountPool( + [FakeClient("fast"), FakeClient("slow-perfect")], + account_ids=["fast", "slow-perfect"], + ) + fast, slow = pool._slots + fast.latency_ewma_ms = 8000 + fast.latency_samples = 100 + fast.successes = 101 + fast.failures = 14 + slow.latency_ewma_ms = 17000 + slow.latency_samples = 8 + slow.successes = 8 + slow.failures = 0 + + async with pool.lease() as lease: + self.assertEqual(lease.account_id, "fast") + async def test_non_retryable_denial_puts_account_in_long_cooldown(self) -> None: pool = NotionAccountPool([FakeClient("one"), FakeClient("two")]) @@ -253,14 +572,125 @@ async def operation(client: FakeClient) -> str: attempts.append(client.name) raise NotionAgentError("HTTP 502", code=ErrorCode.HTTP_ERROR) - with self.assertRaisesRegex(AccountPoolExhausted, "All 2 Notion accounts failed"): - async with pool.lease() as lease: - await lease.run(operation) + with patch("account_pool.POOL_RECOVERY_WAIT_SECONDS", 0): + with self.assertRaisesRegex(AccountPoolExhausted, "All 2 Notion accounts failed"): + async with pool.lease() as lease: + await lease.run(operation) self.assertEqual(attempts, ["one", "two"]) status = await pool.status() self.assertEqual(status["busy"], 0) + async def test_transient_failure_waits_and_retries_without_visible_cooldown(self) -> None: + pool = NotionAccountPool([FakeClient("one")], account_ids=["one"]) + attempts = 0 + + async def operation(_client: FakeClient) -> str: + nonlocal attempts + attempts += 1 + if attempts == 1: + raise httpx.ConnectError("temporary upstream failure") + return "ok" + + with ( + patch("account_pool.DEFAULT_TRANSIENT_COOLDOWN", 0.01), + patch("account_pool.POOL_RECOVERY_WAIT_SECONDS", 0.2), + ): + async with pool.lease() as lease: + result = await lease.run(operation) + + self.assertEqual(result, "ok") + self.assertEqual(attempts, 2) + + async def test_disabled_account_does_not_block_eligible_retry_cycle(self) -> None: + pool = NotionAccountPool( + [FakeClient("one"), FakeClient("two"), FakeClient("disabled")], + account_ids=["one", "two", "disabled"], + ) + pool._slots[2].disabled = True + pool._slots[2].last_error_code = "ModelIntegrityError" + attempts = [] + + async def operation(client: FakeClient) -> str: + attempts.append(client.name) + if len(attempts) <= 2: + raise NotionAgentError( + "temporary Notion failure", + code=ErrorCode.NOTION_ERROR, + subtype="error", + retryable=True, + ) + return "ok" + + with ( + patch("account_pool.TRANSIENT_FAILOVER_COOLDOWN", 0.01), + patch("account_pool.POOL_RECOVERY_WAIT_SECONDS", 0.2), + ): + async with pool.lease() as lease: + result = await lease.run(operation) + + self.assertEqual(result, "ok") + self.assertEqual(attempts[:2], ["one", "two"]) + self.assertEqual(len(attempts), 3) + self.assertNotIn("disabled", attempts) + + async def test_retryable_notion_error_uses_short_interactive_cooldown(self) -> None: + pool = NotionAccountPool( + [FakeClient("one"), FakeClient("two"), FakeClient("three")], + account_ids=["one", "two", "three"], + ) + attempts = 0 + + async def operation(_client: FakeClient) -> str: + nonlocal attempts + attempts += 1 + if attempts <= 3: + raise NotionAgentError( + "temporary Notion failure", + code=ErrorCode.NOTION_ERROR, + retryable=True, + ) + return "ok" + + with ( + patch("account_pool.TRANSIENT_FAILOVER_COOLDOWN", 0.01), + patch("account_pool.POOL_RECOVERY_WAIT_SECONDS", 0.2), + patch("account_pool.MAX_RECOVERY_CYCLES", 1), + ): + async with pool.lease() as lease: + result = await lease.run(operation) + + self.assertEqual(result, "ok") + self.assertEqual(attempts, 4) + self.assertTrue(all( + slot.cooldown_until - time.time() < 0.1 + for slot in pool._slots + )) + + async def test_single_account_repeated_failure_is_bounded_to_one_fast_retry(self) -> None: + pool = NotionAccountPool([FakeClient("one")], account_ids=["one"]) + attempts = 0 + + async def operation(_client: FakeClient) -> str: + nonlocal attempts + attempts += 1 + raise NotionAgentError( + "temporary Notion failure", + code=ErrorCode.NOTION_ERROR, + retryable=True, + ) + + with ( + patch("account_pool.SINGLE_ACCOUNT_TRANSIENT_COOLDOWN", 0.01), + patch("account_pool.POOL_RECOVERY_WAIT_SECONDS", 0.2), + patch("account_pool.MAX_RECOVERY_CYCLES", 1), + ): + with self.assertRaises(AccountPoolExhausted): + async with pool.lease() as lease: + await lease.run(operation) + + self.assertEqual(attempts, 2) + async def test_local_validation_error_does_not_switch_accounts(self) -> None: pool = NotionAccountPool([FakeClient("one"), FakeClient("two")]) attempts = [] @@ -275,6 +705,170 @@ async def operation(client: FakeClient) -> str: self.assertEqual(attempts, ["one"]) + async def test_new_turns_prefer_measured_faster_account(self) -> None: + pool = NotionAccountPool( + [FakeClient("slow"), FakeClient("fast")], + account_ids=["slow", "fast"], + ) + + # Both accounts are explored before latency routing starts. + async with pool.lease() as slow: + self.assertEqual(slow.account_id, "slow") + await slow.run(lambda _client: asyncio.sleep(0, result="ok")) + async with pool.lease() as fast: + self.assertEqual(fast.account_id, "fast") + await fast.run(lambda _client: asyncio.sleep(0, result="ok")) + + pool._slots[0].latency_ewma_ms = 15000 + pool._slots[0].latency_samples = 5 + pool._slots[1].latency_ewma_ms = 9000 + pool._slots[1].latency_samples = 5 + # The exploratory lease calls above also create default-tier and + # default:ultra profile samples with near-zero synthetic asyncio.sleep + # latency. Clear both layers so this legacy-routing assertion + # specifically verifies the intended overall-latency fallback. + for slot in pool._slots: + slot.tier_latency_ewma_ms.clear() + slot.tier_latency_samples.clear() + slot.profile_latency_ewma_ms.clear() + slot.profile_latency_samples.clear() + + async with pool.lease() as selected: + self.assertEqual(selected.account_id, "fast") + + # Thread affinity remains stronger than the latency preference. + async with pool.lease(preferred_account_id="slow") as continued: + self.assertEqual(continued.account_id, "slow") + + async def test_speed_tiers_route_by_independent_latency_profiles(self) -> None: + pool = NotionAccountPool( + [FakeClient("standard-fast"), FakeClient("priority-fast")], + account_ids=["standard-fast", "priority-fast"], + ) + first, second = pool._slots + first.latency_ewma_ms = 5000 + first.latency_samples = 4 + second.latency_ewma_ms = 5000 + second.latency_samples = 4 + first.tier_latency_ewma_ms = {"default": 2000, "priority": 9000} + first.tier_latency_samples = {"default": 3, "priority": 3} + second.tier_latency_ewma_ms = {"default": 8000, "priority": 2500} + second.tier_latency_samples = {"default": 3, "priority": 3} + + async with pool.lease(service_tier="default") as selected: + self.assertEqual(selected.account_id, "standard-fast") + async with pool.lease(service_tier="priority") as selected: + self.assertEqual(selected.account_id, "priority-fast") + + async def test_tier_latency_measurement_does_not_change_reasoning_or_model(self) -> None: + pool = NotionAccountPool([FakeClient("one")], account_ids=["one"]) + async with pool.lease(service_tier="ultrafast") as lease: + await lease.run(lambda _client: asyncio.sleep(0, result="ok")) + + slot = pool._slots[0] + self.assertEqual(slot.tier_latency_samples["ultrafast"], 1) + self.assertGreaterEqual(slot.tier_latency_ewma_ms["ultrafast"], 0) + + async def test_reasoning_profiles_route_independently_within_tier(self) -> None: + pool = NotionAccountPool( + [FakeClient("low-fast"), FakeClient("xhigh-fast")], + account_ids=["low-fast", "xhigh-fast"], + ) + first, second = pool._slots + first.latency_ewma_ms = second.latency_ewma_ms = 5000 + first.latency_samples = second.latency_samples = 4 + first.tier_latency_ewma_ms = {"priority": 4000} + second.tier_latency_ewma_ms = {"priority": 4000} + first.tier_latency_samples = {"priority": 4} + second.tier_latency_samples = {"priority": 4} + first.profile_latency_ewma_ms = { + "priority:low": 1800, + "priority:xhigh": 9000, + } + second.profile_latency_ewma_ms = { + "priority:low": 8000, + "priority:xhigh": 2100, + } + first.profile_latency_samples = { + "priority:low": 3, + "priority:xhigh": 3, + } + second.profile_latency_samples = { + "priority:low": 3, + "priority:xhigh": 3, + } + + async with pool.lease(service_tier="priority", reasoning_effort="low") as selected: + self.assertEqual(selected.account_id, "low-fast") + async with pool.lease(service_tier="priority", reasoning_effort="xhigh") as selected: + self.assertEqual(selected.account_id, "xhigh-fast") + + async def test_profile_learning_explores_healthy_accounts_with_old_failures(self) -> None: + pool = NotionAccountPool( + [FakeClient("measured"), FakeClient("healthy-unmeasured")], + account_ids=["measured", "healthy-unmeasured"], + ) + measured, healthy_unmeasured = pool._slots + measured.latency_ewma_ms = 2000 + measured.latency_samples = 10 + measured.tier_latency_ewma_ms = {"priority": 2000} + measured.tier_latency_samples = {"priority": 5} + measured.profile_latency_ewma_ms = {"priority:low": 1800} + measured.profile_latency_samples = {"priority:low": 1} + + healthy_unmeasured.latency_ewma_ms = 3500 + healthy_unmeasured.latency_samples = 22 + healthy_unmeasured.tier_latency_ewma_ms = {"priority": 3500} + healthy_unmeasured.tier_latency_samples = {"priority": 4} + healthy_unmeasured.successes = 20 + healthy_unmeasured.failures = 2 + + async with pool.lease( + service_tier="priority", reasoning_effort="low" + ) as selected: + self.assertEqual(selected.account_id, "healthy-unmeasured") + + async def test_reasoning_profile_measurements_survive_restart(self) -> None: + with tempfile.TemporaryDirectory() as temporary_directory: + state = Path(temporary_directory) / "pool-state.json" + pool = NotionAccountPool( + [FakeClient("one")], account_ids=["one"], state_path=state + ) + async with pool.lease( + service_tier="priority", reasoning_effort="max" + ) as lease: + await lease.run(lambda _client: asyncio.sleep(0, result="ok")) + + restarted = NotionAccountPool( + [FakeClient("one")], account_ids=["one"], state_path=state + ) + status = await restarted.status() + account = status["accounts"][0] + self.assertEqual(account["profile_latency_samples"]["priority:max"], 1) + self.assertIsNotNone( + account["profile_latency_ewma_ms"]["priority:max"] + ) + + async def test_latency_measurements_survive_restart(self) -> None: + with tempfile.TemporaryDirectory() as temporary_directory: + state = Path(temporary_directory) / "pool-state.json" + pool = NotionAccountPool( + [FakeClient("one")], + account_ids=["one"], + state_path=state, + ) + async with pool.lease() as lease: + await lease.run(lambda _client: asyncio.sleep(0, result="ok")) + + restarted = NotionAccountPool( + [FakeClient("one")], + account_ids=["one"], + state_path=state, + ) + status = await restarted.status() + self.assertEqual(status["accounts"][0]["latency_samples"], 1) + self.assertIsNotNone(status["accounts"][0]["latency_ewma_ms"]) + class AccountDiscoveryTests(unittest.TestCase): @staticmethod @@ -337,6 +931,25 @@ def test_excludes_invalid_and_duplicate_sessions(self) -> None: self.assertEqual(pool.duplicate_accounts, 1) self.assertEqual(pool.invalid_accounts, 1) + def test_configures_model_faithful_patch_mode_for_every_account(self) -> None: + with tempfile.TemporaryDirectory() as temporary_directory: + home = Path(temporary_directory) + self.write_account(home / "notion_account.json", "token-main", "user-main") + self.write_account(home / "accounts" / "account-02.json", "token-two", "user-two") + self.write_account(home / "accounts" / "account-03.json", "token-three", "user-three") + + pool = build_account_pool(home) + + modes = { + slot.client.account_path.name: slot.client.as_patch_response + for slot in pool._slots + } + self.assertEqual(modes, { + "notion_account.json": True, + "account-02.json": True, + "account-03.json": True, + }) + def test_rejects_more_than_ten_unique_valid_accounts(self) -> None: with tempfile.TemporaryDirectory() as temporary_directory: home = Path(temporary_directory) @@ -369,3 +982,122 @@ def test_allows_extra_files_when_one_is_a_duplicate(self) -> None: if __name__ == "__main__": unittest.main() + +class ModelIntegrityFailoverTests(unittest.IsolatedAsyncioTestCase): + async def test_model_mismatch_fails_over_without_disabling_the_account(self) -> None: + pool = NotionAccountPool( + [FakeClient("wrong"), FakeClient("correct")], + account_ids=["wrong", "correct"], + ) + + async def operation(client: FakeClient) -> str: + if client.name == "wrong": + raise account_pool.ModelIntegrityError( + "expected orange-mousse, got oval-kumquat-medium", + requested_model="gpt-5.6-sol", + ) + return "orange-mousse" + + async with pool.lease() as lease: + result = await lease.run(operation) + + self.assertEqual(result, "orange-mousse") + self.assertFalse(pool._slots[0].disabled) + self.assertGreater( + pool._slots[0].model_cooldown_until.get("gpt-5.6-sol", 0), time.time() + ) + self.assertEqual(pool._slots[1].successes, 1) + + async def test_model_mismatch_quarantines_only_that_model_for_hours(self) -> None: + wrong = FakeClient("wrong") + correct = FakeClient("correct") + pool = NotionAccountPool([wrong, correct], account_ids=["wrong", "correct"]) + attempts: list[str] = [] + + async def sol_operation(client: FakeClient) -> str: + attempts.append(client.name) + if client.name == "wrong": + raise account_pool.ModelIntegrityError( + "expected orange-mousse, got oval-kumquat-medium", + requested_model="gpt-5.6-sol", + ) + return "orange-mousse" + + async with pool.lease(required_model="gpt-5.6-sol") as lease: + self.assertEqual(await lease.run(sol_operation), "orange-mousse") + + async with pool.lease(required_model="gpt-5.6-sol") as lease: + self.assertEqual(await lease.run(sol_operation), "orange-mousse") + + self.assertEqual(attempts, ["wrong", "correct", "correct"]) + self.assertFalse(pool._slots[0].disabled) + self.assertGreater( + pool._slots[0].model_cooldown_until["gpt-5.6-sol"], + time.time() + 3600, + ) + + async with pool.lease( + required_model="gpt-5.4", + preferred_account_id="wrong", + ) as lease: + self.assertEqual(await lease.run(lambda client: asyncio.sleep(0, result=client.name)), "wrong") + + +class StaleDisabledAccountRevalidationTests(unittest.IsolatedAsyncioTestCase): + async def test_successful_sol_probe_restores_persisted_auth_disabled_account(self) -> None: + with tempfile.TemporaryDirectory() as temporary_directory: + state_path = Path(temporary_directory) / "pool-state.json" + original = NotionAccountPool( + [RevalidationClient("one", SimpleNamespace(text="OK", model="orange-mousse"))], + account_ids=["one"], + state_path=state_path, + ) + original._slots[0].disabled = True + original._slots[0].last_error_code = str(ErrorCode.AUTH_INVALID) + original._save_state() + + client = RevalidationClient("one", SimpleNamespace(text="OK", model="orange-mousse")) + pool = NotionAccountPool([client], account_ids=["one"], state_path=state_path) + + self.assertEqual(await pool.revalidate_stale_disabled_accounts(), 1) + self.assertFalse(pool._slots[0].disabled) + self.assertEqual(pool._slots[0].last_error_code, "") + self.assertEqual(client.calls[0]["model"], "gpt-5.6-sol") + async with pool.lease() as lease: + self.assertEqual(await lease.run(lambda selected: asyncio.sleep(0, result=selected.name)), "one") + persisted = json.loads(state_path.read_text(encoding="utf-8")) + self.assertFalse(persisted["accounts"]["one"]["disabled"]) + + async def test_failed_or_substituted_probe_keeps_account_disabled(self) -> None: + for result in ( + RuntimeError("provider denied request"), + SimpleNamespace(text="OK", model="oval-kumquat-medium"), + ): + client = RevalidationClient("one", result) + pool = NotionAccountPool([client], account_ids=["one"]) + pool._slots[0].disabled = True + pool._slots[0].last_error_code = str(ErrorCode.PREMIUM_REQUIRED) + + self.assertEqual(await pool.revalidate_stale_disabled_accounts(), 0) + self.assertTrue(pool._slots[0].disabled) + self.assertEqual(pool._slots[0].last_error_code, str(ErrorCode.PREMIUM_REQUIRED)) + + async def test_legacy_model_integrity_disable_is_restored_on_state_load(self) -> None: + with tempfile.TemporaryDirectory() as temporary_directory: + state_path = Path(temporary_directory) / "pool-state.json" + state_path.write_text(json.dumps({ + "version": 1, + "accounts": { + "one": { + "credential_mtime": 0, + "disabled": True, + "cooldown_until": 0, + "last_error_code": "ModelIntegrityError", + }, + }, + }), encoding="utf-8") + pool = NotionAccountPool([FakeClient("one")], account_ids=["one"], state_path=state_path) + + self.assertFalse(pool._slots[0].disabled) + persisted = json.loads(state_path.read_text(encoding="utf-8")) + self.assertFalse(persisted["accounts"]["one"]["disabled"]) diff --git a/bridge/tests/test_conversation_segments.py b/bridge/tests/test_conversation_segments.py index 7160dcb..b98248b 100644 --- a/bridge/tests/test_conversation_segments.py +++ b/bridge/tests/test_conversation_segments.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import os import tempfile import unittest from pathlib import Path @@ -20,6 +21,33 @@ def test_detects_append_only_history_and_rewrites(self) -> None: self.assertEqual(input_prefix_length(first, extended), 1) self.assertIsNone(input_prefix_length(first, rewritten)) + def test_ignores_assistant_message_text_rewrites_for_prefix_detection(self) -> None: + previous = response_input_fingerprints( + { + "input": [ + {"type": "message", "role": "user", "content": "first"}, + {"type": "message", "role": "assistant", "content": "draft one"}, + {"type": "message", "role": "user", "content": "second"}, + ] + } + ) + current = response_input_fingerprints( + { + "input": [ + {"type": "message", "role": "user", "content": "first"}, + { + "type": "message", + "role": "assistant", + "content": "same turn but rewritten by Codex", + }, + {"type": "message", "role": "user", "content": "second"}, + {"type": "message", "role": "assistant", "content": "new reply"}, + {"type": "message", "role": "user", "content": "third"}, + ] + } + ) + self.assertEqual(input_prefix_length(previous, current), 3) + async def test_persists_only_hashed_identity_and_no_conversation_content(self) -> None: with tempfile.TemporaryDirectory() as directory: path = Path(directory) / "conversation-state.json" @@ -38,9 +66,10 @@ async def test_persists_only_hashed_identity_and_no_conversation_content(self) - ) raw = path.read_text(encoding="utf8") self.assertNotIn("secret-codex-thread", raw) - self.assertEqual(path.stat().st_mode & 0o777, 0o600) + if os.name != "nt": + self.assertEqual(path.stat().st_mode & 0o777, 0o600) payload = json.loads(raw) - self.assertEqual(payload["version"], 2) + self.assertEqual(payload["version"], 3) restored = await ConversationSegmentStore(path).get("secret-codex-thread") self.assertIsNotNone(restored) diff --git a/bridge/tests/test_model_catalog.py b/bridge/tests/test_model_catalog.py new file mode 100644 index 0000000..900e015 --- /dev/null +++ b/bridge/tests/test_model_catalog.py @@ -0,0 +1,203 @@ +import asyncio +import json +import tempfile +import unittest +from pathlib import Path + +from model_catalog import BASE_MODEL_IDS, VerifiedModelCatalog + + +class FakeClient: + def __init__(self, response=None, error=None): + self.response = response + self.error = error + self._user_map_cache = {"stale": "value"} + + async def fetch_available_models(self): + if self.error: + raise self.error + return self.response + + +def available(*pairs): + return { + "models": [ + item + if isinstance(item, dict) + else {"modelMessage": item[0], "model": item[1], "isDisabled": False} + for item in pairs + ] + } + + +class VerifiedModelCatalogTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.home = Path(self.temp.name) + self.base = Path(__file__).resolve().parents[2] / "config" / "codex-models.json" + self.base_aliases = ( + Path(__file__).resolve().parents[2] + / "state-template" + / ".notionagents" + / "models.json" + ) + self.catalog = VerifiedModelCatalog( + self.home, + self.base, + base_alias_path=self.base_aliases, + ) + + def tearDown(self): + self.temp.cleanup() + + def test_verified_future_ultrafast_is_exposed_and_keeps_fast(self): + response = available( + { + "modelMessage": "GPT 5.6 Sol", + "model": "orange-mousse", + "isDisabled": False, + "displayGroup": "intelligent", + "modelCardAttributes": {"speed": 3}, + }, + { + "modelMessage": "GPT 5.6 Sol Ultrafast", + "model": "verified-ultrafast-id", + "isDisabled": False, + "displayGroup": "fast", + "modelCardAttributes": {"speed": 5}, + }, + ) + clients = [FakeClient(response), FakeClient(response), FakeClient(response)] + self.assertTrue(asyncio.run(self.catalog.refresh(clients))) + self.assertIn("gpt-5.6-sol-ultrafast", self.catalog.model_ids()) + generated = json.loads( + (self.home / "codex-models.json").read_text(encoding="utf-8") + ) + future = next( + item + for item in generated["models"] + if item["slug"] == "gpt-5.6-sol-ultrafast" + ) + self.assertEqual( + [tier["id"] for tier in future["service_tiers"]], ["priority"] + ) + aliases = json.loads( + (self.home / "models.json").read_text(encoding="utf-8") + ) + self.assertIn("fable-5", aliases["friendly_aliases"]) + self.assertIn("gpt-5.6-sol", aliases["friendly_aliases"]) + self.assertIn("opus-5", aliases["friendly_aliases"]) + self.assertEqual( + aliases["friendly_aliases"]["gpt-5.6-sol-ultrafast"], + "verified-ultrafast-id", + ) + self.assertTrue(all(client._user_map_cache is None for client in clients)) + + def test_invented_alias_is_not_exposed(self): + response = available(("GPT 5.6 Sol", "orange-mousse")) + self.assertTrue(asyncio.run(self.catalog.refresh([FakeClient(response)]))) + self.assertNotIn("gpt-5.6-sol-ultrafast", self.catalog.model_ids()) + + def test_account_disagreement_is_not_exposed(self): + first = available(("GPT 5.6 Sol Ultrafast", "id-a")) + second = available(("GPT 5.6 Sol Ultrafast", "id-b")) + self.assertTrue( + asyncio.run(self.catalog.refresh([FakeClient(first), FakeClient(second)])) + ) + self.assertNotIn("gpt-5.6-sol-ultrafast", self.catalog.model_ids()) + + def test_gradual_future_model_rollout_is_exposed_and_capabilities_are_recorded(self): + common = available(("GPT 5.6 Sol", "orange-mousse")) + early = available( + ("GPT 5.6 Sol", "orange-mousse"), + ("GPT 6.0 Pro", "gpt6-id"), + ) + clients = [FakeClient(common), FakeClient(early)] + self.assertTrue(asyncio.run(self.catalog.refresh(clients))) + self.assertIn("gpt-6.0-pro", self.catalog.model_ids()) + self.assertNotIn("gpt-6.0-pro", clients[0]._notion_available_model_aliases) + self.assertIn("gpt-6.0-pro", clients[1]._notion_available_model_aliases) + self.assertEqual(self.catalog.status()["partially_available_models"], 1) + + def test_refresh_failure_preserves_base_models(self): + self.assertFalse( + asyncio.run( + self.catalog.refresh([FakeClient(error=RuntimeError("offline"))]) + ) + ) + self.assertEqual(self.catalog.model_ids(), BASE_MODEL_IDS) + self.assertEqual(self.catalog.status()["state"], "degraded") + + def test_partial_refresh_applies_verified_accounts_without_inferring_failed_account_support(self): + successful = FakeClient( + available( + ("GPT 5.6 Sol", "orange-mousse"), + ("GPT 6.0 Pro", "gpt6-id"), + ) + ) + failed = FakeClient(error=RuntimeError("offline")) + + self.assertFalse(asyncio.run(self.catalog.refresh([successful, failed]))) + self.assertIn("gpt-6.0-pro", self.catalog.model_ids()) + self.assertIn("gpt-6.0-pro", successful._notion_available_model_aliases) + self.assertEqual(failed._notion_available_model_aliases, frozenset()) + status = self.catalog.status() + self.assertEqual(status["state"], "degraded") + self.assertEqual(status["verified_accounts"], 1) + self.assertEqual(status["dynamic_models"], 1) + self.assertEqual(status["last_error"], "account_refresh_failed") + + def test_fast_model_for_prefers_verified_same_prefix_variant(self): + response = available( + {"modelMessage": "GPT 5.6 Sol", "model": "orange-mousse", "isDisabled": False, "displayGroup": "intelligent", "modelCardAttributes": {"speed": 3}}, + {"modelMessage": "GPT 5.6 Luna", "model": "olive-jellyroll", "isDisabled": False, "displayGroup": "fast", "modelCardAttributes": {"speed": 5}}, + {"modelMessage": "Gemini 3 Flash", "model": "gingerbread", "isDisabled": False, "displayGroup": "fast", "modelCardAttributes": {"speed": 5}}, + ) + clients = [FakeClient(response), FakeClient(response)] + self.assertTrue(asyncio.run(self.catalog.refresh(clients))) + self.assertEqual(self.catalog.fast_model_for("gpt-5.6-sol"), "gpt-5.6-luna") + self.assertIsNone(self.catalog.tier_model_for("gpt-5.6-sol", "priority")) + self.assertIsNone(self.catalog.fast_model_for("opus-5")) + + + def test_ultrafast_tier_keeps_selected_base_model_even_when_verified_variant_exists(self): + response = available( + ("GPT 5.6 Sol", "orange-mousse"), + {"modelMessage": "GPT 5.6 Luna", "model": "olive-jellyroll", "isDisabled": False, "displayGroup": "fast", "modelCardAttributes": {"speed": 5}}, + {"modelMessage": "GPT 5.6 Sol Ultrafast", "model": "verified-ultrafast-id", "isDisabled": False, "displayGroup": "fast", "modelCardAttributes": {"speed": 6}}, + ) + clients = [FakeClient(response), FakeClient(response)] + self.assertTrue(asyncio.run(self.catalog.refresh(clients))) + self.assertEqual(self.catalog.fast_model_for("gpt-5.6-sol"), "gpt-5.6-luna") + self.assertIsNone(self.catalog.tier_model_for("gpt-5.6-sol", "ultrafast")) + + def test_verified_future_gpt_model_keeps_only_released_speed_tiers(self): + response = available(("GPT 6.0 Pro", "gpt6-id")) + clients = [FakeClient(response), FakeClient(response)] + self.assertTrue(asyncio.run(self.catalog.refresh(clients))) + generated = json.loads((self.home / "codex-models.json").read_text(encoding="utf-8")) + future = next(item for item in generated["models"] if item["slug"] == "gpt-6.0-pro") + self.assertEqual([tier["id"] for tier in future["service_tiers"]], ["priority"]) + + def test_explicitly_advertised_ultrafast_tier_is_enabled_automatically(self): + response = available( + { + "modelMessage": "GPT 6.0 Pro", + "model": "gpt6-id", + "isDisabled": False, + "serviceTiers": ["priority", "ultrafast"], + } + ) + clients = [FakeClient(response), FakeClient(response)] + self.assertTrue(asyncio.run(self.catalog.refresh(clients))) + generated = json.loads((self.home / "codex-models.json").read_text(encoding="utf-8")) + future = next(item for item in generated["models"] if item["slug"] == "gpt-6.0-pro") + self.assertEqual( + [tier["id"] for tier in future["service_tiers"]], + ["priority", "ultrafast"], + ) + self.assertTrue(self.catalog.supports_service_tier("gpt-6.0-pro", "ultrafast")) + + +if __name__ == "__main__": + unittest.main() diff --git a/bridge/tests/test_server_regressions.py b/bridge/tests/test_server_regressions.py index 1fa78fa..ea4fbf4 100644 --- a/bridge/tests/test_server_regressions.py +++ b/bridge/tests/test_server_regressions.py @@ -1,5 +1,6 @@ from __future__ import annotations +import asyncio import unittest import json from types import SimpleNamespace @@ -24,10 +25,114 @@ class ResponsesTextRegressionTests(unittest.TestCase): + def test_request_execution_settings_parse_codex_wire_fields(self) -> None: + body = { + "reasoning": {"effort": "MAX"}, + "service_tier": "priority", + } + self.assertEqual(server.request_reasoning_effort(body), "max") + self.assertEqual(server.request_service_tier(body), "priority") + self.assertEqual(server.request_reasoning_effort({}), server.MAX_REASONING_EFFORT) + self.assertIsNone(server.request_service_tier({})) + + def test_fast_service_tier_keeps_reasoning_independent(self) -> None: + self.assertEqual( + server.request_reasoning_effort( + {"model": "gpt-5.6-sol", "service_tier": "priority"} + ), + server.MAX_REASONING_EFFORT, + ) + self.assertEqual( + server.request_reasoning_effort( + {"model": "gpt-5.6-sol-ultrafast", "serviceTier": "PRIORITY"} + ), + server.MAX_REASONING_EFFORT, + ) + + def test_fast_service_tier_does_not_override_explicit_reasoning(self) -> None: + self.assertEqual( + server.request_reasoning_effort( + { + "model": "gpt-5.6-sol", + "reasoning": {"effort": "MAX"}, + "service_tier": "priority", + } + ), + "max", + ) + + def test_fast_service_tier_does_not_change_legacy_model_default(self) -> None: + self.assertEqual( + server.request_reasoning_effort( + {"model": "gpt-5.5", "service_tier": "priority"} + ), + server.MAX_REASONING_EFFORT, + ) + + def test_fast_service_tier_preserves_selected_base_model(self) -> None: + with patch.object(server.model_catalog, "fast_model_for", return_value="gpt-5.6-luna"): + self.assertEqual(server.resolve_requested_model("gpt-5.6-sol", "priority"), "gpt-5.6-sol") + + def test_fast_service_tier_keeps_model_when_no_fast_variant_exists(self) -> None: + with patch.object(server.model_catalog, "fast_model_for", return_value=None): + self.assertEqual(server.resolve_requested_model("gpt-5.6-sol", "priority"), "gpt-5.6-sol") + + def test_ultrafast_service_tier_preserves_selected_base_model(self) -> None: + with patch.object(server.model_catalog, "supports_service_tier", return_value=True): + self.assertEqual( + server.resolve_requested_model("gpt-5.6-sol", "ultrafast"), + "gpt-5.6-sol", + ) + + def test_unreleased_ultrafast_service_tier_is_rejected(self) -> None: + with patch.object(server.model_catalog, "supports_service_tier", return_value=False): + with self.assertRaisesRegex(ValueError, "not currently advertised"): + server.resolve_requested_model("gpt-5.6-sol", "ultrafast") + + def test_invalid_reasoning_is_not_silently_changed_to_ultra(self) -> None: + with self.assertRaisesRegex(ValueError, "unsupported reasoning effort"): + server.request_reasoning_effort({"reasoning": {"effort": "extreme"}}) + + def test_anthropic_messages_route_uses_service_tier_model_resolution(self) -> None: + with patch.object(server, "resolve_requested_model", return_value="gpt-5.6-luna") as mocked: + class Request: + async def json(self): + return {"model": "gpt-5.6-sol", "service_tier": "priority"} + + with patch.object(server, "account_pool", None): + response = asyncio.run(server.anthropic_messages(Request())) + + mocked.assert_called_once_with("gpt-5.6-sol", "priority") + self.assertEqual(response.status_code, 503) + + def test_chat_completions_route_uses_service_tier_model_resolution(self) -> None: + with patch.object(server, "resolve_requested_model", return_value="gpt-5.6-luna") as mocked: + class Request: + async def json(self): + return { + "model": "gpt-5.6-sol", + "service_tier": "priority", + "messages": [{"role": "user", "content": "hello"}], + } + + with patch.object(server, "account_pool", None): + response = asyncio.run(server.completions(Request())) + + mocked.assert_called_once_with("gpt-5.6-sol", "priority") + self.assertEqual(response.status_code, 503) + def test_codex_fable_transport_id_resolves_to_notion_fable(self) -> None: self.assertEqual(resolve_model("gpt-5.5"), "fable-5") self.assertEqual(resolve_model("fable-5"), "fable-5") + def test_authoritatively_discovered_model_resolves_dynamically(self) -> None: + dynamic = (*server.SUPPORTED_MODELS, "gpt-5.6-sol-ultrafast") + with patch.object(server.model_catalog, "model_ids", return_value=dynamic): + self.assertEqual( + resolve_model("gpt-5.6-sol-ultrafast"), + "gpt-5.6-sol-ultrafast", + ) + def test_opus_aliases_resolve_to_notion_opus_5(self) -> None: self.assertEqual(resolve_model("opus-5"), "opus-5") self.assertEqual(resolve_model("opus"), "opus-5") @@ -49,6 +154,15 @@ def test_notion_model_stays_explicit_on_continuation(self) -> None: self.assertEqual(config["model"], "agave-flan") self.assertIs(config["modelFromUser"], True) + def test_models_endpoint_includes_speed_tier_metadata(self) -> None: + payload = asyncio.run(server.models()) + sol = next(item for item in payload["data"] if item["id"] == "gpt-5.6-sol") + self.assertEqual(sol["additional_speed_tiers"], ["fast"]) + self.assertEqual( + [tier["id"] for tier in sol["service_tiers"]], + ["priority"], + ) + def test_input_image_does_not_replace_or_mutate_text(self) -> None: message = { "type": "message", @@ -71,7 +185,7 @@ def test_text_only_planner_prompt_remains_stable(self) -> None: "tools": [], } prompt = responses_planner_prompt(body) - self.assertIn("The local operator's current working directory is /root/project.", prompt) + self.assertIn("The local operator's current working directory is ", prompt) self.assertIn("[user]\nlist files", prompt) def test_namespace_tools_are_flattened_for_native_codex_calls(self) -> None: @@ -327,6 +441,88 @@ async def fake_handle( class ResponsesAffinityIntegrationTests(unittest.IsolatedAsyncioTestCase): + async def test_reasoning_effort_reaches_image_and_correction_paths(self) -> None: + calls = [] + replies = [ + "I don't have access to the file system", + '{"tool":"shell_command","arguments":{"command":"echo ok"}}', + ] + + class Lease: + account_id = "account-a" + + async def __aenter__(self): + return self + + async def __aexit__(self, *_args): + return None + + async def run(self, operation, *, retry_operation=None): + return await operation(SimpleNamespace()) + + class Pool: + size = 1 + + def lease(self, preferred_account_id=None, service_tier=None, reasoning_effort=None, required_model=None): + return Lease() + + async def fake_complete_with_images(_client, **kwargs): + calls.append(kwargs) + return SimpleNamespace( + text=replies.pop(0), + thread_id="notion-thread", + usage=SimpleNamespace(input_tokens=10, output_tokens=2), + ) + + original_pool = server.account_pool + original_affinities = server.turn_affinities + original_segments = server.conversation_segments + server.account_pool = Pool() + server.turn_affinities = TurnAffinityStore() + server.conversation_segments = ConversationSegmentStore() + try: + with ( + patch.object( + server, + "extract_response_images", + return_value=[SimpleNamespace(data=b"image")], + ), + patch.object(server, "estimated_image_tokens", return_value=1), + patch.object( + server, + "complete_with_images", + new=fake_complete_with_images, + ), + ): + response = await handle_openai_responses( + { + "model": "gpt-5.6-sol", + "input": [{"type": "message", "role": "user", "content": "inspect"}], + "tools": [{ + "type": "function", + "name": "shell_command", + "description": "Run one command", + "parameters": { + "type": "object", + "properties": {"command": {"type": "string"}}, + }, + }], + "reasoning": {"effort": "max"}, + "service_tier": "priority", + }, + "image-correction-turn", + conversation_key="image-correction-thread", + ) + finally: + server.account_pool = original_pool + server.turn_affinities = original_affinities + server.conversation_segments = original_segments + + self.assertEqual(len(calls), 2) + self.assertTrue(all(call["reasoning_effort"] == "max" for call in calls)) + self.assertEqual(calls[1]["thread_id"], "notion-thread") + self.assertEqual(response["output"][0]["name"], "shell_command") + async def test_model_change_starts_a_new_notion_thread(self) -> None: calls = [] @@ -357,7 +553,7 @@ class Pool: def __init__(self): self.preferred = [] - def lease(self, preferred_account_id=None): + def lease(self, preferred_account_id=None, service_tier=None, reasoning_effort=None, required_model=None): self.preferred.append(preferred_account_id) return Lease() @@ -371,7 +567,11 @@ def lease(self, preferred_account_id=None): try: first_input = [{"type": "message", "role": "user", "content": "first"}] await handle_openai_responses( - {"model": "fable-5", "input": first_input}, + { + "model": "fable-5", + "input": first_input, + "reasoning": {"effort": "max"}, + }, "turn-1", conversation_key="codex-thread", ) @@ -397,6 +597,90 @@ def lease(self, preferred_account_id=None): self.assertIsNotNone(segment) self.assertEqual(segment.model, "opus-5") + async def test_assistant_message_rewrite_keeps_existing_notion_thread(self) -> None: + calls = [] + + class Client: + async def complete(self, **kwargs): + calls.append(kwargs) + return SimpleNamespace( + text=f"answer {len(calls)}", + thread_id=f"thread-{len(calls)}", + usage=SimpleNamespace(input_tokens=10, output_tokens=2), + ) + + class Lease: + account_id = "account-a" + + async def __aenter__(self): + return self + + async def __aexit__(self, *_args): + return None + + async def run(self, operation, *, retry_operation=None): + return await operation(Client()) + + class Pool: + size = 1 + + def __init__(self): + self.preferred = [] + + def lease(self, preferred_account_id=None, service_tier=None, reasoning_effort=None, required_model=None): + self.preferred.append(preferred_account_id) + return Lease() + + pool = Pool() + original_pool = server.account_pool + original_affinities = server.turn_affinities + original_segments = server.conversation_segments + server.account_pool = pool + server.turn_affinities = TurnAffinityStore() + server.conversation_segments = ConversationSegmentStore() + try: + first_input = [{"type": "message", "role": "user", "content": "first"}] + await handle_openai_responses( + {"model": "fable-5", "input": first_input}, + "turn-1", + conversation_key="codex-thread", + ) + second_input = [ + *first_input, + {"type": "message", "role": "assistant", "content": "original answer"}, + {"type": "message", "role": "user", "content": "next"}, + ] + await handle_openai_responses( + {"model": "fable-5", "input": second_input}, + "turn-2", + conversation_key="codex-thread", + ) + rewritten_input = [ + *first_input, + { + "type": "message", + "role": "assistant", + "content": "assistant text rewritten by Codex storage", + }, + {"type": "message", "role": "user", "content": "next"}, + {"type": "message", "role": "assistant", "content": "second answer"}, + {"type": "message", "role": "user", "content": "third"}, + ] + await handle_openai_responses( + {"model": "fable-5", "input": rewritten_input}, + "turn-3", + conversation_key="codex-thread", + ) + finally: + server.account_pool = original_pool + server.turn_affinities = original_affinities + server.conversation_segments = original_segments + + self.assertEqual(pool.preferred, [None, None, None]) + self.assertNotIn("thread_id", calls[0]) + self.assertEqual(calls[1]["thread_id"], "thread-1") + self.assertEqual(calls[2]["thread_id"], "thread-2") + async def test_same_codex_turn_reuses_account_and_notion_thread(self) -> None: calls = [] replies = [ @@ -431,7 +715,7 @@ class Pool: def __init__(self): self.preferred = [] - def lease(self, preferred_account_id=None): + def lease(self, preferred_account_id=None, service_tier=None, reasoning_effort=None, required_model=None): self.preferred.append(preferred_account_id) return Lease() @@ -477,7 +761,73 @@ def lease(self, preferred_account_id=None): self.assertIn("Plan updated", calls[1]["prompt"]) self.assertNotIn("Tool catalog", calls[1]["prompt"]) - async def test_conversation_continues_across_turns_then_rotates_after_compaction(self) -> None: + async def test_provider_context_limit_starts_bounded_fresh_segment(self) -> None: + calls: list[dict] = [] + + class Client: + async def complete(self, **kwargs): + calls.append(kwargs) + return SimpleNamespace( + text="answer", + thread_id=f"thread-{len(calls)}", + usage=SimpleNamespace(input_tokens=100, output_tokens=2), + ) + + class Lease: + account_id = "account-a" + + async def __aenter__(self): + return self + + async def __aexit__(self, *_args): + return None + + async def run(self, operation, *, retry_operation=None): + return await operation(Client()) + + class Pool: + size = 1 + + def lease(self, **_kwargs): + return Lease() + + original_pool = server.account_pool + original_affinities = server.turn_affinities + original_segments = server.conversation_segments + server.account_pool = Pool() + server.turn_affinities = TurnAffinityStore() + server.conversation_segments = ConversationSegmentStore() + try: + first_input = [{"type": "message", "role": "user", "content": "first task"}] + with patch.object(server, "SEGMENT_ROLLOVER_INPUT_TOKENS", 50): + await handle_openai_responses( + {"model": "fable-5", "input": first_input}, + "turn-1", + conversation_key="codex-thread", + ) + await handle_openai_responses( + { + "model": "fable-5", + "input": [ + *first_input, + {"type": "message", "role": "assistant", "content": "old answer"}, + {"type": "message", "role": "user", "content": "next task"}, + ], + }, + "turn-2", + conversation_key="codex-thread", + ) + finally: + server.account_pool = original_pool + server.turn_affinities = original_affinities + server.conversation_segments = original_segments + + self.assertEqual(len(calls), 2) + self.assertNotIn("thread_id", calls[1]) + self.assertIn("fresh provider conversation segment", calls[1]["prompt"]) + self.assertIn("next task", calls[1]["prompt"]) + + async def test_new_turn_uses_latency_routing_and_compaction_keeps_affinity(self) -> None: calls: list[tuple[str, dict]] = [] class Client: @@ -510,16 +860,24 @@ class Pool: size = 2 def __init__(self): - self.new_segments = 0 self.preferred: list[str | None] = [] - - def lease(self, preferred_account_id=None): + self.avoided: list[str | None] = [] + + def lease( + self, + preferred_account_id=None, + avoid_account_id=None, + service_tier=None, + reasoning_effort=None, + required_model=None, + ): self.preferred.append(preferred_account_id) + self.avoided.append(avoid_account_id) if preferred_account_id: return Lease(preferred_account_id) - account_id = "account-a" if self.new_segments == 0 else "account-b" - self.new_segments += 1 - return Lease(account_id) + # Model the real pool after latency measurements: account-a is + # currently fastest and remains selected for fresh turns. + return Lease("account-a") pool = Pool() original_pool = server.account_pool @@ -531,7 +889,11 @@ def lease(self, preferred_account_id=None): try: first_input = [{"type": "message", "role": "user", "content": "first task"}] await handle_openai_responses( - {"model": "fable-5", "input": first_input}, + { + "model": "fable-5", + "input": first_input, + "reasoning": {"effort": "max"}, + }, "turn-1", conversation_key="codex-thread", ) @@ -541,20 +903,32 @@ def lease(self, preferred_account_id=None): {"type": "message", "role": "user", "content": "next request"}, ] await handle_openai_responses( - {"model": "fable-5", "input": second_input}, + { + "model": "fable-5", + "input": second_input, + "reasoning": {"effort": "max"}, + }, "turn-2", conversation_key="codex-thread", ) compacted = await handle_openai_compaction( - {"model": "fable-5", "input": second_input}, + { + "model": "fable-5", + "input": second_input, + "reasoning": {"effort": "max"}, + }, "compact-turn", "codex-thread", ) final = await handle_openai_responses( - {"model": "fable-5", "input": [ - compacted["output"][0], - {"type": "message", "role": "user", "content": "after compact"}, - ]}, + { + "model": "fable-5", + "input": [ + compacted["output"][0], + {"type": "message", "role": "user", "content": "after compact"}, + ], + "reasoning": {"effort": "max"}, + }, "turn-3", conversation_key="codex-thread", ) @@ -563,17 +937,55 @@ def lease(self, preferred_account_id=None): server.turn_affinities = original_affinities server.conversation_segments = original_segments - self.assertEqual(pool.preferred, [None, "account-a", "account-a", None]) + self.assertEqual(pool.preferred, [None, None, "account-a", None]) + self.assertEqual(pool.avoided, [None, None, None, None]) + self.assertEqual(calls[0][0], "account-a") self.assertEqual(calls[1][0], "account-a") self.assertEqual(calls[1][1]["thread_id"], "thread-account-a") self.assertIn("next request", calls[1][1]["prompt"]) self.assertNotIn("previous answer", calls[1][1]["prompt"]) + self.assertEqual(calls[2][0], "account-a") + self.assertEqual(calls[2][1]["thread_id"], "thread-account-a") self.assertEqual(compacted["output"][0]["type"], "compaction") - self.assertEqual(calls[-1][0], "account-b") + self.assertEqual(calls[-1][0], "account-a") self.assertNotIn("thread_id", calls[-1][1]) self.assertIn("dense summary", calls[-1][1]["prompt"]) - self.assertEqual(final["output"][0]["content"][0]["text"], "answer from account-b") + self.assertTrue(all(call[1]["reasoning_effort"] == "max" for call in calls)) + self.assertEqual(final["output"][0]["content"][0]["text"], "answer from account-a") if __name__ == "__main__": unittest.main() + +class ModelIntegrityValidationTests(unittest.TestCase): + def test_rejects_an_observed_model_that_differs_from_the_selected_alias(self) -> None: + result = SimpleNamespace( + model="oval-kumquat-medium", + raw={"reported_notion_model": "oval-kumquat-medium"}, + thread_id="thread-wrong-model", + ) + with patch.object(server.model_catalog, "notion_model_for", return_value="orange-mousse"): + with self.assertRaises(server.ModelIntegrityError): + server.validate_selected_model( + result, + requested_model="gpt-5.6-sol", + resolved_model="gpt-5.6-sol", + reused_thread=False, + ) + + def test_allows_the_selected_internal_model(self) -> None: + result = SimpleNamespace( + model="orange-mousse", + raw={"reported_notion_model": "orange-mousse"}, + thread_id="thread-correct-model", + ) + with patch.object(server.model_catalog, "notion_model_for", return_value="orange-mousse"): + self.assertIs( + server.validate_selected_model( + result, + requested_model="gpt-5.6-sol", + resolved_model="gpt-5.6-sol", + reused_thread=False, + ), + result, + ) diff --git a/config/codex-cli-config.toml b/config/codex-cli-config.toml index 9b83a4d..9d24ad4 100644 --- a/config/codex-cli-config.toml +++ b/config/codex-cli-config.toml @@ -1,11 +1,14 @@ model = "opus-5" model_provider = "notion-ai" -model_reasoning_effort = "high" +model_reasoning_effort = "medium" +service_tier = "priority" +enabled-reasoning-efforts = ["low", "medium", "high", "xhigh", "max", "ultra"] +show-ultra-in-model-picker-slider = true model_context_window = 210000 model_auto_compact_token_limit = 200000 model_auto_compact_token_limit_scope = "total" tool_output_token_limit = 12000 -model_catalog_json = "__NOTIONCODE_ROOT__/config/codex-models.json" +model_catalog_json = "__USER_HOME__/.notionagents/codex-models.json" [model_providers.notion-ai] name = "Notion AI" @@ -20,3 +23,10 @@ args = ["__NOTIONCODE_ROOT__/notion-private-api-mcp/run-from-account.js"] startup_timeout_sec = 20 tool_timeout_sec = 120 enabled = false # __NOTION_MCP_ENABLED__ + +[mcp_servers.external-inference] +command = "node" +args = ["__NOTIONCODE_ROOT__/notion-private-api-mcp/run-external-inference.js"] +startup_timeout_sec = 20 +tool_timeout_sec = 300 +enabled = true diff --git a/config/codex-models.json b/config/codex-models.json index c70244d..041c3bb 100644 --- a/config/codex-models.json +++ b/config/codex-models.json @@ -17,6 +17,20 @@ { "effort": "high", "description": "Thorough" + }, + { + "effort": "xhigh", + "description": "Extra high" + } + ], + "additional_speed_tiers": [ + "fast" + ], + "service_tiers": [ + { + "id": "priority", + "name": "Fast", + "description": "Keeps the selected model and requests the provider priority tier when supported" } ], "shell_type": "shell_command", @@ -74,6 +88,10 @@ { "reasoningEffort": "high", "description": "Thorough" + }, + { + "reasoningEffort": "xhigh", + "description": "Extra high" } ] }, @@ -94,6 +112,28 @@ { "effort": "high", "description": "Thorough" + }, + { + "effort": "xhigh", + "description": "Extra high" + }, + { + "effort": "max", + "description": "Maximum" + }, + { + "effort": "ultra", + "description": "Ultra" + } + ], + "additional_speed_tiers": [ + "fast" + ], + "service_tiers": [ + { + "id": "priority", + "name": "Fast", + "description": "Keeps the selected model and requests the provider priority tier when supported" } ], "shell_type": "shell_command", @@ -151,6 +191,18 @@ { "reasoningEffort": "high", "description": "Thorough" + }, + { + "reasoningEffort": "xhigh", + "description": "Extra high" + }, + { + "reasoningEffort": "max", + "description": "Maximum" + }, + { + "reasoningEffort": "ultra", + "description": "Ultra" } ] }, diff --git a/configure-external-provider.ps1 b/configure-external-provider.ps1 new file mode 100644 index 0000000..e7cf241 --- /dev/null +++ b/configure-external-provider.ps1 @@ -0,0 +1,43 @@ +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)] + [ValidateSet("openrouter", "vivgrid", "cerebras")] + [string]$Provider, + [switch]$Clear +) + +$ErrorActionPreference = "Stop" +$EnvironmentVariables = @{ + openrouter = "OPENROUTER_API_KEY" + vivgrid = "VIVGRID_API_KEY" + cerebras = "CEREBRAS_API_KEY" +} +$VariableName = $EnvironmentVariables[$Provider] + +if ($Clear) { + [Environment]::SetEnvironmentVariable($VariableName, $null, "User") + [Environment]::SetEnvironmentVariable($VariableName, $null, "Process") + Write-Host "$Provider credential removed from the current Windows user environment." + Write-Host "Restart Codex before using the external-inference MCP again." + exit 0 +} + +$SecureValue = Read-Host "Enter the $Provider API key (input is masked)" -AsSecureString +$Pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureValue) +try { + $PlainValue = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($Pointer) + if ([string]::IsNullOrWhiteSpace($PlainValue)) { + throw "The API key was empty. Nothing was changed." + } + [Environment]::SetEnvironmentVariable($VariableName, $PlainValue, "User") + [Environment]::SetEnvironmentVariable($VariableName, $PlainValue, "Process") +} finally { + if ($Pointer -ne [IntPtr]::Zero) { + [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($Pointer) + } + $PlainValue = $null + $SecureValue.Dispose() +} + +Write-Host "$Provider credential configured for the current Windows user." +Write-Host "The key was not written to Codex config or console output. Restart Codex, then call external_provider_status." diff --git a/install.ps1 b/install.ps1 index 9c062ab..613f567 100644 --- a/install.ps1 +++ b/install.ps1 @@ -1,6 +1,8 @@ [CmdletBinding()] param( [string]$CodeRoot = $HOME, + [ValidateSet("low", "medium", "high", "xhigh", "max", "ultra")] + [string]$ReasoningEffort = "", [switch]$NoAutoStart, [switch]$NoStart ) @@ -15,6 +17,8 @@ $PythonExe = Join-Path $VenvDir "Scripts\python.exe" $AccountHome = Join-Path $HOME ".notionagents" $ModelsTemplate = Join-Path $Root "state-template\.notionagents\models.json" $ModelsPath = Join-Path $AccountHome "models.json" +$CodexModelsTemplate = Join-Path $Root "config\codex-models.json" +$CodexModelsPath = Join-Path $AccountHome "codex-models.json" $RuntimeEnv = Join-Path $RuntimeDir ".env" $StateDir = Join-Path $Root "state" $CodexHome = Join-Path $HOME ".codex" @@ -41,6 +45,7 @@ if ($LASTEXITCODE -ne 0) { throw "Private Notion MCP npm dependency installation & node.exe (Join-Path $Root "scripts\install-model-aliases.mjs") $ModelsTemplate $ModelsPath if ($LASTEXITCODE -ne 0) { throw "Model alias installation failed." } +Copy-Item -LiteralPath $CodexModelsTemplate -Destination $CodexModelsPath -Force & $PythonExe (Join-Path $Root "bridge\migrate_accounts.py") $AccountHome if ($LASTEXITCODE -ne 0) { throw "Notion account migration failed." } @@ -61,10 +66,12 @@ if (-not (Test-Path $RuntimeEnv)) { Write-Utf8NoBom $RuntimeEnv ($runtimeEnvContent + [Environment]::NewLine) } -& node.exe (Join-Path $Root "scripts\install-codex-config.mjs") (Join-Path $Root "config\codex-cli-config.toml") (Join-Path $CodexHome "config.toml") $Root $HOME $NotionMcpEnabled +& node.exe (Join-Path $Root "scripts\install-codex-config.mjs") (Join-Path $Root "config\codex-cli-config.toml") (Join-Path $CodexHome "config.toml") $Root $HOME $NotionMcpEnabled $ReasoningEffort if ($LASTEXITCODE -ne 0) { throw "Codex configuration generation failed." } & node.exe (Join-Path $Root "scripts\patch-codex-webview.mjs") $HOME if ($LASTEXITCODE -ne 0) { throw "Codex VS Code webview compatibility patch failed." } +& node.exe (Join-Path $Root "scripts\patch-codex-desktop.mjs") +if ($LASTEXITCODE -ne 0) { throw "Codex Desktop Fast compatibility patch failed." } & node.exe (Join-Path $Root "scripts\render-config.mjs") (Join-Path $Root "config\opencode.jsonc") (Join-Path $OpenCodeHome "opencode.jsonc") $Root $HOME if ($LASTEXITCODE -ne 0) { throw "OpenCode configuration generation failed." } @@ -80,10 +87,28 @@ $startupDir = [Environment]::GetFolderPath("Startup") $startupCmd = Join-Path $startupDir "notioncode-mcp.cmd" if (-not $NoAutoStart) { $escapedStart = (Join-Path $Root "start.ps1").Replace('"', '""') - @( + $escapedStartupLog = (Join-Path $Root ".runtime\logs\startup.log").Replace('"', '""') + $startupContent = @( "@echo off" - "powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File `"$escapedStart`"" - ) | Set-Content -LiteralPath $startupCmd -Encoding ASCII + "powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File `"$escapedStart`" >> `"$escapedStartupLog`" 2>&1" + ) -join "`r`n" + # Write explicitly instead of piping into Set-Content. On some Windows + # builds an existing zero-byte Startup file can make Set-Content fail with + # "Stream was not readable" even though the file is writable. + [IO.File]::WriteAllText($startupCmd, $startupContent + "`r`n", [Text.Encoding]::ASCII) + + # Older releases created a second Startup entry that directly launched + # notion-agent from a checkout-specific path. Disable only that known legacy + # launcher so login cannot race two independent local service stacks. + $legacyStartupVbs = Join-Path $startupDir "StartNotionAgent.vbs" + if (Test-Path -LiteralPath $legacyStartupVbs -PathType Leaf) { + $legacyText = Get-Content -LiteralPath $legacyStartupVbs -Raw + if ($legacyText -match '(?i)notion-agent\.exe' -and $legacyText -match '(?i)\bserve\b') { + Move-Item -LiteralPath $legacyStartupVbs -Destination ($legacyStartupVbs + ".disabled-notioncode") -Force + } else { + Write-Warning "StartNotionAgent.vbs was not recognized as the legacy NotionCode launcher and was left unchanged." + } + } } if (-not $NoStart) { @@ -94,6 +119,7 @@ if (-not $NoStart) { Write-Host "Installation completed." Write-Host "Notion account directory: $AccountHome" Write-Host "Model aliases: $ModelsPath" +Write-Host "Codex model catalog: $CodexModelsPath" Write-Host "Codex VS Code configuration: $(Join-Path $CodexHome 'config.toml')" Write-Host "OpenCode profile: $OpenCodeHome" Write-Host "Health endpoint: http://127.0.0.1:8765/healthz" diff --git a/notion-private-api-mcp/package.json b/notion-private-api-mcp/package.json index 163f8b5..97ded7f 100644 --- a/notion-private-api-mcp/package.json +++ b/notion-private-api-mcp/package.json @@ -43,7 +43,8 @@ ], "scripts": { "start": "node ./src/server.js", - "check": "node --check ./src/server.js && node --check ./src/notion-client.js && node --check ./src/notion-blocks.js && node --check ./src/markdown.js" + "check": "node --check ./src/server.js && node --check ./src/notion-client.js && node --check ./src/notion-blocks.js && node --check ./src/markdown.js && node --check ./src/external-inference-client.js && node --check ./src/external-inference-server.js && node --check ./run-external-inference.js", + "test": "node --test ./src/external-inference-client.test.js" }, "dependencies": { "@modelcontextprotocol/sdk": "^1.29.0", diff --git a/notion-private-api-mcp/run-external-inference.js b/notion-private-api-mcp/run-external-inference.js new file mode 100644 index 0000000..de98ab1 --- /dev/null +++ b/notion-private-api-mcp/run-external-inference.js @@ -0,0 +1,8 @@ +#!/usr/bin/env node + +import { main } from "./src/external-inference-server.js"; + +main().catch((error) => { + console.error("External inference MCP startup failed:", error instanceof Error ? error.message : String(error)); + process.exit(1); +}); diff --git a/notion-private-api-mcp/src/external-inference-client.js b/notion-private-api-mcp/src/external-inference-client.js new file mode 100644 index 0000000..5d0f888 --- /dev/null +++ b/notion-private-api-mcp/src/external-inference-client.js @@ -0,0 +1,240 @@ +const PROVIDERS = Object.freeze({ + openrouter: Object.freeze({ + name: "OpenRouter", + endpoint: "https://openrouter.ai/api/v1/chat/completions", + modelsEndpoint: "https://openrouter.ai/api/v1/models", + envKey: "OPENROUTER_API_KEY", + defaultModel: "openai/gpt-5.6-sol", + models: Object.freeze([ + "openai/gpt-5.6-sol", + "openai/gpt-5.6-sol-pro", + "anthropic/claude-opus-5-fast", + ]), + reasoningStyle: "openrouter", + }), + vivgrid: Object.freeze({ + name: "Vivgrid", + endpoint: "https://api.vivgrid.com/v1/chat/completions", + modelsEndpoint: "https://api.vivgrid.com/v1/models", + envKey: "VIVGRID_API_KEY", + defaultModel: "gpt-5.6-sol", + models: Object.freeze([ + "gpt-5.6-sol", + "gpt-5.6-terra", + "gpt-5.6-luna", + ]), + reasoningStyle: "openai", + }), + cerebras: Object.freeze({ + name: "Cerebras", + endpoint: "https://api.cerebras.ai/v1/chat/completions", + modelsEndpoint: "https://api.cerebras.ai/v1/models", + envKey: "CEREBRAS_API_KEY", + defaultModel: "gpt-oss-120b", + models: Object.freeze([ + "gpt-oss-120b", + "zai-glm-4.7", + "gemma-4-31b", + ]), + reasoningStyle: "openai", + }), +}); + +const REASONING_EFFORTS = new Set(["none", "low", "medium", "high", "xhigh", "max"]); + +function providerConfig(provider) { + const config = PROVIDERS[provider]; + if (!config) { + throw new Error(`Unsupported external provider: ${provider}`); + } + return config; +} + +function safeProviderMessage(payload, apiKey) { + const candidate = payload?.error?.message ?? payload?.message ?? "Provider returned an error."; + let message = String(candidate); + if (apiKey) message = message.replaceAll(apiKey, "[redacted]"); + return message.slice(0, 500); +} + +function responseText(payload) { + const content = payload?.choices?.[0]?.message?.content; + if (typeof content === "string") return content; + if (Array.isArray(content)) { + return content + .map((part) => typeof part === "string" ? part : part?.text ?? "") + .join(""); + } + throw new Error("External provider returned no assistant text."); +} + +export function externalProviderStatus(env = process.env) { + return Object.entries(PROVIDERS).map(([id, config]) => ({ + id, + name: config.name, + configured: Boolean(env[config.envKey]), + environment_variable: config.envKey, + default_model: config.defaultModel, + models: [...config.models], + })); +} + +export async function discoverExternalModels(provider, { + env = process.env, + fetchImpl = globalThis.fetch, + timeoutMs = 30_000, +} = {}) { + const config = providerConfig(provider); + const apiKey = env[config.envKey]; + if (!apiKey) { + throw new Error(`${config.envKey} is not configured. Run configure-external-provider.ps1 locally and restart Codex.`); + } + if (typeof fetchImpl !== "function") { + throw new Error("This Node.js runtime does not provide fetch()."); + } + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), timeoutMs); + let response; + try { + response = await fetchImpl(config.modelsEndpoint, { + method: "GET", + headers: { authorization: `Bearer ${apiKey}` }, + signal: controller.signal, + }); + } catch (error) { + if (error?.name === "AbortError") { + throw new Error(`${config.name} model discovery timed out after ${timeoutMs} ms.`); + } + throw new Error(`${config.name} model discovery failed before a response was received.`); + } finally { + clearTimeout(timer); + } + let payload; + try { + payload = await response.json(); + } catch { + throw new Error(`${config.name} returned a non-JSON model catalog (${response.status}).`); + } + if (!response.ok) { + throw new Error(`${config.name} model discovery failed (${response.status}): ${safeProviderMessage(payload, apiKey)}`); + } + const entries = Array.isArray(payload?.data) + ? payload.data + : Array.isArray(payload?.models) + ? payload.models + : []; + const models = [...new Set(entries + .map((entry) => typeof entry === "string" ? entry : entry?.id) + .filter((id) => typeof id === "string" && id.trim()) + .map((id) => id.trim()))].sort(); + return { provider, models }; +} + +export function buildExternalRequest({ + provider, + model, + prompt, + system, + reasoningEffort, + maxOutputTokens = 4096, + verifiedModels = [], +}) { + const config = providerConfig(provider); + const selectedModel = model || config.defaultModel; + if (!config.models.includes(selectedModel) && !verifiedModels.includes(selectedModel)) { + throw new Error(`Model ${selectedModel} is not allowlisted for ${provider}.`); + } + if (reasoningEffort && !REASONING_EFFORTS.has(reasoningEffort)) { + throw new Error(`Unsupported reasoning effort: ${reasoningEffort}`); + } + const messages = []; + if (system) messages.push({ role: "system", content: system }); + messages.push({ role: "user", content: prompt }); + const body = { + model: selectedModel, + messages, + stream: false, + max_tokens: maxOutputTokens, + }; + if (reasoningEffort) { + if (config.reasoningStyle === "openrouter") { + body.reasoning = { effort: reasoningEffort }; + } else { + body.reasoning_effort = reasoningEffort; + } + } + return { config, selectedModel, body }; +} + +export async function generateExternal(args, { + env = process.env, + fetchImpl = globalThis.fetch, + timeoutMs = 300_000, + clock = () => Date.now(), +} = {}) { + const config = providerConfig(args.provider); + const apiKey = env[config.envKey]; + if (!apiKey) { + throw new Error(`${config.envKey} is not configured. Run configure-external-provider.ps1 locally and restart Codex.`); + } + if (typeof fetchImpl !== "function") { + throw new Error("This Node.js runtime does not provide fetch()."); + } + let verifiedModels = []; + let modelSource = "static_allowlist"; + if (args.model && !config.models.includes(args.model)) { + const discovered = await discoverExternalModels(args.provider, { + env, + fetchImpl, + timeoutMs: Math.min(timeoutMs, 30_000), + }); + verifiedModels = discovered.models; + modelSource = "live_provider_catalog"; + } + const { selectedModel, body } = buildExternalRequest({ + ...args, + verifiedModels, + }); + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), timeoutMs); + const startedAt = clock(); + let response; + try { + response = await fetchImpl(config.endpoint, { + method: "POST", + headers: { + authorization: `Bearer ${apiKey}`, + "content-type": "application/json", + }, + body: JSON.stringify(body), + signal: controller.signal, + }); + } catch (error) { + if (error?.name === "AbortError") { + throw new Error(`${config.name} request timed out after ${timeoutMs} ms.`); + } + throw new Error(`${config.name} request failed before a response was received.`); + } finally { + clearTimeout(timer); + } + const elapsedMs = Math.max(0, clock() - startedAt); + let payload; + try { + payload = await response.json(); + } catch { + throw new Error(`${config.name} returned a non-JSON response (${response.status}).`); + } + if (!response.ok) { + throw new Error(`${config.name} request failed (${response.status}): ${safeProviderMessage(payload, apiKey)}`); + } + return { + provider: args.provider, + model: selectedModel, + model_source: modelSource, + elapsed_ms: elapsedMs, + text: responseText(payload), + usage: payload.usage ?? null, + }; +} + +export const EXTERNAL_PROVIDER_IDS = Object.freeze(Object.keys(PROVIDERS)); diff --git a/notion-private-api-mcp/src/external-inference-client.test.js b/notion-private-api-mcp/src/external-inference-client.test.js new file mode 100644 index 0000000..7228451 --- /dev/null +++ b/notion-private-api-mcp/src/external-inference-client.test.js @@ -0,0 +1,115 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + buildExternalRequest, + discoverExternalModels, + externalProviderStatus, + generateExternal, +} from "./external-inference-client.js"; + +test("provider status reports only key presence", () => { + const secret = "secret-that-must-not-appear"; + const status = externalProviderStatus({ OPENROUTER_API_KEY: secret }); + assert.equal(status.find(({ id }) => id === "openrouter").configured, true); + assert.equal(status.find(({ id }) => id === "vivgrid").configured, false); + assert.doesNotMatch(JSON.stringify(status), new RegExp(secret)); +}); + +test("OpenRouter uses its verified model id and reasoning object", () => { + const request = buildExternalRequest({ + provider: "openrouter", + prompt: "test", + reasoningEffort: "max", + }); + assert.equal(request.selectedModel, "openai/gpt-5.6-sol"); + assert.deepEqual(request.body.reasoning, { effort: "max" }); + assert.equal(request.body.reasoning_effort, undefined); +}); + +test("provider model allowlist rejects invented aliases", () => { + assert.throws(() => buildExternalRequest({ + provider: "cerebras", + model: "ultrafast-gpt-6", + prompt: "test", + }), /not allowlisted/); +}); + +test("live provider catalog enables a newly released exact model id", async () => { + const secret = "local-cerebras-key"; + const calls = []; + const futureModel = "provider-new-ultrafast-model"; + const fetchImpl = async (url, options) => { + calls.push({ url, options }); + if (url.endsWith("/models")) { + return { + ok: true, + status: 200, + json: async () => ({ data: [{ id: futureModel }, { id: "gpt-oss-120b" }] }), + }; + } + return { + ok: true, + status: 200, + json: async () => ({ + choices: [{ message: { content: "fast result" } }], + usage: { prompt_tokens: 1, completion_tokens: 2 }, + }), + }; + }; + const discovered = await discoverExternalModels("cerebras", { + env: { CEREBRAS_API_KEY: secret }, + fetchImpl, + }); + assert.deepEqual(discovered.models, ["gpt-oss-120b", futureModel]); + const result = await generateExternal({ + provider: "cerebras", + model: futureModel, + prompt: "test", + }, { + env: { CEREBRAS_API_KEY: secret }, + fetchImpl, + }); + assert.equal(result.model, futureModel); + assert.equal(result.model_source, "live_provider_catalog"); + assert.equal(JSON.parse(calls.at(-1).options.body).model, futureModel); + assert.doesNotMatch(JSON.stringify({ discovered, result }), new RegExp(secret)); +}); + +test("generation sends the key only in authorization and returns timing", async () => { + const secret = "local-test-key"; + let captured; + const times = [100, 250]; + const result = await generateExternal({ + provider: "vivgrid", + prompt: "test", + reasoningEffort: "high", + maxOutputTokens: 128, + }, { + env: { VIVGRID_API_KEY: secret }, + clock: () => times.shift(), + fetchImpl: async (url, options) => { + captured = { url, options }; + return { + ok: true, + status: 200, + json: async () => ({ + choices: [{ message: { content: "ok" } }], + usage: { prompt_tokens: 1, completion_tokens: 1 }, + }), + }; + }, + }); + assert.equal(captured.url, "https://api.vivgrid.com/v1/chat/completions"); + assert.equal(captured.options.headers.authorization, `Bearer ${secret}`); + assert.equal(JSON.parse(captured.options.body).reasoning_effort, "high"); + assert.equal(result.elapsed_ms, 150); + assert.equal(result.text, "ok"); + assert.doesNotMatch(JSON.stringify(result), new RegExp(secret)); +}); + +test("generation fails locally when no provider key exists", async () => { + await assert.rejects(generateExternal({ + provider: "cerebras", + prompt: "test", + }, { env: {} }), /CEREBRAS_API_KEY is not configured/); +}); diff --git a/notion-private-api-mcp/src/external-inference-server.js b/notion-private-api-mcp/src/external-inference-server.js new file mode 100644 index 0000000..93fefe6 --- /dev/null +++ b/notion-private-api-mcp/src/external-inference-server.js @@ -0,0 +1,97 @@ +#!/usr/bin/env node + +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import * as z from "zod/v4"; +import { + discoverExternalModels, + externalProviderStatus, + generateExternal, +} from "./external-inference-client.js"; + +function textResult(data) { + return { + content: [{ type: "text", text: JSON.stringify(data, null, 2) }], + structuredContent: data, + }; +} + +function toolError(error) { + return { + content: [{ + type: "text", + text: error instanceof Error ? error.message : String(error), + }], + isError: true, + }; +} + +async function runTool(handler) { + try { + return await handler(); + } catch (error) { + return toolError(error); + } +} + +export function buildExternalInferenceServer() { + const server = new McpServer({ + name: "external-inference-mcp", + version: "0.1.0", + }); + + server.registerTool("external_provider_status", { + title: "External Provider Status", + description: + "Show which optional external inference providers have a locally configured API key. Never returns key values and does not contact providers.", + inputSchema: {}, + }, async () => textResult({ providers: externalProviderStatus() })); + + server.registerTool("external_models", { + title: "External Provider Models", + description: + "Read a provider's live model catalog using its locally configured API key. Key values are never returned. Use this to detect newly released models without inventing aliases.", + inputSchema: { + provider: z.enum(["openrouter", "vivgrid", "cerebras"]) + .describe("External provider whose live model catalog should be read."), + }, + }, async (args) => runTool(async () => textResult(await discoverExternalModels(args.provider)))); + + server.registerTool("external_generate", { + title: "External Model Generate", + description: + "Send one text-generation request to a separately billed external provider and report elapsed time. This does not accelerate Notion AI or reuse Notion usage. Use only when the user explicitly wants an external high-speed model.", + inputSchema: { + provider: z.enum(["openrouter", "vivgrid", "cerebras"]) + .describe("External provider to call."), + user_authorized_external_billing: z.literal(true) + .describe("Must be true only after the user explicitly requested this separately billed external request."), + model: z.string().optional() + .describe("Provider model ID. Static models are accepted locally; new IDs are accepted only after exact verification against the provider's live model catalog."), + prompt: z.string().min(1).max(200000) + .describe("User prompt sent to the external provider."), + system: z.string().max(50000).optional() + .describe("Optional system instruction sent to the external provider."), + reasoning_effort: z.enum(["none", "low", "medium", "high", "xhigh", "max"]) + .optional() + .describe("Optional provider reasoning effort. Ultra is intentionally excluded because these APIs do not expose a verified Ultra wire value."), + max_output_tokens: z.number().int().min(1).max(32768).default(4096) + .describe("Maximum requested output tokens."), + }, + }, async (args) => runTool(async () => textResult(await generateExternal({ + provider: args.provider, + model: args.model, + prompt: args.prompt, + system: args.system, + reasoningEffort: args.reasoning_effort, + maxOutputTokens: args.max_output_tokens, + })))); + + return server; +} + +export async function main() { + const server = buildExternalInferenceServer(); + const transport = new StdioServerTransport(); + await server.connect(transport); +} diff --git a/runtime/.env.example b/runtime/.env.example index 8fc72b2..4048488 100644 --- a/runtime/.env.example +++ b/runtime/.env.example @@ -3,3 +3,13 @@ MCP_PATH_SECRET=replace-with-a-random-secret CODE_ROOT=/path/to/projects PORT=8787 + +# Latency safeguards for the Notion inference bridge. Higher values can be +# chosen for unusually long high/ultra-reasoning tasks. +NOTION_INFERENCE_TIMEOUT_SECONDS=180 +NOTION_POOL_RECOVERY_WAIT_SECONDS=8 +NOTION_MAX_RECOVERY_CYCLES=1 +NOTION_SINGLE_ACCOUNT_TRANSIENT_COOLDOWN_SECONDS=1 +# Optional comma-separated account filenames that benchmark faster with +# Notion's legacy cumulative response stream instead of patch responses. +NOTION_LEGACY_RESPONSE_ACCOUNT_FILES= diff --git a/scripts/check-layout.mjs b/scripts/check-layout.mjs index 0719b5e..b6dfd43 100755 --- a/scripts/check-layout.mjs +++ b/scripts/check-layout.mjs @@ -18,6 +18,8 @@ const requiredShared = [ "notion-private-api-mcp/run-from-account.js", "config/codex-cli-config.toml", "scripts/install-codex-config.mjs", + "scripts/patch-codex-desktop.mjs", + "scripts/patch-codex-desktop.test.mjs", "scripts/patch-codex-webview.mjs", "scripts/test-codex-app-server.mjs", "scripts/check-public-release.mjs", diff --git a/scripts/install-codex-config.mjs b/scripts/install-codex-config.mjs index 99d1bcb..268ff88 100644 --- a/scripts/install-codex-config.mjs +++ b/scripts/install-codex-config.mjs @@ -3,16 +3,25 @@ import fs from "node:fs"; import path from "node:path"; -const [templatePath, destination, projectRoot, userHome, notionMcpEnabled] = process.argv.slice(2); +const [ + templatePath, + destination, + projectRoot, + userHome, + notionMcpEnabled, + requestedReasoningEffort = "", +] = process.argv.slice(2); +const supportedReasoningEfforts = new Set(["low", "medium", "high", "xhigh", "max", "ultra"]); if ( !templatePath || !destination || !projectRoot || !userHome || !["true", "false"].includes(notionMcpEnabled) + || (requestedReasoningEffort && !supportedReasoningEfforts.has(requestedReasoningEffort)) ) { throw new Error( - "usage: install-codex-config.mjs