| 140 | * Initialize SQLite database for usage tracking |
| 141 | */ |
| 142 | export function initDatabase(dbPath: string): Database.Database { |
| 143 | // Ensure directory exists |
| 144 | const dir = path.dirname(dbPath); |
| 145 | if (!fs.existsSync(dir)) { |
| 146 | fs.mkdirSync(dir, { recursive: true }); |
| 147 | } |
| 148 | |
| 149 | const db = new Database(dbPath); |
| 150 | |
| 151 | // Create table if not exists |
| 152 | db.exec(` |
| 153 | CREATE TABLE IF NOT EXISTS usage_snapshots ( |
| 154 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 155 | timestamp INTEGER NOT NULL, |
| 156 | date TEXT NOT NULL, |
| 157 | hour INTEGER NOT NULL, |
| 158 | agent_id TEXT NOT NULL, |
| 159 | model TEXT NOT NULL, |
| 160 | input_tokens INTEGER NOT NULL, |
| 161 | output_tokens INTEGER NOT NULL, |
| 162 | cache_read_tokens INTEGER NOT NULL DEFAULT 0, |
| 163 | cache_write_tokens INTEGER NOT NULL DEFAULT 0, |
| 164 | total_tokens INTEGER NOT NULL, |
| 165 | cost REAL NOT NULL, |
| 166 | created_at INTEGER DEFAULT (strftime('%s', 'now')) |
| 167 | ); |
| 168 | |
| 169 | CREATE INDEX IF NOT EXISTS idx_date ON usage_snapshots(date); |
| 170 | CREATE INDEX IF NOT EXISTS idx_agent ON usage_snapshots(agent_id); |
| 171 | CREATE INDEX IF NOT EXISTS idx_model ON usage_snapshots(model); |
| 172 | CREATE INDEX IF NOT EXISTS idx_timestamp ON usage_snapshots(timestamp); |
| 173 | `); |
| 174 | |
| 175 | return db; |
| 176 | } |
| 177 | |
| 178 | /** |
| 179 | * Save snapshot to database |