diff --git a/app/control/account/backends/local.py b/app/control/account/backends/local.py index 2f01f74a..85eb3971 100644 --- a/app/control/account/backends/local.py +++ b/app/control/account/backends/local.py @@ -64,6 +64,7 @@ class LocalAccountRepository: quota_fast TEXT NOT NULL DEFAULT '{{}}', quota_expert TEXT NOT NULL DEFAULT '{{}}', quota_heavy TEXT NOT NULL DEFAULT '{{}}', + quota_grok_4_3 TEXT NOT NULL DEFAULT '{{}}', usage_use_count INTEGER NOT NULL DEFAULT 0, usage_fail_count INTEGER NOT NULL DEFAULT 0, usage_sync_count INTEGER NOT NULL DEFAULT 0, @@ -84,8 +85,15 @@ class LocalAccountRepository: CREATE INDEX IF NOT EXISTS idx_acc_deleted ON {_TBL} (deleted_at) WHERE deleted_at IS NOT NULL; """) + self._ensure_column_sync(conn, "quota_grok_4_3", "TEXT NOT NULL DEFAULT '{}'") conn.commit() + @staticmethod + def _ensure_column_sync(conn: sqlite3.Connection, name: str, ddl: str) -> None: + cols = {row[1] for row in conn.execute(f"PRAGMA table_info({_TBL})").fetchall()} + if name not in cols: + conn.execute(f"ALTER TABLE {_TBL} ADD COLUMN {name} {ddl}") + def _bump_revision(self, conn: sqlite3.Connection) -> int: conn.execute( f"UPDATE {_META} SET value = CAST(value AS INTEGER) + 1 WHERE key = 'revision'" @@ -105,13 +113,16 @@ class LocalAccountRepository: def _row_to_record(row: sqlite3.Row) -> AccountRecord: d = dict(row) d["tags"] = json.loads(d.get("tags") or "[]") - heavy_raw = d.pop("quota_heavy", "{}") or "{}" - heavy_dict = json.loads(heavy_raw) + heavy_raw = d.pop("quota_heavy", "{}") or "{}" + grok_4_3_raw = d.pop("quota_grok_4_3", "{}") or "{}" + heavy_dict = json.loads(heavy_raw) + grok_4_3_dict = json.loads(grok_4_3_raw) d["quota"] = { "auto": json.loads(d.pop("quota_auto", "{}") or "{}"), "fast": json.loads(d.pop("quota_fast", "{}") or "{}"), "expert": json.loads(d.pop("quota_expert", "{}") or "{}"), - **({"heavy": heavy_dict} if heavy_dict else {}), + **({"heavy": heavy_dict} if heavy_dict else {}), + **({"grok_4_3": grok_4_3_dict} if grok_4_3_dict else {}), } d["ext"] = json.loads(d.get("ext") or "{}") return AccountRecord.model_validate(d) @@ -129,7 +140,8 @@ class LocalAccountRepository: "quota_auto": json.dumps(qs.auto.to_dict()), "quota_fast": json.dumps(qs.fast.to_dict()), "quota_expert": json.dumps(qs.expert.to_dict()), - "quota_heavy": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}", + "quota_heavy": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}", + "quota_grok_4_3": json.dumps(qs.grok_4_3.to_dict()) if qs.grok_4_3 else "{}", "usage_use_count": record.usage_use_count, "usage_fail_count": record.usage_fail_count, "usage_sync_count": record.usage_sync_count, @@ -163,12 +175,12 @@ class LocalAccountRepository: f""" INSERT INTO {_TBL} ( token, pool, status, created_at, updated_at, - tags, quota_auto, quota_fast, quota_expert, quota_heavy, + tags, quota_auto, quota_fast, quota_expert, quota_heavy, quota_grok_4_3, usage_use_count, usage_fail_count, usage_sync_count, ext, revision ) VALUES ( :token, :pool, 'active', :ts, :ts, - :tags, :qa, :qf, :qe, :qh, + :tags, :qa, :qf, :qe, :qh, :qg, 0, 0, 0, :ext, :rev ) ON CONFLICT(token) DO UPDATE SET @@ -188,7 +200,8 @@ class LocalAccountRepository: "qa": json.dumps(qs.auto.to_dict()), "qf": json.dumps(qs.fast.to_dict()), "qe": json.dumps(qs.expert.to_dict()), - "qh": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}", + "qh": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}", + "qg": json.dumps(qs.grok_4_3.to_dict()) if qs.grok_4_3 else "{}", "ext": json.dumps(item.ext), "rev": revision, }, @@ -250,6 +263,8 @@ class LocalAccountRepository: sets["quota_expert"] = json.dumps(patch.quota_expert) if patch.quota_heavy is not None: sets["quota_heavy"] = json.dumps(patch.quota_heavy) + if patch.quota_grok_4_3 is not None: + sets["quota_grok_4_3"] = json.dumps(patch.quota_grok_4_3) # Tags — use set arithmetic to avoid O(n×m) membership tests. tag_set: set[str] = set(record.tags) diff --git a/app/control/account/backends/sql.py b/app/control/account/backends/sql.py index 63a1f419..04587ecb 100644 --- a/app/control/account/backends/sql.py +++ b/app/control/account/backends/sql.py @@ -46,6 +46,7 @@ accounts_table = sa.Table( sa.Column("quota_fast", sa.Text, nullable=False, default="{}"), sa.Column("quota_expert", sa.Text, nullable=False, default="{}"), sa.Column("quota_heavy", sa.Text, nullable=False, default="{}"), + sa.Column("quota_grok_4_3", sa.Text, nullable=False, default="{}"), sa.Column("usage_use_count", sa.Integer, nullable=False, default=0), sa.Column("usage_fail_count", sa.Integer, nullable=False, default=0), sa.Column("usage_sync_count", sa.Integer, nullable=False, default=0), @@ -404,13 +405,16 @@ def _evict_cached_engine(engine: AsyncEngine) -> None: def _row_to_record(row: Any) -> AccountRecord: d = dict(row._mapping) d["tags"] = json.loads(d.get("tags") or "[]") - heavy_raw = d.pop("quota_heavy", "{}") or "{}" - heavy_dict = json.loads(heavy_raw) + heavy_raw = d.pop("quota_heavy", "{}") or "{}" + grok_4_3_raw = d.pop("quota_grok_4_3", "{}") or "{}" + heavy_dict = json.loads(heavy_raw) + grok_4_3_dict = json.loads(grok_4_3_raw) d["quota"] = { "auto": json.loads(d.pop("quota_auto", "{}") or "{}"), "fast": json.loads(d.pop("quota_fast", "{}") or "{}"), "expert": json.loads(d.pop("quota_expert", "{}") or "{}"), - **({"heavy": heavy_dict} if heavy_dict else {}), + **({"heavy": heavy_dict} if heavy_dict else {}), + **({"grok_4_3": grok_4_3_dict} if grok_4_3_dict else {}), } d["ext"] = json.loads(d.get("ext") or "{}") return AccountRecord.model_validate(d) @@ -498,6 +502,7 @@ class SqlAccountRepository: async def _do_initialize(self) -> None: async with self._engine.begin() as conn: await conn.run_sync(metadata.create_all) + await self._ensure_columns(conn) # Seed revision row. if self._dialect == "postgresql": from sqlalchemy.dialects.postgresql import insert as pg_insert @@ -514,6 +519,34 @@ class SqlAccountRepository: .on_duplicate_key_update(value="0") ) + async def _ensure_columns(self, conn: Any) -> None: + """Idempotent ALTER TABLE migrations for columns added after the initial schema.""" + existing = await self._table_columns(conn, _TBL_ACCOUNTS) + if "quota_grok_4_3" not in existing: + await conn.exec_driver_sql( + f"ALTER TABLE {_TBL_ACCOUNTS} " + f"ADD COLUMN quota_grok_4_3 TEXT NOT NULL DEFAULT '{{}}'" + ) + + async def _table_columns(self, conn: Any, table: str) -> set[str]: + if self._dialect == "postgresql": + rows = await conn.execute( + sa.text( + "SELECT column_name FROM information_schema.columns " + "WHERE table_name = :t" + ), + {"t": table}, + ) + else: + rows = await conn.execute( + sa.text( + "SELECT COLUMN_NAME FROM information_schema.columns " + "WHERE table_schema = DATABASE() AND table_name = :t" + ), + {"t": table}, + ) + return {str(r[0]).lower() for r in rows.fetchall()} + async def initialize(self) -> None: await self._ensure_initialized() @@ -590,7 +623,8 @@ class SqlAccountRepository: "quota_auto": json.dumps(qs.auto.to_dict()), "quota_fast": json.dumps(qs.fast.to_dict()), "quota_expert": json.dumps(qs.expert.to_dict()), - "quota_heavy": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}", + "quota_heavy": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}", + "quota_grok_4_3": json.dumps(qs.grok_4_3.to_dict()) if qs.grok_4_3 else "{}", "usage_use_count": 0, "usage_fail_count": 0, "usage_sync_count": 0, @@ -645,6 +679,8 @@ class SqlAccountRepository: updates["quota_expert"] = json.dumps(patch.quota_expert) if patch.quota_heavy is not None: updates["quota_heavy"] = json.dumps(patch.quota_heavy) + if patch.quota_grok_4_3 is not None: + updates["quota_grok_4_3"] = json.dumps(patch.quota_grok_4_3) if patch.usage_use_delta is not None: updates["usage_use_count"] = max(0, record.usage_use_count + patch.usage_use_delta) if patch.usage_fail_delta is not None: diff --git a/app/control/account/commands.py b/app/control/account/commands.py index bb626753..ba501143 100644 --- a/app/control/account/commands.py +++ b/app/control/account/commands.py @@ -36,6 +36,7 @@ class AccountPatch(BaseModel): quota_fast: dict[str, Any] | None = None quota_expert: dict[str, Any] | None = None quota_heavy: dict[str, Any] | None = None + quota_grok_4_3: dict[str, Any] | None = None # Usage counters — delta values (added to existing counts). usage_use_delta: int | None = None usage_fail_delta: int | None = None diff --git a/app/control/account/quota_defaults.py b/app/control/account/quota_defaults.py index 77135318..f5464806 100644 --- a/app/control/account/quota_defaults.py +++ b/app/control/account/quota_defaults.py @@ -114,7 +114,7 @@ def supported_mode_ids(pool: str) -> tuple[int, ...]: supported = _SUPPORTED_MODE_IDS_BY_POOL.get( pool, _SUPPORTED_MODE_IDS_BY_POOL["basic"] ) - return tuple(mode_id for mode_id in (0, 1, 2, 3) if mode_id in supported) + return tuple(mode_id for mode_id in (0, 1, 2, 3, 4) if mode_id in supported) def default_quota_window(pool: str, mode_id: int) -> QuotaWindow | None: diff --git a/app/control/account/refresh.py b/app/control/account/refresh.py index 4424c3e7..c21238d4 100644 --- a/app/control/account/refresh.py +++ b/app/control/account/refresh.py @@ -9,7 +9,7 @@ from app.platform.config.snapshot import get_config from app.platform.logging.logger import logger from app.platform.runtime.clock import now_ms from app.platform.runtime.batch import run_batch -from app.control.model.enums import ALL_MODES_WITH_HEAVY +from app.control.model.enums import ALL_MODES_FULL from .enums import AccountStatus, QuotaSource from .models import AccountRecord, QuotaWindow from .quota_defaults import ( @@ -49,6 +49,7 @@ _MODE_KEYS = { 1: "quota_fast", 2: "quota_expert", 3: "quota_heavy", + 4: "quota_grok_4_3", } @@ -248,7 +249,7 @@ class AccountRefreshService: patches: dict[str, dict] = {} refreshed = False - for mode in ALL_MODES_WITH_HEAVY: + for mode in ALL_MODES_FULL: mode_id = int(mode) if mode_id in windows: patches[_MODE_KEYS[mode_id]] = windows[mode_id].to_dict() @@ -320,7 +321,7 @@ class AccountRefreshService: now = now_ms() patches: dict[str, dict] = {} - for mode in ALL_MODES_WITH_HEAVY: + for mode in ALL_MODES_FULL: mode_id = int(mode) existing = qs.get(mode_id) if existing is None: diff --git a/app/dataplane/reverse/protocol/xai_chat.py b/app/dataplane/reverse/protocol/xai_chat.py index 785f160d..187956ee 100644 --- a/app/dataplane/reverse/protocol/xai_chat.py +++ b/app/dataplane/reverse/protocol/xai_chat.py @@ -8,7 +8,7 @@ import orjson from app.platform.logging.logger import logger from app.platform.config.snapshot import get_config -from app.control.model.enums import ModeId, MODE_STRINGS +from app.control.model.enums import ModeId from app.dataplane.reverse.protocol.xai_chat_reasoning import ReasoningAggregator @@ -49,7 +49,7 @@ def build_chat_payload( "imageGenerationCount": 2, "isAsyncChat": False, "message": message, - "modeId": MODE_STRINGS[mode_id], + "modeId": mode_id.to_api_str(), "responseMetadata": {}, "returnImageBytes": False, "returnRawGrokInXaiRequest": False, @@ -77,7 +77,7 @@ def build_chat_payload( logger.debug( "chat payload built: mode={} message_len={} file_count={}", - MODE_STRINGS[mode_id], len(message), len(file_attachments), + mode_id.to_api_str(), len(message), len(file_attachments), ) return payload diff --git a/app/dataplane/reverse/protocol/xai_usage.py b/app/dataplane/reverse/protocol/xai_usage.py index e04158fe..46adfdc5 100644 --- a/app/dataplane/reverse/protocol/xai_usage.py +++ b/app/dataplane/reverse/protocol/xai_usage.py @@ -20,6 +20,7 @@ _MODE_NAMES: dict[int, str] = { 1: "fast", 2: "expert", 3: "heavy", + 4: "grok-420-computer-use-sa", } # Default window durations used as fallback when API call fails. @@ -28,6 +29,7 @@ _DEFAULT_WINDOW_SECS: dict[int, int] = { 1: 72_000, # fast — 20 h (basic) 2: 36_000, # expert — 10 h (basic) 3: 7_200, # heavy — 2 h (heavy-pool only) + 4: 7_200, # grok_4_3 — 2 h (super/heavy only) } @@ -165,13 +167,13 @@ async def fetch_all_quotas( ) -> dict[int, object] | None: """Fetch quota windows for the requested modes concurrently. - ``mode_ids`` defaults to ``(0, 1, 2, 3)``. Returns ``{mode_id: QuotaWindow}`` + ``mode_ids`` defaults to ``(0, 1, 2, 3, 4)``. Returns ``{mode_id: QuotaWindow}`` for every mode that responded successfully, or ``None`` if every requested mode failed. """ import asyncio - requested = mode_ids or (0, 1, 2, 3) + requested = mode_ids or (0, 1, 2, 3, 4) results = await asyncio.gather( *(_fetch_one(token, mode_id) for mode_id in requested), return_exceptions=True ) diff --git a/app/platform/startup/migration.py b/app/platform/startup/migration.py index f6c97d7f..741f6425 100644 --- a/app/platform/startup/migration.py +++ b/app/platform/startup/migration.py @@ -52,6 +52,7 @@ async def run_startup_migrations( """Run all first-boot migrations. Safe to call on every startup.""" await _migrate_config(config_backend) await _migrate_accounts(account_repo) + await _backfill_grok_4_3_quota(account_repo) # --------------------------------------------------------------------------- @@ -175,7 +176,8 @@ def _record_to_patch(r) -> "AccountPatch": quota_auto=qs.auto.to_dict() if qs.auto else None, quota_fast=qs.fast.to_dict() if qs.fast else None, quota_expert=qs.expert.to_dict() if qs.expert else None, - quota_heavy=qs.heavy.to_dict() if qs.heavy else None, + quota_heavy=qs.heavy.to_dict() if qs.heavy else None, + quota_grok_4_3=qs.grok_4_3.to_dict() if qs.grok_4_3 else None, # Usage counts — target starts at 0, so actual value == delta. usage_use_delta=r.usage_use_count or None, usage_fail_delta=r.usage_fail_count or None, @@ -190,6 +192,44 @@ def _record_to_patch(r) -> "AccountPatch": ) +# --------------------------------------------------------------------------- +# Backfill quota_grok_4_3 for super/heavy accounts imported before the field existed. +# --------------------------------------------------------------------------- + +async def _backfill_grok_4_3_quota(repo: "AccountRepository") -> None: + from app.control.account.commands import AccountPatch, ListAccountsQuery + from app.control.account.quota_defaults import default_quota_window + + patches: list[AccountPatch] = [] + page = 1 + while True: + result = await repo.list_accounts( + ListAccountsQuery(page=page, page_size=_BATCH, include_deleted=False) + ) + for record in result.items: + if record.pool not in ("super", "heavy"): + continue + if record.quota_set().grok_4_3 is not None: + continue + window = default_quota_window(record.pool, 4) + if window is None: + continue + patches.append(AccountPatch(token=record.token, quota_grok_4_3=window.to_dict())) + if page >= result.total_pages: + break + page += 1 + + if not patches: + return + + total = 0 + for i in range(0, len(patches), _BATCH): + batch = patches[i : i + _BATCH] + res = await repo.patch_accounts(batch) + total += res.patched + logger.info("account: backfilled quota_grok_4_3 for {} super/heavy accounts", total) + + # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- diff --git a/app/products/openai/chat.py b/app/products/openai/chat.py index eb5bff3e..4eeab694 100644 --- a/app/products/openai/chat.py +++ b/app/products/openai/chat.py @@ -434,7 +434,7 @@ async def completions( model: str, messages: list[dict], stream: bool | None = None, - thinking: bool | None = None, + emit_think: bool | None = None, tools: list[dict] | None = None, tool_choice: Any = None, temperature: float = 0.8, @@ -450,9 +450,8 @@ async def completions( cfg = get_config() spec = resolve_model(model) is_stream = stream if stream is not None else cfg.get_bool("features.stream", True) - emit_think = ( - thinking if thinking is not None else cfg.get_bool("features.thinking", True) - ) + if emit_think is None: + emit_think = cfg.get_bool("features.thinking", True) logger.info( "chat request accepted: model={} stream={} message_count={}", diff --git a/app/products/openai/router.py b/app/products/openai/router.py index 15c2c65d..98fdffe2 100644 --- a/app/products/openai/router.py +++ b/app/products/openai/router.py @@ -324,11 +324,16 @@ async def chat_completions_endpoint(req: ChatCompletionRequest): request_overrides: dict | None = None if req.deepsearch: request_overrides = {"deepsearchPreset": req.deepsearch} + # reasoning_effort=None → config default; "none" → off; otherwise → on. + if req.reasoning_effort is None: + emit_think: bool | None = None + else: + emit_think = req.reasoning_effort != "none" result = await chat_completions( model=req.model, messages=messages, stream=is_stream, - thinking=req.thinking, + emit_think=emit_think, tools=req.tools, tool_choice=req.tool_choice, temperature=req.temperature or 0.8, diff --git a/app/products/openai/schemas.py b/app/products/openai/schemas.py index f2a6f954..a225785a 100644 --- a/app/products/openai/schemas.py +++ b/app/products/openai/schemas.py @@ -30,7 +30,6 @@ class ChatCompletionRequest(BaseModel): model: str messages: list[MessageItem] stream: bool | None = None - thinking: bool | None = None reasoning_effort: str | None = None temperature: float | None = 0.8 top_p: float | None = 0.95 diff --git a/app/statics/admin/account.html b/app/statics/admin/account.html index 1b103c81..f8983e3f 100644 --- a/app/statics/admin/account.html +++ b/app/statics/admin/account.html @@ -545,6 +545,7 @@ .q-f { background:#f2f8f4; color:#4c9168 } .q-e { background:#f7f3fb; color:#8d6bbd } .q-h { background:#fff4ed; color:#b0632a } + .q-b { background:#fdf2f7; color:#be3f7f } .q-z { background:#f6f6f6; color:#a0a0a6 } /* Token monospace */ @@ -1434,10 +1435,19 @@ function rowHtml(t) { } function qpills(q) { - const modes = [['auto','A','q-a'],['fast','F','q-f'],['expert','E','q-e'],['heavy','H','q-h']]; - return modes.map(([m,l,c]) => { + const modes = [ + ['auto', 'A', 'q-a', true], + ['fast', 'F', 'q-f', true], + ['expert', 'E', 'q-e', true], + ['heavy', 'H', 'q-h', true], + ['grok_4_3', 'B', 'q-b', false], + ]; + return modes.map(([m,l,c,showEmpty]) => { const win = q[m]; - if (win == null) return `${l}:0`; + if (win == null) { + if (!showEmpty) return ''; + return `${l}:0`; + } const r = win.remaining ?? null; return `${l}:${r ?? '?'}`; }).join(''); diff --git a/app/statics/i18n/de.json b/app/statics/i18n/de.json index a1ab4383..c9d974d9 100644 --- a/app/statics/i18n/de.json +++ b/app/statics/i18n/de.json @@ -283,7 +283,8 @@ "auto": "Auto", "fast": "Fast", "expert": "Expert", - "heavy": "Heavy" + "heavy": "Heavy", + "grok_4_3": "Grok 4.3 Beta" }, "status": { "active": "Aktiv", diff --git a/app/statics/i18n/en.json b/app/statics/i18n/en.json index 53e42a4d..0b8dd3f1 100644 --- a/app/statics/i18n/en.json +++ b/app/statics/i18n/en.json @@ -284,7 +284,8 @@ "auto": "Auto", "fast": "Fast", "expert": "Expert", - "heavy": "Heavy" + "heavy": "Heavy", + "grok_4_3": "Grok 4.3 Beta" }, "status": { "active": "Active", diff --git a/app/statics/i18n/es.json b/app/statics/i18n/es.json index 1662bdc7..3ec90709 100644 --- a/app/statics/i18n/es.json +++ b/app/statics/i18n/es.json @@ -283,7 +283,8 @@ "auto": "Auto", "fast": "Fast", "expert": "Expert", - "heavy": "Heavy" + "heavy": "Heavy", + "grok_4_3": "Grok 4.3 Beta" }, "status": { "active": "Activa", diff --git a/app/statics/i18n/fr.json b/app/statics/i18n/fr.json index aea216fc..f947d753 100644 --- a/app/statics/i18n/fr.json +++ b/app/statics/i18n/fr.json @@ -283,7 +283,8 @@ "auto": "Auto", "fast": "Fast", "expert": "Expert", - "heavy": "Heavy" + "heavy": "Heavy", + "grok_4_3": "Grok 4.3 Beta" }, "status": { "active": "Actif", diff --git a/app/statics/i18n/ja.json b/app/statics/i18n/ja.json index 23e75e99..b5fb9ae2 100644 --- a/app/statics/i18n/ja.json +++ b/app/statics/i18n/ja.json @@ -283,7 +283,8 @@ "auto": "Auto", "fast": "Fast", "expert": "Expert", - "heavy": "Heavy" + "heavy": "Heavy", + "grok_4_3": "Grok 4.3 Beta" }, "status": { "active": "有効", diff --git a/app/statics/i18n/zh.json b/app/statics/i18n/zh.json index a275f8c9..6f88402b 100644 --- a/app/statics/i18n/zh.json +++ b/app/statics/i18n/zh.json @@ -284,7 +284,8 @@ "auto": "Auto", "fast": "Fast", "expert": "Expert", - "heavy": "Heavy" + "heavy": "Heavy", + "grok_4_3": "Grok 4.3 Beta" }, "status": { "active": "正常",