ai: restore the quota probe on Codex, rewrite the footer
The Codex migration left /usage returning 501 and no quota signal for the
governor. Codex does expose one after all — it just isn't an HTTP endpoint.
Probe: `codex app-server` is a JSON-RPC-over-stdio surface whose
`account/rateLimits/read` returns the same snapshot the interactive TUI
shows. Handshake is initialize -> `initialized` NOTIFICATION -> read; without
the notification the read never answers. adolf-llm's /usage now drives that
and normalises the result.
Shape change, and why the consumers had to be rewritten rather than repointed:
Kimi reported fixed buckets (window_5h / weekly / window_7d). Codex reports up
to two plan-defined windows, `primary` (long) and `secondary` (shorter burst,
often null), so the payload is now {plan, pct, primary, secondary,
limit_reached} with each row as {pct, window_mins, window_label, resets}. `pct`
is the max across live windows — the single number a gate can read without
knowing which window binds.
Probing spawns a codex process (~2s), so results are cached in memory and on
the workspace volume with a 5min TTL, concurrent probes are de-duped, and a
failed refresh serves the last good reading tagged stale/as_of/age_s rather
than nothing. ?force=1 bypasses the TTL.
kimi-quota-footer-plugin -> codex-quota-footer-plugin (id, mount path and the
openclaw.json entry key all renamed together — they must agree or the plugin
silently fails to load). It now renders whatever windows the plan actually
has, shortest first, and flags limit_reached and stale readings. quota-command
updated for the same payload.
Verified: /usage returns live data (30d 4%, plan free), warm cache serves in
17ms vs ~2s cold, the gateway reaches the route, adolf loads
codex-quota-footer, and the formatter degrades to no footer on empty/null
payloads instead of breaking the reply.
Note: the account reports planType "free", not a paid ChatGPT plan.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014Y5QPagv4iun1ghpwM96Ff
This commit is contained in:
143
ai/codex-quota-footer-plugin/index.js
Normal file
143
ai/codex-quota-footer-plugin/index.js
Normal file
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* Codex Quota Footer (kb #85) — appends a compact usage line to the end of
|
||||
* each of Adolf's outgoing replies, via OpenClaw's `reply_payload_sending`
|
||||
* hook (docs/plugins/hooks.md: "Mutate or cancel normalized reply payloads
|
||||
* before delivery... runs after payload normalization and before channel
|
||||
* delivery, including replies routed back to the originating channel").
|
||||
*
|
||||
* Source of the numbers: the LLM-free `GET /usage` route on adolf-llm, which
|
||||
* drives `codex app-server`'s `account/rateLimits/read` JSON-RPC method — the
|
||||
* same snapshot the interactive Codex TUI shows. No model call anywhere.
|
||||
*
|
||||
* Rewritten 2026-08-01 for the Kimi -> Codex migration. The old payload had
|
||||
* fixed Kimi buckets (window_5h / weekly / window_7d); Codex instead reports
|
||||
* up to two plan-defined windows, `primary` (long, e.g. 30d) and `secondary`
|
||||
* (shorter burst window, may be null), each already normalised by adolf-llm
|
||||
* to { pct, window_label, resets }. The footer therefore renders whatever
|
||||
* windows the plan actually has, labelled from the data, rather than
|
||||
* hardcoding bucket names that may not exist on this plan.
|
||||
*
|
||||
* Never blocks the send path: usage is cached and refreshed in the
|
||||
* background, so a reply is at most decorated with a slightly stale
|
||||
* (<= cacheTtlMs) snapshot, and any error/timeout simply omits the footer
|
||||
* rather than delaying or breaking the message.
|
||||
*
|
||||
* Streaming caveat (verified against /app/dist in the running container,
|
||||
* kb#85): Matrix preview streaming ("draft previews finalize in place",
|
||||
* docs/concepts/streaming.md) delivers the finalized text via a direct
|
||||
* payload edit (`ctx.edit`/`onEditReceipt`) that never calls
|
||||
* deliverOutboundPayloadsInternal, so reply_payload_sending would NOT fire
|
||||
* for that path. Adolf's openclaw.json currently leaves
|
||||
* channels.matrix.streaming unset (default "off"), so every real reply goes
|
||||
* through the normal send path (sendDurableMessageBatch ->
|
||||
* deliverOutboundPayloadsInternal) where this hook does fire. If Matrix
|
||||
* streaming is ever turned on for Adolf, this footer will silently stop
|
||||
* appearing on finalized-in-place replies — re-check this comment first.
|
||||
*/
|
||||
|
||||
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
||||
|
||||
const DEFAULTS = {
|
||||
enabled: true,
|
||||
usageUrl: "http://adolf-llm:8010/usage",
|
||||
cacheTtlMs: 60000, // serve a cached snapshot for up to this long
|
||||
fetchTimeoutMs: 2500, // background fetch only; never on the send path
|
||||
prefix: "— Codex:",
|
||||
showPlan: false, // append the plan name (e.g. "free") when true
|
||||
};
|
||||
|
||||
function normalizeConfig(raw) {
|
||||
const c = raw && typeof raw === "object" ? raw : {};
|
||||
const int = (v, d) => (Number.isFinite(v) && v > 0 ? Math.floor(v) : d);
|
||||
return {
|
||||
enabled: c.enabled !== false,
|
||||
usageUrl: typeof c.usageUrl === "string" && c.usageUrl ? c.usageUrl : DEFAULTS.usageUrl,
|
||||
cacheTtlMs: int(c.cacheTtlMs, DEFAULTS.cacheTtlMs),
|
||||
fetchTimeoutMs: int(c.fetchTimeoutMs, DEFAULTS.fetchTimeoutMs),
|
||||
prefix: typeof c.prefix === "string" && c.prefix ? c.prefix : DEFAULTS.prefix,
|
||||
showPlan: c.showPlan === true,
|
||||
};
|
||||
}
|
||||
|
||||
// One window -> "30d 4%". Falls back to a bare percentage when the backend
|
||||
// didn't report a window duration.
|
||||
function renderRow(row) {
|
||||
if (!row || typeof row.pct !== "number") return null;
|
||||
return row.window_label ? `${row.window_label} ${row.pct}%` : `${row.pct}%`;
|
||||
}
|
||||
|
||||
function formatFooter(usage, cfg) {
|
||||
if (!usage) return null;
|
||||
// Shortest window first — that's the one most likely to bite.
|
||||
const rows = [usage.secondary, usage.primary].map(renderRow).filter(Boolean);
|
||||
if (rows.length === 0) return null;
|
||||
|
||||
let line = `${cfg.prefix} ${rows.join(" · ")}`;
|
||||
if (cfg.showPlan && usage.plan) line += ` (${usage.plan})`;
|
||||
// A limit that has actually been hit matters more than the percentages.
|
||||
if (usage.limit_reached) line += " ⚠ limit reached";
|
||||
// Mark a reading served from a failed refresh so a stale number is never
|
||||
// mistaken for a live one.
|
||||
if (usage.stale) line += " (stale)";
|
||||
return line;
|
||||
}
|
||||
|
||||
export default definePluginEntry({
|
||||
id: "codex-quota-footer",
|
||||
name: "Codex Quota Footer",
|
||||
description: "Appends a compact Codex usage line to the end of each outgoing reply.",
|
||||
register(api) {
|
||||
const cfg = normalizeConfig(api.pluginConfig);
|
||||
|
||||
// Non-blocking cache: the send path never awaits the network. When the
|
||||
// snapshot is stale we kick a background refresh and keep using the last
|
||||
// known one; a quota readout tolerates being a minute stale.
|
||||
let cache = { usage: null, ts: 0 };
|
||||
let refreshing = false;
|
||||
|
||||
async function refresh() {
|
||||
if (refreshing) return;
|
||||
refreshing = true;
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), cfg.fetchTimeoutMs);
|
||||
try {
|
||||
const res = await fetch(cfg.usageUrl, { signal: controller.signal });
|
||||
if (!res.ok) throw new Error(`/usage HTTP ${res.status}`);
|
||||
cache = { usage: await res.json(), ts: Date.now() };
|
||||
} catch (e) {
|
||||
api.logger?.debug?.(`codex-quota-footer: usage refresh failed (${e?.message || e})`);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
refreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Warm the cache at startup so the first reply already carries a footer.
|
||||
refresh();
|
||||
|
||||
// Resolve the current footer, refreshing usage without blocking the send
|
||||
// path (one-shot blocking only on a cold cache).
|
||||
async function currentFooter() {
|
||||
if (!cache.usage) {
|
||||
await refresh();
|
||||
} else if (Date.now() - cache.ts > cfg.cacheTtlMs) {
|
||||
refresh();
|
||||
}
|
||||
return formatFooter(cache.usage, cfg);
|
||||
}
|
||||
|
||||
api.on("reply_payload_sending", async (event) => {
|
||||
try {
|
||||
if (!cfg.enabled) return;
|
||||
const payload = event?.payload;
|
||||
const text = payload?.text;
|
||||
if (typeof text !== "string" || text.trim().length === 0) return;
|
||||
const footer = await currentFooter();
|
||||
if (!footer || text.includes(footer)) return;
|
||||
return { payload: { ...payload, text: `${text}\n\n${footer}` } };
|
||||
} catch (e) {
|
||||
api.logger?.warn?.(`codex-quota-footer: hook failed (${e?.message || e})`);
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
42
ai/codex-quota-footer-plugin/openclaw.plugin.json
Normal file
42
ai/codex-quota-footer-plugin/openclaw.plugin.json
Normal file
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"id": "codex-quota-footer",
|
||||
"name": "Codex Quota Footer",
|
||||
"description": "Appends a compact Codex usage line (the plan's own rate-limit windows, e.g. 5h/30d %) to the end of each of Adolf's outgoing replies, via the reply_payload_sending hook. Reads the LLM-free adolf-llm:8010/usage route, which drives `codex app-server`'s account/rateLimits/read; cached + background-refreshed so it never blocks the send path.",
|
||||
"activation": {
|
||||
"onStartup": true
|
||||
},
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"enabled": { "type": "boolean" },
|
||||
"usageUrl": { "type": "string" },
|
||||
"cacheTtlMs": { "type": "integer", "minimum": 1000, "maximum": 3600000 },
|
||||
"fetchTimeoutMs": { "type": "integer", "minimum": 200, "maximum": 30000 },
|
||||
"prefix": { "type": "string" },
|
||||
"showPlan": { "type": "boolean" }
|
||||
}
|
||||
},
|
||||
"uiHints": {
|
||||
"enabled": {
|
||||
"label": "Codex Quota Footer",
|
||||
"help": "Append a compact Codex usage line to the end of each reply."
|
||||
},
|
||||
"usageUrl": {
|
||||
"label": "Usage URL",
|
||||
"help": "adolf-llm /usage endpoint (default http://adolf-llm:8010/usage)."
|
||||
},
|
||||
"cacheTtlMs": {
|
||||
"label": "Cache TTL (ms)",
|
||||
"help": "How long a fetched usage snapshot is reused before a background refresh (default 60000)."
|
||||
},
|
||||
"prefix": {
|
||||
"label": "Footer Prefix",
|
||||
"help": "Text before the percentages (default \"— Codex:\")."
|
||||
},
|
||||
"showPlan": {
|
||||
"label": "Show Plan Name",
|
||||
"help": "Also show the ChatGPT plan the limits belong to (e.g. \"free\"). Off by default."
|
||||
}
|
||||
}
|
||||
}
|
||||
7
ai/codex-quota-footer-plugin/package.json
Normal file
7
ai/codex-quota-footer-plugin/package.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"name": "codex-quota-footer",
|
||||
"version": "2.0.0",
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
"private": true
|
||||
}
|
||||
Reference in New Issue
Block a user