Skip to main content
For custom agent frameworks built in Node.js, AgentSession gives you the full CostHQ tracking API programmatically — no CLI required. You control when sessions start and end, log AI calls with granular token counts, enforce hard budget caps, and receive callback notifications on every significant event.

Import

Constructor

Pass a human-readable session name as the first argument, then an optional config object:

Key Methods

session.start()

Starts the session and begins the file watcher and git commit poller. Call this before any logAI or canAfford calls. Returns the numeric session ID.

session.logAI(provider, model, tokens, cost, options?)

Logs a single AI call against this session. CostHQ records the tokens, cost, and timestamp, then checks the running total against your budget.
Returns the remaining budget in USD, or null if no budget is set. Throws BudgetExceededError if the new total meets or exceeds the budget.

session.canAfford(amount)

Performs a pre-flight budget check before committing to an expensive API call. Returns true if the estimated cost fits within the remaining budget, or true unconditionally when no budget is set.

session.end(notes?)

Stops the file watcher and git poller, finalises the session, and returns an AgentSessionSummary. Pass an optional notes string to annotate the session.

Budget Enforcement Example

When BudgetExceededError is thrown, the session is automatically ended before the error propagates. You do not need to call session.end() in your catch block.

AgentSessionSummary Fields

session.end() returns an AgentSessionSummary object with the following fields:

runAgentSession Helper

runAgentSession wraps the full start / run / end lifecycle for you. It handles BudgetExceededError gracefully and calls session.end() automatically, even if your agent function throws.
Use runAgentSession for straightforward one-shot tasks. Use new AgentSession() directly when you need finer control — for example, to inspect summary at intermediate checkpoints or to conditionally resume a session.