@causyne/agent 1.20.11 → 1.20.13
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/LICENSE +1 -1
- package/docs/ARCHITECTURE.md +24 -1
- package/package.json +1 -1
- package/src/acp/client.js +9 -2
- package/src/acp/client.ts +11 -2
- package/src/acp/protocol.ts +9 -0
- package/src/agentLoop.js +504 -119
- package/src/agentLoop.ts +477 -121
- package/src/browser/browserRuntime.js +47 -0
- package/src/browser/browserRuntime.ts +45 -0
- package/src/browser/causyneBrowser.js +60 -31
- package/src/browser/causyneBrowser.ts +37 -12
- package/src/browser/workspacePreview.js +52 -0
- package/src/browser/workspacePreview.ts +49 -0
- package/src/core/planCache.js +5 -0
- package/src/core/planCache.ts +5 -0
- package/src/decisionPolicy.js +9 -0
- package/src/decisionPolicy.ts +8 -0
- package/src/historyPruner.js +251 -0
- package/src/historyPruner.ts +263 -0
- package/src/infra/atomicWriter.js +49 -0
- package/src/infra/atomicWriter.ts +63 -0
- package/src/infra/telemetry.js +38 -0
- package/src/infra/telemetry.ts +68 -0
- package/src/observer/coldObserver.js +12 -7
- package/src/observer/coldObserver.ts +12 -7
- package/src/observer/evidence.js +8 -2
- package/src/observer/evidence.ts +9 -2
- package/src/outputRecovery.js +36 -0
- package/src/outputRecovery.ts +33 -0
- package/src/providers/acp.js +114 -46
- package/src/providers/acp.ts +129 -46
- package/src/providers/antigravity.js +264 -82
- package/src/providers/antigravity.ts +273 -87
- package/src/providers/antigravityBridge.js +58 -0
- package/src/providers/antigravityBridge.ts +51 -0
- package/src/providers/base.d.ts +9 -0
- package/src/providers/budgetEnforcer.js +110 -0
- package/src/providers/budgetEnforcer.ts +122 -0
- package/src/providers/collaborationPolicy.js +6 -0
- package/src/providers/collaborationPolicy.ts +7 -0
- package/src/providers/loopGuard.js +84 -0
- package/src/providers/loopGuard.ts +105 -0
- package/src/providers/pi.js +19 -6
- package/src/providers/pi.ts +19 -7
- package/src/providers/toolContracts.js +36 -0
- package/src/providers/toolContracts.ts +48 -0
- package/src/session/sidechainEvents.js +49 -0
- package/src/session/sidechainEvents.ts +98 -0
- package/src/skillsManager.d.ts +1 -0
- package/src/smartToolsUse.js +123 -4
- package/src/smartToolsUse.ts +136 -4
- package/src/subagent/sidechainHarness.js +66 -0
- package/src/subagent/sidechainHarness.ts +91 -0
- package/src/taskContinuation.js +12 -0
- package/src/taskContinuation.ts +13 -0
- package/src/tokenTracker.js +406 -539
- package/src/tokenTracker.ts +569 -0
- package/src/toolPacks.d.ts +2 -0
- package/src/toolPacks.js +1 -1
- package/src/tools/argumentValidation.js +56 -0
- package/src/tools/argumentValidation.ts +50 -0
- package/src/tools/browserAutomator.js +2 -2
- package/src/tools/browserAutomator.ts +3 -2
- package/src/tools/deferredMcpSearch.js +188 -201
- package/src/tools/deferredMcpSearch.ts +250 -0
- package/src/tools/generateMediaViaApi.js +305 -331
- package/src/tools/generateMediaViaApi.ts +330 -0
- package/src/tools/historyPruner.js +5 -0
- package/src/tools/historyPruner.ts +5 -0
- package/src/tools/payloadSanitizer.js +92 -0
- package/src/tools/payloadSanitizer.ts +113 -0
- package/src/tools/registry.d.ts +1 -0
- package/src/tools/sysRun.js +47 -18
- package/src/tools/sysRun.ts +52 -20
- package/src/tools/toolOutputStore.js +180 -0
- package/src/tools/toolOutputStore.ts +209 -0
- package/src/tools/toolSelfRepair.js +26 -1
- package/src/tools/toolSelfRepair.ts +25 -1
- package/src/tui/chatRenderer.d.ts +1 -0
- package/src/tui/chatRenderer.js +4 -2
- package/src/tui/codeStreamRenderer.js +36 -8
- package/src/tui/codeStreamRenderer.ts +38 -8
- package/src/tui/stageSurface.js +1 -0
- package/src/tui/text.js +4 -1
- package/src/tokenTracker.d.ts +0 -1
package/src/tokenTracker.js
CHANGED
|
@@ -1,575 +1,442 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import path from 'path';
|
|
3
|
-
import os from 'os';
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
4
3
|
import { loadConfig } from './config.js';
|
|
5
|
-
|
|
6
4
|
import { causyneHome } from './utils/paths.js';
|
|
7
|
-
|
|
8
5
|
const USAGE_DIR = path.join(causyneHome(), 'usage');
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* The date key for "today", in the USER'S timezone.
|
|
12
|
-
*
|
|
13
|
-
* This was `new Date().toISOString().split('T')[0]`, which is UTC. A daily
|
|
14
|
-
* budget bucketed in UTC does not reset at the user's midnight: in WIB (UTC+7)
|
|
15
|
-
* it rolls over at 07:00 local, in NZDT (UTC+13) at 13:00, in PST (UTC-8) the
|
|
16
|
-
* previous evening. So a user's morning work was charged to "yesterday" and
|
|
17
|
-
* their daily cap could be exhausted before their day had started — and the
|
|
18
|
-
* reset landed in the middle of it.
|
|
19
|
-
*
|
|
20
|
-
* A limit the user sets as "per day" must mean their day. Anything else is a
|
|
21
|
-
* limit they cannot reason about.
|
|
22
|
-
*/
|
|
23
|
-
|
|
24
6
|
let usageQueue = Promise.resolve();
|
|
25
7
|
function withUsageLock(fn) {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
8
|
+
const run = usageQueue.then(fn, fn);
|
|
9
|
+
usageQueue = run.then(() => { }, () => { });
|
|
10
|
+
return run;
|
|
29
11
|
}
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Write a usage file the way the journal does: temp file, then rename.
|
|
33
|
-
*
|
|
34
|
-
* A direct writeFileSync that is interrupted leaves truncated JSON, and
|
|
35
|
-
* getDailyUsage() answers a parse failure with a fresh zeroed record — so a
|
|
36
|
-
* torn write does not surface as an error, it silently ERASES the day's budget.
|
|
37
|
-
* rename() is atomic on the same filesystem, so a reader sees either the whole
|
|
38
|
-
* previous file or the whole new one.
|
|
39
|
-
*/
|
|
40
12
|
function writeUsageFile(file, payload) {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
13
|
+
const temp = `${file}.tmp_${process.pid}`;
|
|
14
|
+
fs.writeFileSync(temp, JSON.stringify(payload, null, 2), { encoding: 'utf8', mode: 0o600 });
|
|
15
|
+
fs.renameSync(temp, file);
|
|
44
16
|
}
|
|
45
|
-
|
|
46
17
|
function localDateKey(when = new Date()) {
|
|
47
|
-
|
|
48
|
-
|
|
18
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
19
|
+
return `${when.getFullYear()}-${pad(when.getMonth() + 1)}-${pad(when.getDate())}`;
|
|
49
20
|
}
|
|
50
|
-
|
|
51
|
-
// Input-token count above which GPT-6 Astra bills on its second rate card
|
|
52
|
-
// ($20/$75 instead of $10/$50). The higher card applies to the whole request,
|
|
53
|
-
// not to the overage alone.
|
|
54
21
|
const ASTRA_LONG_CONTEXT_THRESHOLD = 272000;
|
|
55
|
-
|
|
56
22
|
export class TokenTracker {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
//
|
|
70
|
-
// `promptTokens` is optional and only consulted by providers that publish a
|
|
71
|
-
// SECOND rate card above a context threshold. GPT-6 Astra is the first: past
|
|
72
|
-
// 272,000 input tokens the same request bills at $20 in / $75 out instead of
|
|
73
|
-
// $10 / $50. Ignoring that under-reported long-context runs by 2x — and
|
|
74
|
-
// under-reporting is the worse direction, because the user's real invoice
|
|
75
|
-
// then exceeds the cost shown by Causyne.
|
|
76
|
-
getPricing(promptTokens = 0) {
|
|
77
|
-
const provider = this.config.provider?.toLowerCase();
|
|
78
|
-
const model = this.config.model?.toLowerCase() || '';
|
|
79
|
-
|
|
80
|
-
if (provider === 'deepseek') {
|
|
81
|
-
if (model.includes('pro')) return [0.435, 0.87];
|
|
82
|
-
if (model.includes('flash')) return [0.14, 0.28];
|
|
83
|
-
return [0.14, 0.28]; // Default
|
|
23
|
+
config;
|
|
24
|
+
budget;
|
|
25
|
+
taskTokens;
|
|
26
|
+
taskCostUsd;
|
|
27
|
+
largestStepTokens;
|
|
28
|
+
constructor() {
|
|
29
|
+
this.config = loadConfig();
|
|
30
|
+
this.budget = this.config.tokenBudget || { enabled: false };
|
|
31
|
+
this.taskTokens = 0;
|
|
32
|
+
this.taskCostUsd = 0;
|
|
33
|
+
this.largestStepTokens = 0;
|
|
34
|
+
this.ensureUsageDir();
|
|
84
35
|
}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
36
|
+
getPricing(promptTokens = 0) {
|
|
37
|
+
const provider = this.config.provider?.toLowerCase();
|
|
38
|
+
const model = this.config.model?.toLowerCase() || '';
|
|
39
|
+
if (provider === 'deepseek') {
|
|
40
|
+
if (model.includes('pro'))
|
|
41
|
+
return [0.435, 0.87];
|
|
42
|
+
if (model.includes('flash'))
|
|
43
|
+
return [0.14, 0.28];
|
|
44
|
+
return [0.14, 0.28];
|
|
45
|
+
}
|
|
46
|
+
if (provider === 'muse' || provider === 'meta') {
|
|
47
|
+
if (model.includes('-contributor'))
|
|
48
|
+
return [0.10, 0.20];
|
|
49
|
+
return [1.25, 4.25];
|
|
50
|
+
}
|
|
51
|
+
if (provider === 'qwen' || provider === 'dashscope') {
|
|
52
|
+
if (model.includes('max'))
|
|
53
|
+
return [1.25, 3.75];
|
|
54
|
+
if (model.includes('plus'))
|
|
55
|
+
return [0.32, 1.28];
|
|
56
|
+
if (model.includes('flash'))
|
|
57
|
+
return [0.19, 1.13];
|
|
58
|
+
return [0.32, 1.28];
|
|
59
|
+
}
|
|
60
|
+
if (provider === 'openai') {
|
|
61
|
+
if (model.includes('astra')) {
|
|
62
|
+
return promptTokens > ASTRA_LONG_CONTEXT_THRESHOLD ? [20.00, 75.00] : [10.00, 50.00];
|
|
63
|
+
}
|
|
64
|
+
if (model.includes('sol'))
|
|
65
|
+
return [5.00, 30.00];
|
|
66
|
+
if (model.includes('terra'))
|
|
67
|
+
return [2.50, 15.00];
|
|
68
|
+
if (model.includes('luna'))
|
|
69
|
+
return [1.00, 1.00];
|
|
70
|
+
if (model.includes('mini'))
|
|
71
|
+
return [0.75, 4.50];
|
|
72
|
+
return [5.00, 30.00];
|
|
73
|
+
}
|
|
74
|
+
if (provider === 'anthropic') {
|
|
75
|
+
if (model.includes('fable') || model.includes('mythos'))
|
|
76
|
+
return [10.00, 50.00];
|
|
77
|
+
if (model.includes('opus'))
|
|
78
|
+
return [5.00, 25.00];
|
|
79
|
+
if (model.includes('sonnet-4-6'))
|
|
80
|
+
return [3.00, 15.00];
|
|
81
|
+
if (model.includes('sonnet'))
|
|
82
|
+
return [2.00, 10.00];
|
|
83
|
+
if (model.includes('haiku'))
|
|
84
|
+
return [1.00, 5.00];
|
|
85
|
+
return [2.00, 10.00];
|
|
86
|
+
}
|
|
87
|
+
if (provider === 'gemini') {
|
|
88
|
+
if (model.includes('pro'))
|
|
89
|
+
return [2.00, 12.00];
|
|
90
|
+
if (model.includes('flash-lite'))
|
|
91
|
+
return [0.25, 1.50];
|
|
92
|
+
if (model.includes('3.6-flash') || model.includes('3-6-flash'))
|
|
93
|
+
return [1.50, 7.50];
|
|
94
|
+
if (model.includes('flash'))
|
|
95
|
+
return [1.50, 9.00];
|
|
96
|
+
return [1.50, 9.00];
|
|
97
|
+
}
|
|
98
|
+
if (provider === 'ollama') {
|
|
99
|
+
return [0.00, 0.00];
|
|
100
|
+
}
|
|
101
|
+
if (provider === 'acp' || provider?.startsWith('acp/') || provider === 'antigravity' || provider === 'agy') {
|
|
102
|
+
return [0.00, 0.00];
|
|
103
|
+
}
|
|
104
|
+
return [5.00, 15.00];
|
|
118
105
|
}
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
106
|
+
cachedInputMultiplier() {
|
|
107
|
+
const provider = this.config.provider?.toLowerCase();
|
|
108
|
+
if (provider === 'anthropic') {
|
|
109
|
+
const model = this.config.model?.toLowerCase() || '';
|
|
110
|
+
if (model.includes('fable-5-1'))
|
|
111
|
+
return 0.025;
|
|
112
|
+
return 0.1;
|
|
113
|
+
}
|
|
114
|
+
if (provider === 'deepseek')
|
|
115
|
+
return 0.1;
|
|
116
|
+
if (provider === 'muse' || provider === 'meta') {
|
|
117
|
+
const model = this.config.model?.toLowerCase() || '';
|
|
118
|
+
return model.includes('-contributor') ? 0.02 : 0.12;
|
|
119
|
+
}
|
|
120
|
+
if (provider === 'openai') {
|
|
121
|
+
const model = this.config.model?.toLowerCase() || '';
|
|
122
|
+
if (model.includes('astra'))
|
|
123
|
+
return 0.1;
|
|
124
|
+
}
|
|
125
|
+
return 0.5;
|
|
131
126
|
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
127
|
+
calculateCost(promptTokens, completionTokens, usageDetail = null) {
|
|
128
|
+
const [promptPrice, completionPrice] = this.getPricing(promptTokens);
|
|
129
|
+
const cachedTokens = Math.min(Number(usageDetail?.cachedPromptTokens || 0), promptTokens);
|
|
130
|
+
const writeTokens = Math.min(Number(usageDetail?.cacheWriteTokens || 0), promptTokens - cachedTokens);
|
|
131
|
+
const fullPriceTokens = Math.max(0, promptTokens - cachedTokens - writeTokens);
|
|
132
|
+
const writeMultiplier = Number(usageDetail?.cacheWriteMultiplier || 1.25);
|
|
133
|
+
const promptCost = (fullPriceTokens / 1_000_000) * promptPrice +
|
|
134
|
+
(cachedTokens / 1_000_000) * promptPrice * this.cachedInputMultiplier() +
|
|
135
|
+
(writeTokens / 1_000_000) * promptPrice * writeMultiplier;
|
|
136
|
+
const completionCost = (completionTokens / 1_000_000) * completionPrice;
|
|
137
|
+
return promptCost + completionCost;
|
|
141
138
|
}
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
139
|
+
getMediaPricing(provider = '', model = '', mediaType = 'image') {
|
|
140
|
+
const p = provider.toLowerCase();
|
|
141
|
+
const m = model.toLowerCase();
|
|
142
|
+
if (p === 'muse' || p === 'meta') {
|
|
143
|
+
if (mediaType === 'video_animation')
|
|
144
|
+
return 0;
|
|
145
|
+
return 0.01;
|
|
146
|
+
}
|
|
147
|
+
if (p === 'gemini') {
|
|
148
|
+
if (mediaType === 'video_animation' || m.includes('veo'))
|
|
149
|
+
return 0.05;
|
|
150
|
+
if (m.includes('imagen'))
|
|
151
|
+
return 0.03;
|
|
152
|
+
return 0.03;
|
|
153
|
+
}
|
|
154
|
+
if (p === 'openai') {
|
|
155
|
+
if (mediaType === 'video_animation' || m.includes('sora'))
|
|
156
|
+
return 0.10;
|
|
157
|
+
if (m.includes('dall-e-3'))
|
|
158
|
+
return 0.08;
|
|
159
|
+
return 0.04;
|
|
160
|
+
}
|
|
161
|
+
if (p === 'qwen' || p === 'dashscope') {
|
|
162
|
+
if (mediaType === 'video_animation' || m.includes('wanx') || m.includes('wan2'))
|
|
163
|
+
return 0.04;
|
|
164
|
+
return 0.02;
|
|
165
|
+
}
|
|
166
|
+
if (p === 'pollinations' || p === 'local') {
|
|
167
|
+
return 0.00;
|
|
168
|
+
}
|
|
169
|
+
if (p === 'acp' || p.startsWith('acp/') || p === 'antigravity' || p === 'agy') {
|
|
170
|
+
return 0.00;
|
|
171
|
+
}
|
|
172
|
+
return 0.03;
|
|
146
173
|
}
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
174
|
+
async trackMediaUsage(provider, mediaType, model, quantityUnits = 1, onWarning = null) {
|
|
175
|
+
this.config = loadConfig();
|
|
176
|
+
this.budget = this.config.tokenBudget || { enabled: false };
|
|
177
|
+
const unitPrice = this.getMediaPricing(provider, model, mediaType);
|
|
178
|
+
const cost = unitPrice * (quantityUnits || 1);
|
|
179
|
+
const equivalentTokens = Math.round(cost / 0.000002);
|
|
180
|
+
this.taskTokens += equivalentTokens;
|
|
181
|
+
this.taskCostUsd += cost;
|
|
182
|
+
const cumulative = await this.getCumulativeUsage();
|
|
183
|
+
const daily = await this.getDailyUsage();
|
|
184
|
+
daily.totalTokens += equivalentTokens;
|
|
185
|
+
daily.totalCalls += 1;
|
|
186
|
+
daily.totalCostUsd = (daily.totalCostUsd || 0) + cost;
|
|
187
|
+
await this.saveDailyUsage(daily);
|
|
188
|
+
cumulative.totalTokens += equivalentTokens;
|
|
189
|
+
cumulative.totalCalls += 1;
|
|
190
|
+
cumulative.totalCostUsd = (cumulative.totalCostUsd || 0) + cost;
|
|
191
|
+
await this.saveCumulativeUsage(cumulative);
|
|
192
|
+
if (!this.budget.enabled) {
|
|
193
|
+
return { allowed: true, used: daily.totalTokens, costUsd: daily.totalCostUsd, taskCostUsd: this.taskCostUsd, equivalentTokens };
|
|
194
|
+
}
|
|
195
|
+
if (this.budget.maxCostUsd && daily.totalCostUsd > this.budget.maxCostUsd) {
|
|
196
|
+
if (this.budget.hardStop) {
|
|
197
|
+
return {
|
|
198
|
+
allowed: false,
|
|
199
|
+
reason: `BYOK Monetary Kill-Switch Activated: Media generation cost ($${cost.toFixed(2)}) pushes total spend to $${daily.totalCostUsd.toFixed(2)}, exceeding your $${this.budget.maxCostUsd.toFixed(2)} limit.`,
|
|
200
|
+
used: daily.totalTokens,
|
|
201
|
+
costUsd: daily.totalCostUsd,
|
|
202
|
+
taskCostUsd: this.taskCostUsd,
|
|
203
|
+
equivalentTokens
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
await this.checkAndTriggerAlerts(daily, onWarning);
|
|
208
|
+
return { allowed: true, used: daily.totalTokens, costUsd: daily.totalCostUsd, taskCostUsd: this.taskCostUsd, equivalentTokens };
|
|
154
209
|
}
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
// of the model, not the vendor.
|
|
170
|
-
const model = this.config.model?.toLowerCase() || '';
|
|
171
|
-
if (model.includes('fable-5-1')) return 0.025;
|
|
172
|
-
return 0.1;
|
|
210
|
+
async checkAndTriggerAlerts(daily, onWarning = null) {
|
|
211
|
+
if (!this.budget.enabled)
|
|
212
|
+
return;
|
|
213
|
+
const alertThreshold = this.budget.alertThresholdTokens
|
|
214
|
+
? Number(this.budget.alertThresholdTokens)
|
|
215
|
+
: (this.budget.maxTokensPerDay && this.budget.warningThreshold ? this.budget.maxTokensPerDay * this.budget.warningThreshold : null);
|
|
216
|
+
if (alertThreshold && alertThreshold > 0 && daily.totalTokens >= alertThreshold && !daily.alertSent) {
|
|
217
|
+
daily.alertSent = true;
|
|
218
|
+
await this.saveDailyUsage(daily);
|
|
219
|
+
const msg = `⚠️ Token Budget Alert: Your BYOK usage has reached ${daily.totalTokens.toLocaleString()} tokens (Threshold: ${alertThreshold.toLocaleString()}).`;
|
|
220
|
+
if (onWarning) {
|
|
221
|
+
onWarning(msg);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
173
224
|
}
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
// $0.10 on Contributor is 0.02x. Collapsing both into one vendor number
|
|
179
|
-
// would over-charge a Contributor run by six times on every cached token.
|
|
180
|
-
if (provider === 'muse' || provider === 'meta') {
|
|
181
|
-
const model = this.config.model?.toLowerCase() || '';
|
|
182
|
-
return model.includes('-contributor') ? 0.02 : 0.12;
|
|
225
|
+
ensureUsageDir() {
|
|
226
|
+
if (!fs.existsSync(USAGE_DIR)) {
|
|
227
|
+
fs.mkdirSync(USAGE_DIR, { recursive: true });
|
|
228
|
+
}
|
|
183
229
|
}
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
// a 90% discount, not the 0.5x the rest of this vendor falls back to.
|
|
187
|
-
// Found while verifying the getPricing() rows above; charging 0.5x
|
|
188
|
-
// overstated every cached Astra token FIVEFOLD.
|
|
189
|
-
if (provider === 'openai') {
|
|
190
|
-
const model = this.config.model?.toLowerCase() || '';
|
|
191
|
-
if (model.includes('astra')) return 0.1;
|
|
230
|
+
getDailyFile() {
|
|
231
|
+
return path.join(USAGE_DIR, `${localDateKey()}.json`);
|
|
192
232
|
}
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
// verified against the GPT-5.6 family's current rate card; left as-is
|
|
196
|
-
// rather than guessed at, since overstating is the safer error direction
|
|
197
|
-
// for a number the user reads as a bill.
|
|
198
|
-
return 0.5;
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
/**
|
|
202
|
-
* @param {number} promptTokens Total input tokens (cached + uncached).
|
|
203
|
-
* @param {number} completionTokens Output tokens.
|
|
204
|
-
* @param {object} usageDetail Optional { cachedPromptTokens, cacheWriteTokens }.
|
|
205
|
-
*/
|
|
206
|
-
calculateCost(promptTokens, completionTokens, usageDetail = null) {
|
|
207
|
-
// promptTokens decides the rate card on providers with a context tier.
|
|
208
|
-
const [promptPrice, completionPrice] = this.getPricing(promptTokens);
|
|
209
|
-
|
|
210
|
-
const cachedTokens = Math.min(usageDetail?.cachedPromptTokens || 0, promptTokens);
|
|
211
|
-
const writeTokens = Math.min(usageDetail?.cacheWriteTokens || 0, promptTokens - cachedTokens);
|
|
212
|
-
const fullPriceTokens = Math.max(0, promptTokens - cachedTokens - writeTokens);
|
|
213
|
-
|
|
214
|
-
const writeMultiplier = usageDetail?.cacheWriteMultiplier || 1.25;
|
|
215
|
-
const promptCost =
|
|
216
|
-
(fullPriceTokens / 1_000_000) * promptPrice +
|
|
217
|
-
(cachedTokens / 1_000_000) * promptPrice * this.cachedInputMultiplier() +
|
|
218
|
-
(writeTokens / 1_000_000) * promptPrice * writeMultiplier;
|
|
219
|
-
|
|
220
|
-
const completionCost = (completionTokens / 1_000_000) * completionPrice;
|
|
221
|
-
return promptCost + completionCost;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
// Cost per item (image) or per second (video_animation) in USD (2026 Pricing)
|
|
225
|
-
getMediaPricing(provider = '', model = '', mediaType = 'image') {
|
|
226
|
-
const p = provider.toLowerCase();
|
|
227
|
-
const m = model.toLowerCase();
|
|
228
|
-
|
|
229
|
-
// Muse Image is a flat per-image rate; there is no video model in the
|
|
230
|
-
// family, so a video request must not silently bill at the image rate.
|
|
231
|
-
if (p === 'muse' || p === 'meta') {
|
|
232
|
-
if (mediaType === 'video_animation') return 0;
|
|
233
|
-
return 0.01; // $0.01 per image
|
|
233
|
+
getCumulativeFile() {
|
|
234
|
+
return path.join(USAGE_DIR, 'byok_cumulative.json');
|
|
234
235
|
}
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
236
|
+
async getDailyUsage() {
|
|
237
|
+
const file = this.getDailyFile();
|
|
238
|
+
if (fs.existsSync(file)) {
|
|
239
|
+
try {
|
|
240
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
// Parse error fallback
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return { date: localDateKey(), totalTokens: 0, totalCalls: 0, totalCostUsd: 0 };
|
|
240
247
|
}
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
248
|
+
async getCumulativeUsage() {
|
|
249
|
+
const file = this.getCumulativeFile();
|
|
250
|
+
if (fs.existsSync(file)) {
|
|
251
|
+
try {
|
|
252
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
// Parse error fallback
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
let totalTokens = 0;
|
|
259
|
+
let totalCalls = 0;
|
|
260
|
+
let totalCostUsd = 0;
|
|
261
|
+
try {
|
|
262
|
+
if (fs.existsSync(USAGE_DIR)) {
|
|
263
|
+
const files = fs.readdirSync(USAGE_DIR);
|
|
264
|
+
for (const f of files) {
|
|
265
|
+
if (/^\d{4}-\d{2}-\d{2}\.json$/.test(f)) {
|
|
266
|
+
try {
|
|
267
|
+
const data = JSON.parse(fs.readFileSync(path.join(USAGE_DIR, f), 'utf8'));
|
|
268
|
+
totalTokens += (data.totalTokens || 0);
|
|
269
|
+
totalCalls += (data.totalCalls || 0);
|
|
270
|
+
totalCostUsd += (data.totalCostUsd || 0);
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
// Ignore single unreadable file
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
// Ignore scan failure
|
|
281
|
+
}
|
|
282
|
+
const initialCumulative = { totalTokens, totalCalls, totalCostUsd, backfilled: true, lastUpdated: new Date().toISOString() };
|
|
283
|
+
try {
|
|
284
|
+
writeUsageFile(file, initialCumulative);
|
|
285
|
+
}
|
|
286
|
+
catch {
|
|
287
|
+
// Ignore initial write error
|
|
288
|
+
}
|
|
289
|
+
return initialCumulative;
|
|
245
290
|
}
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
return 0.02; // $0.02 per image
|
|
291
|
+
async saveDailyUsage(usage) {
|
|
292
|
+
writeUsageFile(this.getDailyFile(), usage);
|
|
249
293
|
}
|
|
250
|
-
|
|
251
|
-
|
|
294
|
+
async saveCumulativeUsage(usage) {
|
|
295
|
+
writeUsageFile(this.getCumulativeFile(), usage);
|
|
252
296
|
}
|
|
253
|
-
|
|
254
|
-
|
|
297
|
+
async resetDailyUsage() {
|
|
298
|
+
const file = this.getDailyFile();
|
|
299
|
+
if (fs.existsSync(file)) {
|
|
300
|
+
fs.unlinkSync(file);
|
|
301
|
+
}
|
|
255
302
|
}
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
this.budget = this.config.tokenBudget || { enabled: false };
|
|
262
|
-
|
|
263
|
-
const unitPrice = this.getMediaPricing(provider, model, mediaType);
|
|
264
|
-
const cost = unitPrice * (quantityUnits || 1);
|
|
265
|
-
|
|
266
|
-
// Multimedia Equivalent Units (MEU): convert dollar cost to equivalent tokens ($0.000002/token ~ $2/1M tokens)
|
|
267
|
-
const equivalentTokens = Math.round(cost / 0.000002);
|
|
268
|
-
|
|
269
|
-
this.taskTokens += equivalentTokens;
|
|
270
|
-
this.taskCostUsd += cost;
|
|
271
|
-
|
|
272
|
-
// Read the cumulative total before writing today's file. getCumulativeUsage()
|
|
273
|
-
// backfills from the daily files when its own file is missing, so loading it
|
|
274
|
-
// after the daily increment counted this same call twice.
|
|
275
|
-
const cumulative = await this.getCumulativeUsage();
|
|
276
|
-
const daily = await this.getDailyUsage();
|
|
277
|
-
daily.totalTokens += equivalentTokens;
|
|
278
|
-
daily.totalCalls += 1;
|
|
279
|
-
daily.totalCostUsd = (daily.totalCostUsd || 0) + cost;
|
|
280
|
-
await this.saveDailyUsage(daily);
|
|
281
|
-
|
|
282
|
-
cumulative.totalTokens += equivalentTokens;
|
|
283
|
-
cumulative.totalCalls += 1;
|
|
284
|
-
cumulative.totalCostUsd = (cumulative.totalCostUsd || 0) + cost;
|
|
285
|
-
await this.saveCumulativeUsage(cumulative);
|
|
286
|
-
|
|
287
|
-
if (!this.budget.enabled) {
|
|
288
|
-
return { allowed: true, used: daily.totalTokens, costUsd: daily.totalCostUsd, taskCostUsd: this.taskCostUsd, equivalentTokens };
|
|
303
|
+
async resetCumulativeUsage() {
|
|
304
|
+
const file = this.getCumulativeFile();
|
|
305
|
+
if (fs.existsSync(file)) {
|
|
306
|
+
fs.unlinkSync(file);
|
|
307
|
+
}
|
|
289
308
|
}
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
if (this.budget.hardStop) {
|
|
309
|
+
async getReportedUsage() {
|
|
310
|
+
const daily = await this.getDailyUsage();
|
|
311
|
+
const cumulative = await this.getCumulativeUsage();
|
|
294
312
|
return {
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
313
|
+
usedTokens: daily.totalTokens,
|
|
314
|
+
dailyTokens: daily.totalTokens,
|
|
315
|
+
taskTokens: this.taskTokens,
|
|
316
|
+
lifetimeTokens: cumulative.totalTokens,
|
|
317
|
+
costUsd: daily.totalCostUsd,
|
|
318
|
+
taskCostUsd: this.taskCostUsd,
|
|
319
|
+
lifetimeCostUsd: cumulative.totalCostUsd,
|
|
320
|
+
isDemo: false
|
|
301
321
|
};
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
await this.checkAndTriggerAlerts(daily, onWarning);
|
|
306
|
-
return { allowed: true, used: daily.totalTokens, costUsd: daily.totalCostUsd, taskCostUsd: this.taskCostUsd, equivalentTokens };
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
async checkAndTriggerAlerts(daily, onWarning = null) {
|
|
310
|
-
if (!this.budget.enabled) return;
|
|
311
|
-
|
|
312
|
-
const alertThreshold = this.budget.alertThresholdTokens
|
|
313
|
-
? Number(this.budget.alertThresholdTokens)
|
|
314
|
-
: (this.budget.maxTokensPerDay && this.budget.warningThreshold ? this.budget.maxTokensPerDay * this.budget.warningThreshold : null);
|
|
315
|
-
|
|
316
|
-
if (alertThreshold && alertThreshold > 0 && daily.totalTokens >= alertThreshold && !daily.alertSent) {
|
|
317
|
-
daily.alertSent = true;
|
|
318
|
-
await this.saveDailyUsage(daily);
|
|
319
|
-
|
|
320
|
-
const msg = `⚠️ Token Budget Alert: Your BYOK usage has reached ${daily.totalTokens.toLocaleString()} tokens (Threshold: ${alertThreshold.toLocaleString()}).`;
|
|
321
|
-
if (onWarning) {
|
|
322
|
-
onWarning(msg);
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
ensureUsageDir() {
|
|
328
|
-
if (!fs.existsSync(USAGE_DIR)) {
|
|
329
|
-
fs.mkdirSync(USAGE_DIR, { recursive: true });
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
getDailyFile() {
|
|
334
|
-
return path.join(USAGE_DIR, `${localDateKey()}.json`);
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
getCumulativeFile() {
|
|
338
|
-
return path.join(USAGE_DIR, 'byok_cumulative.json');
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
async getDailyUsage() {
|
|
343
|
-
const file = this.getDailyFile();
|
|
344
|
-
if (fs.existsSync(file)) {
|
|
345
|
-
try {
|
|
346
|
-
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
347
|
-
} catch(e) {}
|
|
348
|
-
}
|
|
349
|
-
return { date: localDateKey(), totalTokens: 0, totalCalls: 0, totalCostUsd: 0 };
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
async getCumulativeUsage() {
|
|
353
|
-
const file = this.getCumulativeFile();
|
|
354
|
-
if (fs.existsSync(file)) {
|
|
355
|
-
try {
|
|
356
|
-
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
357
|
-
} catch(e) {}
|
|
358
322
|
}
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
}
|
|
379
|
-
} catch (err) {}
|
|
380
|
-
|
|
381
|
-
const initialCumulative = { totalTokens, totalCalls, totalCostUsd, backfilled: true, lastUpdated: new Date().toISOString() };
|
|
382
|
-
try {
|
|
383
|
-
writeUsageFile(file, initialCumulative);
|
|
384
|
-
} catch (err) {}
|
|
385
|
-
return initialCumulative;
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
async saveDailyUsage(usage) {
|
|
390
|
-
writeUsageFile(this.getDailyFile(), usage);
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
async saveCumulativeUsage(usage) {
|
|
394
|
-
writeUsageFile(this.getCumulativeFile(), usage);
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
async resetDailyUsage() {
|
|
399
|
-
const file = this.getDailyFile();
|
|
400
|
-
if (fs.existsSync(file)) {
|
|
401
|
-
fs.unlinkSync(file);
|
|
402
|
-
}
|
|
403
|
-
// DO NOT reset cumulative usage here, keeping lifetime tracking separate from fresh budget.
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
async resetCumulativeUsage() {
|
|
407
|
-
const file = this.getCumulativeFile();
|
|
408
|
-
if (fs.existsSync(file)) {
|
|
409
|
-
fs.unlinkSync(file);
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
async getReportedUsage() {
|
|
414
|
-
const daily = await this.getDailyUsage();
|
|
415
|
-
const cumulative = await this.getCumulativeUsage();
|
|
416
|
-
return {
|
|
417
|
-
usedTokens: daily.totalTokens, // UI budget tracks against daily "Fresh" setup
|
|
418
|
-
dailyTokens: daily.totalTokens,
|
|
419
|
-
taskTokens: this.taskTokens,
|
|
420
|
-
lifetimeTokens: cumulative.totalTokens,
|
|
421
|
-
costUsd: daily.totalCostUsd, // UI estimated cost tracks against daily "Fresh" setup
|
|
422
|
-
taskCostUsd: this.taskCostUsd,
|
|
423
|
-
lifetimeCostUsd: cumulative.totalCostUsd,
|
|
424
|
-
isDemo: false
|
|
425
|
-
};
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
/**
|
|
429
|
-
* Can the loop afford ANOTHER step without breaching the task ceiling?
|
|
430
|
-
*
|
|
431
|
-
* WHY THIS EXISTS. trackUsage() checks `taskTokens > maxTokensPerTask` AFTER
|
|
432
|
-
* a call has already been paid for, so the run always overshoots by one step.
|
|
433
|
-
* With ~9,000-token steps a 299,000 ceiling lands at ~308,000 — which breaks
|
|
434
|
-
* the only promise a token cap makes. Asked BEFORE the call, using the
|
|
435
|
-
* largest step seen so far, the ceiling actually holds.
|
|
436
|
-
*
|
|
437
|
-
* The largest step rather than the average, deliberately: a cap that holds
|
|
438
|
-
* on average is a cap that fails on the step that matters.
|
|
439
|
-
*
|
|
440
|
-
* @returns {{allowed:boolean, reason?:string, used:number, limit:number, projected:number}}
|
|
441
|
-
*/
|
|
442
|
-
canAffordAnotherStep() {
|
|
443
|
-
const limit = this.budget && this.budget.enabled && this.budget.hardStop
|
|
444
|
-
? Number(this.budget.maxTokensPerTask || 0)
|
|
445
|
-
: 0;
|
|
446
|
-
if (!limit) return { allowed: true, used: this.taskTokens, limit: 0, projected: this.taskTokens };
|
|
447
|
-
|
|
448
|
-
// Before the first step there is nothing to extrapolate from; let it run.
|
|
449
|
-
const step = this.largestStepTokens || 0;
|
|
450
|
-
const projected = this.taskTokens + step;
|
|
451
|
-
if (step > 0 && projected > limit) {
|
|
452
|
-
return {
|
|
453
|
-
allowed: false,
|
|
454
|
-
reason: `Stopping before the next step would breach the task ceiling: ${this.taskTokens.toLocaleString()} used, `
|
|
455
|
-
+ `the largest step so far was ${step.toLocaleString()}, and ${projected.toLocaleString()} would exceed the ${limit.toLocaleString()} limit.`,
|
|
456
|
-
used: this.taskTokens, limit, projected
|
|
457
|
-
};
|
|
458
|
-
}
|
|
459
|
-
return { allowed: true, used: this.taskTokens, limit, projected };
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
resetTask() {
|
|
463
|
-
this.taskTokens = 0;
|
|
464
|
-
this.taskCostUsd = 0;
|
|
465
|
-
this.largestStepTokens = 0;
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
settle(extra, daily, cumulative) {
|
|
470
|
-
return {
|
|
471
|
-
// Daily scope — what the budget bar and the daily limiter both measure.
|
|
472
|
-
usedTokens: daily.totalTokens,
|
|
473
|
-
dailyTokens: daily.totalTokens,
|
|
474
|
-
dailyCostUsd: daily.totalCostUsd || 0,
|
|
475
|
-
dailyLimit: Number(this.budget && this.budget.maxTokensPerDay) || 0,
|
|
476
|
-
// Task scope — what this run has spent.
|
|
477
|
-
taskTokens: this.taskTokens,
|
|
478
|
-
taskCostUsd: this.taskCostUsd,
|
|
479
|
-
taskLimit: Number(this.budget && this.budget.maxTokensPerTask) || 0,
|
|
480
|
-
// Lifetime scope.
|
|
481
|
-
lifetimeTokens: cumulative.totalTokens,
|
|
482
|
-
lifetimeCostUsd: cumulative.totalCostUsd,
|
|
483
|
-
// Retained for clients built against the older frame. It has always been
|
|
484
|
-
// the daily cost on the allowed path, so it keeps that meaning here
|
|
485
|
-
// rather than acquiring a third one.
|
|
486
|
-
costUsd: daily.totalCostUsd || 0,
|
|
487
|
-
used: this.taskTokens,
|
|
488
|
-
...extra
|
|
489
|
-
};
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
async trackUsage(promptTokens, completionTokens, onWarning = null, usageDetail = null) {
|
|
493
|
-
// Dynamically reload config to apply live budget updates from UI
|
|
494
|
-
this.config = loadConfig();
|
|
495
|
-
this.budget = this.config.tokenBudget || { enabled: false };
|
|
496
|
-
|
|
497
|
-
const total = (promptTokens || 0) + (completionTokens || 0);
|
|
498
|
-
this.taskTokens += total;
|
|
499
|
-
// Feeds canAffordAnotherStep(). The LARGEST step, not the average: a
|
|
500
|
-
// ceiling that holds on average is a ceiling that fails on the step that
|
|
501
|
-
// matters, and every step is bigger than the last as the window grows.
|
|
502
|
-
this.largestStepTokens = Math.max(this.largestStepTokens || 0, total);
|
|
503
|
-
|
|
504
|
-
const cost = this.calculateCost(promptTokens, completionTokens, usageDetail);
|
|
505
|
-
this.taskCostUsd += cost;
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
// Normal BYOK Tracking.
|
|
510
|
-
//
|
|
511
|
-
// Read-modify-write, so it runs inside the lock. Outside it, a condenser
|
|
512
|
-
// pass firing concurrently with the loop silently subtracts its own tokens
|
|
513
|
-
// from the day's total.
|
|
514
|
-
const { daily, cumulative } = await withUsageLock(async () => {
|
|
515
|
-
// getCumulativeUsage() backfills from the daily files when its own file is
|
|
516
|
-
// missing, so it must be read before today's increment is written or the
|
|
517
|
-
// very first call of a fresh install is counted twice.
|
|
518
|
-
const cumulative = await this.getCumulativeUsage();
|
|
519
|
-
const daily = await this.getDailyUsage();
|
|
520
|
-
daily.totalTokens += total;
|
|
521
|
-
daily.totalCalls += 1;
|
|
522
|
-
daily.totalCostUsd = (daily.totalCostUsd || 0) + cost;
|
|
523
|
-
await this.saveDailyUsage(daily);
|
|
524
|
-
|
|
525
|
-
cumulative.totalTokens += total;
|
|
526
|
-
cumulative.totalCalls += 1;
|
|
527
|
-
cumulative.totalCostUsd = (cumulative.totalCostUsd || 0) + cost;
|
|
528
|
-
await this.saveCumulativeUsage(cumulative);
|
|
529
|
-
|
|
530
|
-
return { daily, cumulative };
|
|
531
|
-
});
|
|
532
|
-
|
|
533
|
-
if (!this.budget.enabled) {
|
|
534
|
-
return this.settle({ allowed: true }, daily, cumulative);
|
|
323
|
+
canAffordAnotherStep() {
|
|
324
|
+
const limit = this.budget && this.budget.enabled && this.budget.hardStop
|
|
325
|
+
? Number(this.budget.maxTokensPerTask || 0)
|
|
326
|
+
: 0;
|
|
327
|
+
if (!limit)
|
|
328
|
+
return { allowed: true, used: this.taskTokens, limit: 0, projected: this.taskTokens };
|
|
329
|
+
const step = this.largestStepTokens || 0;
|
|
330
|
+
const projected = this.taskTokens + step;
|
|
331
|
+
if (step > 0 && projected > limit) {
|
|
332
|
+
return {
|
|
333
|
+
allowed: false,
|
|
334
|
+
reason: `Stopping before the next step would breach the task ceiling: ${this.taskTokens.toLocaleString()} used, `
|
|
335
|
+
+ `the largest step so far was ${step.toLocaleString()}, and ${projected.toLocaleString()} would exceed the ${limit.toLocaleString()} limit.`,
|
|
336
|
+
used: this.taskTokens, limit, projected
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
return { allowed: true, used: this.taskTokens, limit, projected };
|
|
535
340
|
}
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
return this.settle({
|
|
541
|
-
allowed: false,
|
|
542
|
-
reason: `BYOK Monetary Kill-Switch Activated: You have spent $${daily.totalCostUsd.toFixed(2)}, which exceeds your $${this.budget.maxCostUsd.toFixed(2)} limit.`
|
|
543
|
-
}, daily, cumulative);
|
|
544
|
-
}
|
|
341
|
+
resetTask() {
|
|
342
|
+
this.taskTokens = 0;
|
|
343
|
+
this.taskCostUsd = 0;
|
|
344
|
+
this.largestStepTokens = 0;
|
|
545
345
|
}
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
346
|
+
settle(extra, daily, cumulative) {
|
|
347
|
+
return {
|
|
348
|
+
usedTokens: daily.totalTokens,
|
|
349
|
+
dailyTokens: daily.totalTokens,
|
|
350
|
+
dailyCostUsd: daily.totalCostUsd || 0,
|
|
351
|
+
dailyLimit: Number(this.budget && this.budget.maxTokensPerDay) || 0,
|
|
352
|
+
taskTokens: this.taskTokens,
|
|
353
|
+
taskCostUsd: this.taskCostUsd,
|
|
354
|
+
taskLimit: Number(this.budget && this.budget.maxTokensPerTask) || 0,
|
|
355
|
+
lifetimeTokens: cumulative.totalTokens,
|
|
356
|
+
lifetimeCostUsd: cumulative.totalCostUsd,
|
|
357
|
+
costUsd: daily.totalCostUsd || 0,
|
|
358
|
+
used: this.taskTokens,
|
|
359
|
+
allowed: true,
|
|
360
|
+
...extra
|
|
361
|
+
};
|
|
556
362
|
}
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
363
|
+
async trackUsage(promptTokens, completionTokens, onWarning = null, usageDetail = null) {
|
|
364
|
+
this.config = loadConfig();
|
|
365
|
+
this.budget = this.config.tokenBudget || { enabled: false };
|
|
366
|
+
const finite = (v) => (Number.isFinite(v) ? Math.max(0, Number(v)) : 0);
|
|
367
|
+
const pTokens = finite(promptTokens);
|
|
368
|
+
const cTokens = finite(completionTokens);
|
|
369
|
+
let freshInput = pTokens;
|
|
370
|
+
let cachedTokens = 0;
|
|
371
|
+
if (usageDetail) {
|
|
372
|
+
if (usageDetail.uncachedPromptTokens !== undefined) {
|
|
373
|
+
freshInput = finite(usageDetail.uncachedPromptTokens);
|
|
374
|
+
cachedTokens = finite(usageDetail.cachedPromptTokens);
|
|
375
|
+
}
|
|
376
|
+
else if (usageDetail.cachedPromptTokens !== undefined) {
|
|
377
|
+
cachedTokens = finite(usageDetail.cachedPromptTokens);
|
|
378
|
+
if (cachedTokens > pTokens) {
|
|
379
|
+
freshInput = pTokens;
|
|
380
|
+
}
|
|
381
|
+
else {
|
|
382
|
+
freshInput = Math.max(0, pTokens - cachedTokens);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
const freshStep = freshInput + cTokens;
|
|
387
|
+
this.taskTokens += freshStep;
|
|
388
|
+
this.largestStepTokens = Math.max(this.largestStepTokens || 0, freshStep);
|
|
389
|
+
const cost = this.calculateCost(promptTokens, completionTokens, usageDetail);
|
|
390
|
+
this.taskCostUsd += cost;
|
|
391
|
+
const { daily, cumulative } = await withUsageLock(async () => {
|
|
392
|
+
const cumulative = await this.getCumulativeUsage();
|
|
393
|
+
const daily = await this.getDailyUsage();
|
|
394
|
+
daily.totalTokens += freshStep;
|
|
395
|
+
daily.totalCalls += 1;
|
|
396
|
+
daily.totalCostUsd = (daily.totalCostUsd || 0) + cost;
|
|
397
|
+
if (cachedTokens > 0) {
|
|
398
|
+
daily.cachedTokens = (daily.cachedTokens || 0) + cachedTokens;
|
|
399
|
+
}
|
|
400
|
+
await this.saveDailyUsage(daily);
|
|
401
|
+
cumulative.totalTokens += freshStep;
|
|
402
|
+
cumulative.totalCalls += 1;
|
|
403
|
+
cumulative.totalCostUsd = (cumulative.totalCostUsd || 0) + cost;
|
|
404
|
+
if (cachedTokens > 0) {
|
|
405
|
+
cumulative.cachedTokens = (cumulative.cachedTokens || 0) + cachedTokens;
|
|
406
|
+
}
|
|
407
|
+
await this.saveCumulativeUsage(cumulative);
|
|
408
|
+
return { daily, cumulative };
|
|
409
|
+
});
|
|
410
|
+
if (!this.budget.enabled) {
|
|
411
|
+
return this.settle({ allowed: true }, daily, cumulative);
|
|
412
|
+
}
|
|
413
|
+
if (this.budget.maxCostUsd && daily.totalCostUsd > this.budget.maxCostUsd) {
|
|
414
|
+
if (this.budget.hardStop) {
|
|
415
|
+
return this.settle({
|
|
416
|
+
allowed: false,
|
|
417
|
+
reason: `BYOK Monetary Kill-Switch Activated: You have spent $${daily.totalCostUsd.toFixed(2)}, which exceeds your $${this.budget.maxCostUsd.toFixed(2)} limit.`
|
|
418
|
+
}, daily, cumulative);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
if (this.budget.maxTokensPerTask && this.taskTokens > this.budget.maxTokensPerTask) {
|
|
422
|
+
if (this.budget.hardStop) {
|
|
423
|
+
return this.settle({
|
|
424
|
+
allowed: false,
|
|
425
|
+
reason: `Task token budget reached: ${this.taskTokens.toLocaleString()} of ${Number(this.budget.maxTokensPerTask).toLocaleString()} tokens for this task.`,
|
|
426
|
+
limit: this.budget.maxTokensPerTask
|
|
427
|
+
}, daily, cumulative);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
if (this.budget.maxTokensPerDay && daily.totalTokens > this.budget.maxTokensPerDay) {
|
|
431
|
+
if (this.budget.hardStop) {
|
|
432
|
+
return this.settle({
|
|
433
|
+
allowed: false,
|
|
434
|
+
reason: `Daily token budget reached: ${daily.totalTokens.toLocaleString()} of ${Number(this.budget.maxTokensPerDay).toLocaleString()} tokens used today.`,
|
|
435
|
+
limit: this.budget.maxTokensPerDay
|
|
436
|
+
}, daily, cumulative);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
await this.checkAndTriggerAlerts(daily, onWarning);
|
|
440
|
+
return this.settle({ allowed: true }, daily, cumulative);
|
|
569
441
|
}
|
|
570
|
-
|
|
571
|
-
await this.checkAndTriggerAlerts(daily, onWarning);
|
|
572
|
-
|
|
573
|
-
return this.settle({ allowed: true }, daily, cumulative);
|
|
574
|
-
}
|
|
575
442
|
}
|