// tools/token-recording.ts — Fire-and-forget token usage recording for all tool calls.
// Called by safeWithTelemetry() after each successful tool execution.
import { join } from 'node:path';
import { countTokens, estimateCost } from '../engine/token-optimizer/counter.js';
import { recordEntry } from '../storage/token-ledger-store.js';
import { hashProjectPath } from '../storage/base-store.js';
/**
 * Record a tool call's token usage to the persistent ledger.
 * Always fire-and-forget — never throws, never blocks the response.
 */
export function recordToolTokens(toolName, projectPath, inputArgs, outputText, sessionId) {
    try {
        const inputStr = typeof inputArgs === 'string' ? inputArgs : JSON.stringify(inputArgs);
        const inputCount = countTokens(inputStr);
        const outputCount = countTokens(outputText);
        const totalTokens = inputCount.tokens + outputCount.tokens;
        const cost = estimateCost(totalTokens, 'claude-sonnet');
        const entry = {
            id: `TXN-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
            timestamp: new Date().toISOString(),
            sessionId,
            toolName,
            model: 'claude-sonnet',
            inputTokens: inputCount.tokens,
            outputTokens: outputCount.tokens,
            totalTokens,
            costUsd: cost.totalCostUsd,
            cached: false,
        };
        const projectHash = hashProjectPath(projectPath);
        const dataDir = join(process.cwd(), 'data');
        void recordEntry(projectHash, dataDir, entry).catch((err) => {
            console.error('[planu] token-recording recordEntry failed:', err);
        });
    }
    catch {
        // Never fail the tool call due to token recording errors
    }
}
/**
 * Extract output text from a ToolResult for token counting.
 * Concatenates all text content items into a single string.
 */
export function extractOutputText(result) {
    return result.content
        .flatMap((item) => (item.type === 'text' && typeof item.text === 'string' ? [item.text] : []))
        .join('\n');
}
//# sourceMappingURL=token-recording.js.map