aggregate sub-agent session tokens in sidebar

This commit is contained in:
nhat.nguyenhong 2026-09-28 13:45:55 +00:00
parent 177e8f6a58
commit a31297c197
3 changed files with 183 additions and 25 deletions

View File

@ -160,6 +160,12 @@ These are load-bearing. Breaking one causes silent failures in opencode.
info's `tokens.cache.read`/`write` come from the provider's V3 info's `tokens.cache.read`/`write` come from the provider's V3
`inputTokens.cacheRead`/`cacheWrite`, and `tokens.input` is non-cached — so total `inputTokens.cacheRead`/`cacheWrite`, and `tokens.input` is non-cached — so total
prompt tokens are `input+cache.read+cache.write` and output includes `reasoning`. 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,12 +225,20 @@ 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`, plus live quota, above the renders a **CommandCode panel in the session sidebar** (`zdr` / `debug`, session token totals, a
built-in panels) that updates live as you toggle. Note that in opencode 1.x the slash menu and the `sub:` line for sub-agent descendants, plus live quota, above the built-in panels) that updates live
as you toggle. 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 aggregated separately: `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 shows
the total on the `sub:` line. The parent's own tokens are unchanged; `sub: none` means 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
@ -256,7 +264,8 @@ 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. Key resolution and fetch failures are redacted and shown countdown ticks every 30 seconds. The `sub:` line is refreshed on the same triggers (it is
independent of quota rate-limiting). Key resolution and fetch failures are redacted and shown
inline; the panel never stays on `loading…` and never blocks the provider. Extra trace lines inline; the panel never stays on `loading…` and never blocks the provider. Extra trace lines
(`tui-quota`) are appended to the debug log only when debug tracing is on. (`tui-quota`) are appended to the debug log only when debug tracing is on.
@ -291,7 +300,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`, session token totals (`in`/`out`/cache `hit`) and live quota | | Sidebar status panel | Yes — a `sidebar_content` panel shows `zdr`/`debug`, session token totals (`in`/`out`/cache `hit`), a separate `sub:` line aggregating every descendant sub-agent session's tokens, 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,22 +51,40 @@ type TuiProvider = { id?: string; key?: string; options?: Record<string, unknown
type TuiProviderConfig = { options?: Record<string, unknown> }; type TuiProviderConfig = { options?: Record<string, unknown> };
type TuiMessageInfo = { type TuiSessionTokens = {
role?: string;
providerID?: string;
modelID?: string;
tokens?: {
input?: number; input?: number;
output?: number; output?: number;
reasoning?: number; reasoning?: number;
cache?: { read?: number; write?: 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> }; session?: {
messages(sessionID: string): ReadonlyArray<TuiMessageInfo>;
get?(sessionID: string): TuiSessionInfo | undefined;
};
}; };
type TuiApi = { type TuiApi = {
@ -76,6 +94,7 @@ 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 };
}; };
@ -84,6 +103,12 @@ 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).
@ -180,6 +205,22 @@ function resolveBaseURL(api: TuiApi): string | undefined {
type CacheSummary = { input: number; output: number; hit: number | undefined }; type CacheSummary = { input: number; output: number; hit: number | undefined };
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 };
}
/** /**
* Session-cumulative token accounting from the reactive session store opencode's built-in * 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 * context panel also reads. `tokens.input` is non-cached, so total prompt tokens are
@ -195,21 +236,80 @@ function sessionCacheSummary(api: TuiApi, sessionID: string | undefined): CacheS
} catch { } catch {
return undefined; return undefined;
} }
let input = 0; const totals: TokenTotals = { input: 0, output: 0, read: 0, seen: 0 };
let output = 0;
let read = 0;
let seen = 0;
for (const message of messages) { for (const message of messages) {
if (message?.role !== "assistant" || !message.tokens) continue; if (message?.role !== "assistant") continue;
const tokens = message.tokens; addMessageTokens(totals, message.tokens);
const cacheRead = tokens.cache?.read ?? 0;
input += (tokens.input ?? 0) + cacheRead + (tokens.cache?.write ?? 0);
output += (tokens.output ?? 0) + (tokens.reasoning ?? 0);
read += cacheRead;
seen++;
} }
if (seen === 0) return undefined; return summarizeTotals(totals);
return { input, output, hit: input > 0 ? (read / input) * 100 : undefined }; }
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);
} }
function formatCache(summary: CacheSummary | undefined): string { function formatCache(summary: CacheSummary | undefined): string {
@ -218,6 +318,12 @@ function formatCache(summary: CacheSummary | undefined): string {
return `in: ${summary.input.toLocaleString()} · out: ${summary.output.toLocaleString()} · hit: ${hit}`; return `in: ${summary.input.toLocaleString()} · out: ${summary.output.toLocaleString()} · hit: ${hit}`;
} }
function formatFamily(summary: CacheSummary | undefined): string {
if (!summary) return "sub: none";
const hit = summary.hit === undefined ? "--" : `${summary.hit.toFixed(1)}%`;
return `sub: in: ${summary.input.toLocaleString()} · out: ${summary.output.toLocaleString()} · hit: ${hit}`;
}
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;
@ -242,12 +348,15 @@ export const tui = async (api: TuiApi): Promise<void> => {
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 [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());
@ -310,6 +419,31 @@ 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);
@ -347,6 +481,7 @@ export const tui = async (api: TuiApi): Promise<void> => {
zdr:{state(toggles().zdr)} debug:{state(toggles().debug)} zdr:{state(toggles().zdr)} debug:{state(toggles().debug)}
</text> </text>
<text fg={theme.current.textMuted}>{formatCache(sessionCacheSummary(api, sessionId()))}</text> <text fg={theme.current.textMuted}>{formatCache(sessionCacheSummary(api, sessionId()))}</text>
<text fg={theme.current.textMuted}>{formatFamily(family())}</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>
))} ))}
@ -368,6 +503,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); if (id !== undefined) setSessionId(id);
return <Status />; return <Status />;
@ -448,13 +584,20 @@ 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(() => void refreshQuota(), quotaIntervalMs()); const quotaTimer = setInterval(() => {
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) => scheduleQuotaRefresh(event?.type ?? type)), api.event.on(type, (event) => {
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);