Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,20 @@
- Check command exit codes, stderr and expected output. Treat any `fatal:` output as failure even if an outer command exits successfully.
- GitHub requires the `Parser (Node)` and `Server (Python)` checks. Preserve branch protection and wait for both before updating `main`.

## Live Verification

- Runtime data under the deployment `data/` directory is user state, not test
fixture. Never write defaults, empty arrays or synthetic ids into `/api/order`,
`/api/hidden`, `/api/requests` or `/api/snapshot` on a live deployment.
- Before any state-changing verification, read the current value and keep it. Restore
that exact saved value afterwards; do not reset it to empty because the test finished.
- Report the before and after values of every mutated field so a change is visible.
- Prefer an isolated local server with fixture data, or a dedicated throwaway account id
that is appended to the saved list and removed by id.
- Never reuse a real account id as a test subject for deletion or mutation checks.
- Treat an unconfirmed restore as an incident: state the risk and the recovery path
instead of describing the run as clean.

## Repository Synchronization

- The Gitea development repository retains its complete history. Publish each requested GitHub synchronization as one reviewed commit based on the current GitHub `main`.
Expand All @@ -42,6 +56,8 @@
- Keep persistent runtime data under `/docker/coding_plan_quota_dashboard/data/`.
- Verify `http://<DEPLOY_HOST>:8080/` returns HTTP 200 after deployment; substitute the actual host privately, never commit it.
- Verify the affected UI or provider flow as well; HTTP 200 alone does not prove the feature works.
- Follow the Live Verification rules when testing against a deployed instance; a
verification run must leave every user state file with its original values and order.
- Quote remote SSH command strings to prevent local expansion of remote variables or command substitutions; prefer a remote script for complex commands.
- For remote background jobs, check process state for zombies as well as completion logs and artifacts; `kill -0` alone is insufficient.

Expand Down
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,14 @@ adheres to [Semantic Versioning](https://semver.org/).

## [Unreleased]

### Fixed
- Google AI quota lookups continue to the next host when a proxy or Google
host drops the connection, instead of failing the account outright.
- Codex new-api business errors now show the provider's `message`.

### Added
- Read-only `GET /api/summary` with each visible account's headline quota and
status for Home Assistant and other home dashboards.
- Initial public release.
- Single-page dashboard for Codex, MiniMax, Volcengine AgentPlan /
CodingPlan, Kimi Code, LongCat, Qianwen AI and Google AI (Gemini 3.5 Flash).
Expand Down
395 changes: 379 additions & 16 deletions README.md

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ services:
environment:
PORT: "8080"
APP_REVISION: "2026-07-14-codex-agentplan-fix"
GOOGLE_AI_USER_AGENT: "${GOOGLE_AI_USER_AGENT:-}"
CLIPROXYAPI_BASE_URL: "${CLIPROXYAPI_BASE_URL:-}"
CLIPROXYAPI_MANAGEMENT_KEY: "${CLIPROXYAPI_MANAGEMENT_KEY:-}"
command: ["python", "/srv/server.py"]
volumes:
- /docker/coding_plan_quota_dashboard/index.html:/srv/index.html:ro
Expand Down
310 changes: 278 additions & 32 deletions index.html

Large diffs are not rendered by default.

217 changes: 179 additions & 38 deletions parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,30 @@ function percent(value) {
}

function normalizeWindows(value) {
return Array.isArray(value.model_remains) ? value.model_remains.map(item => ({
modelName: item.model_name || 'Plan',
interval: {
usedPercent: percent(item.current_interval_used_percent),
totalPercent: percent(item.current_interval_total_percent) || 100,
remainingPercent: Math.max(0, 100 - percent(item.current_interval_used_percent)),
startAt: item.start_time || null,
resetAt: item.end_time || null
},
weekly: {
usedPercent: percent(item.current_weekly_used_percent),
totalPercent: percent(item.current_weekly_total_percent) || 100,
remainingPercent: Math.max(0, 100 - percent(item.current_weekly_used_percent)),
startAt: item.weekly_start_time || null,
resetAt: item.weekly_end_time || null
}
})) : [];
return Array.isArray(value.model_remains) ? value.model_remains.map(item => {
const weeklyTotalRaw = item.current_weekly_total_percent ?? item.current_weekly_total ?? item.weekly_total_percent;
const weeklyTotal = percent(weeklyTotalRaw);
const weeklyStatus = Number(item.current_weekly_status ?? item.weekly_status);
const weeklyAvailable = !!weeklyTotalRaw && weeklyTotal > 0 && !(Number.isFinite(weeklyStatus) && weeklyStatus !== 1);
return {
modelName: item.model_name || 'Plan',
interval: {
usedPercent: percent(item.current_interval_used_percent),
totalPercent: percent(item.current_interval_total_percent) || 100,
remainingPercent: Math.max(0, 100 - percent(item.current_interval_used_percent)),
startAt: item.start_time || null,
resetAt: item.end_time || null
},
weekly: {
available: weeklyAvailable,
usedPercent: percent(item.current_weekly_used_percent),
totalPercent: weeklyTotal || 100,
remainingPercent: Math.max(0, 100 - percent(item.current_weekly_used_percent)),
startAt: item.weekly_start_time || null,
resetAt: item.weekly_end_time || null
}
};
}) : [];
}

function unwrap(value) {
Expand Down Expand Up @@ -134,11 +141,15 @@ function normalizeQianwen(payload) {
if (value && typeof value[key] === 'object') value = value[key];
}
const periods = [];
if (value.per5HourPercentage !== undefined) {
periods.push({ name: '5h', usedPercent: ratioToPercent(value.per5HourPercentage), remainingPercent: Math.max(0, 100 - ratioToPercent(value.per5HourPercentage)), resetAt: firstNumber(value, ['per5HourResetTime']) });
}
if (value.per1WeekPercentage !== undefined) {
periods.push({ name: '1w', usedPercent: ratioToPercent(value.per1WeekPercentage), remainingPercent: Math.max(0, 100 - ratioToPercent(value.per1WeekPercentage)), resetAt: firstNumber(value, ['per1WeekResetTime']) });
const quotaWindows = [
['5h', 'per5HourPercentage', 'per5HourResetTime'],
['1w', 'per1WeekPercentage', 'per1WeekResetTime'],
['monthly', 'per1MonthPercentage', 'per1MonthResetTime']
];
for (const [name, percentKey, resetKey] of quotaWindows) {
if (value[percentKey] === undefined || value[percentKey] === null) continue;
const usedPercent = ratioToPercent(value[percentKey]);
periods.push({ name, usedPercent, remainingPercent: Math.max(0, 100 - usedPercent), resetAt: firstNumber(value, [resetKey]) });
}
const used = periods.length ? Math.max(...periods.map(period => period.usedPercent)) : 0;
return { limit: 100, used, remaining: Math.max(0, 100 - used), unit: '%', periods, updatedAt: Date.now() };
Expand Down Expand Up @@ -258,23 +269,153 @@ function normalizeVolcengine(payload) {
};
}

function normalizeClaude(payload) {
const value = payload && typeof payload === 'object' ? payload : {};
const labels = [['five_hour', '5h'], ['seven_day', 'weekly'],
['seven_day_opus', 'Opus周额度'], ['seven_day_sonnet', 'Sonnet周额度'],
['seven_day_oauth_apps', 'OAuth应用周额度'], ['seven_day_cowork', 'Cowork周额度']];
const periods = [];
for (const [key, name] of labels) {
const bucket = value[key];
const utilization = bucket && typeof bucket === 'object' ? firstNumber(bucket, ['utilization']) : null;
if (utilization === null || utilization === undefined || utilization < 0) continue;
const usedPercent = Math.max(0, Math.min(100, utilization));
periods.push({ name, usedPercent, remainingPercent: 100 - usedPercent,
resetAt: typeof bucket.resets_at === 'string' && Number.isFinite(Date.parse(bucket.resets_at)) ? bucket.resets_at : null });
}
const used = periods.length ? Math.max(...periods.map(period => period.usedPercent)) : 0;
return { limit: periods.length ? 100 : null, used: periods.length ? used : null,
remaining: periods.length ? 100 - used : null, unit: '%', periods, updatedAt: Date.now() };
}

function normalizeGoogleAi(payload) {
const value = unwrap(payload);
const groups = Array.isArray(value.groups) ? value.groups : [];
const group = groups.find(item => String(item?.displayName || '').toLowerCase() === 'gemini models')
|| groups.find(item => String(item?.displayName || '').toLowerCase().includes('gemini'));
if (!group || !Array.isArray(group.buckets)) return { limit: 100, used: 0, remaining: 100, unit: '%', periods: [], updatedAt: Date.now() };
const labels = { '5h': '5h', weekly: 'weekly' };
const periods = group.buckets
.filter(bucket => bucket && labels[bucket.window] && Number.isFinite(Number(bucket.remainingFraction)))
.map(bucket => {
const remaining = Math.max(0, Math.min(1, Number(bucket.remainingFraction)));
const usedPercent = Math.max(0, Math.min(100, (1 - remaining) * 100));
return { name: labels[bucket.window], usedPercent, remainingPercent: Math.max(0, 100 - usedPercent), resetAt: bucket.resetTime || bucket.reset_at || null };
})
.sort((left, right) => ({ '5h': 0, weekly: 1 }[left.name] ?? 9) - ({ '5h': 0, weekly: 1 }[right.name] ?? 9));
const used = periods.length ? Math.max(...periods.map(period => period.usedPercent)) : 0;
return { limit: 100, used, remaining: Math.max(0, 100 - used), unit: '%', periods, updatedAt: Date.now() };
const empty = { limit: null, used: null, remaining: null, unit: '%', periods: [], updatedAt: Date.now() };
if (payload?.error || payload?.success === false || value.error || value.success === false) return empty;
const fraction = bucket => {
const raw = bucket.remainingFraction ?? bucket.remaining_fraction;
if (!['number', 'string'].includes(typeof raw) || (typeof raw === 'string' && !raw.trim())) return null;
const number = Number(raw);
return Number.isFinite(number) && number >= 0 && number <= 1 ? number : null;
};
const period = (name, bucket, remaining) => ({ name, usedPercent: (1 - remaining) * 100,
remainingPercent: remaining * 100,
resetAt: typeof (bucket.resetTime || bucket.reset_at) === 'string'
&& Number.isFinite(Date.parse(bucket.resetTime || bucket.reset_at)) ? (bucket.resetTime || bucket.reset_at) : null });
const catalog = value.models && typeof value.models === 'object' && !Array.isArray(value.models) ? value.models : {};
const available = model => model && typeof model === 'object' && !Array.isArray(model)
&& model.disabled !== true && model.available !== false && model.isInternal !== true;
const version = text => (String(text).match(/\d+(?:[.-]\d+)*/)?.[0] || '0').split(/[.-]/).map(Number);
const compareVersion = (left, right) => {
for (let index = 0; index < Math.max(left.length, right.length); index++) {
const difference = (right[index] || 0) - (left[index] || 0);
if (difference) return difference;
}
return 0;
};
const compareId = (left, right) => left < right ? -1 : left > right ? 1 : 0;
const geminiVersion = id => {
const match = id.match(/^gemini-(\d+)(?:\.(\d+))?(?:\.(\d+))?/);
return [1, 2, 3].map(index => Number(match?.[index] || 0));
};
const isArgon = text => /argon|agron/i.test(text);
const agronPriority = id => id.toLowerCase() === 'gemini-4-argon' ? -4
: id.toLowerCase().startsWith('gemini-4-argon-') ? -3 : id.toLowerCase() === 'gemini-4-agron' ? -2 : -1;
const agronModels = Object.entries(catalog).filter(([id, model]) => /^[A-Za-z0-9._-]+$/.test(id)
&& available(model)
&& isArgon(`${id} ${model.displayName || ''} ${model.model || ''}`))
.sort(([left], [right]) => agronPriority(left) - agronPriority(right)
|| (left < right ? -1 : left > right ? 1 : 0));
const supportsAgron = agronModels.length > 0;
const agronIds = new Set(agronModels.map(([id]) => id));
const groups = (Array.isArray(value.groups) ? value.groups : []).filter(item => item && typeof item === 'object');
const selectGroup = agron => {
const available = groups.filter(item => isArgon(String(item.displayName || '')) === agron);
const preferred = agron ? ['gemini4argon', 'gemini4agron'] : ['geminimodels'];
return preferred.map(name => available.find(item => String(item.displayName || '').toLowerCase().replace(/[^a-z0-9]/g, '') === name)).find(Boolean)
|| available.find(item => agron || String(item.displayName || '').toLowerCase().includes('gemini'));
};
const group = selectGroup(supportsAgron);
const modelName = /argon/i.test(`${group?.displayName || ''} ${agronModels.map(([id, model]) => `${id} ${model.displayName || ''} ${model.model || ''}`).join(' ')}`)
? 'GEMINI 4 ARGON' : 'GEMINI 4 AGRON';
const readWindows = selectedGroup => {
const windows = new Map();
for (const bucket of Array.isArray(selectedGroup?.buckets) ? selectedGroup.buckets : []) {
if (!bucket) continue;
const name = String(bucket.window || '').toLowerCase();
if (!['5h', 'weekly'].includes(name)) continue;
const remaining = fraction(bucket);
if (remaining === null) continue;
if (!windows.has(name) || remaining * 100 < windows.get(name).remainingPercent)
windows.set(name, period(name, bucket, remaining));
}
return windows;
};
const candidates = (Array.isArray(value.buckets) ? value.buckets : [])
.filter(bucket => bucket && typeof bucket === 'object')
.map(bucket => [bucket.modelId ?? bucket.model_id, bucket]);
for (const [id, model] of Object.entries(catalog))
if (available(model)) candidates.push([id, model.quotaInfo ?? model.quota_info]);
const compareModel = (left, right, agron) => agron
? agronPriority(left) - agronPriority(right) || compareId(left, right)
: compareVersion(geminiVersion(left), geminiVersion(right))
|| (/-tiered$/.test(left) ? 1 : /-(high|medium|low)$/.test(left) ? 2 : 0)
- (/-tiered$/.test(right) ? 1 : /-(high|medium|low)$/.test(right) ? 2 : 0)
|| compareId(left, right);
const allModels = new Map();
for (const [id, bucket] of candidates) {
if (typeof id !== 'string' || !/^[A-Za-z0-9._-]+$/.test(id) || !bucket || typeof bucket !== 'object') continue;
const metadata = catalog[id];
if (metadata && !available(metadata)) continue;
if (!/^(gemini|claude|gpt)-/i.test(id) && !metadata?.displayName && !agronIds.has(id)) continue;
const remaining = fraction(bucket);
if (remaining === null) continue;
if (!allModels.has(id) || remaining * 100 < allModels.get(id).remainingPercent) {
const { name, ...quota } = period(id, bucket, remaining);
allModels.set(id, { modelId: id, modelName: typeof metadata?.displayName === 'string'
&& metadata.displayName.trim() ? metadata.displayName.trim() : id, ...quota });
}
}
const family = id => /^gemini-/i.test(id) ? 0 : /^claude-/i.test(id) ? 1 : /^gpt-/i.test(id) ? 2 : 3;
const displayModels = [...allModels.values()].sort((left, right) => family(left.modelId) - family(right.modelId)
|| compareVersion(version(left.modelName), version(right.modelName)) || compareId(left.modelId, right.modelId));
const modelDetails = displayModels.length ? { modelQuotas: displayModels } : {};
const modelQuotas = agron => candidates.filter(([id, bucket]) => typeof id === 'string'
&& (agron ? agronIds.has(id) : /^gemini-[a-z0-9._-]+$/.test(id) && !isArgon(id))
&& (!catalog[id] || available(catalog[id]))
&& bucket && typeof bucket === 'object' && fraction(bucket) !== null)
.map(([id, bucket]) => ({ ...period(id, bucket, fraction(bucket)), modelId: id }))
.sort((left, right) => compareModel(left.modelId, right.modelId, agron)
|| left.remainingPercent - right.remainingPercent);
const windows = readWindows(group);
const geminiWindows = supportsAgron ? readWindows(selectGroup(false)) : new Map();
const geminiPeriods = ['5h', 'weekly'].filter(name => geminiWindows.has(name))
.map(name => ({ ...geminiWindows.get(name), name: `gemini-${name}`,
label: `Gemini · ${name === '5h' ? '5小时' : '周额度'}` }));
// Argon accounts can also return an ordinary Gemini model quota without a window.
const geminiModel = supportsAgron ? modelQuotas(false)[0] : null;
if (geminiModel) {
const { modelId, ...quota } = geminiModel;
geminiPeriods.push({ ...quota, name: 'gemini-model', label: `${modelId} · 模型额度` });
}
const periods = (supportsAgron ? ['weekly', '5h'] : ['5h', 'weekly'])
.filter(name => windows.has(name)).map(name => windows.get(name));
if (periods.length) {
const used = supportsAgron ? periods[0].usedPercent : Math.max(...periods.map(item => item.usedPercent));
if (supportsAgron) for (const item of periods)
item.label = `${modelName} · ${item.name === 'weekly' ? '周限额' : '5小时限额'}`;
return { limit: 100, used, remaining: 100 - used, unit: '%', periods: [...periods, ...geminiPeriods], ...modelDetails,
...(supportsAgron ? { modelId: agronModels[0][0], modelName, planLabel: 'Agron',
quotaSource: 'agron', primaryPeriodName: periods[0].name } : {}), updatedAt: Date.now() };
}
const models = modelQuotas(supportsAgron);
if (!models.length) return empty;
const { modelId, ...selected } = models[0];
if (supportsAgron) selected.label = `${modelName} · 模型额度`;
return { limit: 100, used: selected.usedPercent, remaining: selected.remainingPercent,
unit: '%', periods: [selected, ...geminiPeriods], ...modelDetails, modelId, quotaSource: 'model',
...(supportsAgron ? { modelName, planLabel: 'Agron', primaryPeriodName: selected.name } : {}),
updatedAt: Date.now() };
}

module.exports = { normalizeCodex, normalizeCodexCredits, normalizeCodexNewApi, normalizeCodexUsage, normalizeMiniMax, normalizeKimi, normalizeQianwen, normalizeZhipu, normalizeLongCat, normalizeVolcengine, normalizeGoogleAi };
module.exports = { normalizeCodex, normalizeCodexCredits, normalizeCodexNewApi, normalizeCodexUsage, normalizeMiniMax, normalizeKimi, normalizeQianwen, normalizeZhipu, normalizeLongCat, normalizeVolcengine, normalizeGoogleAi, normalizeClaude };
8 changes: 8 additions & 0 deletions scripts/agy-quota-rotation.example.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"dashboardUrl": "http://localhost:8080",
"timeoutSeconds": 65,
"accountIds": {
"alpha": "acc_alpha",
"beta": "acc_beta"
}
}
Loading
Loading