pyb-ts
Version:
PYB-CLI - Minimal AI Agent with multi-model support and CLI interface
78 lines (77 loc) • 2.08 kB
JavaScript
import chalk from "chalk";
import { useEffect } from "react";
import { formatDuration } from "./utils/format.js";
import {
getCurrentProjectConfig,
saveCurrentProjectConfig
} from "@utils/config";
import { SESSION_ID } from "./utils/log.js";
import { LIST_ITEM } from "@constants/figures";
const STATE = {
totalCost: 0,
totalAPIDuration: 0,
startTime: Date.now()
};
function addToTotalCost(cost, duration) {
STATE.totalCost += cost;
STATE.totalAPIDuration += duration;
}
function getTotalCost() {
return STATE.totalCost;
}
function getTotalDuration() {
return Date.now() - STATE.startTime;
}
function getTotalAPIDuration() {
return STATE.totalAPIDuration;
}
function formatCost(cost) {
return `$${cost > 0.5 ? round(cost, 100).toFixed(2) : cost.toFixed(4)}`;
}
function formatTotalCost() {
return chalk.grey(
`${LIST_ITEM}Total cost: ${formatCost(STATE.totalCost)}
${LIST_ITEM}Total duration (API): ${formatDuration(STATE.totalAPIDuration)}
${LIST_ITEM}Total duration (wall): ${formatDuration(getTotalDuration())}`
);
}
function useCostSummary() {
useEffect(() => {
const f = () => {
process.stdout.write("\n" + formatTotalCost() + "\n");
const projectConfig = getCurrentProjectConfig();
saveCurrentProjectConfig({
...projectConfig,
lastCost: STATE.totalCost,
lastAPIDuration: STATE.totalAPIDuration,
lastDuration: getTotalDuration(),
lastSessionId: SESSION_ID
});
};
process.on("exit", f);
return () => {
process.off("exit", f);
};
}, []);
}
function round(number, precision) {
return Math.round(number * precision) / precision;
}
function resetStateForTests() {
if (process.env.NODE_ENV !== "test") {
throw new Error("resetStateForTests can only be called in tests");
}
STATE.startTime = Date.now();
STATE.totalCost = 0;
STATE.totalAPIDuration = 0;
}
export {
addToTotalCost,
formatTotalCost,
getTotalAPIDuration,
getTotalCost,
getTotalDuration,
resetStateForTests,
useCostSummary
};
//# sourceMappingURL=cost-tracker.js.map