feat: usage tracking plugin and tunnel command improvements
Usage plugin (F18): - Create src/plugins/usage/ with UsageStore, UsageBudget - Listen to usage:recorded events, buffer with debounced flush - Budget checking with warning/exceeded notifications (dedup) - /usage command showing monthly spending summary - 26 tests for store and budget logic - Registered in core-plugins Tunnel commands (F24): - /tunnel <port> [label] creates user tunnels - /tunnel stop <port> stops user tunnels - /tunnels lists all active tunnels with details Resume (F7): - Added TODO for over-budget interactive selection
This commit is contained in:
parent
18c590d719
commit
0bc34ca93e
@ -8,6 +8,7 @@ import fileServicePlugin from './file-service/index.js'
|
||||
import contextPlugin from './context/index.js'
|
||||
import speechPlugin from './speech/index.js'
|
||||
import notificationsPlugin from './notifications/index.js'
|
||||
import usagePlugin from './usage/index.js'
|
||||
import tunnelPlugin from './tunnel/index.js'
|
||||
import apiServerPlugin from './api-server/index.js'
|
||||
import telegramPlugin from './telegram/index.js'
|
||||
@ -19,6 +20,7 @@ export const corePlugins = [
|
||||
contextPlugin,
|
||||
speechPlugin,
|
||||
notificationsPlugin,
|
||||
usagePlugin,
|
||||
// Infrastructure plugins
|
||||
tunnelPlugin,
|
||||
apiServerPlugin,
|
||||
|
||||
@ -210,6 +210,9 @@ async function executeResume(
|
||||
parse_mode: "HTML",
|
||||
});
|
||||
|
||||
// TODO: Over-budget interactive selection not yet implemented (F7)
|
||||
// Spec says: show options when context > 30K tokens, auto-select after 60s
|
||||
|
||||
const { session, contextResult } = await core.createSessionWithContext({
|
||||
channelId: "telegram",
|
||||
agentName,
|
||||
|
||||
@ -142,11 +142,39 @@ function createTunnelPlugin(): OpenACPPlugin {
|
||||
|
||||
ctx.registerCommand({
|
||||
name: 'tunnel',
|
||||
description: 'Show tunnel status and URL',
|
||||
description: 'Manage tunnels: /tunnel <port> [label] | /tunnel stop <port>',
|
||||
category: 'plugin',
|
||||
handler: async () => {
|
||||
handler: async (args) => {
|
||||
const parts = args.raw.trim().split(/\s+/)
|
||||
|
||||
// /tunnel stop <port>
|
||||
if (parts[0] === 'stop' && parts[1]) {
|
||||
const port = parseInt(parts[1], 10)
|
||||
if (isNaN(port)) return { type: 'error', message: 'Invalid port number' }
|
||||
try {
|
||||
await tunnelSvc.stopTunnel(port)
|
||||
return { type: 'text', text: `Tunnel on port ${port} stopped.` }
|
||||
} catch (err) {
|
||||
return { type: 'error', message: (err as Error).message }
|
||||
}
|
||||
}
|
||||
|
||||
// /tunnel <port> [label]
|
||||
if (parts[0] && parts[0] !== '') {
|
||||
const port = parseInt(parts[0], 10)
|
||||
if (isNaN(port)) return { type: 'error', message: 'Invalid port number' }
|
||||
const label = parts.slice(1).join(' ') || undefined
|
||||
try {
|
||||
const entry = await tunnelSvc.addTunnel(port, { label })
|
||||
return { type: 'text', text: `Tunnel created: ${entry.publicUrl ?? 'starting...'}` }
|
||||
} catch (err) {
|
||||
return { type: 'error', message: (err as Error).message }
|
||||
}
|
||||
}
|
||||
|
||||
// /tunnel (no args) — show current tunnel URL
|
||||
const url = tunnelSvc.getPublicUrl()
|
||||
return { type: 'text', text: `Tunnel active: ${url}` }
|
||||
return { type: 'text', text: url ? `Tunnel: ${url}` : 'No tunnel active.' }
|
||||
},
|
||||
})
|
||||
|
||||
@ -155,10 +183,16 @@ function createTunnelPlugin(): OpenACPPlugin {
|
||||
description: 'List active tunnels',
|
||||
category: 'plugin',
|
||||
handler: async () => {
|
||||
const url = tunnelSvc.getPublicUrl()
|
||||
return { type: 'list', title: 'Active Tunnels', items: [
|
||||
{ label: 'Primary', detail: url },
|
||||
]}
|
||||
const userTunnels = tunnelSvc.listTunnels()
|
||||
const systemUrl = tunnelSvc.getPublicUrl()
|
||||
const items = [
|
||||
{ label: 'System', detail: systemUrl },
|
||||
...userTunnels.map(t => ({
|
||||
label: t.label ?? `Port ${t.port}`,
|
||||
detail: `${t.publicUrl ?? t.status} (${t.provider})`,
|
||||
})),
|
||||
]
|
||||
return { type: 'list', title: 'Active Tunnels', items }
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
208
src/plugins/usage/__tests__/usage-budget.test.ts
Normal file
208
src/plugins/usage/__tests__/usage-budget.test.ts
Normal file
@ -0,0 +1,208 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { UsageBudget } from '../usage-budget.js'
|
||||
import type { UsagePluginConfig } from '../usage-budget.js'
|
||||
import { UsageStore } from '../usage-store.js'
|
||||
import type { PluginStorage } from '../../../core/plugin/types.js'
|
||||
|
||||
function mockStorage(): PluginStorage {
|
||||
const data = new Map<string, unknown>()
|
||||
return {
|
||||
get: vi.fn(async <T>(key: string) => data.get(key) as T | undefined),
|
||||
set: vi.fn(async <T>(key: string, value: T) => { data.set(key, value) }),
|
||||
delete: vi.fn(async (key: string) => { data.delete(key) }),
|
||||
list: vi.fn(async () => [...data.keys()]),
|
||||
getDataDir: vi.fn(() => '/tmp/usage-test'),
|
||||
}
|
||||
}
|
||||
|
||||
function makeRecord(cost: number) {
|
||||
return {
|
||||
id: `rec-${Math.random()}`,
|
||||
sessionId: 'sess-1',
|
||||
agentName: 'claude',
|
||||
tokensUsed: 1000,
|
||||
contextSize: 5000,
|
||||
cost: { amount: cost, currency: 'USD' },
|
||||
timestamp: new Date().toISOString(),
|
||||
}
|
||||
}
|
||||
|
||||
describe('UsageBudget', () => {
|
||||
let store: UsageStore
|
||||
let storage: PluginStorage
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
storage = mockStorage()
|
||||
store = new UsageStore(storage)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
store.destroy()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('check', () => {
|
||||
it('returns ok when no budget is set', async () => {
|
||||
const budget = new UsageBudget(store, { monthlyBudget: 0 })
|
||||
const result = budget.check()
|
||||
expect(result.status).toBe('ok')
|
||||
expect(result.message).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns ok when spending is below threshold', async () => {
|
||||
await store.append(makeRecord(5.00))
|
||||
const budget = new UsageBudget(store, { monthlyBudget: 100, warningThreshold: 0.8 })
|
||||
|
||||
const result = budget.check()
|
||||
expect(result.status).toBe('ok')
|
||||
expect(result.message).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns warning when threshold is crossed', async () => {
|
||||
await store.append(makeRecord(85.00))
|
||||
const budget = new UsageBudget(store, { monthlyBudget: 100, warningThreshold: 0.8 })
|
||||
|
||||
const result = budget.check()
|
||||
expect(result.status).toBe('warning')
|
||||
expect(result.message).toContain('Budget warning')
|
||||
expect(result.message).toContain('$85.00')
|
||||
expect(result.message).toContain('$100.00')
|
||||
expect(result.message).toContain('85%')
|
||||
})
|
||||
|
||||
it('returns exceeded when budget is exceeded', async () => {
|
||||
await store.append(makeRecord(110.00))
|
||||
const budget = new UsageBudget(store, { monthlyBudget: 100, warningThreshold: 0.8 })
|
||||
|
||||
const result = budget.check()
|
||||
expect(result.status).toBe('exceeded')
|
||||
expect(result.message).toContain('Budget exceeded')
|
||||
expect(result.message).toContain('$110.00')
|
||||
})
|
||||
|
||||
it('deduplicates notifications - only notifies on status change', async () => {
|
||||
const config: UsagePluginConfig = { monthlyBudget: 100, warningThreshold: 0.8 }
|
||||
|
||||
await store.append(makeRecord(85.00))
|
||||
const budget = new UsageBudget(store, config)
|
||||
|
||||
// First check: warning with message
|
||||
const first = budget.check()
|
||||
expect(first.status).toBe('warning')
|
||||
expect(first.message).toBeDefined()
|
||||
|
||||
// Second check at same level: no message
|
||||
const second = budget.check()
|
||||
expect(second.status).toBe('warning')
|
||||
expect(second.message).toBeUndefined()
|
||||
})
|
||||
|
||||
it('escalates from warning to exceeded', async () => {
|
||||
const config: UsagePluginConfig = { monthlyBudget: 100, warningThreshold: 0.8 }
|
||||
|
||||
await store.append(makeRecord(85.00))
|
||||
const budget = new UsageBudget(store, config)
|
||||
|
||||
const warning = budget.check()
|
||||
expect(warning.status).toBe('warning')
|
||||
expect(warning.message).toBeDefined()
|
||||
|
||||
// Add more cost to exceed budget
|
||||
await store.append(makeRecord(20.00))
|
||||
|
||||
const exceeded = budget.check()
|
||||
expect(exceeded.status).toBe('exceeded')
|
||||
expect(exceeded.message).toContain('Budget exceeded')
|
||||
})
|
||||
|
||||
it('resets notification tracking on month boundary', async () => {
|
||||
const config: UsagePluginConfig = { monthlyBudget: 100, warningThreshold: 0.8 }
|
||||
|
||||
await store.append(makeRecord(85.00))
|
||||
const budget = new UsageBudget(store, config)
|
||||
|
||||
// Trigger warning
|
||||
const first = budget.check()
|
||||
expect(first.message).toBeDefined()
|
||||
|
||||
// Simulate month change by advancing time
|
||||
const nextMonth = new Date()
|
||||
nextMonth.setMonth(nextMonth.getMonth() + 1)
|
||||
vi.setSystemTime(nextMonth)
|
||||
|
||||
// Add usage in new month
|
||||
await store.append(makeRecord(85.00))
|
||||
|
||||
// Should get a new warning since month changed
|
||||
const afterReset = budget.check()
|
||||
expect(afterReset.status).toBe('warning')
|
||||
expect(afterReset.message).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getStatus', () => {
|
||||
it('returns status with zero budget', () => {
|
||||
const budget = new UsageBudget(store, { monthlyBudget: 0 })
|
||||
const status = budget.getStatus()
|
||||
expect(status.status).toBe('ok')
|
||||
expect(status.used).toBe(0)
|
||||
expect(status.budget).toBe(0)
|
||||
expect(status.percent).toBe(0)
|
||||
})
|
||||
|
||||
it('returns correct percentage', async () => {
|
||||
await store.append(makeRecord(25.00))
|
||||
const budget = new UsageBudget(store, { monthlyBudget: 100 })
|
||||
|
||||
const status = budget.getStatus()
|
||||
expect(status.status).toBe('ok')
|
||||
expect(status.used).toBeCloseTo(25.00)
|
||||
expect(status.budget).toBe(100)
|
||||
expect(status.percent).toBe(25)
|
||||
})
|
||||
|
||||
it('returns warning status at threshold', async () => {
|
||||
await store.append(makeRecord(80.00))
|
||||
const budget = new UsageBudget(store, { monthlyBudget: 100, warningThreshold: 0.8 })
|
||||
|
||||
const status = budget.getStatus()
|
||||
expect(status.status).toBe('warning')
|
||||
})
|
||||
|
||||
it('returns exceeded status over budget', async () => {
|
||||
await store.append(makeRecord(120.00))
|
||||
const budget = new UsageBudget(store, { monthlyBudget: 100 })
|
||||
|
||||
const status = budget.getStatus()
|
||||
expect(status.status).toBe('exceeded')
|
||||
expect(status.percent).toBe(120)
|
||||
})
|
||||
})
|
||||
|
||||
describe('progressBar', () => {
|
||||
it('renders correct bar at 50%', () => {
|
||||
const budget = new UsageBudget(store, { monthlyBudget: 100 })
|
||||
const bar = budget.progressBar(0.5)
|
||||
expect(bar).toBe('\u2588\u2588\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591')
|
||||
})
|
||||
|
||||
it('renders full bar at 100%', () => {
|
||||
const budget = new UsageBudget(store, { monthlyBudget: 100 })
|
||||
const bar = budget.progressBar(1.0)
|
||||
expect(bar).toBe('\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588')
|
||||
})
|
||||
|
||||
it('caps bar at 10 filled blocks for values over 100%', () => {
|
||||
const budget = new UsageBudget(store, { monthlyBudget: 100 })
|
||||
const bar = budget.progressBar(1.5)
|
||||
expect(bar).toBe('\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588')
|
||||
})
|
||||
|
||||
it('renders empty bar at 0%', () => {
|
||||
const budget = new UsageBudget(store, { monthlyBudget: 100 })
|
||||
const bar = budget.progressBar(0)
|
||||
expect(bar).toBe('\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591')
|
||||
})
|
||||
})
|
||||
})
|
||||
198
src/plugins/usage/__tests__/usage-store.test.ts
Normal file
198
src/plugins/usage/__tests__/usage-store.test.ts
Normal file
@ -0,0 +1,198 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { UsageStore } from '../usage-store.js'
|
||||
import type { PluginStorage } from '../../../core/plugin/types.js'
|
||||
import type { UsageRecord } from '../../../core/types.js'
|
||||
|
||||
function mockStorage(): PluginStorage {
|
||||
const data = new Map<string, unknown>()
|
||||
return {
|
||||
get: vi.fn(async <T>(key: string) => data.get(key) as T | undefined),
|
||||
set: vi.fn(async <T>(key: string, value: T) => { data.set(key, value) }),
|
||||
delete: vi.fn(async (key: string) => { data.delete(key) }),
|
||||
list: vi.fn(async () => [...data.keys()]),
|
||||
getDataDir: vi.fn(() => '/tmp/usage-test'),
|
||||
}
|
||||
}
|
||||
|
||||
function makeRecord(overrides: Partial<UsageRecord> = {}): UsageRecord {
|
||||
return {
|
||||
id: 'rec-1',
|
||||
sessionId: 'sess-1',
|
||||
agentName: 'claude',
|
||||
tokensUsed: 1000,
|
||||
contextSize: 5000,
|
||||
cost: { amount: 0.05, currency: 'USD' },
|
||||
timestamp: new Date().toISOString(),
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('UsageStore', () => {
|
||||
let storage: PluginStorage
|
||||
let store: UsageStore
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
storage = mockStorage()
|
||||
store = new UsageStore(storage)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
store.destroy()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('append', () => {
|
||||
it('adds record to in-memory cache', async () => {
|
||||
const record = makeRecord()
|
||||
await store.append(record)
|
||||
|
||||
const total = store.getMonthlyTotal()
|
||||
expect(total.totalCost).toBe(0.05)
|
||||
expect(total.currency).toBe('USD')
|
||||
})
|
||||
|
||||
it('loads from storage on first append for a new month key', async () => {
|
||||
const existing = makeRecord({ id: 'old-1', cost: { amount: 0.10, currency: 'USD' } })
|
||||
const key = `records:${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}`
|
||||
await storage.set(key, [existing])
|
||||
|
||||
await store.append(makeRecord({ id: 'new-1' }))
|
||||
|
||||
const total = store.getMonthlyTotal()
|
||||
expect(total.totalCost).toBeCloseTo(0.15)
|
||||
})
|
||||
|
||||
it('schedules debounced flush', async () => {
|
||||
await store.append(makeRecord())
|
||||
expect(storage.set).not.toHaveBeenCalledWith(expect.stringContaining('records:'), expect.anything())
|
||||
|
||||
vi.advanceTimersByTime(2000)
|
||||
await vi.waitFor(() => {
|
||||
expect(storage.set).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('getMonthlyTotal', () => {
|
||||
it('returns zero for empty cache', () => {
|
||||
const total = store.getMonthlyTotal()
|
||||
expect(total.totalCost).toBe(0)
|
||||
expect(total.currency).toBe('USD')
|
||||
})
|
||||
|
||||
it('sums costs across multiple records', async () => {
|
||||
await store.append(makeRecord({ id: '1', cost: { amount: 0.10, currency: 'USD' } }))
|
||||
await store.append(makeRecord({ id: '2', cost: { amount: 0.25, currency: 'USD' } }))
|
||||
await store.append(makeRecord({ id: '3', cost: { amount: 0.05, currency: 'USD' } }))
|
||||
|
||||
const total = store.getMonthlyTotal()
|
||||
expect(total.totalCost).toBeCloseTo(0.40)
|
||||
})
|
||||
|
||||
it('handles records without cost', async () => {
|
||||
await store.append(makeRecord({ id: '1', cost: undefined }))
|
||||
await store.append(makeRecord({ id: '2', cost: { amount: 0.10, currency: 'USD' } }))
|
||||
|
||||
const total = store.getMonthlyTotal()
|
||||
expect(total.totalCost).toBeCloseTo(0.10)
|
||||
})
|
||||
|
||||
it('returns totals for specific month', async () => {
|
||||
await store.append(makeRecord({ id: '1', timestamp: '2026-01-15T00:00:00Z', cost: { amount: 0.50, currency: 'USD' } }))
|
||||
await store.append(makeRecord({ id: '2', timestamp: '2026-02-15T00:00:00Z', cost: { amount: 0.30, currency: 'USD' } }))
|
||||
|
||||
const janTotal = store.getMonthlyTotal(new Date('2026-01-15'))
|
||||
expect(janTotal.totalCost).toBeCloseTo(0.50)
|
||||
|
||||
const febTotal = store.getMonthlyTotal(new Date('2026-02-15'))
|
||||
expect(febTotal.totalCost).toBeCloseTo(0.30)
|
||||
})
|
||||
})
|
||||
|
||||
describe('flush', () => {
|
||||
it('writes all dirty keys to storage', async () => {
|
||||
await store.append(makeRecord())
|
||||
await store.flush()
|
||||
|
||||
const key = `records:${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}`
|
||||
expect(storage.set).toHaveBeenCalledWith(key, expect.any(Array))
|
||||
})
|
||||
|
||||
it('clears dirty set after flush', async () => {
|
||||
await store.append(makeRecord());
|
||||
|
||||
// Reset mock to track only flush calls
|
||||
(storage.set as ReturnType<typeof vi.fn>).mockClear()
|
||||
|
||||
await store.flush()
|
||||
expect(storage.set).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Second flush should not write again
|
||||
(storage.set as ReturnType<typeof vi.fn>).mockClear()
|
||||
await store.flush()
|
||||
expect(storage.set).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('cancels pending debounced flush', async () => {
|
||||
await store.append(makeRecord())
|
||||
|
||||
// Manually flush — this should clear the pending debounce timer
|
||||
// and write all dirty keys to storage
|
||||
store.flush()
|
||||
|
||||
// Advance past the debounce period and verify no extra writes occur
|
||||
const setCalls = (storage.set as ReturnType<typeof vi.fn>).mock.calls.length
|
||||
vi.advanceTimersByTime(5000)
|
||||
|
||||
// No additional set calls beyond what flush() already did
|
||||
expect((storage.set as ReturnType<typeof vi.fn>).mock.calls.length).toBe(setCalls)
|
||||
})
|
||||
})
|
||||
|
||||
describe('loadFromStorage', () => {
|
||||
it('loads current month records into cache', async () => {
|
||||
const key = `records:${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}`
|
||||
const existing = [makeRecord({ id: 'stored-1', cost: { amount: 1.00, currency: 'USD' } })]
|
||||
await storage.set(key, existing)
|
||||
|
||||
await store.loadFromStorage()
|
||||
|
||||
const total = store.getMonthlyTotal()
|
||||
expect(total.totalCost).toBeCloseTo(1.00)
|
||||
})
|
||||
|
||||
it('handles empty storage gracefully', async () => {
|
||||
await store.loadFromStorage()
|
||||
|
||||
const total = store.getMonthlyTotal()
|
||||
expect(total.totalCost).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('cleanupExpired', () => {
|
||||
it('deletes records older than retention period', async () => {
|
||||
// Store old records under a key from 6 months ago
|
||||
await storage.set('records:2025-01', [makeRecord()])
|
||||
await storage.set('records:2025-06', [makeRecord()])
|
||||
// Current month should stay
|
||||
const currentKey = `records:${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}`
|
||||
await storage.set(currentKey, [makeRecord()])
|
||||
|
||||
await store.cleanupExpired(90)
|
||||
|
||||
expect(storage.delete).toHaveBeenCalledWith('records:2025-01')
|
||||
expect(storage.delete).toHaveBeenCalledWith('records:2025-06')
|
||||
expect(storage.delete).not.toHaveBeenCalledWith(currentKey)
|
||||
})
|
||||
|
||||
it('does nothing when no expired keys exist', async () => {
|
||||
const currentKey = `records:${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}`
|
||||
await storage.set(currentKey, [makeRecord()])
|
||||
|
||||
await store.cleanupExpired(90)
|
||||
|
||||
expect(storage.delete).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
193
src/plugins/usage/index.ts
Normal file
193
src/plugins/usage/index.ts
Normal file
@ -0,0 +1,193 @@
|
||||
import { nanoid } from 'nanoid'
|
||||
import type { OpenACPPlugin, InstallContext, NotificationService } from '../../core/plugin/types.js'
|
||||
import type { UsageRecordEvent, UsageRecord } from '../../core/types.js'
|
||||
import { UsageStore } from './usage-store.js'
|
||||
import { UsageBudget } from './usage-budget.js'
|
||||
import type { UsagePluginConfig } from './usage-budget.js'
|
||||
|
||||
function createUsagePlugin(): OpenACPPlugin {
|
||||
let store: UsageStore | undefined
|
||||
|
||||
return {
|
||||
name: '@openacp/usage',
|
||||
version: '1.0.0',
|
||||
description: 'Token usage tracking and budget enforcement',
|
||||
essential: false,
|
||||
optionalPluginDependencies: { '@openacp/notifications': '^1.0.0' },
|
||||
permissions: [
|
||||
'events:read',
|
||||
'services:register',
|
||||
'services:use',
|
||||
'commands:register',
|
||||
'storage:read',
|
||||
'storage:write',
|
||||
],
|
||||
|
||||
async setup(ctx) {
|
||||
const config: UsagePluginConfig = {
|
||||
monthlyBudget: (ctx.pluginConfig.monthlyBudget as number | undefined) ?? 0,
|
||||
warningThreshold: (ctx.pluginConfig.warningThreshold as number | undefined) ?? 0.8,
|
||||
retentionDays: (ctx.pluginConfig.retentionDays as number | undefined) ?? 90,
|
||||
}
|
||||
|
||||
store = new UsageStore(ctx.storage)
|
||||
const budget = new UsageBudget(store, config)
|
||||
|
||||
// Load existing records into memory cache
|
||||
await store.loadFromStorage()
|
||||
|
||||
// Clean old records on startup
|
||||
await store.cleanupExpired(config.retentionDays ?? 90)
|
||||
|
||||
// Listen to usage events from core
|
||||
ctx.on('usage:recorded', ((...args: unknown[]) => {
|
||||
const record = args[0] as UsageRecordEvent
|
||||
const usageRecord: UsageRecord = {
|
||||
id: nanoid(),
|
||||
sessionId: record.sessionId,
|
||||
agentName: record.agentName,
|
||||
timestamp: record.timestamp,
|
||||
tokensUsed: record.tokensUsed,
|
||||
contextSize: record.contextSize,
|
||||
cost: record.cost,
|
||||
}
|
||||
|
||||
void (async () => {
|
||||
await store!.append(usageRecord)
|
||||
|
||||
const result = budget.check()
|
||||
if (result.message) {
|
||||
const notifications = ctx.getService<NotificationService>('notifications')
|
||||
if (notifications) {
|
||||
await notifications.notifyAll({
|
||||
sessionId: record.sessionId,
|
||||
type: 'budget_warning',
|
||||
summary: result.message,
|
||||
})
|
||||
}
|
||||
}
|
||||
})()
|
||||
}) as (...args: unknown[]) => void)
|
||||
|
||||
// Register /usage command
|
||||
ctx.registerCommand({
|
||||
name: 'usage',
|
||||
description: 'Show usage summary for current month',
|
||||
category: 'plugin',
|
||||
handler: async () => {
|
||||
const status = budget.getStatus()
|
||||
const lines = [
|
||||
'Usage (this month):',
|
||||
` Spent: $${status.used.toFixed(2)}`,
|
||||
` Budget: ${status.budget > 0 ? `$${status.budget.toFixed(2)}` : 'not set'}`,
|
||||
` Status: ${status.status} (${status.percent}%)`,
|
||||
]
|
||||
return { type: 'text' as const, text: lines.join('\n') }
|
||||
},
|
||||
})
|
||||
|
||||
// Expose service for other plugins
|
||||
ctx.registerService('usage', { store, budget })
|
||||
|
||||
ctx.log.info('Usage tracking ready')
|
||||
},
|
||||
|
||||
async teardown() {
|
||||
if (store) {
|
||||
await store.flush()
|
||||
store.destroy()
|
||||
}
|
||||
},
|
||||
|
||||
async install(ctx: InstallContext) {
|
||||
const budget = await ctx.terminal.text({
|
||||
message: 'Monthly budget in USD (0 = no limit):',
|
||||
defaultValue: '0',
|
||||
validate: (v) => {
|
||||
const n = Number(v.trim())
|
||||
if (isNaN(n) || n < 0) return 'Must be a non-negative number'
|
||||
return undefined
|
||||
},
|
||||
})
|
||||
|
||||
const threshold = await ctx.terminal.text({
|
||||
message: 'Warning threshold (0-1, e.g. 0.8 = warn at 80%):',
|
||||
defaultValue: '0.8',
|
||||
validate: (v) => {
|
||||
const n = Number(v.trim())
|
||||
if (isNaN(n) || n < 0 || n > 1) return 'Must be between 0 and 1'
|
||||
return undefined
|
||||
},
|
||||
})
|
||||
|
||||
const retention = await ctx.terminal.text({
|
||||
message: 'Retention days:',
|
||||
defaultValue: '90',
|
||||
validate: (v) => {
|
||||
const n = Number(v.trim())
|
||||
if (isNaN(n) || n < 1) return 'Must be a positive number'
|
||||
return undefined
|
||||
},
|
||||
})
|
||||
|
||||
await ctx.settings.setAll({
|
||||
monthlyBudget: Number(budget.trim()),
|
||||
warningThreshold: Number(threshold.trim()),
|
||||
retentionDays: Number(retention.trim()),
|
||||
})
|
||||
|
||||
ctx.terminal.log.success('Usage plugin configured')
|
||||
},
|
||||
|
||||
async configure(ctx: InstallContext) {
|
||||
const current = await ctx.settings.getAll()
|
||||
|
||||
const budget = await ctx.terminal.text({
|
||||
message: 'Monthly budget in USD (0 = no limit):',
|
||||
defaultValue: String(current.monthlyBudget ?? 0),
|
||||
validate: (v) => {
|
||||
const n = Number(v.trim())
|
||||
if (isNaN(n) || n < 0) return 'Must be a non-negative number'
|
||||
return undefined
|
||||
},
|
||||
})
|
||||
|
||||
const threshold = await ctx.terminal.text({
|
||||
message: 'Warning threshold (0-1, e.g. 0.8 = warn at 80%):',
|
||||
defaultValue: String(current.warningThreshold ?? 0.8),
|
||||
validate: (v) => {
|
||||
const n = Number(v.trim())
|
||||
if (isNaN(n) || n < 0 || n > 1) return 'Must be between 0 and 1'
|
||||
return undefined
|
||||
},
|
||||
})
|
||||
|
||||
const retention = await ctx.terminal.text({
|
||||
message: 'Retention days:',
|
||||
defaultValue: String(current.retentionDays ?? 90),
|
||||
validate: (v) => {
|
||||
const n = Number(v.trim())
|
||||
if (isNaN(n) || n < 1) return 'Must be a positive number'
|
||||
return undefined
|
||||
},
|
||||
})
|
||||
|
||||
await ctx.settings.setAll({
|
||||
monthlyBudget: Number(budget.trim()),
|
||||
warningThreshold: Number(threshold.trim()),
|
||||
retentionDays: Number(retention.trim()),
|
||||
})
|
||||
|
||||
ctx.terminal.log.success('Usage plugin configured')
|
||||
},
|
||||
|
||||
async uninstall(ctx: InstallContext, opts: { purge: boolean }) {
|
||||
if (opts.purge) {
|
||||
await ctx.settings.clear()
|
||||
}
|
||||
ctx.terminal.log.success('Usage plugin removed')
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export default createUsagePlugin()
|
||||
72
src/plugins/usage/usage-budget.ts
Normal file
72
src/plugins/usage/usage-budget.ts
Normal file
@ -0,0 +1,72 @@
|
||||
import type { UsageStore } from './usage-store.js'
|
||||
|
||||
export interface UsagePluginConfig {
|
||||
monthlyBudget?: number
|
||||
warningThreshold?: number
|
||||
retentionDays?: number
|
||||
}
|
||||
|
||||
export type BudgetStatus = 'ok' | 'warning' | 'exceeded'
|
||||
|
||||
export class UsageBudget {
|
||||
private lastNotifiedStatus: BudgetStatus = 'ok'
|
||||
private lastNotifiedMonth: number
|
||||
|
||||
constructor(
|
||||
private store: UsageStore,
|
||||
private config: UsagePluginConfig,
|
||||
) {
|
||||
this.lastNotifiedMonth = new Date().getMonth()
|
||||
}
|
||||
|
||||
/** Check budget and return notification if status changed */
|
||||
check(): { status: BudgetStatus; message?: string } {
|
||||
const budget = this.config.monthlyBudget ?? 0
|
||||
if (budget <= 0) return { status: 'ok' }
|
||||
|
||||
const { totalCost } = this.store.getMonthlyTotal()
|
||||
const percent = totalCost / budget
|
||||
const threshold = this.config.warningThreshold ?? 0.8
|
||||
const currentMonth = new Date().getMonth()
|
||||
|
||||
// Reset notification tracking on month change
|
||||
if (currentMonth !== this.lastNotifiedMonth) {
|
||||
this.lastNotifiedStatus = 'ok'
|
||||
this.lastNotifiedMonth = currentMonth
|
||||
}
|
||||
|
||||
let status: BudgetStatus = 'ok'
|
||||
if (percent >= 1) status = 'exceeded'
|
||||
else if (percent >= threshold) status = 'warning'
|
||||
|
||||
// Only notify on status escalation (ok -> warning -> exceeded)
|
||||
let message: string | undefined
|
||||
if (status !== 'ok' && status !== this.lastNotifiedStatus) {
|
||||
const bar = this.progressBar(percent)
|
||||
message = status === 'exceeded'
|
||||
? `Budget exceeded! ${bar} $${totalCost.toFixed(2)} / $${budget.toFixed(2)}`
|
||||
: `Budget warning: ${bar} $${totalCost.toFixed(2)} / $${budget.toFixed(2)} (${(percent * 100).toFixed(0)}%)`
|
||||
this.lastNotifiedStatus = status
|
||||
}
|
||||
|
||||
return { status, message }
|
||||
}
|
||||
|
||||
/** Get current budget status for /usage command */
|
||||
getStatus(): { status: string; used: number; budget: number; percent: number } {
|
||||
const { totalCost } = this.store.getMonthlyTotal()
|
||||
const budget = this.config.monthlyBudget ?? 0
|
||||
const percent = budget > 0 ? Math.round((totalCost / budget) * 100) : 0
|
||||
let status = 'ok'
|
||||
if (budget > 0) {
|
||||
if (totalCost >= budget) status = 'exceeded'
|
||||
else if (totalCost >= budget * (this.config.warningThreshold ?? 0.8)) status = 'warning'
|
||||
}
|
||||
return { status, used: totalCost, budget, percent }
|
||||
}
|
||||
|
||||
progressBar(percent: number): string {
|
||||
const filled = Math.min(Math.round(percent * 10), 10)
|
||||
return '\u2588'.repeat(filled) + '\u2591'.repeat(10 - filled)
|
||||
}
|
||||
}
|
||||
89
src/plugins/usage/usage-store.ts
Normal file
89
src/plugins/usage/usage-store.ts
Normal file
@ -0,0 +1,89 @@
|
||||
import type { PluginStorage } from '../../core/plugin/types.js'
|
||||
import type { UsageRecord } from '../../core/types.js'
|
||||
|
||||
const DEBOUNCE_MS = 2000
|
||||
|
||||
export class UsageStore {
|
||||
private cache = new Map<string, UsageRecord[]>()
|
||||
private dirty = new Set<string>()
|
||||
private flushTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
constructor(private storage: PluginStorage) {}
|
||||
|
||||
/** Load current month's records into memory on startup */
|
||||
async loadFromStorage(): Promise<void> {
|
||||
const key = this.monthKey(new Date().toISOString())
|
||||
const records = (await this.storage.get<UsageRecord[]>(key)) ?? []
|
||||
this.cache.set(key, records)
|
||||
}
|
||||
|
||||
/** Append a record (in-memory, schedules debounced flush) */
|
||||
async append(record: UsageRecord): Promise<void> {
|
||||
const key = this.monthKey(record.timestamp)
|
||||
if (!this.cache.has(key)) {
|
||||
const existing = (await this.storage.get<UsageRecord[]>(key)) ?? []
|
||||
this.cache.set(key, existing)
|
||||
}
|
||||
this.cache.get(key)!.push(record)
|
||||
this.dirty.add(key)
|
||||
this.scheduleFlush()
|
||||
}
|
||||
|
||||
/** Get monthly cost total (reads from cache) */
|
||||
getMonthlyTotal(date?: Date): { totalCost: number; currency: string } {
|
||||
const key = this.monthKey((date ?? new Date()).toISOString())
|
||||
const records = this.cache.get(key) ?? []
|
||||
const totalCost = records.reduce((sum, r) => sum + (r.cost?.amount ?? 0), 0)
|
||||
const currency = records.find(r => r.cost?.currency)?.cost?.currency ?? 'USD'
|
||||
return { totalCost, currency }
|
||||
}
|
||||
|
||||
/** Flush all dirty keys to storage immediately */
|
||||
async flush(): Promise<void> {
|
||||
if (this.flushTimer) {
|
||||
clearTimeout(this.flushTimer)
|
||||
this.flushTimer = null
|
||||
}
|
||||
for (const key of this.dirty) {
|
||||
const records = this.cache.get(key)
|
||||
if (records) await this.storage.set(key, records)
|
||||
}
|
||||
this.dirty.clear()
|
||||
}
|
||||
|
||||
/** Delete records older than retention period */
|
||||
async cleanupExpired(retentionDays: number): Promise<void> {
|
||||
const keys = await this.storage.list()
|
||||
const cutoff = new Date()
|
||||
cutoff.setDate(cutoff.getDate() - retentionDays)
|
||||
const cutoffKey = this.monthKey(cutoff.toISOString())
|
||||
|
||||
for (const key of keys) {
|
||||
if (key.startsWith('records:') && key < cutoffKey) {
|
||||
await this.storage.delete(key)
|
||||
this.cache.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Destroy timers for clean shutdown */
|
||||
destroy(): void {
|
||||
if (this.flushTimer) {
|
||||
clearTimeout(this.flushTimer)
|
||||
this.flushTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleFlush(): void {
|
||||
if (this.flushTimer) return
|
||||
this.flushTimer = setTimeout(() => {
|
||||
this.flushTimer = null
|
||||
void this.flush()
|
||||
}, DEBOUNCE_MS)
|
||||
}
|
||||
|
||||
private monthKey(timestamp: string): string {
|
||||
const d = new Date(timestamp)
|
||||
return `records:${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user