Compare commits

..

No commits in common. "fa1c8e9354c0adbe453b38dafd02b356fa53ec00" and "49d518871b169b015c6b1fd1d02d441d0c320441" have entirely different histories.

3 changed files with 8 additions and 266 deletions

View File

@ -155,17 +155,6 @@ These are load-bearing. Breaking one causes silent failures in opencode.
never re-renders). The slot handler itself re-runs on session change, which masks the bug — never re-renders). The slot handler itself re-runs on session change, which masks the bug —
it looks "fixed" after `/session` but stays stale on fresh launch. The built-in it looks "fixed" after `/session` but stays stale on fresh launch. The built-in
`internal:sidebar-context` plugin reads its memos inside JSX for the same reason. `internal:sidebar-context` plugin reads its memos inside JSX for the same reason.
Session token accounting is available to the panel via the same reactive store the
built-in context panel uses, `api.state.session.messages(sessionID)`: each assistant
info's `tokens.cache.read`/`write` come from the provider's V3
`inputTokens.cacheRead`/`cacheWrite`, and `tokens.input` is non-cached — so total
prompt tokens are `input+cache.read+cache.write` and output includes `reasoning`.
Sub-agents (`task` tool) run in child sessions (`session.parent_id`) and are **not** in
the current session's message list, so the panel separately walks descendants with
`api.client.session.children({ sessionID })` (the V1 plugin API exposes the SDK client as
`api.client`) and sums each child's tokens — preferring the v2 session store's aggregate
`api.state.session.get(id).tokens`, falling back to `api.client.session.messages`. Do not
assume the parent's tokens include children, and keep the walk bounded (depth/breadth).
14. **Slash commands and `Ctrl+P` share one registry.** In opencode 1.x the slash menu queries 14. **Slash commands and `Ctrl+P` share one registry.** In opencode 1.x the slash menu queries
the same `namespace: "palette"` commands the palette lists (both filter out `hidden: true`). the same `namespace: "palette"` commands the palette lists (both filter out `hidden: true`).
A slash-only entry is not expressible; registering `/cc-*` also adds them to `Ctrl+P`. A slash-only entry is not expressible; registering `/cc-*` also adds them to `Ctrl+P`.

View File

@ -225,22 +225,12 @@ Linux/macOS). Two rules for the entry:
not a plugin — it loads as dead weight into every session. not a plugin — it loads as dead weight into every session.
Restart opencode after registering the plugin; then type `/cc-` for autocomplete. The plugin also Restart opencode after registering the plugin; then type `/cc-` for autocomplete. The plugin also
renders a **CommandCode panel in the session sidebar** (`zdr` / `debug`, combined main + sub-agent renders a **CommandCode panel in the session sidebar** (`zdr` / `debug`, plus live quota, above the
token totals (`in` / `out` / cache `hit`), plus live quota, above the built-in panels) that updates built-in panels) that updates live as you toggle. Note that in opencode 1.x the slash menu and the
live as you toggle. `in` and `out` show the combined main-agent and descendant total with the
sub-agent-only contribution in parentheses (omitted when there are no sub-agents); `hit` is the
cache-read percentage weighted across both. Note that in opencode 1.x the slash menu and the
`Ctrl+P` palette read the same command registry, so these entries appear in both. If you run opencode `Ctrl+P` palette read the same command registry, so these entries appear in both. If you run opencode
against a remote server, the TUI-side file is not visible to the provider on the server host — use against a remote server, the TUI-side file is not visible to the provider on the server host — use
the env vars or `providerOptions` there. the env vars or `providerOptions` there.
Sub-agent tokens are included in the same totals: `task`-tool subagents run in child sessions
(`session.parent_id`), so their usage is not in the current session's message list. The panel walks
descendants with the SDK's `session.children` endpoint (bounded depth/breadth), reads each child's
aggregate tokens from the session store or falls back to summing its assistant messages, and adds
them to the combined `in` / `out` / `hit`. The parenthetical delta in `in` and `out` is sub-agent
usage alone; it is omitted when no descendant sessions were found.
## Quota tracking ## Quota tracking
`/cc-usage` and the sidebar show CommandCode's **5-hour**, **weekly** and **monthly** usage for the `/cc-usage` and the sidebar show CommandCode's **5-hour**, **weekly** and **monthly** usage for the
@ -266,10 +256,9 @@ event that may never reach the TUI bus — all debounced) and when the active se
but never more than once every 2 minutes; every 5 minutes as a fallback but never more than once every 2 minutes; every 5 minutes as a fallback
(`COMMANDCODE_QUOTA_INTERVAL_MS` overrides the fallback interval — see (`COMMANDCODE_QUOTA_INTERVAL_MS` overrides the fallback interval — see
[Environment variables](#environment-variables)) and the [Environment variables](#environment-variables)) and the
countdown ticks every 30 seconds. The token totals (including the sub-agent delta) are refreshed on countdown ticks every 30 seconds. Key resolution and fetch failures are redacted and shown
the same triggers (they are independent of quota rate-limiting). Key resolution and fetch failures inline; the panel never stays on `loading…` and never blocks the provider. Extra trace lines
are redacted and shown inline; the panel never stays on `loading…` and never blocks the provider. (`tui-quota`) are appended to the debug log only when debug tracing is on.
Extra trace lines (`tui-quota`) are appended to the debug log only when debug tracing is on.
Headless check (no TUI), reading the key from `COMMANDCODE_API_KEY` or the opencode config: Headless check (no TUI), reading the key from `COMMANDCODE_API_KEY` or the opencode config:
@ -302,7 +291,7 @@ The API key is never logged; quota errors pass through `redact()` like every oth
| Retry with backoff | Yes — 429/5xx and network errors, honouring `Retry-After`; also retryable `error` events that arrive inside an HTTP 200 stream before any content (gateway 520s) | | Retry with backoff | Yes — 429/5xx and network errors, honouring `Retry-After`; also retryable `error` events that arrive inside an HTTP 200 stream before any content (gateway 520s) |
| Credential redaction | Yes — error bodies are scrubbed before surfacing | | Credential redaction | Yes — error bodies are scrubbed before surfacing |
| Runtime toggles | Yes — `/cc-zdr` and `/cc-debug` flip the shared toggle file without a restart | | Runtime toggles | Yes — `/cc-zdr` and `/cc-debug` flip the shared toggle file without a restart |
| Sidebar status panel | Yes — a `sidebar_content` panel shows `zdr`/`debug`, combined main + sub-agent token totals (`in`/`out` with a sub-agent-only delta, plus cache `hit`), and live quota | | Sidebar status panel | Yes — a `sidebar_content` panel shows `zdr`/`debug` and live quota |
| Quota tracking | Yes — 5-hour/weekly/monthly meters via `/cc-usage`, the sidebar, and `npm run quota` | | Quota tracking | Yes — 5-hour/weekly/monthly meters via `/cc-usage`, the sidebar, and `npm run quota` |
### `tool_choice` handling ### `tool_choice` handling

View File

@ -51,40 +51,9 @@ type TuiProvider = { id?: string; key?: string; options?: Record<string, unknown
type TuiProviderConfig = { options?: Record<string, unknown> }; type TuiProviderConfig = { options?: Record<string, unknown> };
type TuiSessionTokens = {
input?: number;
output?: number;
reasoning?: number;
cache?: { read?: number; write?: number };
};
type TuiMessageInfo = {
role?: string;
providerID?: string;
modelID?: string;
tokens?: TuiSessionTokens;
};
type TuiSessionInfo = {
id: string;
parentID?: string;
tokens?: TuiSessionTokens;
};
type TuiClient = {
session: {
children(input: { sessionID: string }): Promise<{ data?: ReadonlyArray<TuiSessionInfo> }>;
messages(input: { sessionID: string; limit?: number }): Promise<{ data?: ReadonlyArray<{ info?: TuiMessageInfo }> }>;
};
};
type TuiState = { type TuiState = {
config?: { provider?: Record<string, TuiProviderConfig | undefined> }; config?: { provider?: Record<string, TuiProviderConfig | undefined> };
provider?: ReadonlyArray<TuiProvider>; provider?: ReadonlyArray<TuiProvider>;
session?: {
messages(sessionID: string): ReadonlyArray<TuiMessageInfo>;
get?(sessionID: string): TuiSessionInfo | undefined;
};
}; };
type TuiApi = { type TuiApi = {
@ -94,7 +63,6 @@ type TuiApi = {
event: { on(type: string, handler: (event?: { type?: string }) => void): () => void }; event: { on(type: string, handler: (event?: { type?: string }) => void): () => void };
theme: TuiTheme; theme: TuiTheme;
state: TuiState; state: TuiState;
client?: TuiClient;
lifecycle: { onDispose(fn: () => void): () => void }; lifecycle: { onDispose(fn: () => void): () => void };
}; };
@ -103,12 +71,6 @@ const CATEGORY = "CommandCode";
const SIDEBAR_ORDER = 90; const SIDEBAR_ORDER = 90;
const DEFAULT_QUOTA_INTERVAL_MS = 300_000; const DEFAULT_QUOTA_INTERVAL_MS = 300_000;
const MIN_REFRESH_INTERVAL_MS = 120_000; const MIN_REFRESH_INTERVAL_MS = 120_000;
// Sub-agent (child session) accounting limits: the sidebar walks descendants via the SDK's
// session.children endpoint, so cap the breadth/depth and per-session message fetch to keep it
// cheap even for runaway task trees.
const FAMILY_MAX_DEPTH = 4;
const FAMILY_MAX_SESSIONS = 50;
const FAMILY_MESSAGE_LIMIT = 100;
// Extra TUI-bus signals that mark the end of a turn. `session.idle` is a server // Extra TUI-bus signals that mark the end of a turn. `session.idle` is a server
// plugin event and may never fire here; these keep the panel fresh regardless. // plugin event and may never fire here; these keep the panel fresh regardless.
// All event-driven refreshes are floored to MIN_REFRESH_INTERVAL_MS (hard skip). // All event-driven refreshes are floored to MIN_REFRESH_INTERVAL_MS (hard skip).
@ -203,162 +165,6 @@ function resolveBaseURL(api: TuiApi): string | undefined {
return resolveRef(commandCodeOptions(api)?.["baseURL"]); return resolveRef(commandCodeOptions(api)?.["baseURL"]);
} }
type CacheSummary = { input: number; output: number; hit: number | undefined; read: number };
type TokenTotals = { input: number; output: number; read: number; seen: number };
function addMessageTokens(totals: TokenTotals, tokens: TuiSessionTokens | 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,
};
}
/**
* Session-cumulative token accounting from the reactive session store opencode's built-in
* context panel also reads. `tokens.input` is non-cached, so total prompt tokens are
* input+cache.read+cache.write; output includes reasoning. `hit` is cacheRead/total-input.
*/
function sessionCacheSummary(api: TuiApi, sessionID: string | undefined): CacheSummary | undefined {
if (!sessionID) return undefined;
let messages: ReadonlyArray<TuiMessageInfo>;
try {
const list = api.state?.session?.messages(sessionID);
if (!Array.isArray(list)) return undefined;
messages = list;
} catch {
return undefined;
}
const totals: TokenTotals = { input: 0, output: 0, read: 0, seen: 0 };
for (const message of messages) {
if (message?.role !== "assistant") continue;
addMessageTokens(totals, message.tokens);
}
return summarizeTotals(totals);
}
function safeSessionGet(api: TuiApi, sessionID: string): TuiSessionInfo | undefined {
try {
return api.state?.session?.get?.(sessionID);
} catch {
return undefined;
}
}
/**
* Prefer the child session's aggregate tokens (the v2 store exposes them), and fall back to
* summing its assistant messages when the aggregate is absent. Mirrors sessionCacheSummary so
* parent and descendant numbers use the same math.
*/
async function addChildTokens(api: TuiApi, child: TuiSessionInfo, totals: TokenTotals): Promise<void> {
const aggregate = safeSessionGet(api, child.id)?.tokens ?? child.tokens;
if (aggregate) {
addMessageTokens(totals, aggregate);
return;
}
const client = api.client;
if (!client?.session?.messages) return;
try {
const response = await client.session.messages({ sessionID: child.id, limit: FAMILY_MESSAGE_LIMIT });
for (const entry of response?.data ?? []) {
if (entry?.info?.role !== "assistant") continue;
addMessageTokens(totals, entry.info.tokens);
}
} catch (error) {
trace("family-messages-error", redact(error instanceof Error ? error.message : String(error)));
}
}
/**
* Walk every descendant sub-agent session (task tool children can nest) via the SDK
* `session.children` endpoint and sum their token usage. Never throws into the render path.
*/
async function collectFamily(api: TuiApi, rootID: string): Promise<CacheSummary | undefined> {
const client = api.client;
if (!client?.session?.children) return undefined;
const totals: TokenTotals = { input: 0, output: 0, read: 0, seen: 0 };
const visited = new Set<string>([rootID]);
let frontier: string[] = [rootID];
let counted = 0;
for (let depth = 0; depth < FAMILY_MAX_DEPTH && frontier.length > 0 && counted < FAMILY_MAX_SESSIONS; depth++) {
const next: string[] = [];
for (const id of frontier) {
let children: ReadonlyArray<TuiSessionInfo>;
try {
const response = await client.session.children({ sessionID: id });
children = Array.isArray(response?.data) ? response.data : [];
} catch (error) {
trace("family-children-error", redact(error instanceof Error ? error.message : String(error)));
continue;
}
for (const child of children) {
if (!child?.id || visited.has(child.id) || counted >= FAMILY_MAX_SESSIONS) continue;
visited.add(child.id);
next.push(child.id);
counted++;
await addChildTokens(api, child, totals);
}
}
frontier = next;
}
trace("family-collected", `root=${rootID}`, `sessions=${counted}`, `seen=${totals.seen}`);
return summarizeTotals(totals);
}
type TokenView = {
input: number;
output: number;
subInput: number;
subOutput: number;
hasSub: boolean;
hit: number | undefined;
empty: boolean;
};
function combineTokens(main: CacheSummary | undefined, sub: CacheSummary | undefined): TokenView {
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,
};
}
function formatIn(view: TokenView): string {
if (view.empty) return "in: --";
const delta = view.hasSub ? ` (+${view.subInput.toLocaleString()})` : "";
return `in: ${view.input.toLocaleString()}${delta}`;
}
function formatOut(view: TokenView): string {
if (view.empty) return "out: --";
const delta = view.hasSub ? ` (+${view.subOutput.toLocaleString()})` : "";
return `out: ${view.output.toLocaleString()}${delta}`;
}
function formatHit(view: TokenView): string {
if (view.empty || view.hit === undefined) return "hit: --";
return `hit: ${view.hit.toFixed(1)}%`;
}
function quotaIntervalMs(): number { function quotaIntervalMs(): number {
const raw = Number(safeEnv("COMMANDCODE_QUOTA_INTERVAL_MS")); const raw = Number(safeEnv("COMMANDCODE_QUOTA_INTERVAL_MS"));
return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_QUOTA_INTERVAL_MS; return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_QUOTA_INTERVAL_MS;
@ -382,16 +188,12 @@ export const tui = async (api: TuiApi): Promise<void> => {
const [quota, setQuota] = createSignal<QuotaResult | null>(null); const [quota, setQuota] = createSignal<QuotaResult | null>(null);
const [now, setNow] = createSignal(Date.now()); const [now, setNow] = createSignal(Date.now());
const [updatedAt, setUpdatedAt] = createSignal(0); const [updatedAt, setUpdatedAt] = createSignal(0);
const [sessionId, setSessionId] = createSignal<string | undefined>(undefined);
const [family, setFamily] = createSignal<CacheSummary | undefined>(undefined);
let inflight = false; let inflight = false;
let pending = false; let pending = false;
let lastRefreshAt = 0; let lastRefreshAt = 0;
let debounceTimer: ReturnType<typeof setTimeout> | undefined; let debounceTimer: ReturnType<typeof setTimeout> | undefined;
let lastSessionId: string | undefined; let lastSessionId: string | undefined;
let familyRequestId = 0;
let familyTimer: ReturnType<typeof setTimeout> | undefined;
const refresh = (): void => setToggles(readToggles()); const refresh = (): void => setToggles(readToggles());
@ -454,31 +256,6 @@ export const tui = async (api: TuiApi): Promise<void> => {
}, delayMs); }, delayMs);
}; };
// Stale responses are dropped via a monotonic request id rather than an inflight lock, so a
// session switch during a slow walk can never leave the panel showing the previous session.
const refreshFamily = async (sessionID: string | undefined): Promise<void> => {
const requestId = ++familyRequestId;
if (sessionID === undefined) {
setFamily(undefined);
return;
}
try {
const result = await collectFamily(api, sessionID);
if (requestId === familyRequestId) setFamily(result);
} catch (error) {
if (requestId === familyRequestId) setFamily(undefined);
trace("family-throw", redact(error instanceof Error ? error.message : String(error)));
}
};
const scheduleFamilyRefresh = (sessionID: string | undefined, delayMs = 800): void => {
if (familyTimer !== undefined) clearTimeout(familyTimer);
familyTimer = setTimeout(() => {
familyTimer = undefined;
void refreshFamily(sessionID);
}, delayMs);
};
const flip = (name: ToggleName): void => { const flip = (name: ToggleName): void => {
const next = toggle(name); const next = toggle(name);
setToggles(next); setToggles(next);
@ -507,7 +284,6 @@ export const tui = async (api: TuiApi): Promise<void> => {
const Status = () => { const Status = () => {
const theme = api.theme; const theme = api.theme;
const view = () => combineTokens(sessionCacheSummary(api, sessionId()), family());
return ( return (
<box flexDirection="column" gap={0}> <box flexDirection="column" gap={0}>
<text fg={theme.current.text}> <text fg={theme.current.text}>
@ -516,9 +292,6 @@ export const tui = async (api: TuiApi): Promise<void> => {
<text fg={theme.current.textMuted}> <text fg={theme.current.textMuted}>
zdr:{state(toggles().zdr)} debug:{state(toggles().debug)} zdr:{state(toggles().zdr)} debug:{state(toggles().debug)}
</text> </text>
<text fg={theme.current.textMuted}>{formatIn(view())}</text>
<text fg={theme.current.textMuted}>{formatOut(view())}</text>
<text fg={theme.current.textMuted}>{formatHit(view())}</text>
{windowsOf(quota()).map((w) => ( {windowsOf(quota()).map((w) => (
<text fg={tone(w, theme)}>{shortWindow(w, now())}</text> <text fg={tone(w, theme)}>{shortWindow(w, now())}</text>
))} ))}
@ -540,9 +313,7 @@ export const tui = async (api: TuiApi): Promise<void> => {
if (id !== undefined && id !== lastSessionId) { if (id !== undefined && id !== lastSessionId) {
lastSessionId = id; lastSessionId = id;
scheduleQuotaRefresh("session-change"); scheduleQuotaRefresh("session-change");
scheduleFamilyRefresh(id);
} }
if (id !== undefined) setSessionId(id);
return <Status />; return <Status />;
}, },
}, },
@ -621,20 +392,13 @@ export const tui = async (api: TuiApi): Promise<void> => {
void refreshQuota(); void refreshQuota();
const toggleTimer = setInterval(refresh, 1500); const toggleTimer = setInterval(refresh, 1500);
const clockTimer = setInterval(() => setNow(Date.now()), 30_000); const clockTimer = setInterval(() => setNow(Date.now()), 30_000);
const quotaTimer = setInterval(() => { const quotaTimer = setInterval(() => void refreshQuota(), quotaIntervalMs());
void refreshQuota();
void refreshFamily(sessionId());
}, quotaIntervalMs());
const unsubs = QUOTA_TRIGGER_EVENTS.map((type) => const unsubs = QUOTA_TRIGGER_EVENTS.map((type) =>
api.event.on(type, (event) => { api.event.on(type, (event) => scheduleQuotaRefresh(event?.type ?? type)),
scheduleQuotaRefresh(event?.type ?? type);
scheduleFamilyRefresh(sessionId());
}),
); );
api.lifecycle.onDispose(() => { api.lifecycle.onDispose(() => {
for (const unsub of unsubs) unsub(); for (const unsub of unsubs) unsub();
if (debounceTimer !== undefined) clearTimeout(debounceTimer); if (debounceTimer !== undefined) clearTimeout(debounceTimer);
if (familyTimer !== undefined) clearTimeout(familyTimer);
clearInterval(toggleTimer); clearInterval(toggleTimer);
clearInterval(clockTimer); clearInterval(clockTimer);
clearInterval(quotaTimer); clearInterval(quotaTimer);