// ==UserScript== // @name Codex 额度用量分析 // @namespace http://tampermonkey.net/ // @version 3.4.0 // @description 兼容个人账号:展示真实每日 Token,并按模型/速度权重折算 Credits // @author Jun Zhao, Canxin, loongphy // @match https://chatgpt.com/codex/cloud/settings/analytics* // @grant GM_addStyle // @run-at document-idle // ==/UserScript== (function () { "use strict"; if (window.__codexQuotaCompassInjected) return; window.__codexQuotaCompassInjected = true; const CONFIG = { TARGET_WINDOW_SECONDS: 7 * 24 * 60 * 60, DAY_MS: 24 * 60 * 60 * 1000, USE_UTC_DAY: true, EPS: 1e-9, USD_PER_CREDIT: 40 / 1000, }; const HTML_ESCAPE = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'", }; const escapeHtml = (value) => String(value ?? "").replace(/[&<>"']/g, (ch) => HTML_ESCAPE[ch]); const n = (value) => { if (typeof value === "string") value = value.replace(/,/g, "").trim(); const parsed = Number(value); return Number.isFinite(parsed) ? parsed : 0; }; const clamp = (value, min = 0, max = 1) => Math.min(max, Math.max(min, n(value))); const trimFixed = (value, digits = 2) => { const str = n(value).toFixed(digits); return str.replace(/\.?0+$/, ""); }; const firstFinite = (...values) => { for (const value of values) { const num = n(value); if (Number.isFinite(num) && num > 0) return num; } return 0; }; const asArray = (value) => (Array.isArray(value) ? value : []); const fmtNum = (value) => { const num = n(value); const abs = Math.abs(num); const sign = num < 0 ? "-" : ""; if (abs >= 1e12) return sign + trimFixed(abs / 1e12, 2) + "T"; if (abs >= 1e9) return sign + trimFixed(abs / 1e9, 2) + "B"; if (abs >= 1e6) return sign + trimFixed(abs / 1e6, 2) + "M"; if (abs >= 1e3) return sign + trimFixed(abs / 1e3, 2) + "K"; return num.toLocaleString(); }; const fmtUsd = (value) => `$ ${n(value).toFixed(2)}`; const tokenParts = (obj = {}) => ({ uncachedInput: n(obj.uncached_text_input_tokens), cachedInput: n(obj.cached_text_input_tokens), output: n(obj.text_output_tokens), }); const tokenTotal = (obj = {}) => { const total = n(obj.text_total_tokens); const parts = tokenParts(obj); const derived = parts.uncachedInput + parts.cachedInput + parts.output; return total > 0 ? total : derived; }; const normalizeModelName = (value) => String(value || "UNKNOWN").trim().toLowerCase(); const normalizeSpeed = (value, fallback = "standard") => String(value || fallback).trim().toLowerCase(); const fmtCalcNumber = (value, digits = 6) => trimFixed(value, digits); const fmtCredits = (value) => trimFixed(value, 3); const fmtSharePercent = (ratio) => `${fmtCalcNumber(clamp(ratio) * 100, 2)}%`; const formatModelCreditCalculation = (row = {}) => [ `${row.name || "该模型"} · ${row.speed || "unknown"}`, "按每天的模型/速度相对权重,对当天真实 Credits 进行折算。", `${fmtCredits(row.estimatedCredits)} Credits × $${CONFIG.USD_PER_CREDIT.toFixed( 2, )} = $${n(row.estimatedUsd).toFixed(2)}`, "该分配不代表模型级原始 Token。", ].join("\n"); const fmtEstimatedUsd = (value) => fmtUsd(value); const pad2 = (value) => String(value).padStart(2, "0"); const dateKeyFromMs = (ms) => { const d = new Date(ms); if (!Number.isFinite(d.getTime())) return ""; if (CONFIG.USE_UTC_DAY) return d.toISOString().slice(0, 10); return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`; }; const dayStartMs = (dateKey) => { const [year, month, day] = String(dateKey || "") .slice(0, 10) .split("-") .map(Number); if (!year || !month || !day) return NaN; return CONFIG.USE_UTC_DAY ? Date.UTC(year, month - 1, day) : new Date(year, month - 1, day).getTime(); }; const formatCycleDateTime = (ms) => { const d = new Date(ms); if (!Number.isFinite(d.getTime())) return "未知"; return `${d.getFullYear()}/${pad2(d.getMonth() + 1)}/${pad2( d.getDate(), )} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`; }; const formatPercentFromRatio = (ratio) => { const pct = clamp(ratio) * 100; return `${pct >= 10 ? pct.toFixed(1) : pct.toFixed(2)}%`; }; async function getSessionAuth() { try { const res = await fetch("/api/auth/session", { credentials: "include", cache: "no-store", headers: { Accept: "application/json", "Cache-Control": "no-cache", Pragma: "no-cache", }, }); if (!res.ok) return null; const session = await res.json(); const token = session?.accessToken || session?.access_token || session?.token || null; const accountId = session?.account?.id || session?.account_id || session?.accountId || null; if (!token || !accountId) { console.warn( "[Codex Quota Compass] Current session did not include the required token/account ID.", ); return null; } return { token, accountId }; } catch (error) { console.warn( "[Codex Quota Compass] Failed to fetch current session authentication.", error, ); return null; } } async function apiGet(path, auth) { const res = await fetch(path, { headers: { Authorization: `Bearer ${auth.token}`, "ChatGPT-Account-Id": auth.accountId, Accept: "application/json", "Cache-Control": "no-cache", Pragma: "no-cache", }, credentials: "include", cache: "no-store", }); const text = await res.text(); let json = null; if (text) { try { json = JSON.parse(text); } catch { // ignore parse error } } if (!res.ok) { const detail = json?.detail || json?.message || (typeof json?.error === "string" ? json.error : json?.error?.message) || text.slice(0, 200); throw new Error( `${path}: ${res.status} ${res.statusText}${detail ? `: ${detail}` : ""}`, ); } if (json === null) throw new Error("接口返回的不是 JSON。"); return json; } const getRateLimitObject = (usage = {}) => usage?.rate_limit || usage?.rateLimit || usage?.rate_limits || usage?.rateLimits || usage?.limits || {}; const looksLikeWindow = (value) => { if (!value || typeof value !== "object" || Array.isArray(value)) return false; return [ "limit_window_seconds", "window_seconds", "duration_seconds", "reset_at", "resetAt", "used_percent", "usedPercent", "used_ratio", "remaining", "limit", "used", ].some((key) => Object.prototype.hasOwnProperty.call(value, key)); }; const rateLimitWindows = (rateLimit = {}) => { const windows = []; if (Array.isArray(rateLimit?.windows)) { rateLimit.windows.forEach((value, index) => { if (looksLikeWindow(value)) { windows.push({ ...value, _window_name: value.name || value.window_name || `window_${index + 1}`, }); } }); } Object.entries(rateLimit || {}).forEach(([key, value]) => { if (looksLikeWindow(value)) { windows.push({ ...value, _window_name: key, }); } }); return windows; }; const getWindowDurationSeconds = (quotaWindow) => firstFinite( quotaWindow?.limit_window_seconds, quotaWindow?.window_seconds, quotaWindow?.duration_seconds, ); const pickQuotaWindow = (rateLimit = {}) => { const windows = rateLimitWindows(rateLimit); if (windows.length === 0 && looksLikeWindow(rateLimit)) { return { ...rateLimit, _window_name: "rate_limit" }; } if (windows.length === 0) return null; const withDuration = windows.filter((w) => getWindowDurationSeconds(w) > 0); if (withDuration.length > 0) { return [...withDuration].sort( (a, b) => Math.abs(getWindowDurationSeconds(a) - CONFIG.TARGET_WINDOW_SECONDS) - Math.abs(getWindowDurationSeconds(b) - CONFIG.TARGET_WINDOW_SECONDS), )[0]; } if (rateLimit.secondary_window) { return { ...rateLimit.secondary_window, _window_name: "secondary_window" }; } return windows[0]; }; const toEpochMs = (secondsOrMsOrIso) => { if (typeof secondsOrMsOrIso === "string") { const trimmed = secondsOrMsOrIso.trim(); const numeric = Number(trimmed); if (Number.isFinite(numeric) && numeric > 0) { return numeric > 1e12 ? numeric : numeric * 1000; } const parsed = Date.parse(trimmed); return Number.isFinite(parsed) ? parsed : NaN; } const value = n(secondsOrMsOrIso); if (!value) return NaN; return value > 1e12 ? value : value * 1000; }; const cycleRangeFromWindow = (quotaWindow) => { const resetMs = toEpochMs( quotaWindow?.reset_at || quotaWindow?.resetAt || quotaWindow?.resets_at || quotaWindow?.end_at || quotaWindow?.window_end, ); const durationMs = getWindowDurationSeconds(quotaWindow) * 1000; const nowMs = Date.now(); if (Number.isFinite(resetMs) && durationMs > 0) { return { cycleStartMs: resetMs - durationMs, cycleEndMs: resetMs, }; } return { cycleStartMs: nowMs - CONFIG.TARGET_WINDOW_SECONDS * 1000, cycleEndMs: nowMs, }; }; const usedRatioFromWindow = (quotaWindow) => { if (!quotaWindow) return 0; const rawRatio = firstFinite( quotaWindow.used_ratio, quotaWindow.usedRatio, quotaWindow.fraction_used, ); if (rawRatio > 0) return clamp(rawRatio); const rawPercent = firstFinite(quotaWindow.used_percent, quotaWindow.usedPercent); if (rawPercent > 0) return clamp(rawPercent / 100); const limit = firstFinite( quotaWindow.limit, quotaWindow.credit_limit, quotaWindow.credits_limit, quotaWindow.max, ); const used = firstFinite( quotaWindow.used, quotaWindow.used_credits, quotaWindow.consumed, quotaWindow.consumed_credits, ); const remaining = firstFinite( quotaWindow.remaining, quotaWindow.remaining_credits, quotaWindow.available, quotaWindow.available_credits, ); if (limit > 0 && used > 0) return clamp(used / limit); if (limit > 0 && remaining > 0) return clamp((limit - remaining) / limit); return 0; }; const usedPercentTextFromWindow = (quotaWindow) => { const rawPercent = firstFinite(quotaWindow?.used_percent, quotaWindow?.usedPercent); if (rawPercent > 0) return `${trimFixed(rawPercent, 2)}%`; const ratio = usedRatioFromWindow(quotaWindow); return ratio > CONFIG.EPS ? formatPercentFromRatio(ratio) : "未知"; }; const extractDailyList = (payload) => { if (Array.isArray(payload)) return payload; const candidates = [ payload?.data, payload?.items, payload?.results, payload?.daily, payload?.daily_usage, payload?.dailyWorkspaceUsageCounts, payload?.daily_workspace_usage_counts, payload?.workspace_usage_counts, ]; for (const candidate of candidates) { if (Array.isArray(candidate)) return candidate; } return []; }; const buildDailyUsageFromLegacy = (dailyList) => asArray(dailyList) .map((row) => { const dateKey = String(row?.date || "").slice(0, 10); const totals = row?.totals || {}; const credits = n(totals.credits); return { ...row, date: dateKey, totals, _credits: credits, _estimatedUsd: credits * CONFIG.USD_PER_CREDIT, }; }) .filter( (row) => row.date && (tokenTotal(row.totals) > CONFIG.EPS || row._credits > CONFIG.EPS || n(row.totals?.turns) > 0), ); const makeDailyRow = (item) => { const dateKey = String(item?.date || "").slice(0, 10); return { ...item, totals: item?.totals || item || {}, _displayDate: dateKey, _dateKey: dateKey, _sortTs: dayStartMs(dateKey), }; }; const getCurrentCycleDailyRows = ( dailyList, cycleStartMs, cycleEndMs, nowMs = Date.now(), ) => { const currentCycleList = []; const cycleStartDayMs = dayStartMs(dateKeyFromMs(cycleStartMs)); const effectiveCycleEndMs = Math.min(cycleEndMs, nowMs); const cycleEndDayMs = dayStartMs(dateKeyFromMs(effectiveCycleEndMs)); asArray(dailyList).forEach((item) => { const dateKey = String(item?.date || "").slice(0, 10); const bucketStart = dayStartMs(dateKey); if (!Number.isFinite(bucketStart)) return; if (bucketStart > nowMs) return; const row = makeDailyRow(item); if (bucketStart >= cycleStartDayMs && bucketStart <= cycleEndDayMs) { currentCycleList.push(row); } }); return currentCycleList.sort((a, b) => a._sortTs - b._sortTs); }; const getStats = (list) => { return list.reduce( (acc, row) => { const totals = row.totals || {}; const parts = tokenParts(totals); acc.tokens += tokenTotal(totals); acc.uncachedInputTokens += parts.uncachedInput; acc.cachedInputTokens += parts.cachedInput; acc.outputTokens += parts.output; acc.credits += n(totals.credits); acc.turns += n(totals.turns); acc.estimatedUsd += n(row._estimatedUsd); return acc; }, { tokens: 0, uncachedInputTokens: 0, cachedInputTokens: 0, outputTokens: 0, credits: 0, turns: 0, estimatedUsd: 0, }, ); }; const getModelDisplayName = (item = {}) => normalizeModelName( item.model || item.model_id || item.model_name || item.name || item.id, ); const isGpt56Model = (modelName) => /^gpt[-_.]?5[.-]?6(?:$|[-_.])/.test(normalizeModelName(modelName)); const aggregateModelUsage = (modelDistributionList, dailyUsageList) => { const modelTotals = new Map(); const dailyCredits = new Map( asArray(dailyUsageList).map((row) => [ String(row?.date || row?._dateKey || "").slice(0, 10), n(row?.totals?.credits), ]), ); const datesWithModelWeights = new Set(); const ensureModel = (name, speed = "standard") => { const normalizedName = normalizeModelName(name); const normalizedSpeed = normalizeSpeed(speed); const key = `${normalizedName}\u0000${normalizedSpeed}`; if (!modelTotals.has(key)) { modelTotals.set(key, { name: normalizedName, speed: normalizedSpeed, estimatedCredits: 0, estimatedUsd: 0, share: 0, dates: new Set(), isGpt56: isGpt56Model(normalizedName), isUnallocated: false, }); } return modelTotals.get(key); }; asArray(modelDistributionList).forEach((row) => { const dateKey = String(row?.date || "").slice(0, 10); const actualCredits = n(dailyCredits.get(dateKey)); if (!dateKey || actualCredits <= CONFIG.EPS) return; const weightedModels = asArray(row?.models) .map((item) => ({ item, weight: n(item?.credits) })) .filter(({ item, weight }) => getModelDisplayName(item) && weight > 0); const weightTotal = weightedModels.reduce( (sum, { weight }) => sum + weight, 0, ); if (weightTotal <= CONFIG.EPS) return; datesWithModelWeights.add(dateKey); weightedModels.forEach(({ item, weight }) => { const current = ensureModel( getModelDisplayName(item), normalizeSpeed(item.speed), ); current.estimatedCredits += actualCredits * (weight / weightTotal); current.dates.add(dateKey); }); }); asArray(dailyUsageList).forEach((row) => { const dateKey = String(row?.date || row?._dateKey || "").slice(0, 10); const actualCredits = n(row?.totals?.credits); if ( !dateKey || actualCredits <= CONFIG.EPS || datesWithModelWeights.has(dateKey) ) { return; } const current = ensureModel("待同步/未归属", "unknown"); current.estimatedCredits += actualCredits; current.dates.add(dateKey); current.isUnallocated = true; }); const rows = [...modelTotals.values()]; const totalCredits = rows.reduce( (sum, row) => sum + row.estimatedCredits, 0, ); rows.forEach((row) => { row.estimatedUsd = row.estimatedCredits * CONFIG.USD_PER_CREDIT; row.share = totalCredits > CONFIG.EPS ? row.estimatedCredits / totalCredits : 0; row.sourceDays = row.dates.size; delete row.dates; }); rows.sort( (a, b) => Number(a.isUnallocated) - Number(b.isUnallocated) || Number(b.isGpt56) - Number(a.isGpt56) || a.name.localeCompare(b.name) || (a.speed === "standard" ? 0 : a.speed === "fast" ? 1 : 2) - (b.speed === "standard" ? 0 : b.speed === "fast" ? 1 : 2) || b.estimatedCredits - a.estimatedCredits, ); const estimatedUsd = rows.reduce((sum, row) => sum + row.estimatedUsd, 0); const gpt56Rows = rows.filter((row) => row.isGpt56); const sumGpt56 = (key) => gpt56Rows.reduce((sum, row) => sum + n(row[key]), 0); const gpt56Credits = sumGpt56("estimatedCredits"); return { rows, totalCredits, estimatedUsd, gpt56: { estimatedCredits: gpt56Credits, estimatedUsd: sumGpt56("estimatedUsd"), share: totalCredits > CONFIG.EPS ? gpt56Credits / totalCredits : 0, }, }; }; const renderModelSummary = (modelStats, scopeLabel) => { if (modelStats.rows.length === 0) { return `
🤖 ${escapeHtml(scopeLabel)}各模型用量
模型/速度分布数据尚未同步。
`; } return `
🤖 ${escapeHtml(scopeLabel)}各模型用量 按每天的模型/速度相对权重折算真实 Credits
${modelStats.rows .map( (row) => ` `, ) .join("")}
模型 速度 折算 Credits 周期占比 美元等价 覆盖天数
${escapeHtml(row.name)} ${escapeHtml(row.speed || "-")} ${fmtCredits( row.estimatedCredits, )} ${fmtSharePercent( row.share, )} ${fmtUsd(row.estimatedUsd)} ${row.sourceDays}
`; }; const renderTable = (list, stats) => { const rows = [...list].sort((a, b) => b._sortTs - a._sortTs); return `
${ rows.length === 0 ? `` : rows .map((row) => { const totals = row.totals || {}; const parts = tokenParts(totals); return ` `; }) .join("") }
日期 Credits 美元等价 总 Tokens 未缓存输入 缓存输入 输出 轮数
数据尚未同步,请静置 8 小时后重试
${escapeHtml(row._displayDate || row.date)} ${fmtCredits( totals.credits, )} ${fmtEstimatedUsd(row._estimatedUsd)} ${fmtNum(tokenTotal(totals))} ${fmtNum(parts.uncachedInput)} ${fmtNum(parts.cachedInput)} ${fmtNum(parts.output)} ${fmtNum(totals.turns)}
`; }; const showPanel = (data) => { const root = document.getElementById("codex-compass-root"); if (!root) return; const { quotaWindow, dailyList, modelDistributionList, cycleStartMs, cycleEndMs, nowMs, } = data; const currentCycleList = getCurrentCycleDailyRows( dailyList, cycleStartMs, cycleEndMs, nowMs, ); const currentStats = getStats(currentCycleList); const currentModelDistributionList = getCurrentCycleDailyRows( modelDistributionList, cycleStartMs, cycleEndMs, nowMs, ); const usedRatio = usedRatioFromWindow(quotaWindow); const usedPercentText = usedPercentTextFromWindow(quotaWindow); const estCycleUsd = usedRatio > CONFIG.EPS && currentStats.estimatedUsd > 0 ? currentStats.estimatedUsd / usedRatio : NaN; const estCycleUsdText = Number.isFinite(estCycleUsd) && estCycleUsd > 0 ? fmtEstimatedUsd(estCycleUsd) : "未知"; const estTokens = usedRatio > CONFIG.EPS && currentStats.tokens > 0 ? currentStats.tokens / usedRatio : NaN; const estTokensText = Number.isFinite(estTokens) && estTokens > 0 ? fmtNum(estTokens) : "未知"; const cycleRangeText = `${formatCycleDateTime(cycleStartMs)} → ${formatCycleDateTime( cycleEndMs, )}`; const currentCycleModelStats = aggregateModelUsage( currentModelDistributionList, currentCycleList, ); const modelStats = currentCycleModelStats; const modelScopeLabel = "本周期"; root.innerHTML = `
📊 Codex 配额分析 V3.4.0
${escapeHtml(cycleRangeText)}
数据统计存在延迟 为获得更准确的结果,建议停止使用并静置 8 小时后再查看。
已用比例
${escapeHtml(usedPercentText)}
本周期 Credits
${fmtCredits(currentStats.credits)}
Credits 美元等价
${fmtEstimatedUsd(currentStats.estimatedUsd)}
本周期 Tokens
${fmtNum(currentStats.tokens)}
未缓存输入
${fmtNum(currentStats.uncachedInputTokens)}
缓存输入
${fmtNum(currentStats.cachedInputTokens)}
输出 Tokens
${fmtNum(currentStats.outputTokens)}
预计周期总额
${escapeHtml(estCycleUsdText)}
每日 Credits、轮数及输入/缓存/输出 Token 来自旧版稳定接口; 模型与 Standard/Fast 分布来自当前 Analytics 接口。模型级 Credits 按同一天的相对权重折算, 不代表模型级原始 Token。美元等价统一按 $${CONFIG.USD_PER_CREDIT.toFixed( 2, )}/Credit 计算,不等同于 API 账单。 预计周期 Tokens:${escapeHtml(estTokensText)}。最新数据可能延迟数小时。
${renderModelSummary(modelStats, modelScopeLabel)}
📅 本周期每日用量
${renderTable(currentCycleList, currentStats)}
`; root.style.display = "block"; document.getElementById("compass-close-btn").onclick = () => { root.style.display = "none"; }; }; const run = async () => { const btn = document.getElementById("codex-compass-btn"); if (!btn || btn.disabled) return; btn.disabled = true; btn.innerText = "分析中..."; try { const auth = await getSessionAuth(); if (!auth) { alert("会话鉴权失败,请确保已登录,或刷新页面后重试。"); return; } const usage = await apiGet("/backend-api/wham/usage", auth); const rateLimit = getRateLimitObject(usage); const quotaWindow = pickQuotaWindow(rateLimit); const { cycleStartMs, cycleEndMs } = cycleRangeFromWindow(quotaWindow); const nowMs = Date.now(); const queryStartMs = cycleStartMs - CONFIG.DAY_MS; const startDate = dateKeyFromMs(queryStartMs); const endDate = dateKeyFromMs(nowMs + CONFIG.DAY_MS); const dailyParams = new URLSearchParams({ start_date: startDate, end_date: endDate, group_by: "day", }); const [legacyDailyData, modelDistributionData] = await Promise.all([ apiGet( `/backend-api/wham/analytics/daily-workspace-usage-counts?${dailyParams.toString()}`, auth, ), apiGet( `/backend-api/wham/usage/daily-token-usage-breakdown?${dailyParams.toString()}`, auth, ), ]); const dailyList = buildDailyUsageFromLegacy( extractDailyList(legacyDailyData), ); const modelDistributionList = extractDailyList(modelDistributionData); showPanel({ quotaWindow, dailyList, modelDistributionList, cycleStartMs, cycleEndMs, nowMs, }); } catch (e) { console.error("[Codex Quota Compass]", e); alert("错误: " + (e?.message || String(e))); } finally { btn.disabled = false; btn.innerText = "📊 运行用量分析"; } }; GM_addStyle(` #codex-compass-root { --compass-text: #171717; --compass-muted: #6b6b6b; --compass-border: #e5e5e5; --compass-surface: #ffffff; --compass-canvas: #f7f7f8; --compass-green: #0d8f6f; --compass-green-soft: #edf9f5; --compass-blue-soft: #f3f7ff; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); width: min(1220px, calc(100vw - 36px)); max-height: calc(100vh - 32px); padding: 0 22px 22px; overflow-x: hidden !important; overflow-y: auto !important; color: var(--compass-text); background: var(--compass-canvas); border: 1px solid rgba(0, 0, 0, 0.1); border-radius: 18px; box-shadow: 0 24px 80px rgba(0, 0, 0, 0.24), 0 2px 12px rgba(0, 0, 0, 0.08); box-sizing: border-box; display: none; z-index: 2147483647; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif; font-size: 14px; line-height: 1.5; scrollbar-color: #c7c7c7 transparent; scrollbar-width: thin; } #codex-compass-root * { box-sizing: border-box; } #codex-compass-root::-webkit-scrollbar { width: 9px; height: 9px; } #codex-compass-root::-webkit-scrollbar-thumb, .table-container::-webkit-scrollbar-thumb { background: #c9c9c9; border: 2px solid transparent; border-radius: 999px; background-clip: padding-box; } .compass-header { position: sticky; top: 0; z-index: 10; display: flex; align-items: center; justify-content: space-between; gap: 16px; margin: 0 -22px 18px; padding: 17px 22px 15px; background: rgba(247, 247, 248, 0.94); border-bottom: 1px solid rgba(0, 0, 0, 0.08); backdrop-filter: blur(14px); } .compass-header-main { display: flex; min-width: 0; flex: 1 1 auto; flex-direction: column; gap: 3px; } .compass-header-right { display: flex; flex: 0 0 auto; max-width: none; align-items: center; justify-content: flex-end; } .compass-product-title { display: flex; align-items: center; gap: 9px; margin: 0; color: var(--compass-text); font-size: 20px; font-weight: 720; letter-spacing: -0.025em; line-height: 1.25; text-align: left; } .version-badge { display: inline-flex; align-items: center; height: 21px; padding: 0 7px; color: #555; background: #ececec; border: 1px solid #dedede; border-radius: 999px; font-size: 10.5px; font-weight: 650; letter-spacing: 0; } .compass-title { color: var(--compass-muted); font-size: 12.5px; font-weight: 450; line-height: 1.4; } .compass-close { display: inline-flex; width: 36px; height: 36px; align-items: center; justify-content: center; padding: 0; color: #666; background: transparent; border: 0; border-radius: 10px; font-family: inherit; font-size: 27px; font-weight: 300; line-height: 1; cursor: pointer; flex-shrink: 0; user-select: none; transition: background 120ms ease, color 120ms ease, transform 120ms ease; } .compass-close:hover { color: #111; background: #e9e9ea; transform: scale(1.04); } .compass-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; margin-bottom: 12px; } .top-delay-banner { display: flex; align-items: flex-start; gap: 10px; margin: 0 0 14px; padding: 10px 13px; color: #80520c; background: linear-gradient(135deg, #fff9e9 0%, #fff5d8 100%); border: 1px solid #efd69a; border-radius: 11px; font-size: 12.5px; line-height: 1.5; } .top-delay-banner strong { display: block; margin-bottom: 1px; color: #704407; font-size: 13px; font-weight: 700; } .top-delay-banner span:not(.top-delay-icon) { color: #986a20; } .top-delay-icon { flex: 0 0 auto; margin-top: 1px; font-size: 17px; line-height: 1.2; } .compass-card { position: relative; min-height: 120px; min-width: 0; padding: 18px; overflow: hidden; background: var(--compass-surface); border: 1px solid var(--compass-border); border-radius: 14px; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.025); } .compass-card::before { position: absolute; top: 0; right: 0; left: 0; height: 3px; background: #d9d9d9; content: ""; } .compass-card.highlight { background: linear-gradient(145deg, #f6fffb 0%, #edf9f5 100%); border-color: #cbe9dd; } .compass-card.highlight::before { background: linear-gradient(90deg, #12a37f, #55c7a8); } .card-label { margin-bottom: 8px; color: var(--compass-muted); font-size: 13.5px; font-weight: 600; letter-spacing: 0.01em; } .card-value { color: var(--compass-text); font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: clamp(24px, 2.25vw, 30px); font-weight: 740; letter-spacing: -0.045em; line-height: 1.1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .compass-card.highlight .card-value { color: var(--compass-green); } .compass-token-strip { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; margin-bottom: 14px; overflow: visible; background: transparent; border: 0; border-radius: 0; } .token-metric { min-height: 84px; min-width: 0; padding: 15px 15px; background: var(--compass-surface); border: 1px solid var(--compass-border); border-radius: 12px; } .token-metric.emphasized { background: linear-gradient(145deg, #f7fffc, var(--compass-green-soft)); border-color: #cbe9dd; } .token-metric-label { margin-bottom: 6px; color: var(--compass-muted); font-size: 13px; font-weight: 570; } .token-metric-value { overflow: hidden; color: var(--compass-text); font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 18px; font-weight: 700; letter-spacing: -0.02em; text-overflow: ellipsis; white-space: nowrap; } .token-metric.emphasized .token-metric-value { color: var(--compass-green); } .compass-note { margin-bottom: 14px; padding: 11px 13px; color: #496056; background: #f3faf7; border: 1px solid #d5ebe2; border-color: #d5ebe2; border-radius: 11px; font-size: 12px; line-height: 1.6; } .compass-note.pricing { color: #3f5d51; background: #f3faf7; border-color: #d5ebe2; } .compass-section { display: block; clear: both; margin: 14px 0 0 !important; padding: 17px !important; background: var(--compass-surface); border: 1px solid var(--compass-border); border-radius: 15px; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.025); } .compass-section-title { display: block; clear: both; margin: 0 0 12px !important; color: var(--compass-text) !important; font-size: 15px !important; font-weight: 680 !important; letter-spacing: -0.01em; line-height: 1.4 !important; } .section-title-note { display: inline-block; margin-left: 7px !important; color: #7a7a7a !important; font-size: 11.5px; font-weight: 450 !important; } .empty-state { padding: 18px; color: #777; background: #fafafa; border: 1px solid #ededed; border-radius: 10px; text-align: center; } .table-container, .table-container.wide, .table-container.compact { display: block; width: 100% !important; min-width: 0 !important; max-width: 100% !important; margin: 0; clear: both; overflow-x: auto !important; overflow-y: hidden !important; background: #fff; border: 1px solid #e8e8e8; border-radius: 11px; scrollbar-color: #c7c7c7 transparent; scrollbar-width: thin; } .compass-table { display: table !important; width: 100% !important; min-width: 820px !important; border-collapse: collapse !important; border-spacing: 0 !important; table-layout: auto !important; color: #242424; font-size: 13px !important; } .model-summary-table { min-width: 820px !important; } .wide-table { min-width: 1040px !important; } .compass-table th, .compass-table td { display: table-cell !important; padding: 10px 12px !important; border-bottom: 1px solid #ededed !important; font-size: 13px !important; line-height: 1.4 !important; vertical-align: middle !important; white-space: nowrap !important; } .compass-table thead { display: table-header-group !important; } .compass-table tbody { display: table-row-group !important; } .compass-table tfoot { display: table-footer-group !important; } .compass-table tr { display: table-row !important; } .compass-table th { color: #626262 !important; background: #f7f7f8 !important; font-size: 12px !important; font-weight: 650 !important; letter-spacing: 0.015em; text-align: left !important; } .compass-table td:first-child, .compass-table th:first-child { min-width: 140px !important; white-space: normal !important; } .compass-table tbody tr { transition: background 100ms ease; } .compass-table tbody tr:hover { background: #f7faf9 !important; } .gpt56-model-row { background: var(--compass-blue-soft) !important; } .fast-model-row { background: #fffbf2 !important; } .gpt56-model-row td:first-child { color: #315b9a !important; font-weight: 680 !important; } .gpt56-model-row td:nth-child(2) { color: inherit !important; font-weight: inherit !important; } .speed-badge { display: inline-flex; min-width: 66px; align-items: center; justify-content: center; padding: 3px 8px; border: 1px solid transparent; border-radius: 999px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif; font-size: 10.5px; font-weight: 700; letter-spacing: 0.035em; text-transform: uppercase; } .speed-badge.is-standard { color: #4b5563; background: #f3f4f6; border-color: #e5e7eb; } .speed-badge.is-fast { color: #9a5b08; background: #fff5d9; border-color: #f3d590; } .cost-hover { display: inline-block; padding: 2px 6px; color: var(--compass-green); background: rgba(13, 143, 111, 0.07); border-bottom: 1px dotted currentColor; border-radius: 5px; font-weight: 700; } .compass-footer-row { background: #fafafa !important; border-top: 1px solid #dedede !important; font-weight: 680 !important; } .grand-total-row { background: #effaf6 !important; } #codex-compass-btn { position: fixed; bottom: 22px; right: 22px; padding: 11px 17px; color: #fff; background: #111; border: 1px solid rgba(255, 255, 255, 0.14); border-radius: 12px; box-shadow: 0 10px 28px rgba(0, 0, 0, 0.2); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif; font-size: 13px; font-weight: 650; letter-spacing: -0.005em; transition: transform 120ms ease, box-shadow 120ms ease, background 120ms ease; cursor: pointer; z-index: 2147483646; } #codex-compass-btn:disabled { opacity: 0.72; cursor: wait; } #codex-compass-btn:hover:not(:disabled) { background: #272727; box-shadow: 0 13px 34px rgba(0, 0, 0, 0.24); transform: translateY(-1px); } @media (max-width: 980px) { #codex-compass-root { width: calc(100vw - 24px); } .compass-grid, .compass-token-strip { grid-template-columns: repeat(2, minmax(0, 1fr)); } } @media (max-width: 680px) { #codex-compass-root { top: 8px; width: calc(100vw - 12px); max-height: calc(100vh - 16px); padding: 0 12px 14px; border-radius: 14px; transform: translateX(-50%); } .compass-header { margin: 0 -12px 12px; padding: 13px 12px 11px; flex-direction: row; gap: 8px; } .compass-header-right { width: auto; } .compass-product-title { font-size: 17px; } .version-badge { height: 19px; font-size: 9.5px; } .compass-title { font-size: 11px; } .compass-close { width: 32px; height: 32px; } .compass-grid, .compass-token-strip { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; } .compass-card { min-height: 104px; padding: 14px; } .card-label { font-size: 12px; } .card-value { font-size: 22px; } .token-metric { min-height: 74px; padding: 12px; } .token-metric-label { font-size: 12px; } .token-metric-value { font-size: 16px; } .top-delay-banner { gap: 8px; margin-bottom: 10px; padding: 9px 10px; font-size: 11px; } .top-delay-banner strong { font-size: 12px; } .compass-note { font-size: 11px; } .compass-section { padding: 12px !important; border-radius: 12px; } .compass-section-title { font-size: 14px !important; } .section-title-note { display: block; margin: 3px 0 0 !important; font-size: 10.5px; } .compass-table { min-width: 820px !important; font-size: 12px !important; } .model-summary-table { min-width: 800px !important; } .compass-table th, .compass-table td { padding: 8px 9px !important; font-size: 12px !important; } .compass-table th { font-size: 11px !important; } #codex-compass-btn { right: 12px; bottom: 12px; padding: 10px 14px; font-size: 12px; } } `); const mount = () => { if (document.getElementById("codex-compass-btn")) return; const btn = document.createElement("button"); btn.id = "codex-compass-btn"; btn.innerText = "📊 运行用量分析"; btn.onclick = run; document.body.appendChild(btn); const root = document.createElement("div"); root.id = "codex-compass-root"; document.body.appendChild(root); }; if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", mount, { once: true }); } else { mount(); } })();