467 lines
18 KiB
TypeScript
467 lines
18 KiB
TypeScript
// opencode 2 TUI plugin exposing /cc-zdr, /cc-debug, /cc-status and /cc-usage, plus a sidebar
|
|
// panel showing the current toggle state and live CommandCode quota. It flips the shared toggle
|
|
// file (see ../src/toggles.ts) that the provider reads on every request, so a change takes
|
|
// effect without restarting opencode, and reads the alpha billing endpoints (see
|
|
// ../src/quota.ts) with the provider's API key for the 5-hour, weekly and monthly meters.
|
|
//
|
|
// This is an opencode 2 plugin (`Plugin.define` from `@opencode/plugin/tui`). opencode loads
|
|
// the `tui` part from a plugin directory registered in `cli.json` (`"plugins": ["<abs>/plugin"]`),
|
|
// compiles this file with its Bun/Solid transform, and maps `solid-js`,
|
|
// `@opencode/plugin/tui` and the JSX runtime to its internal modules; that keeps this package
|
|
// free of runtime dependencies. `../src/*.js` imports resolve to the sibling TS sources.
|
|
|
|
import { readFileSync } from "node:fs";
|
|
import { homedir } from "node:os";
|
|
import { join } from "node:path";
|
|
|
|
import { createEffect, createMemo, createSignal } from "solid-js";
|
|
|
|
import { Plugin } from "@opencode/plugin/tui";
|
|
|
|
import { fetchQuota, formatQuota, formatReset, percent, quotaBar, type QuotaResult } from "../src/quota.js";
|
|
import { PROVIDER_ID } from "../src/constants.js";
|
|
import { debugWhen } from "../src/log.js";
|
|
import { redact } from "../src/redact.js";
|
|
import { debugEnabled, readToggles, toggle, type ToggleName, type Toggles } from "../src/toggles.js";
|
|
|
|
const CATEGORY = "CommandCode";
|
|
const DEFAULT_QUOTA_INTERVAL_MS = 300_000;
|
|
const MIN_REFRESH_INTERVAL_MS = 120_000;
|
|
// Sub-agent (child session) accounting cap. The sidebar reads the host's reactive family
|
|
// index (`data.session.family`), so the cap only bounds how much of a runaway task tree
|
|
// is summed.
|
|
const FAMILY_MAX_SESSIONS = 50;
|
|
// Server events that mark progress or the end of a turn. All event-driven refreshes are
|
|
// floored to MIN_REFRESH_INTERVAL_MS (hard skip).
|
|
const QUOTA_TRIGGER_EVENTS = [
|
|
"session.usage.updated",
|
|
"session.execution.succeeded",
|
|
"session.execution.failed",
|
|
"session.idle",
|
|
"session.status",
|
|
] as const;
|
|
|
|
type TokenUsageView = {
|
|
input?: number;
|
|
output?: number;
|
|
reasoning?: number;
|
|
cache?: { read?: number; write?: number };
|
|
};
|
|
|
|
type TokenTotals = { input: number; output: number; read: number; seen: number };
|
|
|
|
type CacheSummary = { input: number; output: number; hit: number | undefined; read: number };
|
|
|
|
function safeEnv(name: string): string | undefined {
|
|
try {
|
|
return typeof process === "undefined" ? undefined : process.env?.[name];
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
/** Debug-only trace to the shared debug file. Silent unless debug is on; never logs the key. */
|
|
function trace(...args: unknown[]): void {
|
|
debugWhen(debugEnabled(), "tui-quota", ...args);
|
|
}
|
|
|
|
function state(value: boolean | undefined): string {
|
|
return value === true ? "on" : "off";
|
|
}
|
|
|
|
function summary(toggles: Toggles = readToggles()): string {
|
|
return `zdr=${state(toggles.zdr)}, debug=${state(toggles.debug)}`;
|
|
}
|
|
|
|
/** Expands an `{env:NAME}` config reference; other templates are treated as unset. */
|
|
function resolveRef(value: unknown): string | undefined {
|
|
if (typeof value !== "string" || value.length === 0) return undefined;
|
|
const trimmed = value.trim();
|
|
const template = /^\{env:([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(trimmed);
|
|
if (template) return template[1] ? safeEnv(template[1]) : undefined;
|
|
if (/^\{.*\}$/.test(trimmed)) return undefined;
|
|
return trimmed;
|
|
}
|
|
|
|
function addTokens(totals: TokenTotals, tokens: TokenUsageView | undefined): void {
|
|
if (!tokens) return;
|
|
const cacheRead = tokens.cache?.read ?? 0;
|
|
totals.input += (tokens.input ?? 0) + cacheRead + (tokens.cache?.write ?? 0);
|
|
totals.output += (tokens.output ?? 0) + (tokens.reasoning ?? 0);
|
|
totals.read += cacheRead;
|
|
totals.seen++;
|
|
}
|
|
|
|
function summarizeTotals(totals: TokenTotals): CacheSummary | undefined {
|
|
if (totals.seen === 0) return undefined;
|
|
return {
|
|
input: totals.input,
|
|
output: totals.output,
|
|
hit: totals.input > 0 ? (totals.read / totals.input) * 100 : undefined,
|
|
read: totals.read,
|
|
};
|
|
}
|
|
|
|
// The location provider collection is not synced by the host; fetch it once so the
|
|
// configured `settings.apiKey` / `headers.Authorization` / `baseURL` can be read. Falls
|
|
// back to the global opencode.json for setups where the client omits credential settings.
|
|
let providerInfo: { settings?: Record<string, unknown>; headers?: Record<string, unknown> } | undefined;
|
|
let providerInfoResolved = false;
|
|
|
|
async function ensureProviderInfo(context: Plugin.Context): Promise<void> {
|
|
if (providerInfoResolved) return;
|
|
providerInfoResolved = true;
|
|
try {
|
|
const location = context.location ?? context.data.location.default();
|
|
await context.data.location.provider.sync(location);
|
|
const provider = context.data.location.provider.list(location)?.find((entry) => entry?.id === PROVIDER_ID);
|
|
providerInfo = {
|
|
settings: provider?.settings as Record<string, unknown> | undefined,
|
|
headers: provider?.headers as Record<string, unknown> | undefined,
|
|
};
|
|
} catch (error) {
|
|
trace("provider-sync-error", redact(error instanceof Error ? error.message : String(error)));
|
|
}
|
|
}
|
|
|
|
function configFromFile(): Record<string, unknown> | undefined {
|
|
try {
|
|
const configHome = safeEnv("XDG_CONFIG_HOME") ?? join(homedir(), ".config");
|
|
const parsed = JSON.parse(readFileSync(join(configHome, "opencode", "opencode.json"), "utf8")) as Record<
|
|
string,
|
|
unknown
|
|
>;
|
|
const providers = parsed["providers"] as Record<string, unknown> | undefined;
|
|
const legacy = parsed["provider"] as Record<string, unknown> | undefined;
|
|
const entry = (providers?.[PROVIDER_ID] ?? legacy?.[PROVIDER_ID]) as Record<string, unknown> | undefined;
|
|
if (!entry) return undefined;
|
|
return {
|
|
...((entry["settings"] as Record<string, unknown> | undefined) ??
|
|
(entry["options"] as Record<string, unknown> | undefined)),
|
|
headers: entry["headers"] ?? (entry["options"] as Record<string, unknown> | undefined)?.["headers"],
|
|
};
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
function resolveApiKeySource(): { key?: string; source: string } {
|
|
const file = configFromFile();
|
|
const named: Array<[string, unknown]> = [
|
|
["provider.settings.apiKey", providerInfo?.settings?.["apiKey"]],
|
|
["provider.headers.Authorization", providerInfo?.headers?.["Authorization"] ?? providerInfo?.headers?.["authorization"]],
|
|
["config.settings.apiKey", file?.["apiKey"]],
|
|
["config.headers.Authorization", file?.["headers"] && (file["headers"] as Record<string, unknown>)["Authorization"]],
|
|
["COMMANDCODE_API_KEY", safeEnv("COMMANDCODE_API_KEY")],
|
|
];
|
|
for (const [source, candidate] of named) {
|
|
const value = resolveRef(candidate);
|
|
if (value) return { key: value.replace(/^Bearer\s+/i, ""), source };
|
|
}
|
|
return { source: "none" };
|
|
}
|
|
|
|
function resolveBaseURL(): string | undefined {
|
|
return resolveRef(providerInfo?.settings?.["baseURL"] ?? configFromFile()?.["baseURL"]);
|
|
}
|
|
|
|
export default Plugin.define({
|
|
id: "commandcode-toggles",
|
|
setup(context) {
|
|
const [toggles, setToggles] = createSignal(readToggles());
|
|
const [quota, setQuota] = createSignal<QuotaResult | null>(null);
|
|
const [now, setNow] = createSignal(Date.now());
|
|
const [updatedAt, setUpdatedAt] = createSignal(0);
|
|
|
|
let inflight = false;
|
|
let pending = false;
|
|
let lastRefreshAt = 0;
|
|
let debounceTimer: ReturnType<typeof setTimeout> | undefined;
|
|
|
|
const refreshQuota = async (): Promise<void> => {
|
|
if (inflight) {
|
|
pending = true;
|
|
trace("coalesced", "inflight");
|
|
return;
|
|
}
|
|
const since = Date.now() - lastRefreshAt;
|
|
if (lastRefreshAt > 0 && since < MIN_REFRESH_INTERVAL_MS) {
|
|
trace("rate-limited", `remainingMs=${MIN_REFRESH_INTERVAL_MS - since}`);
|
|
return;
|
|
}
|
|
inflight = true;
|
|
try {
|
|
await ensureProviderInfo(context);
|
|
const { key: apiKey, source } = resolveApiKeySource();
|
|
if (!apiKey) {
|
|
setQuota({ ok: false, error: { kind: "config", message: "No API key found" } });
|
|
setNow(Date.now());
|
|
trace("no-key", `source=${source}`);
|
|
return;
|
|
}
|
|
trace("fetch-start", `source=${source}`);
|
|
const result = await fetchQuota({ apiKey, baseURL: resolveBaseURL() });
|
|
setQuota(result);
|
|
if (result.ok) {
|
|
trace(
|
|
"fetch-ok",
|
|
`windows=${result.quota.windows.map((w) => `${w.id}:${w.used}/${w.cap}`).join(",")}`,
|
|
);
|
|
} else {
|
|
trace("fetch-error", `kind=${result.error.kind}`);
|
|
}
|
|
} catch (error) {
|
|
// Key resolution, provider list access, and fetch can all throw; surface it
|
|
// instead of wedging the panel on `loading…`.
|
|
const message = redact(error instanceof Error ? error.message : String(error));
|
|
setQuota({ ok: false, error: { kind: "network", message } });
|
|
trace("fetch-throw", message);
|
|
} finally {
|
|
inflight = false;
|
|
lastRefreshAt = Date.now();
|
|
setNow(Date.now());
|
|
setUpdatedAt(Date.now());
|
|
if (pending) {
|
|
pending = false;
|
|
trace("flush-pending");
|
|
void refreshQuota();
|
|
}
|
|
}
|
|
};
|
|
|
|
const scheduleQuotaRefresh = (reason: string, delayMs = 800): void => {
|
|
trace("scheduled", `reason=${reason}`, `delayMs=${delayMs}`);
|
|
if (debounceTimer !== undefined) clearTimeout(debounceTimer);
|
|
debounceTimer = setTimeout(() => {
|
|
debounceTimer = undefined;
|
|
void refreshQuota();
|
|
}, delayMs);
|
|
};
|
|
|
|
const flip = (name: ToggleName): void => {
|
|
const next = toggle(name);
|
|
setToggles(next);
|
|
context.ui.toast.show({
|
|
title: CATEGORY,
|
|
message: `${name} ${state(next[name])} (${summary(next)})`,
|
|
variant: next[name] === true ? "success" : "info",
|
|
});
|
|
};
|
|
|
|
const SidebarPanel = (props: { sessionID: string | undefined }) => {
|
|
// Session-cumulative token accounting from the reactive session store. The server
|
|
// sums per-step deltas into `SessionInfo.tokens` (`input` is non-cached, so total
|
|
// prompt tokens are input+cache.read+cache.write; output includes reasoning), which
|
|
// matches the provider's V3 usage shape. Family members (sub-agent sessions) come
|
|
// from the host's family index and are summed the same way.
|
|
const main = createMemo(() => {
|
|
const id = props.sessionID;
|
|
if (!id) return undefined;
|
|
const info = context.data.session.get(id);
|
|
if (!info) return undefined;
|
|
const totals: TokenTotals = { input: 0, output: 0, read: 0, seen: 0 };
|
|
addTokens(totals, info.tokens as TokenUsageView | undefined);
|
|
return summarizeTotals(totals);
|
|
});
|
|
const family = createMemo(() => {
|
|
const id = props.sessionID;
|
|
if (!id) return undefined;
|
|
const totals: TokenTotals = { input: 0, output: 0, read: 0, seen: 0 };
|
|
const members = context.data.session.family(id);
|
|
for (const member of members.slice(0, FAMILY_MAX_SESSIONS)) {
|
|
addTokens(totals, context.data.session.get(member)?.tokens as TokenUsageView | undefined);
|
|
}
|
|
return summarizeTotals(totals);
|
|
});
|
|
const spent = createMemo(() => {
|
|
const id = props.sessionID;
|
|
if (!id) return 0;
|
|
return context.data.session.cost(id);
|
|
});
|
|
const view = createMemo(() => {
|
|
const sub = family();
|
|
const input = (main()?.input ?? 0) + (sub?.input ?? 0);
|
|
const output = (main()?.output ?? 0) + (sub?.output ?? 0);
|
|
const read = (main()?.read ?? 0) + (sub?.read ?? 0);
|
|
return {
|
|
input,
|
|
output,
|
|
subInput: sub?.input ?? 0,
|
|
subOutput: sub?.output ?? 0,
|
|
hasSub: sub !== undefined,
|
|
hit: input > 0 ? (read / input) * 100 : undefined,
|
|
empty: main() === undefined && sub === undefined,
|
|
};
|
|
});
|
|
|
|
// Session changes refresh the quota meters (rate-limited inside refreshQuota).
|
|
createEffect(() => {
|
|
if (props.sessionID) scheduleQuotaRefresh("session-change");
|
|
});
|
|
|
|
const theme = context.theme;
|
|
const errorColor = theme.text.feedback.error.base;
|
|
const warningColor = theme.text.feedback.warning.base;
|
|
const successColor = theme.text.feedback.success.base;
|
|
// Reads toggles()/quota()/view()/now() inside the JSX so Solid tracks the signals.
|
|
// Hoisting them into a `const` above the return would subscribe once under a
|
|
// non-tracking owner and freeze the panel after first paint.
|
|
return (
|
|
<box flexDirection="column" gap={0}>
|
|
<text fg={theme.text.base}>
|
|
<b>CommandCode</b>
|
|
</text>
|
|
<text fg={theme.text.muted}>
|
|
zdr:{state(toggles().zdr)} debug:{state(toggles().debug)}
|
|
</text>
|
|
<text fg={theme.text.muted}>
|
|
{view().empty
|
|
? "in: --"
|
|
: `in: ${view().input.toLocaleString()}${view().hasSub ? ` (+${view().subInput.toLocaleString()})` : ""}`}
|
|
</text>
|
|
<text fg={theme.text.muted}>
|
|
{view().empty
|
|
? "out: --"
|
|
: `out: ${view().output.toLocaleString()}${view().hasSub ? ` (+${view().subOutput.toLocaleString()})` : ""}`}
|
|
</text>
|
|
<text fg={theme.text.muted}>
|
|
{view().empty || view().hit === undefined ? "hit: --" : `hit: ${view().hit?.toFixed(1)}%`}
|
|
</text>
|
|
{view().empty || spent() <= 0 ? null : <text fg={theme.text.muted}>spent: ${spent().toFixed(2)}</text>}
|
|
{(quota()?.ok === true
|
|
? (quota() as Extract<QuotaResult, { ok: true }>).quota.windows
|
|
: []
|
|
).map((w) => {
|
|
const label = w.id === "fiveHour" ? "5h" : w.id === "weekly" ? "7d" : "mo";
|
|
const reset = formatReset(w.resetAtMs, now());
|
|
const amount =
|
|
w.id === "monthly" ? `$${w.used.toFixed(2)}/$${w.cap.toFixed(2)}` : `${percent(w.used, w.cap)}%`;
|
|
return (
|
|
<text
|
|
fg={
|
|
w.exceeded || percent(w.used, w.cap) >= 100
|
|
? errorColor
|
|
: percent(w.used, w.cap) >= 80
|
|
? warningColor
|
|
: successColor
|
|
}
|
|
>
|
|
{`${label} ${quotaBar(w.used, w.cap, 8)} ${amount}${reset ? ` · ${reset}` : ""}`}
|
|
</text>
|
|
);
|
|
})}
|
|
{quota()?.ok === false ? (
|
|
<text fg={errorColor}>quota: {(quota() as Extract<QuotaResult, { ok: false }>).error.message}</text>
|
|
) : quota() === null ? (
|
|
<text fg={theme.text.muted}>quota: loading…</text>
|
|
) : null}
|
|
<text fg={theme.text.muted}>
|
|
updated @ {updatedAt() > 0 ? new Date(updatedAt()).toTimeString().slice(0, 8) : "--:--:--"}
|
|
</text>
|
|
</box>
|
|
);
|
|
};
|
|
|
|
context.ui.slot({
|
|
append: "sidebar.content",
|
|
render: (input) => <SidebarPanel sessionID={input.sessionID} />,
|
|
});
|
|
|
|
context.keymap.layer(() => ({
|
|
mode: "global",
|
|
commands: [
|
|
{
|
|
id: "commandcode-toggles.zdr",
|
|
title: "CommandCode: toggle ZDR header",
|
|
description: "Send the x-cmd-zdr header on requests",
|
|
group: CATEGORY,
|
|
palette: true,
|
|
slash: { name: "cc-zdr" },
|
|
run: () => flip("zdr"),
|
|
},
|
|
{
|
|
id: "commandcode-toggles.debug",
|
|
title: "CommandCode: toggle debug tracing",
|
|
description: "Write a redacted request and stream trace to a log file",
|
|
group: CATEGORY,
|
|
palette: true,
|
|
slash: { name: "cc-debug" },
|
|
run: () => flip("debug"),
|
|
},
|
|
{
|
|
id: "commandcode-toggles.status",
|
|
title: "CommandCode: show toggle status",
|
|
description: "Show the current zdr and debug state",
|
|
group: CATEGORY,
|
|
palette: true,
|
|
slash: { name: "cc-status" },
|
|
run: () => context.ui.toast.show({ title: CATEGORY, message: summary(), variant: "info" }),
|
|
},
|
|
{
|
|
id: "commandcode-toggles.usage",
|
|
title: "CommandCode: show usage and quota",
|
|
description: "Show the 5-hour, weekly and monthly quota from the CommandCode API",
|
|
group: CATEGORY,
|
|
palette: true,
|
|
slash: { name: "cc-usage" },
|
|
run: async () => {
|
|
await ensureProviderInfo(context);
|
|
const { key: apiKey } = resolveApiKeySource();
|
|
if (!apiKey) {
|
|
context.ui.toast.show({
|
|
title: CATEGORY,
|
|
message: `No API key found. Set providers.${PROVIDER_ID}.settings.apiKey or COMMANDCODE_API_KEY.`,
|
|
variant: "warning",
|
|
});
|
|
return;
|
|
}
|
|
let result: QuotaResult;
|
|
try {
|
|
result = await fetchQuota({ apiKey, baseURL: resolveBaseURL() });
|
|
} catch (error) {
|
|
const message = redact(error instanceof Error ? error.message : String(error));
|
|
setQuota({ ok: false, error: { kind: "network", message } });
|
|
trace("usage-throw", message);
|
|
context.ui.toast.show({ title: CATEGORY, message, variant: "error" });
|
|
return;
|
|
}
|
|
if (!result.ok) {
|
|
setQuota(result);
|
|
context.ui.toast.show({ title: CATEGORY, message: result.error.message, variant: "error" });
|
|
return;
|
|
}
|
|
setQuota(result);
|
|
setNow(Date.now());
|
|
setUpdatedAt(Date.now());
|
|
context.ui.toast.show({
|
|
title: CATEGORY,
|
|
message: formatQuota(result.quota),
|
|
variant: "info",
|
|
duration: 15000,
|
|
});
|
|
},
|
|
},
|
|
],
|
|
}));
|
|
|
|
void refreshQuota();
|
|
const toggleTimer = setInterval(() => setToggles(readToggles()), 1500);
|
|
const clockTimer = setInterval(() => setNow(Date.now()), 30_000);
|
|
const configIntervalMs = Number(safeEnv("COMMANDCODE_QUOTA_INTERVAL_MS"));
|
|
const quotaTimer = setInterval(() => {
|
|
void refreshQuota();
|
|
}, Number.isFinite(configIntervalMs) && configIntervalMs > 0 ? configIntervalMs : DEFAULT_QUOTA_INTERVAL_MS);
|
|
const unsubEvents = QUOTA_TRIGGER_EVENTS.map((type) =>
|
|
context.data.on(type, () => scheduleQuotaRefresh(type)),
|
|
);
|
|
|
|
return () => {
|
|
for (const unsub of unsubEvents) unsub();
|
|
if (debounceTimer !== undefined) clearTimeout(debounceTimer);
|
|
clearInterval(toggleTimer);
|
|
clearInterval(clockTimer);
|
|
clearInterval(quotaTimer);
|
|
};
|
|
},
|
|
});
|