UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

328 lines • 16.4 kB
import { createHash } from "node:crypto"; import { isAbsolute, relative, resolve, sep } from "node:path"; import { slotsOfOwnKind } from "@earendil-works/pi-ai/auth/pool/kinds"; import { applyAccountOrder, rendezvousOrder } from "@earendil-works/pi-ai/auth/pool/select"; import { accountLabel } from "@earendil-works/pi-ai/auth/pool/slots"; import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui"; import { ANTHROPIC_SUBSCRIPTION_PROVIDER_ID } from "../../../core/extensions/builtin/anthropic-subscription/provider-id.js"; import { theme } from "../theme/theme.js"; import { planFooterLayout } from "./footer-layout.js"; import { buildRightLabel, colorRightSide } from "./footer-right-label.js"; const FAST_MODE_INDICATOR = "\u26a1 "; /** * Sanitize text for display in a single-line status. * Removes newlines, tabs, carriage returns, and other control characters. */ function sanitizeStatusText(text) { // Replace newlines, tabs, carriage returns with space, then collapse multiple spaces return text .replace(/[\r\n\t]/g, " ") .replace(/ +/g, " ") .trim(); } /** * Format token counts for footer display using oh-my-pi-style K/M/B abbreviation. * Examples: "999", "6.8K", "546K", "1M", "1.5M", "2B". */ export function formatTokens(count) { const n = Math.round(count); if (n < 1_000) return n.toString(); if (n < 10_000) return `${trim1(n / 1_000)}K`; if (n < 1_000_000) return `${Math.round(n / 1_000)}K`; if (n < 10_000_000) return `${trim1(n / 1_000_000)}M`; if (n < 1_000_000_000) return `${Math.round(n / 1_000_000)}M`; if (n < 10_000_000_000) return `${trim1(n / 1_000_000_000)}B`; return `${Math.round(n / 1_000_000_000)}B`; } function formatBlockedUntil(until) { const date = new Date(until); return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`; } export function accountFooterSuffix(credential, sessionId, options = {}) { const pooled = credential; // Only slots the credential can serve with; a mixed pool's other-kind slot never does (senpi#3486). const slots = credential ? slotsOfOwnKind(credential) : []; if (slots.length < 2) return ""; const now = options.now ?? Date.now(); // Block state rides on the stored slots at runtime (SlotBlockState) but // is not part of the CredentialSlot type, so read it through unknown. const blockedUntilOf = (slot) => slot.blockedUntil; const isBlocked = (slot) => { const until = blockedUntilOf(slot); return until !== undefined && until > now; }; const ranked = applyAccountOrder(pooled?.order, rendezvousOrder(sessionId, slots, (input) => createHash("sha256").update(input).digest().readBigUInt64BE(0))); const storedPinned = Object.entries(credential ?? {}).find(([key]) => key === "pinned")?.[1]; const pinnedName = options.pinnedAccount ?? storedPinned; const pinnedSlot = pinnedName === undefined ? undefined : slots.find((slot) => slot.name === pinnedName); if (pinnedSlot) { if (!isBlocked(pinnedSlot)) return `@${footerAccountLabel(pinnedSlot)}`; const until = blockedUntilOf(pinnedSlot); const serving = ranked.find((slot) => slot !== pinnedSlot && !isBlocked(slot)); if (serving) return `@${footerAccountLabel(serving)} (${footerAccountLabel(pinnedSlot)} blocked until ${formatBlockedUntil(until)})`; return `@${footerAccountLabel(pinnedSlot)} (blocked until ${formatBlockedUntil(until)})`; } const winner = ranked.find((slot) => !isBlocked(slot)) ?? ranked[0]; if (winner === undefined) return ""; if (isBlocked(winner)) return `@${footerAccountLabel(winner)} (blocked until ${formatBlockedUntil(blockedUntilOf(winner))})`; return `@${footerAccountLabel(winner)}`; } /** * Widest account label the provider segment carries. A label wider than this * is truncated with an ellipsis here rather than pushing the whole provider * segment past the layout budget, which would drop the account indicator. */ const ACCOUNT_FOOTER_MAX_COLUMNS = 24; function footerAccountLabel(slot) { return truncateToWidth(accountLabel(slot), ACCOUNT_FOOTER_MAX_COLUMNS, "…"); } /** Format with up to 1 decimal place, dropping trailing `.0`. */ function trim1(n) { const s = n.toFixed(1); return s.endsWith(".0") ? s.slice(0, -2) : s; } export function formatCwdForFooter(cwd, home) { if (!home) return cwd; const resolvedCwd = resolve(cwd); const resolvedHome = resolve(home); const relativeToHome = relative(resolvedHome, resolvedCwd); const isInsideHome = relativeToHome === "" || (relativeToHome !== ".." && !relativeToHome.startsWith(`..${sep}`) && !isAbsolute(relativeToHome)); if (!isInsideHome) return cwd; return relativeToHome === "" ? "~" : `~${sep}${relativeToHome}`; } /** * Footer component that shows pwd, token stats, and context usage. * Computes token/context stats from session, gets git branch and extension statuses from provider. */ export class FooterComponent { constructor(session, footerData, options = {}) { this.autoCompactEnabled = true; this.compactionDelegated = false; this.session = session; this.footerData = footerData; this.resolveAccountPin = options.resolveAccountPin; } setSession(session) { this.session = session; } setAutoCompactEnabled(enabled) { this.autoCompactEnabled = enabled; } /** * Marks the context meter while an external owner (the Claude Agent SDK) * manages compaction natively, so a saturated meter reads as delegated * rather than stalled. */ setCompactionDelegated(delegated) { this.compactionDelegated = delegated; } /** * No-op: git branch caching now handled by provider. * Kept for compatibility with existing call sites in interactive-mode. */ invalidate() { // No-op: git branch is cached/invalidated by provider } /** * Clean up resources. * Git watcher cleanup now handled by provider. */ dispose() { // Git watcher cleanup handled by provider } render(width) { const state = this.session.state; // O(1) running totals maintained by SessionManager (identical to summing // usage over all entries; totals are not branch-scoped). const usageTotals = this.session.sessionManager.getUsageTotals(); const totalCacheRead = usageTotals.cacheRead; const totalCacheWrite = usageTotals.cacheWrite; const totalCost = usageTotals.cost; const latestCacheHitRate = usageTotals.latestCacheHitRate; // Calculate context usage from session (handles compaction correctly). // After compaction, tokens are unknown until the next LLM response. const contextUsage = this.session.getContextUsage(); const contextWindow = contextUsage?.contextWindow ?? state.model?.contextWindow ?? 0; const contextPercentValue = contextUsage?.percent ?? 0; const contextPercent = contextUsage?.percent !== null ? contextPercentValue.toFixed(1) : "?"; const contextTokens = typeof contextUsage?.tokens === "number" ? formatTokens(contextUsage.tokens) : typeof contextUsage?.percent === "number" ? formatTokens(Math.round((contextWindow * contextUsage.percent) / 100)) : "?"; // Segments in priority order: anchors (pwd, branch, context) and the model // label always stay; middle stats elide from the right when space runs out. // The width ladder itself lives in ./footer-layout.ts. const separator = " • "; const sepColored = theme.fg("borderMuted", separator); const pwdRaw = formatCwdForFooter(this.session.sessionManager.getCwd(), process.env.HOME || process.env.USERPROFILE); const branch = this.footerData.getGitBranch(); const sessionName = this.session.sessionManager.getSessionName(); const anchor = [{ plain: pwdRaw, colored: theme.fg("accent", pwdRaw) }]; if (branch) anchor.push({ plain: branch, colored: theme.fg("warning", branch) }); const pwdIndex = 0; const dim = (plain) => ({ plain, colored: theme.fg("dim", plain) }); const middle = []; if (sessionName) middle.push({ plain: sessionName, colored: theme.fg("muted", sessionName) }); if ((totalCacheRead > 0 || totalCacheWrite > 0) && latestCacheHitRate !== undefined && latestCacheHitRate >= 10) { middle.push(dim(`CH${latestCacheHitRate.toFixed(1)}%`)); } // Kimi Coding is subscription-backed despite using API-key authentication. const usingSubscription = state.model ? state.model.provider === "kimi-coding" || this.session.modelRuntime.isUsingSubscription(state.model.provider) : false; // The subagent tree's spend (reported by the extension that runs it) follows the session's own, // oh-my-pi style: `$0.380 (+1.270)`, so a session that fans out does not look cheaper than it is. const subagentCost = this.footerData.getSubagentCost?.() ?? 0; if (totalCost || usingSubscription || subagentCost > 0) { const subagentStr = subagentCost > 0 ? ` (+${subagentCost.toFixed(3)})` : ""; const costStr = `$${totalCost.toFixed(3)}${usageTotals.costUnknown ? "+?" : ""}${usingSubscription ? " (sub)" : ""}${subagentStr}`; middle.push({ plain: costStr, colored: theme.fg("success", costStr) }); } const autoIndicator = this.autoCompactEnabled ? " (auto)" : ""; const delegationIndicator = this.compactionDelegated ? " (SDK)" : ""; const ctxBase = contextPercent === "?" ? `${contextTokens}/${formatTokens(contextWindow)} (?)${autoIndicator}` : `${contextTokens}/${formatTokens(contextWindow)} (${contextPercent}%)${autoIndicator}`; const colorCtx = (text) => contextPercentValue > 90 ? theme.fg("error", text) : contextPercentValue > 70 ? theme.fg("warning", text) : theme.fg("muted", text); // The delegation marker stays muted even when the saturated meter is // error/warning tinted: SDK-owned compaction is expected state, not alarm. const makeTail = (withMarker) => ({ plain: withMarker ? `${ctxBase}${delegationIndicator}` : ctxBase, colored: withMarker ? `${colorCtx(ctxBase)}${theme.fg("muted", delegationIndicator)}` : colorCtx(ctxBase), }); let tail = makeTail(delegationIndicator !== ""); // Model label pinned to the right edge; the forms ladder and what each form // may cost the left side live in ./footer-right-label.ts. const modelName = state.model?.id || "no-model"; const fastIndicator = this.session.isFastModeActive() ? FAST_MODE_INDICATOR : ""; const routed = this.session.routedModel; const pending = this.session.pendingModelSwitch; let accountSuffix = ""; if (state.model) { try { const sessionId = this.session.sessionManager.getSessionId(); // The resolver carries the Anthropic CLI/settings pin; resolve // it only when the current model uses the Anthropic // subscription provider. A same-named slot of another pooled // provider (e.g. openai-codex "default") keeps its own stored // pin instead (senpi#6222 review). const pinnedAccount = state.model.provider === ANTHROPIC_SUBSCRIPTION_PROVIDER_ID ? this.resolveAccountPin?.(sessionId) : undefined; accountSuffix = accountFooterSuffix(this.session.modelRegistry.authStorage.get(state.model.provider), sessionId, pinnedAccount === undefined ? undefined : { pinnedAccount }); } catch { // The footer must render even when credential storage is unreadable. } } const providerPrefix = (this.footerData.getAvailableProviderCount() > 1 || accountSuffix !== "") && state.model ? `(${state.model.provider}${accountSuffix}) ` : ""; const rightLabel = buildRightLabel({ modelName, fastIndicator, routed: routed ? { modelId: routed.model.id, thinkingLevel: routed.thinkingLevel } : undefined, pending: pending ? { modelId: pending.model.id } : undefined, reasoning: state.model?.reasoning === true, thinkingLevel: state.thinkingLevel || "off", providerPrefix, separator, }); const { forms, floor: floorRight, floorRuns } = rightLabel; const marker = { plain: "…", colored: theme.fg("dim", "…") }; const planWithTail = (tailSegment) => planFooterLayout({ width, anchor, pwdIndex, middle, tail: tailSegment, right: { forms }, separator, minPadding: 2, ellipsisMarker: marker, }); let plan = planWithTail(tail); // Head elision keeps the string tail, so at narrow widths it can leave a // chopped marker fragment like "…SDK)". Render the complete marker or drop // it entirely — never a fragment. if (delegationIndicator !== "" && plan.kind === "left-elided" && !plan.leftPlain.includes(delegationIndicator.trimStart())) { tail = makeTail(false); plan = planWithTail(tail); } const joinSegments = (segments) => ({ colored: segments.map((segment) => segment.colored).join(sepColored), width: visibleWidth(segments.map((segment) => segment.plain).join(separator)), }); let left; let right; if (plan.kind === "full") { right = forms[plan.rightForm] ?? floorRight; left = joinSegments([...anchor, ...middle, tail]); } else if (plan.kind === "middle-elided") { right = forms[plan.rightForm] ?? floorRight; const segments = [...anchor, ...middle.slice(0, plan.keptMiddleCount)]; if (plan.showMarker) segments.push(marker); segments.push(tail); left = joinSegments(segments); } else if (plan.kind === "pwd-elided") { right = forms[plan.rightForm] ?? floorRight; const segments = [ ...anchor.map((segment, index) => index === pwdIndex ? { plain: plan.pwdPlain, colored: theme.fg("accent", plan.pwdPlain) } : segment), ...middle.slice(0, plan.keptMiddleCount), ]; if (plan.showMarker) segments.push(marker); segments.push(tail); left = joinSegments(segments); } else if (plan.kind === "left-elided") { right = floorRight; left = { colored: theme.fg("muted", plan.leftPlain), width: visibleWidth(plan.leftPlain) }; } else { left = { colored: "", width: 0 }; right = { plain: plan.rightPlain, colored: colorRightSide(floorRuns, plan.rightPlain) }; } const rightWidth = visibleWidth(right.plain); const padding = " ".repeat(Math.max(0, width - left.width - rightWidth)); const lines = [left.colored + padding + right.colored]; // Add extension statuses on a single line, sorted by key alphabetically const extensionStatuses = this.footerData.getExtensionStatuses(); if (extensionStatuses.size > 0) { const sortedStatuses = Array.from(extensionStatuses.entries()) .sort(([a], [b]) => a.localeCompare(b)) .map(([, text]) => sanitizeStatusText(text)); const statusLine = sortedStatuses.join(" "); // Truncate to terminal width with dim ellipsis for consistency with footer style lines.push(truncateToWidth(statusLine, width, theme.fg("dim", "..."))); } return lines; } } //# sourceMappingURL=footer.js.map