import { KimiWireReader, kimiCountedTokens, type KimiWireReason, type KimiWireRow } from "../adapters/kimi-wire-usage.ts"; import type { TaskAttribution } from "./attribution.ts"; import { TokenWindow } from "./token-window.ts"; /** * The hub's own count of Kimi's consumption (#285 phase 2): the wire-log rows of the session the adapter owns become `usage` and * `tokens` events and a rolling 5 h window against `budget.kimi_tokens_5h`. Read at a turn end, when a `usage_update` arrives and for * a bounded backoff after each cue. Each scheduled slice returns to the event loop before the next one. The ports keep the event log, * the budget, the clock and delayed scheduling in the daemon. */ export const KIMI_WINDOW_MS = 5 * 3_600_000; /** A turn's rows are written after it starts: a row older than the hub's first sight of the session (less this slack) is history. */ const FLOOR_SLACK_MS = 1000; const PASSES = 16; const FOLLOW_UP_DELAYS_MS = [250, 1000, 2000] as const; const TURN_INTERVAL_LIMIT = 32; /** Failures a retry can cure: the log was not there yet, or was cut mid-write. Anything else says the count no longer matches the log. */ const TRANSIENT: ReadonlySet = new Set(["no-index", "io-error", "partial-line"]); export type KimiUsageScheduler = (delayMs: number, run: () => void) => () => void; export interface KimiTurnStart { id: string; startedAt: number; attribution: TaskAttribution } export interface KimiRowAttribution { attribution: TaskAttribution; turn?: string } interface KimiTurnInterval extends KimiTurnStart { endedAt?: number } export interface KimiUsagePorts { /** Kimi's data home. */ home: string; /** Per-call byte bound of the reader (its default otherwise); a test shrinks it to force several passes. */ maxBytes?: number; /** Numeric I/O observations for deterministic benchmarks; no path, row or native text. */ observe?(stats: { bytes: number; discovery: number }): void; now(): number; /** `budget.kimi_tokens_5h`, read live: 0 turns the window off, never the events. */ ceiling(): number; /** The adapter's own session id, undefined when none is bound. */ session(peer: string): string | undefined; /** One delayed drain at a time. Its cancellation leaves no live timer. Production uses an unreferenced timer. */ schedule?: KimiUsageScheduler; /** One usage event and its counted tokens (`counted` is the one rule in `kimiCountedTokens`), with its captured turn attribution. */ record(peer: string, row: KimiWireRow, counted: number, attributed: KimiRowAttribution): void; /** The window as a reading: `used` is not clamped here. */ report(peer: string, window: { used: number; resetsAt: number; ceiling: number }): void; /** The count cannot be trusted now: the peer's `tokens` reading is dropped, so it shows unknown rather than a short number. */ forget(peer: string): void; /** One line per peer and reason; carries no path, id or text from the log. */ notice(line: string): void; } interface Bound { session: string; reader: KimiWireReader; floor: number; turns: KimiTurnInterval[]; followUp: number; passes: number; backlog: boolean; burst: boolean; reportPending: boolean; pending?: () => void; unknown?: KimiWireReason; noticed?: KimiWireReason; } export class KimiUsage { private readonly bound = new Map(); private readonly window = new TokenWindow(KIMI_WINDOW_MS); private readonly seen = new Set(); /** A log that stopped matching the count leaves the window short of the truth until its rows age out. */ private reviewerReplayUnknown = false; private readonly reviewerAttempts = new Set(); private readonly taintedUntil = new Map(); private readonly reviewerSources = new Set(); private stopped = false; constructor(private readonly ports: KimiUsagePorts) {} /** Rows an earlier hub run already recorded: never counted twice, and still inside the window. */ seed(rows: { id: string; at: number; counted: number }[]): void { for (const row of rows) { this.seen.add(row.id); if (row.counted > 0 && this.ports.now() - row.at <= KIMI_WINDOW_MS) this.window.add(row.at, row.counted); } } /** * What the count can say now, for `ahub doctor`, the notes under `ahub budget` and the dashboard. Carries a reason code at most (never a path, id or text from the log). * `off`: no ceiling, so no window. `unreadable`: a log read unknown or was tainted. `counting`: a clean log is bound. `waiting`: no Kimi session is bound yet. */ status(): { state: "off" | "waiting" | "counting" } | { state: "unreadable"; reason: string } { if (!this.ports.ceiling()) return { state: "off" }; for (const state of this.bound.values()) if (state.unknown) return { state: "unreadable", reason: state.unknown }; const now = this.ports.now(); if (this.reviewerReplayUnknown || this.reviewerAttempts.size) return { state: "unreadable", reason: "log changed since it was counted" }; for (const until of this.taintedUntil.values()) if (now < until) return { state: "unreadable", reason: "log changed since it was counted" }; return { state: this.bound.size || this.reviewerSources.size ? "counting" : "waiting" }; } /** The peer went offline: its log is no longer read, so an unreadable state of it must not hold the other peers' figure unknown. */ drop(peer: string): void { const held = this.bound.get(peer); if (held) this.cancel(held); this.bound.delete(peer); } /** Stop only delayed work. A final synchronous offline read can still use the bound readers. */ stop(): void { this.stopped = true; for (const state of this.bound.values()) this.cancel(state); } /** A new window: the old counts would pause the peer again at once (after a budget resume). */ reset(): void { this.window.reset(); this.taintedUntil.clear(); } /** Called when a turn starts. It binds the session, fixes the history floor and captures this turn's immutable attribution. */ turnStarted(peer: string, turn?: KimiTurnStart): void { const bound = this.bind(peer); if (!bound || !turn || bound.turns.some(interval => interval.id === turn.id)) return; bound.turns.push({ ...turn, attribution: { ...turn.attribution } }); if (bound.turns.length > TURN_INTERVAL_LIMIT) bound.turns.splice(0, bound.turns.length - TURN_INTERVAL_LIMIT); } turnEnded(peer: string, turn: string, endedAt: number): void { const bound = this.bound.get(peer); const index = bound?.turns.findIndex(interval => interval.id === turn) ?? -1; if (!bound || index < 0) return; bound.turns[index] = { ...bound.turns[index]!, endedAt }; } private cancel(bound: Bound): void { bound.pending?.(); bound.pending = undefined; bound.burst = false; bound.followUp = 0; } private bind(peer: string): Bound | undefined { const session = this.ports.session(peer), held = this.bound.get(peer); if (!session) { if (held) this.cancel(held); this.bound.delete(peer); return undefined; } if (held?.session === session) return held; if (held) this.cancel(held); const next: Bound = { session, reader: new KimiWireReader({ home: this.ports.home, sessionId: session, ...(this.ports.maxBytes ? { maxBytes: this.ports.maxBytes } : {}) }), floor: this.ports.now() - FLOOR_SLACK_MS, turns: [], followUp: 0, passes: 0, backlog: false, burst: false, reportPending: false, }; this.bound.set(peer, next); return next; } collect(peer: string, scheduled = false, terminal = false): void { const bound = this.bind(peer); if (!bound) return; try { if (bound.passes >= PASSES) bound.passes = 0; let added = 0, more = false; // Without a scheduler or for the terminal offline read, retain the bounded synchronous drain. Other scheduled work uses one slice per invocation. for (let pass = 0, slices = terminal || !this.ports.schedule ? PASSES : 1; pass < slices; pass++) { const read = bound.reader.readSlice(); // A successful slice records and commits every row before a later slice can fail. An event failure leaves the slice uncommitted, // so the next drain reads it again and the seen set removes only rows whose events already succeeded. if (read.status === "unknown") { bound.backlog = false; bound.passes = 0; this.unknown(peer, bound, read.reason); return; } this.ports.observe?.(bound.reader.stats()); try { added += this.record(peer, bound, read.rows); } catch (error) { bound.backlog = false; bound.passes = 0; throw error; } read.commit(); more = read.more; bound.backlog = more; bound.passes = more ? bound.passes + 1 : 0; if (!more) break; } const recovered = bound.unknown !== undefined; bound.unknown = undefined; // ponytail: PASSES slices per cue burst. A longer backlog continues in the next burst, and no figure is reported until it is // caught up: a window that is still catching up would be short. Upgrade: seek to the end at bind. if (!more && (added > 0 || recovered || bound.reportPending)) { this.report(peer); bound.reportPending = false; } } finally { if (this.bound.get(peer) === bound) this.schedule(peer, bound, scheduled); } } /** Terminal private-home callers must prove the entire bounded drain completed before forwarding its rows. */ complete(peer: string): boolean { const bound = this.bound.get(peer); return !!bound && !bound.unknown && !bound.backlog; } /** One shared account counter/event attribution, including fresh reviewer profiles read before deletion. */ observeReviewer(peer: string, row: KimiWireRow, attributed: KimiRowAttribution): boolean { const counters = [row.inputOther, row.inputCacheCreation, row.inputCacheRead, row.output]; if (!/^[a-f0-9]{32}$/.test(row.id) || !Number.isFinite(row.at) || row.at <= 0 || counters.some(value => !Number.isSafeInteger(value) || value < 0) || !Number.isSafeInteger(counters.reduce((sum, value) => sum + value, 0))) throw new Error("invalid reviewer usage observation"); if (this.seen.has(row.id)) return false; const counted = kimiCountedTokens(row); this.ports.record(peer, row, counted, attributed); this.seen.add(row.id); this.reviewerSources.add(peer); this.window.add(Math.min(row.at, this.ports.now()), counted); this.report(peer); return true; } reviewerReplayIncomplete(peer: string): void { this.reviewerReplayUnknown = true; this.ports.forget(peer); } /** Unresolved owned attempts have no proven window end. Neither restart nor a host cap clears them. */ reviewerAccounting(peer: string, attempt: string, outcome: "started" | "complete" | "unknown"): void { if (!/^[a-f0-9]{32}$/.test(attempt)) throw new Error("invalid reviewer accounting identity"); if (outcome === "complete") this.reviewerAttempts.delete(attempt); else this.reviewerAttempts.add(attempt); if (this.reviewerReplayUnknown || this.reviewerAttempts.size) this.ports.forget(peer); else this.report(peer); } private schedule(peer: string, bound: Bound, scheduled: boolean): void { const schedule = this.ports.schedule; if (!schedule || this.stopped) return; const run = () => { bound.pending = undefined; if (this.bound.get(peer) === bound) try { this.collect(peer, true); } catch { /* scheduled retries stay bounded */ } }; if (bound.backlog && bound.passes < PASSES) { if (!bound.pending) bound.pending = schedule(0, run); return; } if (bound.pending) { // A fresh cue during the last pending follow-up still gets a complete bounded retry sequence, without adding another timer. if (!scheduled && bound.followUp >= FOLLOW_UP_DELAYS_MS.length - 1) { bound.burst = true; bound.followUp = 0; } return; } if (!bound.burst) { bound.burst = true; bound.followUp = 0; } if (bound.followUp >= FOLLOW_UP_DELAYS_MS.length) { bound.burst = false; bound.followUp = 0; return; } const delay = FOLLOW_UP_DELAYS_MS[bound.followUp++]!; bound.pending = schedule(delay, run); } private record(peer: string, bound: Bound, rows: KimiWireRow[]): number { let added = 0; const now = this.ports.now(); for (const row of rows) { if (this.seen.has(row.id) || row.at < bound.floor) continue; const counted = kimiCountedTokens(row), attributed = this.attribute(bound, row.at); this.ports.record(peer, row, counted, attributed); this.seen.add(row.id); this.window.add(Math.min(row.at, now), counted); if (counted > 0) bound.reportPending = true; added += counted; } return added; } private attribute(bound: Bound, at: number): KimiRowAttribution { const matches = bound.turns.filter(interval => at >= interval.startedAt && (interval.endedAt === undefined || at <= interval.endedAt)); if (matches.length !== 1) return { attribution: { attribution: "unattributed" } }; const turn = matches[0]!; return { attribution: { ...turn.attribution }, turn: turn.id }; } private unknown(peer: string, bound: Bound, reason: KimiWireReason): void { bound.unknown = reason; try { this.ports.forget(peer); } catch { /* the reading ages out on its own */ } if (!TRANSIENT.has(reason)) this.taintedUntil.set(peer, this.ports.now() + KIMI_WINDOW_MS); if (bound.noticed === reason) return; bound.noticed = reason; try { this.ports.notice(`kimi usage unknown (${reason}): the hub counts no Kimi tokens it cannot read cleanly`); } catch { /* a notice never costs a turn */ } } /** The window as a reading, only while every Kimi peer's log reads cleanly: otherwise the figure is unknown, never a short count. */ private report(peer: string): void { const ceiling = this.ports.ceiling(), now = this.ports.now(); if (!ceiling || this.reviewerReplayUnknown || this.reviewerAttempts.size) return; for (const state of this.bound.values()) if (state.unknown) return; for (const until of this.taintedUntil.values()) if (now < until) return; const oldest = this.window.oldest(now); this.ports.report(peer, { used: this.window.sum(now) / ceiling, resetsAt: (oldest ?? now) + KIMI_WINDOW_MS, ceiling }); } } /** * The rows an earlier run recorded, from its `usage` events: their ids are never counted again, and the recent ones refill the window. * Only rows recorded after the last `resumedAt` (the newest `budget_resume` of a soft-token peer) refill it: a resume starts a new window * (`reset`), and that is not persisted anywhere else, so a restart would otherwise bring the pre-resume rows back and pause the peer again. */ export function kimiSeedRows(events: readonly { type: string; source?: unknown; id?: unknown; measuredAt?: unknown; at?: unknown; inputTokens?: unknown; cacheWriteTokens?: unknown; outputTokens?: unknown }[], resumedAt = 0): { id: string; at: number; counted: number }[] { const n = (value: unknown): number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0; return events.flatMap(e => { if (e.type !== "usage" || e.source !== "kimi_wire" || typeof e.id !== "string") return []; const measured = Date.parse(typeof e.measuredAt === "string" ? e.measuredAt : typeof e.at === "string" ? e.at : ""); const recorded = Date.parse(typeof e.at === "string" ? e.at : ""); if (!Number.isFinite(measured)) return []; // A row before the resume keeps its id (never recounted) and counts for nothing: `counted: 0` leaves the window alone. const counted = Number.isFinite(recorded) && recorded <= resumedAt ? 0 : kimiCountedTokens({ inputOther: n(e.inputTokens), inputCacheCreation: n(e.cacheWriteTokens), output: n(e.outputTokens) }); return [{ id: e.id, at: measured, counted }]; }); }