@causyne/agent 1.20.10 → 1.20.12

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.
Files changed (88) hide show
  1. package/LICENSE +1 -1
  2. package/docs/ARCHITECTURE.md +24 -1
  3. package/package.json +1 -1
  4. package/src/acp/client.js +9 -2
  5. package/src/acp/client.ts +11 -2
  6. package/src/acp/protocol.ts +9 -0
  7. package/src/agentLoop.js +504 -119
  8. package/src/agentLoop.ts +477 -121
  9. package/src/browser/browserRuntime.js +47 -0
  10. package/src/browser/browserRuntime.ts +45 -0
  11. package/src/browser/causyneBrowser.js +60 -31
  12. package/src/browser/causyneBrowser.ts +37 -12
  13. package/src/browser/workspacePreview.js +52 -0
  14. package/src/browser/workspacePreview.ts +49 -0
  15. package/src/core/planCache.js +5 -0
  16. package/src/core/planCache.ts +5 -0
  17. package/src/decisionPolicy.js +9 -0
  18. package/src/decisionPolicy.ts +8 -0
  19. package/src/historyPruner.js +251 -0
  20. package/src/historyPruner.ts +263 -0
  21. package/src/infra/atomicWriter.js +49 -0
  22. package/src/infra/atomicWriter.ts +63 -0
  23. package/src/infra/telemetry.js +38 -0
  24. package/src/infra/telemetry.ts +68 -0
  25. package/src/observer/coldObserver.js +12 -7
  26. package/src/observer/coldObserver.ts +12 -7
  27. package/src/observer/evidence.js +8 -2
  28. package/src/observer/evidence.ts +9 -2
  29. package/src/outputRecovery.js +36 -0
  30. package/src/outputRecovery.ts +33 -0
  31. package/src/providers/acp.js +114 -46
  32. package/src/providers/acp.ts +129 -46
  33. package/src/providers/antigravity.js +262 -91
  34. package/src/providers/antigravity.ts +270 -99
  35. package/src/providers/antigravityBridge.js +58 -0
  36. package/src/providers/antigravityBridge.ts +51 -0
  37. package/src/providers/base.d.ts +9 -0
  38. package/src/providers/budgetEnforcer.js +110 -0
  39. package/src/providers/budgetEnforcer.ts +122 -0
  40. package/src/providers/collaborationPolicy.js +6 -0
  41. package/src/providers/collaborationPolicy.ts +7 -0
  42. package/src/providers/loopGuard.js +84 -0
  43. package/src/providers/loopGuard.ts +105 -0
  44. package/src/providers/pi.js +19 -6
  45. package/src/providers/pi.ts +19 -7
  46. package/src/providers/toolContracts.js +36 -0
  47. package/src/providers/toolContracts.ts +48 -0
  48. package/src/session/sidechainEvents.js +49 -0
  49. package/src/session/sidechainEvents.ts +98 -0
  50. package/src/skillsManager.d.ts +1 -0
  51. package/src/smartToolsUse.js +123 -4
  52. package/src/smartToolsUse.ts +136 -4
  53. package/src/stallGuard.js +3 -12
  54. package/src/stallGuard.ts +3 -12
  55. package/src/subagent/sidechainHarness.js +66 -0
  56. package/src/subagent/sidechainHarness.ts +91 -0
  57. package/src/taskContinuation.js +12 -0
  58. package/src/taskContinuation.ts +13 -0
  59. package/src/tokenTracker.js +406 -539
  60. package/src/tokenTracker.ts +569 -0
  61. package/src/toolPacks.d.ts +2 -0
  62. package/src/toolPacks.js +1 -1
  63. package/src/tools/argumentValidation.js +56 -0
  64. package/src/tools/argumentValidation.ts +50 -0
  65. package/src/tools/browserAutomator.js +2 -2
  66. package/src/tools/browserAutomator.ts +3 -2
  67. package/src/tools/deferredMcpSearch.js +188 -201
  68. package/src/tools/deferredMcpSearch.ts +250 -0
  69. package/src/tools/generateMediaViaApi.js +305 -331
  70. package/src/tools/generateMediaViaApi.ts +330 -0
  71. package/src/tools/historyPruner.js +5 -0
  72. package/src/tools/historyPruner.ts +5 -0
  73. package/src/tools/payloadSanitizer.js +92 -0
  74. package/src/tools/payloadSanitizer.ts +113 -0
  75. package/src/tools/registry.d.ts +1 -0
  76. package/src/tools/sysRun.js +47 -18
  77. package/src/tools/sysRun.ts +52 -20
  78. package/src/tools/toolOutputStore.js +180 -0
  79. package/src/tools/toolOutputStore.ts +209 -0
  80. package/src/tools/toolSelfRepair.js +26 -1
  81. package/src/tools/toolSelfRepair.ts +25 -1
  82. package/src/tui/chatRenderer.d.ts +1 -0
  83. package/src/tui/chatRenderer.js +4 -2
  84. package/src/tui/codeStreamRenderer.js +36 -8
  85. package/src/tui/codeStreamRenderer.ts +38 -8
  86. package/src/tui/stageSurface.js +1 -0
  87. package/src/tui/text.js +4 -1
  88. package/src/tokenTracker.d.ts +0 -1
@@ -0,0 +1,569 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { loadConfig } from './config.js';
4
+ import { causyneHome } from './utils/paths.js';
5
+
6
+ const USAGE_DIR = path.join(causyneHome(), 'usage');
7
+
8
+ let usageQueue: Promise<unknown> = Promise.resolve();
9
+ function withUsageLock<T>(fn: () => Promise<T>): Promise<T> {
10
+ const run = usageQueue.then(fn, fn);
11
+ usageQueue = run.then(() => {}, () => {});
12
+ return run;
13
+ }
14
+
15
+ function writeUsageFile(file: string, payload: unknown): void {
16
+ const temp = `${file}.tmp_${process.pid}`;
17
+ fs.writeFileSync(temp, JSON.stringify(payload, null, 2), { encoding: 'utf8', mode: 0o600 });
18
+ fs.renameSync(temp, file);
19
+ }
20
+
21
+ function localDateKey(when: Date = new Date()): string {
22
+ const pad = (n: number) => String(n).padStart(2, '0');
23
+ return `${when.getFullYear()}-${pad(when.getMonth() + 1)}-${pad(when.getDate())}`;
24
+ }
25
+
26
+ const ASTRA_LONG_CONTEXT_THRESHOLD = 272000;
27
+
28
+ export interface TokenBudgetConfig {
29
+ enabled?: boolean;
30
+ hardStop?: boolean;
31
+ maxTokensPerDay?: number;
32
+ maxTokensPerTask?: number;
33
+ maxCostUsd?: number;
34
+ alertThresholdTokens?: number;
35
+ warningThreshold?: number;
36
+ }
37
+
38
+ export interface TrackerConfig {
39
+ provider?: string;
40
+ model?: string;
41
+ tokenBudget?: TokenBudgetConfig;
42
+ [key: string]: unknown;
43
+ }
44
+
45
+ export interface UsageDetail {
46
+ cachedPromptTokens?: number;
47
+ cacheWriteTokens?: number;
48
+ cacheWriteMultiplier?: number;
49
+ uncachedPromptTokens?: number;
50
+ [key: string]: unknown;
51
+ }
52
+
53
+ export interface DailyUsage {
54
+ date: string;
55
+ totalTokens: number;
56
+ totalCalls: number;
57
+ totalCostUsd: number;
58
+ cachedTokens?: number;
59
+ alertSent?: boolean;
60
+ [key: string]: unknown;
61
+ }
62
+
63
+ export interface CumulativeUsage {
64
+ totalTokens: number;
65
+ totalCalls: number;
66
+ totalCostUsd: number;
67
+ cachedTokens?: number;
68
+ backfilled?: boolean;
69
+ lastUpdated?: string;
70
+ [key: string]: unknown;
71
+ }
72
+
73
+ export interface AffordStepResult {
74
+ allowed: boolean;
75
+ reason?: string;
76
+ used: number;
77
+ limit: number;
78
+ projected: number;
79
+ }
80
+
81
+ export interface SettledUsage {
82
+ allowed: boolean;
83
+ reason?: string;
84
+ usedTokens: number;
85
+ dailyTokens: number;
86
+ dailyCostUsd: number;
87
+ dailyLimit: number;
88
+ taskTokens: number;
89
+ taskCostUsd: number;
90
+ taskLimit: number;
91
+ lifetimeTokens: number;
92
+ lifetimeCostUsd: number;
93
+ costUsd: number;
94
+ used: number;
95
+ limit?: number;
96
+ equivalentTokens?: number;
97
+ [key: string]: unknown;
98
+ }
99
+
100
+ export class TokenTracker {
101
+ config: TrackerConfig;
102
+ budget: TokenBudgetConfig;
103
+ taskTokens: number;
104
+ taskCostUsd: number;
105
+ largestStepTokens: number;
106
+
107
+ constructor() {
108
+ this.config = loadConfig() as TrackerConfig;
109
+ this.budget = this.config.tokenBudget || { enabled: false };
110
+ this.taskTokens = 0;
111
+ this.taskCostUsd = 0;
112
+ this.largestStepTokens = 0;
113
+ this.ensureUsageDir();
114
+ }
115
+
116
+ getPricing(promptTokens: number = 0): [number, number] {
117
+ const provider = this.config.provider?.toLowerCase();
118
+ const model = this.config.model?.toLowerCase() || '';
119
+
120
+ if (provider === 'deepseek') {
121
+ if (model.includes('pro')) return [0.435, 0.87];
122
+ if (model.includes('flash')) return [0.14, 0.28];
123
+ return [0.14, 0.28];
124
+ }
125
+
126
+ if (provider === 'muse' || provider === 'meta') {
127
+ if (model.includes('-contributor')) return [0.10, 0.20];
128
+ return [1.25, 4.25];
129
+ }
130
+
131
+ if (provider === 'qwen' || provider === 'dashscope') {
132
+ if (model.includes('max')) return [1.25, 3.75];
133
+ if (model.includes('plus')) return [0.32, 1.28];
134
+ if (model.includes('flash')) return [0.19, 1.13];
135
+ return [0.32, 1.28];
136
+ }
137
+
138
+ if (provider === 'openai') {
139
+ if (model.includes('astra')) {
140
+ return promptTokens > ASTRA_LONG_CONTEXT_THRESHOLD ? [20.00, 75.00] : [10.00, 50.00];
141
+ }
142
+ if (model.includes('sol')) return [5.00, 30.00];
143
+ if (model.includes('terra')) return [2.50, 15.00];
144
+ if (model.includes('luna')) return [1.00, 1.00];
145
+ if (model.includes('mini')) return [0.75, 4.50];
146
+ return [5.00, 30.00];
147
+ }
148
+
149
+ if (provider === 'anthropic') {
150
+ if (model.includes('fable') || model.includes('mythos')) return [10.00, 50.00];
151
+ if (model.includes('opus')) return [5.00, 25.00];
152
+ if (model.includes('sonnet-4-6')) return [3.00, 15.00];
153
+ if (model.includes('sonnet')) return [2.00, 10.00];
154
+ if (model.includes('haiku')) return [1.00, 5.00];
155
+ return [2.00, 10.00];
156
+ }
157
+
158
+ if (provider === 'gemini') {
159
+ if (model.includes('pro')) return [2.00, 12.00];
160
+ if (model.includes('flash-lite')) return [0.25, 1.50];
161
+ if (model.includes('3.6-flash') || model.includes('3-6-flash')) return [1.50, 7.50];
162
+ if (model.includes('flash')) return [1.50, 9.00];
163
+ return [1.50, 9.00];
164
+ }
165
+
166
+ if (provider === 'ollama') {
167
+ return [0.00, 0.00];
168
+ }
169
+
170
+ if (provider === 'acp' || provider?.startsWith('acp/') || provider === 'antigravity' || provider === 'agy') {
171
+ return [0.00, 0.00];
172
+ }
173
+
174
+ return [5.00, 15.00];
175
+ }
176
+
177
+ cachedInputMultiplier(): number {
178
+ const provider = this.config.provider?.toLowerCase();
179
+ if (provider === 'anthropic') {
180
+ const model = this.config.model?.toLowerCase() || '';
181
+ if (model.includes('fable-5-1')) return 0.025;
182
+ return 0.1;
183
+ }
184
+ if (provider === 'deepseek') return 0.1;
185
+
186
+ if (provider === 'muse' || provider === 'meta') {
187
+ const model = this.config.model?.toLowerCase() || '';
188
+ return model.includes('-contributor') ? 0.02 : 0.12;
189
+ }
190
+
191
+ if (provider === 'openai') {
192
+ const model = this.config.model?.toLowerCase() || '';
193
+ if (model.includes('astra')) return 0.1;
194
+ }
195
+
196
+ return 0.5;
197
+ }
198
+
199
+ calculateCost(promptTokens: number, completionTokens: number, usageDetail: UsageDetail | null = null): number {
200
+ const [promptPrice, completionPrice] = this.getPricing(promptTokens);
201
+
202
+ const cachedTokens = Math.min(Number(usageDetail?.cachedPromptTokens || 0), promptTokens);
203
+ const writeTokens = Math.min(Number(usageDetail?.cacheWriteTokens || 0), promptTokens - cachedTokens);
204
+ const fullPriceTokens = Math.max(0, promptTokens - cachedTokens - writeTokens);
205
+
206
+ const writeMultiplier = Number(usageDetail?.cacheWriteMultiplier || 1.25);
207
+ const promptCost =
208
+ (fullPriceTokens / 1_000_000) * promptPrice +
209
+ (cachedTokens / 1_000_000) * promptPrice * this.cachedInputMultiplier() +
210
+ (writeTokens / 1_000_000) * promptPrice * writeMultiplier;
211
+
212
+ const completionCost = (completionTokens / 1_000_000) * completionPrice;
213
+ return promptCost + completionCost;
214
+ }
215
+
216
+ getMediaPricing(provider: string = '', model: string = '', mediaType: string = 'image'): number {
217
+ const p = provider.toLowerCase();
218
+ const m = model.toLowerCase();
219
+
220
+ if (p === 'muse' || p === 'meta') {
221
+ if (mediaType === 'video_animation') return 0;
222
+ return 0.01;
223
+ }
224
+
225
+ if (p === 'gemini') {
226
+ if (mediaType === 'video_animation' || m.includes('veo')) return 0.05;
227
+ if (m.includes('imagen')) return 0.03;
228
+ return 0.03;
229
+ }
230
+ if (p === 'openai') {
231
+ if (mediaType === 'video_animation' || m.includes('sora')) return 0.10;
232
+ if (m.includes('dall-e-3')) return 0.08;
233
+ return 0.04;
234
+ }
235
+ if (p === 'qwen' || p === 'dashscope') {
236
+ if (mediaType === 'video_animation' || m.includes('wanx') || m.includes('wan2')) return 0.04;
237
+ return 0.02;
238
+ }
239
+ if (p === 'pollinations' || p === 'local') {
240
+ return 0.00;
241
+ }
242
+ if (p === 'acp' || p.startsWith('acp/') || p === 'antigravity' || p === 'agy') {
243
+ return 0.00;
244
+ }
245
+ return 0.03;
246
+ }
247
+
248
+ async trackMediaUsage(
249
+ provider: string,
250
+ mediaType: string,
251
+ model: string,
252
+ quantityUnits: number = 1,
253
+ onWarning: ((msg: string) => void) | null = null
254
+ ): Promise<{ allowed: boolean; used: number; costUsd: number; taskCostUsd: number; equivalentTokens: number; reason?: string }> {
255
+ this.config = loadConfig() as TrackerConfig;
256
+ this.budget = this.config.tokenBudget || { enabled: false };
257
+
258
+ const unitPrice = this.getMediaPricing(provider, model, mediaType);
259
+ const cost = unitPrice * (quantityUnits || 1);
260
+
261
+ const equivalentTokens = Math.round(cost / 0.000002);
262
+
263
+ this.taskTokens += equivalentTokens;
264
+ this.taskCostUsd += cost;
265
+
266
+ const cumulative = await this.getCumulativeUsage();
267
+ const daily = await this.getDailyUsage();
268
+ daily.totalTokens += equivalentTokens;
269
+ daily.totalCalls += 1;
270
+ daily.totalCostUsd = (daily.totalCostUsd || 0) + cost;
271
+ await this.saveDailyUsage(daily);
272
+
273
+ cumulative.totalTokens += equivalentTokens;
274
+ cumulative.totalCalls += 1;
275
+ cumulative.totalCostUsd = (cumulative.totalCostUsd || 0) + cost;
276
+ await this.saveCumulativeUsage(cumulative);
277
+
278
+ if (!this.budget.enabled) {
279
+ return { allowed: true, used: daily.totalTokens, costUsd: daily.totalCostUsd, taskCostUsd: this.taskCostUsd, equivalentTokens };
280
+ }
281
+
282
+ if (this.budget.maxCostUsd && daily.totalCostUsd > this.budget.maxCostUsd) {
283
+ if (this.budget.hardStop) {
284
+ return {
285
+ allowed: false,
286
+ 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.`,
287
+ used: daily.totalTokens,
288
+ costUsd: daily.totalCostUsd,
289
+ taskCostUsd: this.taskCostUsd,
290
+ equivalentTokens
291
+ };
292
+ }
293
+ }
294
+
295
+ await this.checkAndTriggerAlerts(daily, onWarning);
296
+ return { allowed: true, used: daily.totalTokens, costUsd: daily.totalCostUsd, taskCostUsd: this.taskCostUsd, equivalentTokens };
297
+ }
298
+
299
+ async checkAndTriggerAlerts(daily: DailyUsage, onWarning: ((msg: string) => void) | null = null): Promise<void> {
300
+ if (!this.budget.enabled) return;
301
+
302
+ const alertThreshold = this.budget.alertThresholdTokens
303
+ ? Number(this.budget.alertThresholdTokens)
304
+ : (this.budget.maxTokensPerDay && this.budget.warningThreshold ? this.budget.maxTokensPerDay * this.budget.warningThreshold : null);
305
+
306
+ if (alertThreshold && alertThreshold > 0 && daily.totalTokens >= alertThreshold && !daily.alertSent) {
307
+ daily.alertSent = true;
308
+ await this.saveDailyUsage(daily);
309
+
310
+ const msg = `⚠️ Token Budget Alert: Your BYOK usage has reached ${daily.totalTokens.toLocaleString()} tokens (Threshold: ${alertThreshold.toLocaleString()}).`;
311
+ if (onWarning) {
312
+ onWarning(msg);
313
+ }
314
+ }
315
+ }
316
+
317
+ ensureUsageDir(): void {
318
+ if (!fs.existsSync(USAGE_DIR)) {
319
+ fs.mkdirSync(USAGE_DIR, { recursive: true });
320
+ }
321
+ }
322
+
323
+ getDailyFile(): string {
324
+ return path.join(USAGE_DIR, `${localDateKey()}.json`);
325
+ }
326
+
327
+ getCumulativeFile(): string {
328
+ return path.join(USAGE_DIR, 'byok_cumulative.json');
329
+ }
330
+
331
+ async getDailyUsage(): Promise<DailyUsage> {
332
+ const file = this.getDailyFile();
333
+ if (fs.existsSync(file)) {
334
+ try {
335
+ return JSON.parse(fs.readFileSync(file, 'utf8')) as DailyUsage;
336
+ } catch {
337
+ // Parse error fallback
338
+ }
339
+ }
340
+ return { date: localDateKey(), totalTokens: 0, totalCalls: 0, totalCostUsd: 0 };
341
+ }
342
+
343
+ async getCumulativeUsage(): Promise<CumulativeUsage> {
344
+ const file = this.getCumulativeFile();
345
+ if (fs.existsSync(file)) {
346
+ try {
347
+ return JSON.parse(fs.readFileSync(file, 'utf8')) as CumulativeUsage;
348
+ } catch {
349
+ // Parse error fallback
350
+ }
351
+ }
352
+
353
+ let totalTokens = 0;
354
+ let totalCalls = 0;
355
+ let totalCostUsd = 0;
356
+ try {
357
+ if (fs.existsSync(USAGE_DIR)) {
358
+ const files = fs.readdirSync(USAGE_DIR);
359
+ for (const f of files) {
360
+ if (/^\d{4}-\d{2}-\d{2}\.json$/.test(f)) {
361
+ try {
362
+ const data = JSON.parse(fs.readFileSync(path.join(USAGE_DIR, f), 'utf8')) as DailyUsage;
363
+ totalTokens += (data.totalTokens || 0);
364
+ totalCalls += (data.totalCalls || 0);
365
+ totalCostUsd += (data.totalCostUsd || 0);
366
+ } catch {
367
+ // Ignore single unreadable file
368
+ }
369
+ }
370
+ }
371
+ }
372
+ } catch {
373
+ // Ignore scan failure
374
+ }
375
+
376
+ const initialCumulative: CumulativeUsage = { totalTokens, totalCalls, totalCostUsd, backfilled: true, lastUpdated: new Date().toISOString() };
377
+ try {
378
+ writeUsageFile(file, initialCumulative);
379
+ } catch {
380
+ // Ignore initial write error
381
+ }
382
+ return initialCumulative;
383
+ }
384
+
385
+ async saveDailyUsage(usage: DailyUsage): Promise<void> {
386
+ writeUsageFile(this.getDailyFile(), usage);
387
+ }
388
+
389
+ async saveCumulativeUsage(usage: CumulativeUsage): Promise<void> {
390
+ writeUsageFile(this.getCumulativeFile(), usage);
391
+ }
392
+
393
+ async resetDailyUsage(): Promise<void> {
394
+ const file = this.getDailyFile();
395
+ if (fs.existsSync(file)) {
396
+ fs.unlinkSync(file);
397
+ }
398
+ }
399
+
400
+ async resetCumulativeUsage(): Promise<void> {
401
+ const file = this.getCumulativeFile();
402
+ if (fs.existsSync(file)) {
403
+ fs.unlinkSync(file);
404
+ }
405
+ }
406
+
407
+ async getReportedUsage(): Promise<{
408
+ usedTokens: number;
409
+ dailyTokens: number;
410
+ taskTokens: number;
411
+ lifetimeTokens: number;
412
+ costUsd: number;
413
+ taskCostUsd: number;
414
+ lifetimeCostUsd: number;
415
+ isDemo: boolean;
416
+ }> {
417
+ const daily = await this.getDailyUsage();
418
+ const cumulative = await this.getCumulativeUsage();
419
+ return {
420
+ usedTokens: daily.totalTokens,
421
+ dailyTokens: daily.totalTokens,
422
+ taskTokens: this.taskTokens,
423
+ lifetimeTokens: cumulative.totalTokens,
424
+ costUsd: daily.totalCostUsd,
425
+ taskCostUsd: this.taskCostUsd,
426
+ lifetimeCostUsd: cumulative.totalCostUsd,
427
+ isDemo: false
428
+ };
429
+ }
430
+
431
+ canAffordAnotherStep(): AffordStepResult {
432
+ const limit = this.budget && this.budget.enabled && this.budget.hardStop
433
+ ? Number(this.budget.maxTokensPerTask || 0)
434
+ : 0;
435
+ if (!limit) return { allowed: true, used: this.taskTokens, limit: 0, projected: this.taskTokens };
436
+
437
+ const step = this.largestStepTokens || 0;
438
+ const projected = this.taskTokens + step;
439
+ if (step > 0 && projected > limit) {
440
+ return {
441
+ allowed: false,
442
+ reason: `Stopping before the next step would breach the task ceiling: ${this.taskTokens.toLocaleString()} used, `
443
+ + `the largest step so far was ${step.toLocaleString()}, and ${projected.toLocaleString()} would exceed the ${limit.toLocaleString()} limit.`,
444
+ used: this.taskTokens, limit, projected
445
+ };
446
+ }
447
+ return { allowed: true, used: this.taskTokens, limit, projected };
448
+ }
449
+
450
+ resetTask(): void {
451
+ this.taskTokens = 0;
452
+ this.taskCostUsd = 0;
453
+ this.largestStepTokens = 0;
454
+ }
455
+
456
+ settle(extra: Record<string, unknown>, daily: DailyUsage, cumulative: CumulativeUsage): SettledUsage {
457
+ return {
458
+ usedTokens: daily.totalTokens,
459
+ dailyTokens: daily.totalTokens,
460
+ dailyCostUsd: daily.totalCostUsd || 0,
461
+ dailyLimit: Number(this.budget && this.budget.maxTokensPerDay) || 0,
462
+ taskTokens: this.taskTokens,
463
+ taskCostUsd: this.taskCostUsd,
464
+ taskLimit: Number(this.budget && this.budget.maxTokensPerTask) || 0,
465
+ lifetimeTokens: cumulative.totalTokens,
466
+ lifetimeCostUsd: cumulative.totalCostUsd,
467
+ costUsd: daily.totalCostUsd || 0,
468
+ used: this.taskTokens,
469
+ allowed: true,
470
+ ...extra
471
+ };
472
+ }
473
+
474
+ async trackUsage(
475
+ promptTokens: number,
476
+ completionTokens: number,
477
+ onWarning: ((msg: string) => void) | null = null,
478
+ usageDetail: UsageDetail | null = null
479
+ ): Promise<SettledUsage> {
480
+ this.config = loadConfig() as TrackerConfig;
481
+ this.budget = this.config.tokenBudget || { enabled: false };
482
+
483
+ const finite = (v: number | undefined | null): number => (Number.isFinite(v) ? Math.max(0, Number(v)) : 0);
484
+ const pTokens = finite(promptTokens);
485
+ const cTokens = finite(completionTokens);
486
+
487
+ let freshInput = pTokens;
488
+ let cachedTokens = 0;
489
+ if (usageDetail) {
490
+ if (usageDetail.uncachedPromptTokens !== undefined) {
491
+ freshInput = finite(usageDetail.uncachedPromptTokens);
492
+ cachedTokens = finite(usageDetail.cachedPromptTokens);
493
+ } else if (usageDetail.cachedPromptTokens !== undefined) {
494
+ cachedTokens = finite(usageDetail.cachedPromptTokens);
495
+ if (cachedTokens > pTokens) {
496
+ freshInput = pTokens;
497
+ } else {
498
+ freshInput = Math.max(0, pTokens - cachedTokens);
499
+ }
500
+ }
501
+ }
502
+ const freshStep = freshInput + cTokens;
503
+
504
+ this.taskTokens += freshStep;
505
+ this.largestStepTokens = Math.max(this.largestStepTokens || 0, freshStep);
506
+
507
+ const cost = this.calculateCost(promptTokens, completionTokens, usageDetail);
508
+ this.taskCostUsd += cost;
509
+
510
+ const { daily, cumulative } = await withUsageLock(async () => {
511
+ const cumulative = await this.getCumulativeUsage();
512
+ const daily = await this.getDailyUsage();
513
+ daily.totalTokens += freshStep;
514
+ daily.totalCalls += 1;
515
+ daily.totalCostUsd = (daily.totalCostUsd || 0) + cost;
516
+ if (cachedTokens > 0) {
517
+ daily.cachedTokens = (daily.cachedTokens || 0) + cachedTokens;
518
+ }
519
+ await this.saveDailyUsage(daily);
520
+
521
+ cumulative.totalTokens += freshStep;
522
+ cumulative.totalCalls += 1;
523
+ cumulative.totalCostUsd = (cumulative.totalCostUsd || 0) + cost;
524
+ if (cachedTokens > 0) {
525
+ cumulative.cachedTokens = (cumulative.cachedTokens || 0) + cachedTokens;
526
+ }
527
+ await this.saveCumulativeUsage(cumulative);
528
+
529
+ return { daily, cumulative };
530
+ });
531
+
532
+ if (!this.budget.enabled) {
533
+ return this.settle({ allowed: true }, daily, cumulative);
534
+ }
535
+
536
+ if (this.budget.maxCostUsd && daily.totalCostUsd > this.budget.maxCostUsd) {
537
+ if (this.budget.hardStop) {
538
+ return this.settle({
539
+ allowed: false,
540
+ reason: `BYOK Monetary Kill-Switch Activated: You have spent $${daily.totalCostUsd.toFixed(2)}, which exceeds your $${this.budget.maxCostUsd.toFixed(2)} limit.`
541
+ }, daily, cumulative);
542
+ }
543
+ }
544
+
545
+ if (this.budget.maxTokensPerTask && this.taskTokens > this.budget.maxTokensPerTask) {
546
+ if (this.budget.hardStop) {
547
+ return this.settle({
548
+ allowed: false,
549
+ reason: `Task token budget reached: ${this.taskTokens.toLocaleString()} of ${Number(this.budget.maxTokensPerTask).toLocaleString()} tokens for this task.`,
550
+ limit: this.budget.maxTokensPerTask
551
+ }, daily, cumulative);
552
+ }
553
+ }
554
+
555
+ if (this.budget.maxTokensPerDay && daily.totalTokens > this.budget.maxTokensPerDay) {
556
+ if (this.budget.hardStop) {
557
+ return this.settle({
558
+ allowed: false,
559
+ reason: `Daily token budget reached: ${daily.totalTokens.toLocaleString()} of ${Number(this.budget.maxTokensPerDay).toLocaleString()} tokens used today.`,
560
+ limit: this.budget.maxTokensPerDay
561
+ }, daily, cumulative);
562
+ }
563
+ }
564
+
565
+ await this.checkAndTriggerAlerts(daily, onWarning);
566
+
567
+ return this.settle({ allowed: true }, daily, cumulative);
568
+ }
569
+ }
@@ -6,3 +6,5 @@ export function isWebIntent(...args: any[]): any;
6
6
  export function getPackCatalogue(...args: any[]): any;
7
7
  export const PACK_PLAYBOOKS: any;
8
8
  export const PACKS: any;
9
+ export const PACK_NAMES: string[];
10
+ export function isResidentTool(toolName: string): boolean;
package/src/toolPacks.js CHANGED
@@ -369,7 +369,7 @@ When the user asks you to build, create, test, expand, or develop a game, follow
369
369
 
370
370
  const GAME_INTENT = /\b(game|games|gamedev|godot|unity|unreal|rpg|platformer|roguelike|arcade|sprite|spritesheet|tilemap|voxel|minecraft|aetheria|voxellia|nes|snes|gameplay|player character|level design|boss fight)\b|\.(tscn|gd)\b/i;
371
371
 
372
- const WEB_INTENT = /\b(web|webpage|website|frontend|front-end|landing page|homepage|dashboard|portfolio|html|css|scss|tailwind|bootstrap|react|vue|svelte|angular|next\.?js|nuxt|astro|ui|ux|user interface|web app|webapp|spa|dom|responsive|ui forge|component forge|component generation|ui component)\b/i;
372
+ const WEB_INTENT = /\b(web|webpage|website|frontend|front-end|landing page|homepage|dashboard|portfolio|html|css|scss|tailwind|bootstrap|react|vue|svelte|angular|next\.?js|nuxt|astro|ui|ux|user interface|web app|webapp|spa|dom|responsive|ui forge|component forge|component generation|ui component|three\.?js|threejs|webgl|canvas|babylon)\b/i;
373
373
 
374
374
  const MEDIA_INTENT = /\b(image|images|picture|photo|render|3d model|blender|animation|animate|video|movie|film|audio|sound|sfx|music|song|voice|tts|text.to.speech|narration|podcast|thumbnail|poster|illustration|logo)\b/i;
375
375
 
@@ -0,0 +1,56 @@
1
+ /** Validate canonical arguments before execution, without inventing missing values. */
2
+ export function validateToolArguments(value, schema) {
3
+ const errors = [];
4
+ const visit = (item, node, at, depth) => {
5
+ if (depth > 32 || errors.length >= 12)
6
+ return;
7
+ for (const keyword of ['anyOf', 'oneOf']) {
8
+ const variants = node[keyword];
9
+ if (Array.isArray(variants) && variants.length > 0) {
10
+ const matches = variants.filter(variant => variant && typeof variant === 'object'
11
+ && validateToolArguments(item, variant).length === 0).length;
12
+ if (matches === 0 || (keyword === 'oneOf' && matches !== 1)) {
13
+ errors.push(`${at} does not satisfy ${keyword}`);
14
+ return;
15
+ }
16
+ }
17
+ }
18
+ const types = Array.isArray(node.type) ? node.type : node.type ? [node.type] : [];
19
+ const hasType = (type) => {
20
+ switch (type) {
21
+ case 'null': return item === null;
22
+ case 'object': return item !== null && typeof item === 'object' && !Array.isArray(item);
23
+ case 'array': return Array.isArray(item);
24
+ case 'integer': return typeof item === 'number' && Number.isSafeInteger(item);
25
+ case 'number': return typeof item === 'number' && Number.isFinite(item);
26
+ case 'string':
27
+ case 'boolean': return typeof item === type;
28
+ default: return true; // Unknown dialect constraints remain the tool's responsibility.
29
+ }
30
+ };
31
+ if (types.length && !types.some(hasType)) {
32
+ errors.push(`${at} must be ${types.join(' or ')}`);
33
+ return;
34
+ }
35
+ if (Array.isArray(node.enum) && !node.enum.some(entry => JSON.stringify(entry) === JSON.stringify(item))) {
36
+ errors.push(`${at} must be one of ${JSON.stringify(node.enum)}`);
37
+ }
38
+ if (item !== null && typeof item === 'object' && !Array.isArray(item)) {
39
+ const record = item;
40
+ for (const required of node.required || []) {
41
+ if (!Object.hasOwn(record, required) || record[required] === undefined)
42
+ errors.push(`${at}.${required} is required`);
43
+ }
44
+ for (const [key, child] of Object.entries(node.properties || {})) {
45
+ if (Object.hasOwn(record, key) && record[key] !== undefined)
46
+ visit(record[key], child, `${at}.${key}`, depth + 1);
47
+ }
48
+ }
49
+ if (Array.isArray(item) && node.items && !Array.isArray(node.items)) {
50
+ item.forEach((entry, index) => visit(entry, node.items, `${at}[${index}]`, depth + 1));
51
+ }
52
+ };
53
+ if (schema)
54
+ visit(value, schema, 'arguments', 0);
55
+ return errors;
56
+ }
@@ -0,0 +1,50 @@
1
+ import type { ParameterSchema } from './toolSelfRepair.js';
2
+
3
+ /** Validate canonical arguments before execution, without inventing missing values. */
4
+ export function validateToolArguments(value: unknown, schema?: ParameterSchema): string[] {
5
+ const errors: string[] = [];
6
+ const visit = (item: unknown, node: ParameterSchema, at: string, depth: number): void => {
7
+ if (depth > 32 || errors.length >= 12) return;
8
+ for (const keyword of ['anyOf', 'oneOf'] as const) {
9
+ const variants = node[keyword];
10
+ if (Array.isArray(variants) && variants.length > 0) {
11
+ const matches = variants.filter(variant => variant && typeof variant === 'object'
12
+ && validateToolArguments(item, variant as ParameterSchema).length === 0).length;
13
+ if (matches === 0 || (keyword === 'oneOf' && matches !== 1)) {
14
+ errors.push(`${at} does not satisfy ${keyword}`);
15
+ return;
16
+ }
17
+ }
18
+ }
19
+ const types = Array.isArray(node.type) ? node.type : node.type ? [node.type] : [];
20
+ const hasType = (type: string): boolean => {
21
+ switch (type) {
22
+ case 'null': return item === null;
23
+ case 'object': return item !== null && typeof item === 'object' && !Array.isArray(item);
24
+ case 'array': return Array.isArray(item);
25
+ case 'integer': return typeof item === 'number' && Number.isSafeInteger(item);
26
+ case 'number': return typeof item === 'number' && Number.isFinite(item);
27
+ case 'string': case 'boolean': return typeof item === type;
28
+ default: return true; // Unknown dialect constraints remain the tool's responsibility.
29
+ }
30
+ };
31
+ if (types.length && !types.some(hasType)) { errors.push(`${at} must be ${types.join(' or ')}`); return; }
32
+ if (Array.isArray(node.enum) && !node.enum.some(entry => JSON.stringify(entry) === JSON.stringify(item))) {
33
+ errors.push(`${at} must be one of ${JSON.stringify(node.enum)}`);
34
+ }
35
+ if (item !== null && typeof item === 'object' && !Array.isArray(item)) {
36
+ const record = item as Record<string, unknown>;
37
+ for (const required of node.required || []) {
38
+ if (!Object.hasOwn(record, required) || record[required] === undefined) errors.push(`${at}.${required} is required`);
39
+ }
40
+ for (const [key, child] of Object.entries(node.properties || {})) {
41
+ if (Object.hasOwn(record, key) && record[key] !== undefined) visit(record[key], child, `${at}.${key}`, depth + 1);
42
+ }
43
+ }
44
+ if (Array.isArray(item) && node.items && !Array.isArray(node.items)) {
45
+ item.forEach((entry, index) => visit(entry, node.items!, `${at}[${index}]`, depth + 1));
46
+ }
47
+ };
48
+ if (schema) visit(value, schema, 'arguments', 0);
49
+ return errors;
50
+ }