DEV Community
Follow
52 Days, 2,340 Rows, Every Cost Logged as Zero: The Stop Hook Trap
The author's student side hustle grew into a real business by autonomously running an AI environment. This setup moved beyond issuing instructions to letting the system operate independently, even while the author slept. A key component is a "Stop hook" that triggers automatically upon session completion. This hook is crucial for tracking AI usage costs, as autonomous agents can silently consume resources without direct oversight.The initial cost tracking mechanism failed for 52 days and over 2,300 log entries because the Stop hook's input lacked essential usage and model data. The revised approach focuses on reading the session's transcript file directly, as it is the only reliable data source. This transcript contains detailed logs of assistant responses, including token usage and the model employed.The system utilizes a rate table that defines costs per million tokens for different models like Haiku, Sonnet, and Opus. It also accounts for the cost implications of AI caching, where cache reads can be significantly cheaper than regular input. Robust error handling is implemented to ensure that minor issues, like unreadable files or invalid log lines, do not halt the entire tracking process.The script includes a triple fallback mechanism for determining the session ID, ensuring that even under varied execution contexts, a session identifier is captured. Finally, the cost calculation uses a specific rounding technique to maintain precision at six decimal places, mitigating floating-point arithmetic errors. The cumulative design of the log entries allows for partial data recovery even if a session terminates unexpectedly.