Files
AgapHost/ai/quota-command-openclaw-plugin/index.js
alvis 752d31475c 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
2026-08-01 08:19:35 +00:00

74 lines
3.1 KiB
JavaScript

/**
* Kimi Quota Command (kb #62) — registers `/quota` on Adolf's Matrix channel.
*
* OpenClaw's native-command dispatch (`api.registerCommand`) runs a
* `/`-prefixed command BEFORE the agent turn: no model is invoked, so this
* never spends a Kimi turn (unlike asking Adolf in prose "what's my quota").
* It hits adolf-llm's own GET /usage route (server.js, kb #62 piece 1), which
* itself talks straight to Kimi's managed-usage API — no LLM anywhere in the
* path.
*
* Gating: `requireAuth: true` (the registerCommand default) restricts the
* command to `ctx.isAuthorizedSender`, i.e. the same Matrix DM allowlist
* (`channels.matrix.dm.allowFrom` in openclaw.json) that already gates every
* other interaction with Adolf. No separate owner-only tier is needed here —
* it's a read-only status line, not a privileged action.
*/
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
// adolf-llm is a sibling service on the same `openai` compose network —
// reached by service name, not localhost/host.docker.internal.
const USAGE_URL = "http://adolf-llm:8010/usage";
const FETCH_TIMEOUT_MS = 5000;
function pct(row) {
return row && typeof row.pct === "number" ? `${row.pct}%` : "n/a";
}
async function fetchUsage() {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
try {
const res = await fetch(USAGE_URL, { signal: controller.signal });
const body = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(body?.error || `adolf-llm /usage HTTP ${res.status}`);
return body;
} finally {
clearTimeout(timer);
}
}
export default definePluginEntry({
id: "quota-command",
name: "Codex Quota Command",
description:
"LLM-free /quota command: reads Adolf's Codex usage from adolf-llm:8010/usage and replies with a compact readout.",
register(api) {
api.registerCommand({
name: "quota",
description: "Show Codex quota usage for the plan's rate-limit windows — no model call.",
acceptsArgs: false,
requireAuth: true,
handler: async () => {
try {
const usage = await fetchUsage();
// Codex reports up to two plan-defined windows rather than Kimi's
// fixed 5h/weekly/7d buckets; render whichever exist, shortest
// first, labelled from the data itself.
const rows = [usage.secondary, usage.primary]
.filter((r) => r && typeof r.pct === "number")
.map((r) => (r.window_label ? `${r.window_label} ${r.pct}%` : pct(r)));
let line = rows.length ? `Codex: ${rows.join(" · ")}` : "Codex: no rate-limit windows reported";
if (usage.plan) line += ` (${usage.plan} plan)`;
if (usage.limit_reached) line += " ⚠ limit reached";
if (usage.stale) line += ` — stale, ${usage.age_s}s old`;
return { text: line, suppressReply: true };
} catch (e) {
api.logger?.warn?.(`quota-command: fetch failed (${e?.message || e})`);
return { text: `Codex quota unavailable: ${e?.message || e}`, suppressReply: true };
}
},
});
},
});