diff --git a/AGENTS.md b/AGENTS.md index 199ed93..4f59013 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 `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 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`. diff --git a/README.md b/README.md index 47bf07a..2a9e240 100644 --- a/README.md +++ b/README.md @@ -225,12 +225,20 @@ Linux/macOS). Two rules for the entry: 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 -renders a **CommandCode panel in the session sidebar** (`zdr` / `debug`, 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 +renders a **CommandCode panel in the session sidebar** (`zdr` / `debug`, session token totals, a +`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 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. +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 `/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 (`COMMANDCODE_QUOTA_INTERVAL_MS` overrides the fallback interval — see [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 (`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) | | 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 | -| 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` | ### `tool_choice` handling diff --git a/src/tui.tsx b/src/tui.tsx index efcfdf3..89c671f 100644 --- a/src/tui.tsx +++ b/src/tui.tsx @@ -51,22 +51,40 @@ type TuiProvider = { id?: string; key?: string; options?: Record }; +type TuiSessionTokens = { + input?: number; + output?: number; + reasoning?: number; + cache?: { read?: number; write?: number }; +}; + type TuiMessageInfo = { role?: string; providerID?: string; modelID?: string; - tokens?: { - input?: number; - output?: number; - reasoning?: number; - cache?: { read?: number; write?: number }; + tokens?: TuiSessionTokens; +}; + +type TuiSessionInfo = { + id: string; + parentID?: string; + tokens?: TuiSessionTokens; +}; + +type TuiClient = { + session: { + children(input: { sessionID: string }): Promise<{ data?: ReadonlyArray }>; + messages(input: { sessionID: string; limit?: number }): Promise<{ data?: ReadonlyArray<{ info?: TuiMessageInfo }> }>; }; }; type TuiState = { config?: { provider?: Record }; provider?: ReadonlyArray; - session?: { messages(sessionID: string): ReadonlyArray }; + session?: { + messages(sessionID: string): ReadonlyArray; + get?(sessionID: string): TuiSessionInfo | undefined; + }; }; type TuiApi = { @@ -76,6 +94,7 @@ type TuiApi = { event: { on(type: string, handler: (event?: { type?: string }) => void): () => void }; theme: TuiTheme; state: TuiState; + client?: TuiClient; lifecycle: { onDispose(fn: () => void): () => void }; }; @@ -84,6 +103,12 @@ const CATEGORY = "CommandCode"; const SIDEBAR_ORDER = 90; const DEFAULT_QUOTA_INTERVAL_MS = 300_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 // 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). @@ -180,6 +205,22 @@ function resolveBaseURL(api: TuiApi): string | 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 * 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 { return undefined; } - let input = 0; - let output = 0; - let read = 0; - let seen = 0; + const totals: TokenTotals = { input: 0, output: 0, read: 0, seen: 0 }; for (const message of messages) { - if (message?.role !== "assistant" || !message.tokens) continue; - const tokens = 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 (message?.role !== "assistant") continue; + addMessageTokens(totals, message.tokens); } - if (seen === 0) return undefined; - return { input, output, hit: input > 0 ? (read / input) * 100 : undefined }; + 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 { + 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 { + 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([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; + 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 { @@ -218,6 +318,12 @@ function formatCache(summary: CacheSummary | undefined): string { 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 { const raw = Number(safeEnv("COMMANDCODE_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 => { const [now, setNow] = createSignal(Date.now()); const [updatedAt, setUpdatedAt] = createSignal(0); const [sessionId, setSessionId] = createSignal(undefined); + const [family, setFamily] = createSignal(undefined); let inflight = false; let pending = false; let lastRefreshAt = 0; let debounceTimer: ReturnType | undefined; let lastSessionId: string | undefined; + let familyRequestId = 0; + let familyTimer: ReturnType | undefined; const refresh = (): void => setToggles(readToggles()); @@ -310,6 +419,31 @@ export const tui = async (api: TuiApi): Promise => { }, 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 => { + 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 next = toggle(name); setToggles(next); @@ -347,6 +481,7 @@ export const tui = async (api: TuiApi): Promise => { zdr:{state(toggles().zdr)} debug:{state(toggles().debug)} {formatCache(sessionCacheSummary(api, sessionId()))} + {formatFamily(family())} {windowsOf(quota()).map((w) => ( {shortWindow(w, now())} ))} @@ -368,6 +503,7 @@ export const tui = async (api: TuiApi): Promise => { if (id !== undefined && id !== lastSessionId) { lastSessionId = id; scheduleQuotaRefresh("session-change"); + scheduleFamilyRefresh(id); } if (id !== undefined) setSessionId(id); return ; @@ -448,13 +584,20 @@ export const tui = async (api: TuiApi): Promise => { void refreshQuota(); const toggleTimer = setInterval(refresh, 1500); 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) => - api.event.on(type, (event) => scheduleQuotaRefresh(event?.type ?? type)), + api.event.on(type, (event) => { + scheduleQuotaRefresh(event?.type ?? type); + scheduleFamilyRefresh(sessionId()); + }), ); api.lifecycle.onDispose(() => { for (const unsub of unsubs) unsub(); if (debounceTimer !== undefined) clearTimeout(debounceTimer); + if (familyTimer !== undefined) clearTimeout(familyTimer); clearInterval(toggleTimer); clearInterval(clockTimer); clearInterval(quotaTimer);