// src/cost-cursor.ts // Grok Build (formerly Cursor) cost source (round 2, R3). // // The app keeps no usage in its transcripts (checked on 3.32.24: messages // only). Its `stop` hook does carry the turn's tokens: input_tokens, // output_tokens, cache_read_tokens, cache_write_tokens, with the model and // the session. node9's native `stop` entry (`node9 log --agent cursor`) // appends one line per turn to ~/.node9/cost/cursor-turns.jsonl (no prompt // text, no reply), and this source turns those lines into the same // DailyEntry rows every other agent uploads: one per (day, model, project, // session). // // A model with no public price (Grok Build's own grok-4.x and composer // models) keeps its tokens with a cost of 0: no guessed price (decision D2). import fs from 'fs'; import os from 'os'; import path from 'path'; import { pricingFor, normalizeModel } from './pricing/litellm.js'; import type { CostSource, DailyEntry } from './costSync.js'; import { ensureOwnDir, isSameOwnDir } from './utils/own-dir.js'; /** Past this size the file is moved to `.1` (one previous file is kept). */ const ROTATE_BYTES = 5 * 1024 * 1024; export function cursorTurnsFile(home: string = os.homedir()): string { return path.join(home, '.node9', 'cost', 'cursor-turns.jsonl'); } /** One turn as recorded: tokens and where they were spent, nothing said. */ export interface CursorTurn { ts: string; sessionId: string; model: string; workspace: string; input: number; output: number; cacheRead: number; cacheWrite: number; } const count = (v: unknown): number => typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.floor(v) : 0; /** The turn a `stop` payload describes, or null when it carries no tokens. */ export function cursorTurnFromStop( payload: Record, workspace: string | undefined, now: Date = new Date() ): CursorTurn | null { const turn = { input: count(payload.input_tokens), output: count(payload.output_tokens), cacheRead: count(payload.cache_read_tokens), cacheWrite: count(payload.cache_write_tokens), }; if (turn.input + turn.output + turn.cacheRead + turn.cacheWrite === 0) return null; const model = typeof payload.model_id === 'string' && payload.model_id ? payload.model_id : typeof payload.model === 'string' ? payload.model : ''; const sessionId = typeof payload.session_id === 'string' ? payload.session_id : typeof payload.conversation_id === 'string' ? payload.conversation_id : ''; return { ts: now.toISOString(), sessionId: sessionId.slice(0, 200), model: model.slice(0, 200), workspace: (workspace ?? '').slice(0, 1000), ...turn, }; } /** Append one turn. Best-effort: a lost line costs one turn's figure, never * the hook. Never throws. */ export function recordCursorTurn(turn: CursorTurn, home: string = os.homedir()): void { try { const file = cursorTurnsFile(home); const dir = path.dirname(file); const own = ensureOwnDir(dir); if (!own) return; try { if (fs.lstatSync(file).size > ROTATE_BYTES) fs.renameSync(file, `${file}.1`); } catch { /* no file yet */ } if (!isSameOwnDir(dir, own)) return; const fd = fs.openSync( file, fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT | (fs.constants.O_NOFOLLOW ?? 0), 0o600 ); try { fs.writeSync(fd, JSON.stringify(turn) + '\n'); } finally { fs.closeSync(fd); } } catch { /* best-effort */ } } function priceTurn(model: string, t: CursorTurn): number { const tuple = pricingFor(model); if (!tuple) return 0; const [pin, pout, pcw, pcr] = tuple; return t.input * pin + t.output * pout + t.cacheWrite * pcw + t.cacheRead * pcr; } /** Recorded turns as DailyEntry rows, one per (day, model, project, session). * Pure: exported for unit tests. */ export function parseCursorTurns(lines: string[], sinceMs?: number): DailyEntry[] { const combined = new Map(); for (const raw of lines) { if (!raw.trim()) continue; let t: CursorTurn; try { t = JSON.parse(raw) as CursorTurn; } catch { continue; } if (!t || typeof t.ts !== 'string' || typeof t.model !== 'string') continue; const at = Date.parse(t.ts); if (!Number.isFinite(at) || (sinceMs !== undefined && at < sinceMs)) continue; const turn: CursorTurn = { ...t, input: count(t.input), output: count(t.output), cacheRead: count(t.cacheRead), cacheWrite: count(t.cacheWrite), }; const date = t.ts.slice(0, 10); const model = normalizeModel(t.model || 'unknown'); const workingDir = typeof t.workspace === 'string' ? t.workspace : ''; const runId = typeof t.sessionId === 'string' ? t.sessionId : ''; const key = `${date}::${model}::${workingDir}::${runId}`; const costUSD = priceTurn(t.model, turn); const prev = combined.get(key); if (prev) { prev.costUSD += costUSD; prev.inputTokens += turn.input; prev.outputTokens += turn.output; prev.cacheReadTokens += turn.cacheRead; prev.cacheWriteTokens += turn.cacheWrite; } else { combined.set(key, { date, model, workingDir, runId, costUSD, inputTokens: turn.input, outputTokens: turn.output, cacheReadTokens: turn.cacheRead, cacheWriteTokens: turn.cacheWrite, }); } } return [...combined.values()]; } export const cursorSource: CostSource = { id: 'cursor', available(): boolean { const file = cursorTurnsFile(); return fs.existsSync(file) || fs.existsSync(`${file}.1`); }, collect(sinceMs?: number): DailyEntry[] { const file = cursorTurnsFile(); const lines: string[] = []; for (const f of [`${file}.1`, file]) { try { lines.push(...fs.readFileSync(f, 'utf8').split('\n')); } catch { /* absent */ } } return parseCursorTurns(lines, sinceMs); }, };