@goodandready/dsh-cost-meter 0.8.28 → 0.8.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/analytics.js CHANGED
@@ -90,4 +90,59 @@ export function calculateBurnRateAndProjection(turns, totalCostUsd, options = {}
90
90
  projectedCostUsd,
91
91
  confidence,
92
92
  }
93
- }
93
+ }
94
+
95
+ /**
96
+ * Returns estimated context window token limit for model identifier.
97
+ */
98
+ export function getFallbackContextLength(model) {
99
+ const m = String(model || '').toLowerCase()
100
+ if (m.includes('claude-3-5') || m.includes('claude-3-7') || m.includes('claude-3-opus')) return 200000
101
+ if (m.includes('claude')) return 200000
102
+ if (m.includes('gemini-1.5') || m.includes('gemini-2.0') || m.includes('gemini-exp')) return 1000000
103
+ if (m.includes('gpt-4.1') || m.includes('gpt-4o') || m.includes('o1') || m.includes('o3')) return 128000
104
+ if (m.includes('qwen-2.5') || m.includes('qwq')) return 128000
105
+ if (m.includes('deepseek')) return 128000
106
+ return 128000
107
+ }
108
+
109
+ /**
110
+ * Calculates context window saturation metrics and compaction risk.
111
+ *
112
+ * @param {Array<{ turn: number, uncachedInputTokens?: number, cacheReadTokens?: number }>} turns
113
+ * @param {object} [tariff]
114
+ * @param {object} [route]
115
+ * @returns {{ currentTokens: number, contextLength: number, saturationPercent: number, riskLevel: 'low' | 'moderate' | 'high', nextTurnEstUsd: number }}
116
+ */
117
+ export function calculateContextMetrics(turns, tariff, route) {
118
+ const lastTurn = (Array.isArray(turns) && turns.length > 0) ? turns[turns.length - 1] : null
119
+ const currentTokens = lastTurn
120
+ ? (Number(lastTurn.uncachedInputTokens || 0) + Number(lastTurn.cacheReadTokens || 0))
121
+ : 0
122
+
123
+ const contextLength = (tariff && Number(tariff.contextLength)) || getFallbackContextLength(route?.model)
124
+ const saturationPercent = contextLength > 0
125
+ ? Math.min(100, Math.round((currentTokens / contextLength) * 100))
126
+ : 0
127
+
128
+ let riskLevel = 'low'
129
+ if (saturationPercent >= 80) {
130
+ riskLevel = 'high'
131
+ } else if (saturationPercent >= 50) {
132
+ riskLevel = 'moderate'
133
+ }
134
+
135
+ const rates = tariff?.schedule?.base || {}
136
+ const inputRate = Number(rates.input) || 0.14
137
+ const nextTurnEstUsd = currentTokens > 0
138
+ ? Number(((currentTokens * inputRate) / 1e6).toFixed(6))
139
+ : 0
140
+
141
+ return {
142
+ currentTokens,
143
+ contextLength,
144
+ saturationPercent,
145
+ riskLevel,
146
+ nextTurnEstUsd,
147
+ }
148
+ }