@swarmvaultai/engine 0.7.24 → 0.7.26

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.
@@ -0,0 +1,65 @@
1
+ // src/token-estimation.ts
2
+ function estimateTokens(text) {
3
+ if (!text) {
4
+ return 0;
5
+ }
6
+ let codeChars = 0;
7
+ let proseChars = 0;
8
+ for (const line of text.split("\n")) {
9
+ const trimmed = line.trim();
10
+ if (trimmed.startsWith("```") || trimmed.startsWith("- `") || trimmed.startsWith("import ") || trimmed.startsWith("export ") || trimmed.startsWith("const ") || trimmed.startsWith("function ") || trimmed.startsWith("class ") || trimmed.startsWith("def ") || trimmed.startsWith("fn ") || /^\s*[{}[\]();]/.test(trimmed) || /^\w+\s*[=:]\s*/.test(trimmed)) {
11
+ codeChars += line.length;
12
+ } else {
13
+ proseChars += line.length;
14
+ }
15
+ }
16
+ return Math.ceil(codeChars / 3 + proseChars / 4);
17
+ }
18
+ var KIND_WEIGHTS = {
19
+ index: 10,
20
+ graph_report: 8,
21
+ module: 7,
22
+ concept: 6,
23
+ source: 5,
24
+ community_summary: 5,
25
+ entity: 4,
26
+ output: 3,
27
+ insight: 2
28
+ };
29
+ function estimatePageTokens(pageId, path, kind, content, nodeDegree, confidence) {
30
+ const tokens = estimateTokens(content);
31
+ const kindWeight = KIND_WEIGHTS[kind] ?? 1;
32
+ const priority = kindWeight * (1 + (nodeDegree ?? 0) * 0.1) * (confidence ?? 0.5);
33
+ return { pageId, path, kind, tokens, priority };
34
+ }
35
+ function trimToTokenBudget(pages, maxTokens) {
36
+ const totalTokens = pages.reduce((sum, p) => sum + p.tokens, 0);
37
+ if (totalTokens <= maxTokens) {
38
+ return { kept: pages, dropped: [], totalTokens, budgetTokens: maxTokens, keptTokens: totalTokens };
39
+ }
40
+ const sorted = [...pages].sort((a, b) => b.priority - a.priority);
41
+ const kept = [];
42
+ const dropped = [];
43
+ let accumulated = 0;
44
+ for (const page of sorted) {
45
+ if (accumulated + page.tokens <= maxTokens) {
46
+ kept.push(page);
47
+ accumulated += page.tokens;
48
+ } else {
49
+ dropped.push(page);
50
+ }
51
+ }
52
+ return {
53
+ kept,
54
+ dropped,
55
+ totalTokens,
56
+ budgetTokens: maxTokens,
57
+ keptTokens: accumulated
58
+ };
59
+ }
60
+
61
+ export {
62
+ estimateTokens,
63
+ estimatePageTokens,
64
+ trimToTokenBudget
65
+ };