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
12 changes: 12 additions & 0 deletions opencode-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,18 @@ What the section shows:

Usage comes from `cmduse` polled every 5 seconds, read from opencode's message store for the per-model and per-session rows, and cached from `mpc` for the catalog. Every block remembers its last reading, so a remount, a session switch or a network outage repaints instead of blanking; the model figure is keyed by model and session, so switching models never shows the previous model's numbers.

## Settings

`/cmd-settings` is a dialog over that same file, so a view option is changed without hand-editing JSON. Five settings, written as you pick them:

- **Colours** — `off` (default) or `on`: tint status rows green/amber/red; `off` keeps bold and dim only.
- **OpenCode plan** — `go` (default) or `go-plus`: which per-model monthly limits the Go section renders.
- **Refresh** — `2s`, `5s` (default), `10s`, `30s` or `1m`: account poll cadence, one CLI spawn per tick.
- **Local cost rows** — `off` (default), `session` or `window`: where the per-model `$` figure comes from.
- **Cost refresh** — `30s`, `1m` (default) or `5m`: how often that figure is re-scanned; hidden while cost rows are `off`.

The local cost figure lives inside each message's JSON, so summing it scans the whole store — 0.5-1.9s measured on a 1.3 GiB store, on the UI thread. That is why it defaults to `off`, and why turning it on gives it its own slow interval instead of riding the account poll.

## Commands

Each command passes its arguments through to the CLI that owns it, and each has an agent-facing tool of the same name, so the model can fetch the same text without you typing a slash command.
Expand Down
2 changes: 1 addition & 1 deletion opencode-plugin/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@jeffreyjyz/opencode-command-code",
"version": "0.5.26",
"version": "0.5.27",
"description": "Command Code provider + usage dashboard for opencode: two providers (Anthropic wire for Claude, OpenAI wire for everything else) against api.commandcode.ai, live model list, plan gating, /cmd-usage. Requires the cmduse CLI for usage rendering.",
"type": "module",
"main": "dist/index.js",
Expand Down
26 changes: 25 additions & 1 deletion opencode-plugin/src/constants/sidebar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,33 @@ export const FIVE_HOUR_SECS = 5 * 3600;
/** Weekly window length in seconds. Mirrors cmduse_core::WEEKLY_SECS. */
export const WEEKLY_SECS = 7 * 86400;

/** Sidebar poll cadences offered by /cmd-settings, in ms. */
export const POLL_CHOICES = [2_000, 5_000, 10_000, 30_000, 60_000, 300_000] as const;

/** One tick per 5s is the cadence every build before /cmd-settings shipped. */
export const POLL_DEFAULT_MS = 5_000;

/**
* Where the per-model cost row comes from. `off` is the default because that
* figure lives inside each message's JSON: summing it scans the whole
* `session_message` table (0.5-1.9s measured on a 1.3 GiB store) and that scan
* on the TUI thread is what stalled keystrokes. Percent windows come from the
* account API and cost nothing locally.
*/
export const COST_MODES = ["off", "session", "window"] as const;
export type CostMode = (typeof COST_MODES)[number];
export const COST_MODE_DEFAULT: CostMode = "off";

/** Re-scan intervals for the opt-in cost row, in ms. */
export const COST_REFRESH_CHOICES = [30_000, 60_000, 300_000] as const;
export const COST_REFRESH_DEFAULT_MS = 60_000;

/** Colour is OFF unless asked for; the OpenCode Go plan defaults to `go` (see
* sidebar/prefs.ts). */
* sidebar/prefs.ts). Declared last because it reads the constants above. */
export const PREF_DEFAULTS: Prefs = {
colors: false,
ocPlan: OC_PLAN_DEFAULT,
pollMs: POLL_DEFAULT_MS,
cost: COST_MODE_DEFAULT,
costMs: COST_REFRESH_DEFAULT_MS,
};
6 changes: 2 additions & 4 deletions opencode-plugin/src/constants/timing.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
// Poll cadences, spawn bounds and cache TTLs.

/** Sidebar poll cadence: one cmduse/ocuse spawn plus the local store reads. */
export const POLL_MS = 5_000;
// Poll cadences, spawn bounds and cache TTLs. The sidebar's own cadence is a
// setting (`prefs.pollMs`), so no fixed interval lives here.

/** How long one sidebar CLI spawn may run before it is killed. An outage can
* leave a fetch hanging through cmduse's retry ladder, and the poll interval
Expand Down
92 changes: 92 additions & 0 deletions opencode-plugin/src/sidebar/local-cost.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Local cost rows, memoised so the panel's poll never pays for the scan.
// Each figure lives in a `session_message` row's JSON, so summing it is an
// account-wide `json_extract … GROUP BY` over 1.3 GiB: 35ms/739ms/1 875ms for
// the 5h/7d/30d windows, with a disk-spilling sort. On the 5s poll that held the
// TUI thread 49.8% busy and lagged typing. `cost: "off"` (default) returns
// before any database is opened; an enabled mode answers from memory for `costMs`.
import { FIVE_HOUR_SECS, WEEKLY_SECS } from "../constants/sidebar";
import { loadPrefs } from "./prefs";
import type { ModelUsage } from "./rows";
import { loadModelUsage, loadModelWindowStart, loadSessionUsage, usageDbPath } from "./usageDb";
import type { ZenWindowStarts } from "./zen";

/** One memoised read: the same key inside `costMs` answers from memory. */
function memoize<T>() {
let slot: { key: string; at: number; value?: T } | undefined;
return {
read(key: string, costMs: number, now: number, scan: () => T | undefined): T | undefined {
if (slot && slot.key === key && now - slot.at < costMs) return slot.value;
slot = { key, at: now, value: scan() };
return slot.value;
},
clear(): void {
slot = undefined;
},
};
}

const sessionMemo = memoize<ModelUsage>();
const modelMemo = memoize<ModelUsage>();
const windowsMemo = memoize<ZenWindowStarts>();

/** Forget every figure, so the next read scans again. */
export function resetLocalCost(): void {
sessionMemo.clear();
modelMemo.clear();
windowsMemo.clear();
}

/**
* This conversation's own totals: one indexed read on `session_v2`, the cheapest
* row the panel has. Undefined when the cost rows are off or the host has not
* resolved a session yet.
*/
export function sessionCost(
sessionID: string | undefined,
now = Date.now(),
): ModelUsage | undefined {
const prefs = loadPrefs();
if (prefs.cost === "off" || !sessionID) return undefined;
return sessionMemo.read(
sessionID,
prefs.costMs,
now,
() => loadSessionUsage(sessionID) ?? undefined,
);
}

/**
* One model's spend inside one conversation. Session scope is required: the
* period-wide figure counts every conversation, and dividing it by this
* session's total read as "over 100% of session".
*/
export function modelCost(
modelID: string | undefined,
sessionID: string | undefined,
now = Date.now(),
): ModelUsage | undefined {
const prefs = loadPrefs();
if (prefs.cost === "off" || !modelID || !sessionID) return undefined;
return modelMemo.read(
`${sessionID}\u0000${modelID}`,
prefs.costMs,
now,
() => loadModelUsage(modelID, 0, usageDbPath(), sessionID) ?? undefined,
);
}

/**
* The active model's rolling-window starts. Account-wide and the most expensive
* read here (two scans, one per window), so it is the `window` mode only.
*/
export function modelWindows(
modelID: string | undefined,
now = Date.now(),
): ZenWindowStarts | undefined {
const prefs = loadPrefs();
if (prefs.cost !== "window" || !modelID) return undefined;
return windowsMemo.read(modelID, prefs.costMs, now, () => ({
fiveHour: loadModelWindowStart(modelID, now - FIVE_HOUR_SECS * 1000) ?? undefined,
weekly: loadModelWindowStart(modelID, now - WEEKLY_SECS * 1000) ?? undefined,
}));
}
89 changes: 85 additions & 4 deletions opencode-plugin/src/sidebar/prefs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,38 @@
// disk per render), so flipping the file lands on the next poll without a
// restart. Nothing here throws: a missing, unreadable or malformed file leaves
// the defaults standing, and an unknown plan falls back to `go` with a warning.
import { readFileSync } from "node:fs";
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { dirname, join } from "node:path";
import { OPENCODE_DIR, PREFS_FILE } from "../constants/paths";
import { OC_PLAN_DEFAULT, OC_PLANS, type OcPlan, PREF_DEFAULTS } from "../constants/sidebar";
import {
COST_MODE_DEFAULT,
COST_MODES,
COST_REFRESH_CHOICES,
COST_REFRESH_DEFAULT_MS,
type CostMode,
OC_PLAN_DEFAULT,
OC_PLANS,
type OcPlan,
POLL_CHOICES,
POLL_DEFAULT_MS,
PREF_DEFAULTS,
} from "../constants/sidebar";
import { PREFS_CACHE_MS } from "../constants/timing";

export interface Prefs {
colors: boolean;
/** OpenCode Go plan the sidebar renders per-model limits for. */
ocPlan: OcPlan;
/** Sidebar poll cadence in ms; one of `POLL_CHOICES`. */
pollMs: number;
/**
* Where the per-model cost row reads from. `off` scans nothing: the figure
* sits inside each message's JSON, so summing it stalls the TUI thread.
*/
cost: CostMode;
/** Opt-in cost re-scan interval in ms; one of `COST_REFRESH_CHOICES`. */
costMs: number;
}

let cached: { at: number; prefs: Prefs } | undefined;
Expand All @@ -47,13 +68,73 @@ function planFrom(value: unknown, source: string): OcPlan | undefined {

/** Only a literal `true` enables colour; an unknown plan falls back to `go`. */
export function parsePrefs(raw: unknown): Prefs {
const obj = raw as { colors?: unknown; ocPlan?: unknown } | undefined;
const obj = raw as
| { colors?: unknown; ocPlan?: unknown; pollMs?: unknown; cost?: unknown; costMs?: unknown }
| undefined;
return {
colors: obj?.colors === true,
ocPlan: planFrom(obj?.ocPlan, "file") ?? OC_PLAN_DEFAULT,
pollMs: numberFrom(obj?.pollMs, POLL_CHOICES, POLL_DEFAULT_MS, "pollMs"),
cost: costFrom(obj?.cost),
costMs: numberFrom(obj?.costMs, COST_REFRESH_CHOICES, COST_REFRESH_DEFAULT_MS, "costMs"),
};
}

/**
* A numeric setting only ever takes a value the settings dialog can produce,
* so a hand-edited file cannot pick a 1ms poll or a 0ms re-scan.
*/
function numberFrom(
value: unknown,
choices: readonly number[],
fallback: number,
name: string,
): number {
if (value === undefined) return fallback;
if (typeof value === "number" && choices.includes(value)) return value;
console.warn(
`[command-code] ignoring unknown ${name} ${JSON.stringify(value)}; using ${fallback}`,
);
return fallback;
}

function costFrom(value: unknown): CostMode {
if (value === undefined) return COST_MODE_DEFAULT;
if (typeof value === "string" && (COST_MODES as readonly string[]).includes(value)) {
return value as CostMode;
}
console.warn(
`[command-code] ignoring unknown cost mode ${JSON.stringify(value)}; using "${COST_MODE_DEFAULT}"`,
);
return COST_MODE_DEFAULT;
}

/**
* Write one or more settings back to the prefs file, keeping keys this build
* does not know yet (the file is shared with the provider half). Atomic:
* a crash mid-write must not leave an unreadable config behind, because every
* read below falls back to defaults and would silently reset the user.
*/
export function savePrefs(patch: Partial<Prefs>, env: NodeJS.ProcessEnv = process.env): Prefs {
const path = prefsPath(env);
let raw: Record<string, unknown> = {};
try {
const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
raw = parsed as Record<string, unknown>;
}
} catch {
// absent or malformed: the patch still writes a valid file
}
const next = { ...raw, ...patch };
mkdirSync(dirname(path), { recursive: true });
const temporary = `${path}.${process.pid}.tmp`;
writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, "utf8");
renameSync(temporary, path);
cached = undefined;
return parsePrefs(next);
}

/** Env override, then the file, then the default. Cached for `PREFS_CACHE_MS`. */
export function loadPrefs(env: NodeJS.ProcessEnv = process.env, now = Date.now()): Prefs {
if (cached && now - cached.at < PREFS_CACHE_MS) return cached.prefs;
Expand Down
101 changes: 101 additions & 0 deletions opencode-plugin/src/sidebar/settings-rows.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// Rows of the /cmd-settings dialog, kept free of JSX so both hosts and the
// tests can read them as plain data (the panel does the same for sidebar rows).
//
// Every row is a cycle: `values()` is the label list in display order, `value()`
// is what is stored now, `set()` writes it back to the prefs file. Labels are
// the only strings the dialog shows, so the stored file stays typed and the
// panel keeps its own parsing rules.
import {
COST_MODES,
COST_REFRESH_CHOICES,
POLL_CHOICES,
type CostMode,
type OcPlan,
} from "../constants/sidebar";
import type { Prefs } from "./prefs";

export interface SettingRow {
readonly title: string;
readonly values: () => readonly string[];
readonly value: () => string;
readonly set: (label: string) => void;
/** A row that only applies while another setting allows it. */
readonly hidden?: () => boolean;
readonly describe?: (label: string) => string;
}

/** `5000` reads `5s`, `300000` reads `5m`. */
export function durationLabel(ms: number): string {
return ms >= 60_000 ? `${ms / 60_000}m` : `${ms / 1_000}s`;
}

const onOff = (value: boolean): string => (value ? "on" : "off");

/**
* The setting list, in the order the dialog shows it. `prefs` is a getter, not
* a snapshot: the dialog re-reads after each change so a hidden row appears the
* moment the cost mode leaves `off`.
*/
export function settingRows(
prefs: () => Prefs,
save: (patch: Partial<Prefs>) => void,
): SettingRow[] {
return [
{
title: "Colours",
values: () => ["off", "on"],
value: () => onOff(prefs().colors),
set: (label) => save({ colors: label === "on" }),
describe: (label) =>
label === "on"
? "Tint status rows green/amber/red; plain text keeps bold and dim only."
: "Plain text only. Bold marks headlines, dim marks labels.",
},
{
title: "OpenCode plan",
values: () => ["go", "go-plus"],
value: () => prefs().ocPlan,
set: (label) => save({ ocPlan: label as OcPlan }),
describe: (label) =>
label === "go-plus"
? "Per-model monthly limits are the Go Plus ones."
: "Per-model monthly limits are the standard Go ones.",
},
{
title: "Refresh",
values: () => POLL_CHOICES.map(durationLabel),
value: () => durationLabel(prefs().pollMs),
set: (label) => {
const index = POLL_CHOICES.map(durationLabel).indexOf(label);
if (index !== -1) save({ pollMs: POLL_CHOICES[index] });
},
describe: (label) =>
`Poll the account API every ${label}. Shorter is fresher and costs one CLI spawn per tick.`,
},
{
title: "Local cost rows",
values: () => [...COST_MODES],
value: () => prefs().cost,
set: (candidate) => {
if ((COST_MODES as readonly string[]).includes(candidate)) {
save({ cost: candidate as CostMode });
}
},
describe: (candidate) =>
candidate === "off"
? "No database reads at all: the panel shows account percentages only."
: "Reads this machine's message store for a $ figure. The scan takes 0.5-1.9s on a large store, so it runs on its own slower interval.",
},
{
title: "Cost refresh",
values: () => COST_REFRESH_CHOICES.map(durationLabel),
value: () => durationLabel(prefs().costMs),
set: (label) => {
const index = COST_REFRESH_CHOICES.map(durationLabel).indexOf(label);
if (index !== -1) save({ costMs: COST_REFRESH_CHOICES[index] });
},
hidden: () => prefs().cost === "off",
describe: (label) => `Re-scan the message store for cost every ${label}.`,
},
];
}
Loading
Loading