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
137 changes: 119 additions & 18 deletions pm-stack/aggregator/scripts/gather-quota.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ import {
GATHERER_SOURCE,
entriesWithPoolSplits,
entryFromResult,
entryHasMeasuredWindow,
entryFromFileExport,
entryFromTurso,
lastKnownEntries,
Expand Down Expand Up @@ -491,20 +492,60 @@ async function runClinePass(tickIso: string): Promise<ProviderRun | null> {
async function runMetaModule(quota: QuotaModule, tickIso: string): Promise<ProviderRun> {
const t0 = Date.now();
try {
// This explicit ask IS the OpenCode-side mechanism, in-process:
// it is the same fetch the OpenChamber CLI's quota subcommand
// runs for a named provider (`openchamber quota meta --json`,
// packages/web/bin/lib/commands-quota.js in the OpenChamber
// fork) — credentials asked from the OpenCode server
// (GET /api/credential, family 1), and an explicit ask is always
// fetched even when the provider is turned off in routing
// (the listing filter governs listing, never an explicit ask).
// The provider then reads Meta's own plan endpoint
// (POST https://api.meta.ai/muse-code/key) with the OpenCode
// `meta` credential, falling back to the Muse CLI account
// token in ~/.config/muse/auth.json when OpenCode holds only
// the minted inference key. OpenCode's internal route_attempt
// history is NOT a substitute: it meters tokens/cost, and Meta's
// plan percentage exists only on Meta's endpoint.
const results = await quota.fetchQuotaForProviderInstances("meta");
const entries = results.map((r) => entryFromResult(r, tickIso));
const anyOk = entries.some((e) => e.state === "ok");
const firstBad = entries.find((e) => e.state !== "ok");
return finalizeRun("meta", entries, t0);
} catch (err) {
return {
id: "meta",
state: anyOk ? "ok" : "error",
state: "error",
ms: Date.now() - t0,
entries,
...(!anyOk && firstBad?.error ? { error: firstBad.error } : {}),
entries: [],
error: safeProviderReason(err instanceof Error ? err.message : String(err)),
};
}
}

/**
* The Command Code explicit ask: the Meta pattern, for the same
* reason. `commandcode` is disabled as a routing door in the
* OpenCode config (definitions kept, flipped off in
* disabled_providers), so the provider listing can drop
* `command-code` even though its credential and plan are live —
* and a provider absent from the listing produced no run at all:
* no error, no #1268 retention, just a silently missing row.
* Drew's read was "working" because an explicit ask always works:
* the module fetches a named provider even when routing turns it
* off (`openchamber quota command-code --json` is the CLI form).
* The read is the PLAN read (see keepCommandCodePlanWindows):
* monthly from the included-credits bucket, 5h/weekly from
* windowLimits — never the purchased/free credit balances.
* No outer timeout, mirroring runMetaModule.
*/
async function runCommandCodeModule(quota: QuotaModule, tickIso: string): Promise<ProviderRun> {
const t0 = Date.now();
try {
const results = await quota.fetchQuotaForProviderInstances("command-code");
const entries = results.map((r) => entryFromResult(r, tickIso));
return keepCommandCodePlanWindows(finalizeRun("command-code", entries, t0));
} catch (err) {
return {
id: "meta",
id: "command-code",
state: "error",
ms: Date.now() - t0,
entries: [],
Expand All @@ -523,23 +564,69 @@ interface ProviderRun {
retained?: boolean;
}

/**
* Build a run from mapped entries, with the ok-but-null downgrade.
* A run whose entries are all "ok" yet carry NO measured window
* (every pctOfLimit null — Meta's active-but-no-subs_usage shape
* since 2026-11-03) is not a successful read: previously it passed
* as ok, so #1268 retention (which only fires on error runs) never
* engaged and quota-current.json published fresh null rows over the
* last good percentages. Downgrade it to an error run carrying the
* mapper's no-data reason, flip its entries to error so retention
* can replace them with last-known rows, and let the heartbeat say
* why. The entries' failureClass / lastSuccessAt (when the module
* provides them) ride along in the reason.
*/
function finalizeRun(id: string, entries: QuotaCurrentEntry[], t0: number): ProviderRun {
const anyOk = entries.some((e) => e.state === "ok");
const anyMeasured = entries.some((e) => entryHasMeasuredWindow(e));
if (anyOk && !anyMeasured) {
const reason =
entries.find((e) => e.error)?.error ??
"no-data: provider reported ok but no window carried a percentage";
for (const e of entries) {
if (e.state === "ok") e.state = "error";
if (!e.error) e.error = reason;
}
return { id, state: "error", ms: Date.now() - t0, entries, error: reason };
}
const firstBad = entries.find((e) => e.state !== "ok");
return {
id,
state: anyOk ? "ok" : "error",
ms: Date.now() - t0,
entries,
...(!anyOk && firstBad?.error ? { error: firstBad.error } : {}),
};
}

/** Command Code plan windows (Drew's rule, 2026-11-01: Command Code
* reads use PLAN, not BALANCE). The module's provider also returns
* balance windows (purchased_credits / free_credits: label-only, no
* percentage); those are balances, never quota, so they are stripped
* from the entry's windows — the raw payload stays on entry.usage —
* and no consumer or snapshot writer can mistake a balance for a
* plan reading or read the plan windows as "empty" because the
* first window is a balance. */
const COMMAND_CODE_PLAN_WINDOWS = new Set(["5h", "weekly", "monthly"]);
function keepCommandCodePlanWindows(run: ProviderRun): ProviderRun {
for (const entry of run.entries) {
entry.windows = entry.windows.filter((w) => COMMAND_CODE_PLAN_WINDOWS.has(w.name));
}
return run;
}

async function runProvider(quota: QuotaModule, id: string, tickIso: string): Promise<ProviderRun> {
const t0 = Date.now();
try {
const results = await withTimeout(quota.fetchQuotaForProviderInstances(id), timeoutMs, id);
const entries = results.map((r) => entryFromResult(r, tickIso));
// A provider is ok when at least one credential row answered;
// a failing row (e.g. Codex's token-sharing login, which OpenAI
// refuses by design) keeps its error on its own entry.
const anyOk = entries.some((e) => e.state === "ok");
const firstBad = entries.find((e) => e.state !== "ok");
return {
id,
state: anyOk ? "ok" : "error",
ms: Date.now() - t0,
entries,
...(!anyOk && firstBad?.error ? { error: firstBad.error } : {}),
};
// A provider is ok when at least one credential row answered
// with a measured window; a failing row (e.g. Codex's
// token-sharing login, which OpenAI refuses by design) keeps its
// error on its own entry, and an ok-but-null row degrades the
// run (see finalizeRun).
return finalizeRun(id, entries, t0);
} catch (err) {
return {
id,
Expand Down Expand Up @@ -791,6 +878,20 @@ async function main(): Promise<number> {
else runs[metaIdx] = metaRun;
}

// Command Code: exactly one run survives, mirroring Meta above.
// A listed run with a measured plan window wins (balance windows
// stripped); otherwise the explicit ask replaces or appends it,
// so a routing-disabled provider still gets its plan read.
const ccIdx = runs.findIndex((r) => r.id === "command-code");
if (ccIdx !== -1 && runs[ccIdx].entries.some((e) => e.state === "ok" && entryHasMeasuredWindow(e))) {
keepCommandCodePlanWindows(runs[ccIdx]);
console.log("quota-gatherer: command-code ok via provider listing - explicit module ask skipped");
} else {
const ccRun = await runCommandCodeModule(quota, tickAt);
if (ccIdx === -1) runs.push(ccRun);
else runs[ccIdx] = ccRun;
}

// The Claude auth source exposes an expiry timestamp. Persist only that
// metadata and its source class, never the credential object or values.
const claudeRun = runs.find((run) => run.id === "claude");
Expand Down
6 changes: 6 additions & 0 deletions pm-stack/aggregator/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1334,6 +1334,12 @@ export interface QuotaCurrentEntry {
/** Provenance class for the provider's credential source; never a credential value. */
credentialSource?: "claude-code" | "opencode" | "environment";
planLabel?: string;
/** Provider-side failure classification, when the quota module
* carries one (e.g. meta's "no-data"); never a credential value. */
failureClass?: string;
/** ISO time of the provider's last successful read, when the quota
* module carries one; lets readers age a degraded row honestly. */
lastSuccessAt?: string;
state: "ok" | "error" | "unconfigured";
measuredAt: string;
/** #1268: ISO time of the tick that retained this entry from the
Expand Down
41 changes: 41 additions & 0 deletions pm-stack/aggregator/src/quota-gather-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ export interface QuotaProviderResult {
credentialLabel?: string;
credentialExpiresAt?: number | string | null;
credentialSource?: "claude-code" | "opencode" | "environment";
/** Provider-side failure classification (OpenChamber quota module:
* e.g. meta's "no-data" / "unauthorized" / "exhausted"). Preserved
* so an ok-but-null read can be told apart from a measurement. */
failureClass?: string;
/** Epoch ms of the provider's last successful read in-process, when
* the module carries one (meta does); null = never succeeded. */
lastSuccessAt?: number | null;
quotaExhausted?: boolean;
}

interface RawWindow {
Expand Down Expand Up @@ -344,6 +352,10 @@ export function entryFromResult(result: QuotaProviderResult, tickIso: string): Q
if (result.credentialSource) entry.credentialSource = result.credentialSource;
if (result.planLabel) entry.planLabel = result.planLabel;
if (result.error) entry.error = safeProviderReason(result.error);
if (typeof result.failureClass === "string" && result.failureClass !== "") entry.failureClass = result.failureClass;
if (typeof result.lastSuccessAt === "number" && Number.isFinite(result.lastSuccessAt) && result.lastSuccessAt > 0) {
entry.lastSuccessAt = new Date(result.lastSuccessAt).toISOString();
}
if (result.usage != null) entry.usage = result.usage;

const pushWindow = (name: string, raw: RawWindow | null | undefined): void => {
Expand Down Expand Up @@ -379,9 +391,38 @@ export function entryFromResult(result: QuotaProviderResult, tickIso: string): Q
}
}
}
// Ok-but-null is NOT a measurement. A provider can answer ok:true
// with every window's percentage unknown — Meta's plan endpoint
// does exactly this on a 200 / is_subs_active:true response with no
// subs_usage (the provider's "post-roll empty state", meta.js in
// the OpenChamber quota module) — and since 2026-11-03 that shape
// has replaced Meta's last good percentage read (100% weekly,
// 2026-11-03T21:00Z) with fresh-looking null rows on every tick.
// Name it on the entry so the gatherer can degrade the run to an
// error and #1268 retention can keep the last-known rows, stale
// with this reason, instead of publishing null as current data.
if (result.ok && !entryHasMeasuredWindow(entry) && !entry.error) {
entry.error = `no-data: provider reported ok but no window carried a percentage${
entry.failureClass ? ` (failureClass=${entry.failureClass})` : ""
}${entry.lastSuccessAt ? ` (provider lastSuccessAt=${entry.lastSuccessAt})` : ""}`;
}
return entry;
}

/**
* Whether an entry carries at least one measured window: a
* percentage window, or the CNY balance label that recordsFromEntries
* treats as a measurement in its own unit (#1052, the DeepSeek
* reserve — a label-only provider must not degrade on this rule).
* Plain USD/credit balance labels do NOT count: a balance is not a
* plan reading.
*/
export function entryHasMeasuredWindow(entry: QuotaCurrentEntry): boolean {
return entry.windows.some(
(w) => w.pctOfLimit != null || (w.valueLabel != null && /^¥\s*[\d,]+(?:\.\d+)?/.test(w.valueLabel.trim())),
);
}

/**
* Snapshot records for one tick: ONE pct record per serviceId|window
* key whose VALUE changed since the gatherer last appended it (the
Expand Down