tuxevil-rotator 3.0.0

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 (142) hide show
  1. package/CHANGELOG.md +773 -0
  2. package/LICENSE +21 -0
  3. package/README.md +341 -0
  4. package/bin/pi-antigravity-rotator.js +27 -0
  5. package/bin/tuxevil-rotator.js +5 -0
  6. package/package.json +63 -0
  7. package/src/account-store.ts +542 -0
  8. package/src/admin-auth.ts +126 -0
  9. package/src/body-limit.ts +52 -0
  10. package/src/cli.ts +293 -0
  11. package/src/compat/cache.ts +38 -0
  12. package/src/compat/model-specs.ts +82 -0
  13. package/src/compat/schema-sanitizer.ts +284 -0
  14. package/src/compat.ts +2357 -0
  15. package/src/compression/index.ts +92 -0
  16. package/src/compression/lite.ts +210 -0
  17. package/src/compression/preservation.ts +183 -0
  18. package/src/compression/rtk/command-detector.ts +170 -0
  19. package/src/compression/rtk/deduplicator.ts +39 -0
  20. package/src/compression/rtk/filter-loader.ts +84 -0
  21. package/src/compression/rtk/filter-types.ts +25 -0
  22. package/src/compression/rtk/filters/aws.json +34 -0
  23. package/src/compression/rtk/filters/biome.json +35 -0
  24. package/src/compression/rtk/filters/build-eslint.json +37 -0
  25. package/src/compression/rtk/filters/build-typescript.json +33 -0
  26. package/src/compression/rtk/filters/build-vite.json +41 -0
  27. package/src/compression/rtk/filters/build-webpack.json +34 -0
  28. package/src/compression/rtk/filters/bundle-install.json +35 -0
  29. package/src/compression/rtk/filters/composer.json +81 -0
  30. package/src/compression/rtk/filters/curl.json +34 -0
  31. package/src/compression/rtk/filters/df.json +34 -0
  32. package/src/compression/rtk/filters/docker-build.json +78 -0
  33. package/src/compression/rtk/filters/docker-logs.json +42 -0
  34. package/src/compression/rtk/filters/docker-ps.json +33 -0
  35. package/src/compression/rtk/filters/dotnet.json +47 -0
  36. package/src/compression/rtk/filters/du.json +33 -0
  37. package/src/compression/rtk/filters/error-stacktrace.json +41 -0
  38. package/src/compression/rtk/filters/gcloud.json +34 -0
  39. package/src/compression/rtk/filters/generic-output.json +32 -0
  40. package/src/compression/rtk/filters/gh.json +98 -0
  41. package/src/compression/rtk/filters/git-branch.json +45 -0
  42. package/src/compression/rtk/filters/git-diff.json +33 -0
  43. package/src/compression/rtk/filters/git-log.json +33 -0
  44. package/src/compression/rtk/filters/git-status.json +40 -0
  45. package/src/compression/rtk/filters/golangci-lint.json +34 -0
  46. package/src/compression/rtk/filters/gradle.json +47 -0
  47. package/src/compression/rtk/filters/json-output.json +40 -0
  48. package/src/compression/rtk/filters/kubectl.json +99 -0
  49. package/src/compression/rtk/filters/make.json +38 -0
  50. package/src/compression/rtk/filters/mypy.json +34 -0
  51. package/src/compression/rtk/filters/npm-audit.json +43 -0
  52. package/src/compression/rtk/filters/npm-install.json +41 -0
  53. package/src/compression/rtk/filters/nx.json +34 -0
  54. package/src/compression/rtk/filters/pip.json +41 -0
  55. package/src/compression/rtk/filters/playwright.json +42 -0
  56. package/src/compression/rtk/filters/poetry-install.json +35 -0
  57. package/src/compression/rtk/filters/prettier.json +40 -0
  58. package/src/compression/rtk/filters/ps.json +34 -0
  59. package/src/compression/rtk/filters/rsync.json +33 -0
  60. package/src/compression/rtk/filters/rubocop.json +34 -0
  61. package/src/compression/rtk/filters/ruff.json +40 -0
  62. package/src/compression/rtk/filters/shell-find.json +33 -0
  63. package/src/compression/rtk/filters/shell-grep.json +37 -0
  64. package/src/compression/rtk/filters/shell-ls.json +33 -0
  65. package/src/compression/rtk/filters/ssh.json +43 -0
  66. package/src/compression/rtk/filters/systemctl-status.json +43 -0
  67. package/src/compression/rtk/filters/terraform-plan.json +34 -0
  68. package/src/compression/rtk/filters/test-cargo.json +42 -0
  69. package/src/compression/rtk/filters/test-go.json +41 -0
  70. package/src/compression/rtk/filters/test-jest.json +43 -0
  71. package/src/compression/rtk/filters/test-pytest.json +41 -0
  72. package/src/compression/rtk/filters/test-vitest.json +43 -0
  73. package/src/compression/rtk/filters/tofu-plan.json +34 -0
  74. package/src/compression/rtk/filters/turbo.json +34 -0
  75. package/src/compression/rtk/filters/uv-sync.json +35 -0
  76. package/src/compression/rtk/filters/wget.json +34 -0
  77. package/src/compression/rtk/index.ts +103 -0
  78. package/src/compression/rtk/line-filter.ts +124 -0
  79. package/src/compression/rtk/smart-truncate.ts +71 -0
  80. package/src/config-defaults.ts +93 -0
  81. package/src/config-normalize.ts +48 -0
  82. package/src/config-storage.ts +21 -0
  83. package/src/dashboard.ts +1169 -0
  84. package/src/db-store.ts +188 -0
  85. package/src/doctor.ts +115 -0
  86. package/src/env.ts +15 -0
  87. package/src/exposure.ts +17 -0
  88. package/src/fetch-with-retry.ts +93 -0
  89. package/src/idempotency.ts +137 -0
  90. package/src/index.ts +267 -0
  91. package/src/key-auth.ts +159 -0
  92. package/src/key-migrations.ts +84 -0
  93. package/src/logger.ts +92 -0
  94. package/src/login.ts +48 -0
  95. package/src/notification-poller.ts +155 -0
  96. package/src/onboarding.ts +754 -0
  97. package/src/paths.ts +153 -0
  98. package/src/providers/adapter.ts +131 -0
  99. package/src/providers/credential-helpers.ts +72 -0
  100. package/src/providers/google-antigravity/code-assist.ts +161 -0
  101. package/src/providers/google-antigravity/credentials.ts +24 -0
  102. package/src/providers/google-antigravity/forward.ts +424 -0
  103. package/src/providers/google-antigravity/index.ts +168 -0
  104. package/src/providers/google-antigravity/login.ts +285 -0
  105. package/src/providers/google-antigravity/oauth.ts +314 -0
  106. package/src/providers/google-antigravity/quota.ts +152 -0
  107. package/src/providers/google-antigravity/translators.ts +1663 -0
  108. package/src/providers/ollama/api-key-validation.ts +59 -0
  109. package/src/providers/ollama/credentials.ts +28 -0
  110. package/src/providers/ollama/forward.ts +306 -0
  111. package/src/providers/ollama/index.ts +85 -0
  112. package/src/providers/ollama/login.ts +55 -0
  113. package/src/providers/ollama/prediction.ts +188 -0
  114. package/src/providers/ollama/quota-poll-store.ts +160 -0
  115. package/src/providers/ollama/quota.ts +189 -0
  116. package/src/providers/ollama/translators.ts +256 -0
  117. package/src/providers/ollama/usage-windows.ts +48 -0
  118. package/src/providers/proxy-dispatcher.ts +269 -0
  119. package/src/providers/registry.ts +70 -0
  120. package/src/proxy.ts +2446 -0
  121. package/src/rate-limit-parser.ts +126 -0
  122. package/src/response-headers.ts +98 -0
  123. package/src/responses-store.ts +159 -0
  124. package/src/rotator.ts +3614 -0
  125. package/src/settings-repository.ts +327 -0
  126. package/src/spend-logger.ts +696 -0
  127. package/src/static/dashboard-keys.js +384 -0
  128. package/src/static/dashboard-logs.js +797 -0
  129. package/src/static/dashboard.css +2740 -0
  130. package/src/static/dashboard.js +3177 -0
  131. package/src/storage.ts +105 -0
  132. package/src/systemd-env.ts +214 -0
  133. package/src/telemetry.ts +384 -0
  134. package/src/token-encryption.ts +199 -0
  135. package/src/types.ts +897 -0
  136. package/src/validators.ts +218 -0
  137. package/src/version-check.ts +225 -0
  138. package/src/virtual-keys.ts +312 -0
  139. package/tools/telemetry-receiver/README.md +147 -0
  140. package/tools/telemetry-receiver/package.json +13 -0
  141. package/tools/telemetry-receiver/receiver.js +2334 -0
  142. package/tuxevil-rotator_logo.png +0 -0
@@ -0,0 +1,92 @@
1
+ import type { ChatMessage } from "../providers/google-antigravity/translators.js";
2
+ import { compressLite } from "./lite.js";
3
+ import { compressRTK } from "./rtk/index.js";
4
+
5
+ export type CompressionMode = "off" | "lite" | "rtk" | "rtk+lite";
6
+
7
+ export interface CompressionStats {
8
+ mode: CompressionMode;
9
+ originalChars: number;
10
+ compressedChars: number;
11
+ savedChars: number;
12
+ savingsPercent: number;
13
+ techniques: string[];
14
+ }
15
+
16
+ export function parseCompressionMode(
17
+ reqHeader?: string | string[] | null,
18
+ configDefault: string = "off",
19
+ ): CompressionMode {
20
+ const headerVal = Array.isArray(reqHeader) ? reqHeader[0] : reqHeader;
21
+ const raw = (headerVal || configDefault || "off").trim().toLowerCase();
22
+ if (raw === "lite") return "lite";
23
+ if (raw === "rtk") return "rtk";
24
+ if (raw === "rtk+lite" || raw === "lite+rtk") return "rtk+lite";
25
+ return "off";
26
+ }
27
+
28
+ export function applyPromptCompression(
29
+ messages: ChatMessage[],
30
+ mode: CompressionMode,
31
+ options?: { model?: string },
32
+ ): {
33
+ messages: ChatMessage[];
34
+ stats: CompressionStats | null;
35
+ } {
36
+ if (mode === "off" || !messages || messages.length === 0) {
37
+ return { messages, stats: null };
38
+ }
39
+
40
+ function countChars(msgs: ChatMessage[]): number {
41
+ let total = 0;
42
+ for (const m of msgs) {
43
+ if (typeof m.content === "string") {
44
+ total += m.content.length;
45
+ } else if (Array.isArray(m.content)) {
46
+ for (const p of m.content) {
47
+ if (p.type === "text" && typeof p.text === "string") {
48
+ total += p.text.length;
49
+ }
50
+ }
51
+ }
52
+ }
53
+ return total;
54
+ }
55
+
56
+ const originalChars = countChars(messages);
57
+ let currentMessages = messages;
58
+ const techniques: string[] = [];
59
+
60
+ if (mode === "lite" || mode === "rtk+lite") {
61
+ const liteRes = compressLite(currentMessages, options);
62
+ currentMessages = liteRes.messages;
63
+ techniques.push(...liteRes.techniques);
64
+ }
65
+
66
+ if (mode === "rtk" || mode === "rtk+lite") {
67
+ const rtkRes = compressRTK(currentMessages);
68
+ currentMessages = rtkRes.messages;
69
+ if (rtkRes.compressed) {
70
+ techniques.push("rtk");
71
+ }
72
+ }
73
+
74
+ const compressedChars = countChars(currentMessages);
75
+ const savedChars = Math.max(0, originalChars - compressedChars);
76
+ const savingsPercent =
77
+ originalChars > 0 ? Math.round((savedChars / originalChars) * 100) : 0;
78
+
79
+ const stats: CompressionStats = {
80
+ mode,
81
+ originalChars,
82
+ compressedChars,
83
+ savedChars,
84
+ savingsPercent,
85
+ techniques,
86
+ };
87
+
88
+ return {
89
+ messages: currentMessages,
90
+ stats,
91
+ };
92
+ }
@@ -0,0 +1,210 @@
1
+ import {
2
+ extractPreservedBlocks,
3
+ restorePreservedBlocks,
4
+ } from "./preservation.js";
5
+ import type { ChatMessage } from "../providers/google-antigravity/translators.js";
6
+
7
+ export interface LiteCompressionOptions {
8
+ /** Maximum length for tool result messages before truncation (default: 2000) */
9
+ maxToolResultChars?: number;
10
+ /** Replace base64 image data URLs / image parts with text placeholders (default: false) */
11
+ replaceImages?: boolean;
12
+ /** Character length limit for system prompt deduplication hash comparison (default: 200) */
13
+ maxSystemCharsHash?: number;
14
+ /** Target model name for model-specific optimizations */
15
+ model?: string;
16
+ }
17
+
18
+ export interface LiteCompressionResult {
19
+ messages: ChatMessage[];
20
+ compressed: boolean;
21
+ techniques: string[];
22
+ tokensSavedEstimate: number;
23
+ }
24
+
25
+ /**
26
+ * Collapses consecutive newlines (>2 -> 2) and strips trailing whitespace per line,
27
+ * while respecting preserved blocks (code, URLs, paths, env vars, etc.).
28
+ */
29
+ export function collapseWhitespace(text: string): string {
30
+ if (!text || typeof text !== "string") return text || "";
31
+ const { text: extracted, blocks } = extractPreservedBlocks(text);
32
+ // Collapse 3+ newlines to 2
33
+ let processed = extracted.replace(/\n{3,}/g, "\n\n");
34
+ // Strip trailing spaces/tabs on each line
35
+ processed = processed.replace(/[ \t]+$/gm, "");
36
+ return restorePreservedBlocks(processed, blocks);
37
+ }
38
+
39
+ /**
40
+ * Applies all 5 lossless lite compression techniques to a list of messages.
41
+ */
42
+ export function compressLite(
43
+ messages: ChatMessage[],
44
+ options: LiteCompressionOptions = {},
45
+ ): LiteCompressionResult {
46
+ if (!Array.isArray(messages) || messages.length === 0) {
47
+ return {
48
+ messages: messages || [],
49
+ compressed: false,
50
+ techniques: [],
51
+ tokensSavedEstimate: 0,
52
+ };
53
+ }
54
+
55
+ const maxToolResultChars = options.maxToolResultChars ?? 2000;
56
+ const replaceImages = options.replaceImages ?? false;
57
+ const maxSystemCharsHash = options.maxSystemCharsHash ?? 200;
58
+
59
+ const techniquesUsed = new Set<string>();
60
+ let originalCharCount = 0;
61
+ let compressedCharCount = 0;
62
+
63
+ // Track system prompts seen so far for deduplication
64
+ const seenSystemPrompts = new Set<string>();
65
+
66
+ const processedMessages: ChatMessage[] = [];
67
+
68
+ for (const msg of messages) {
69
+ const rawContentStr = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
70
+ originalCharCount += rawContentStr.length;
71
+
72
+ // 1. System Prompt Deduplication
73
+ if (msg.role === "system" || msg.role === "developer") {
74
+ const textContent = typeof msg.content === "string"
75
+ ? msg.content
76
+ : (Array.isArray(msg.content)
77
+ ? msg.content.map((p) => (typeof p === "string" ? p : p.text || "")).join("\n")
78
+ : "");
79
+ const promptKey = textContent.slice(0, maxSystemCharsHash).trim();
80
+ if (seenSystemPrompts.has(promptKey)) {
81
+ techniquesUsed.add("dedup_system_prompt");
82
+ continue; // Drop duplicate system prompt
83
+ }
84
+ seenSystemPrompts.add(promptKey);
85
+ }
86
+
87
+ // Clone message for modification
88
+ let newContent = msg.content;
89
+ let modified = false;
90
+
91
+ // 2. Base64 Image replacement (if requested or data URL detected)
92
+ if (replaceImages) {
93
+ if (typeof newContent === "string") {
94
+ if (newContent.includes("data:image/")) {
95
+ newContent = newContent.replace(
96
+ /data:image\/([a-zA-Z0-9+-]+);base64,[A-Za-z0-9+/=]+/g,
97
+ (_match, format) => `[image: ${format}]`,
98
+ );
99
+ modified = true;
100
+ techniquesUsed.add("replace_image_urls");
101
+ }
102
+ } else if (Array.isArray(newContent)) {
103
+ const updatedParts = newContent.map((part) => {
104
+ if (part && typeof part === "object") {
105
+ if (part.type === "image_url" && typeof part.image_url === "object" && part.image_url) {
106
+ const url = (part.image_url as { url?: string }).url || "";
107
+ const match = url.match(/^data:image\/([a-zA-Z0-9+-]+);base64,/);
108
+ const fmt = match ? match[1] : "image";
109
+ modified = true;
110
+ techniquesUsed.add("replace_image_urls");
111
+ return { type: "text", text: `[image: ${fmt}]` };
112
+ }
113
+ if (part.type === "text" && typeof part.text === "string" && part.text.includes("data:image/")) {
114
+ const text = part.text.replace(
115
+ /data:image\/([a-zA-Z0-9+-]+);base64,[A-Za-z0-9+/=]+/g,
116
+ (_m, format) => `[image: ${format}]`,
117
+ );
118
+ modified = true;
119
+ techniquesUsed.add("replace_image_urls");
120
+ return { ...part, text };
121
+ }
122
+ }
123
+ return part;
124
+ });
125
+ if (modified) {
126
+ newContent = updatedParts;
127
+ }
128
+ }
129
+ }
130
+
131
+ // 3. Tool Result Truncation (> maxToolResultChars)
132
+ if (msg.role === "tool" || msg.tool_call_id) {
133
+ if (typeof newContent === "string" && newContent.length > maxToolResultChars) {
134
+ const { text: extracted, blocks } = extractPreservedBlocks(newContent);
135
+ if (extracted.length > maxToolResultChars) {
136
+ // Truncate at word boundary backoff
137
+ let cutoff = maxToolResultChars;
138
+ const spaceIdx = extracted.lastIndexOf(" ", cutoff);
139
+ const newlineIdx = extracted.lastIndexOf("\n", cutoff);
140
+ const lastBoundary = Math.max(spaceIdx, newlineIdx);
141
+ if (lastBoundary > cutoff * 0.7) {
142
+ cutoff = lastBoundary;
143
+ }
144
+ const truncatedExtracted = extracted.slice(0, cutoff) + "\n...[truncated]";
145
+ newContent = restorePreservedBlocks(truncatedExtracted, blocks);
146
+ modified = true;
147
+ techniquesUsed.add("compress_tool_results");
148
+ }
149
+ }
150
+ }
151
+
152
+ // 4. Whitespace Collapsing
153
+ if (typeof newContent === "string") {
154
+ const collapsed = collapseWhitespace(newContent);
155
+ if (collapsed !== newContent) {
156
+ newContent = collapsed;
157
+ modified = true;
158
+ techniquesUsed.add("collapse_whitespace");
159
+ }
160
+ } else if (Array.isArray(newContent)) {
161
+ const updatedParts = newContent.map((part) => {
162
+ if (part && typeof part === "object" && part.type === "text" && typeof part.text === "string") {
163
+ const collapsed = collapseWhitespace(part.text);
164
+ if (collapsed !== part.text) {
165
+ modified = true;
166
+ techniquesUsed.add("collapse_whitespace");
167
+ return { ...part, text: collapsed };
168
+ }
169
+ }
170
+ return part;
171
+ });
172
+ if (modified) {
173
+ newContent = updatedParts;
174
+ }
175
+ }
176
+
177
+ const processedMsg: ChatMessage = modified
178
+ ? { ...msg, content: newContent }
179
+ : msg;
180
+
181
+ // 5. Redundant Consecutive Message Removal
182
+ if (processedMessages.length > 0) {
183
+ const prev = processedMessages[processedMessages.length - 1];
184
+ if (
185
+ prev.role === processedMsg.role &&
186
+ JSON.stringify(prev.content) === JSON.stringify(processedMsg.content) &&
187
+ prev.name === processedMsg.name &&
188
+ prev.tool_call_id === processedMsg.tool_call_id
189
+ ) {
190
+ techniquesUsed.add("remove_redundant_content");
191
+ continue; // Skip consecutive duplicate message
192
+ }
193
+ }
194
+
195
+ processedMessages.push(processedMsg);
196
+ const newContentStr = typeof processedMsg.content === "string" ? processedMsg.content : JSON.stringify(processedMsg.content);
197
+ compressedCharCount += newContentStr.length;
198
+ }
199
+
200
+ const charsSaved = Math.max(0, originalCharCount - compressedCharCount);
201
+ // Estimate ~4 chars per token
202
+ const tokensSavedEstimate = Math.round(charsSaved / 4);
203
+
204
+ return {
205
+ messages: processedMessages,
206
+ compressed: techniquesUsed.size > 0,
207
+ techniques: Array.from(techniquesUsed),
208
+ tokensSavedEstimate,
209
+ };
210
+ }
@@ -0,0 +1,183 @@
1
+ import { randomBytes } from "node:crypto";
2
+
3
+ export interface PreservedBlock {
4
+ id: string;
5
+ placeholder: string;
6
+ originalText: string;
7
+ type:
8
+ | "code_block"
9
+ | "inline_code"
10
+ | "url"
11
+ | "file_path"
12
+ | "env_var"
13
+ | "version"
14
+ | "stack_trace";
15
+ }
16
+
17
+ export interface ExtractionResult {
18
+ text: string;
19
+ blocks: PreservedBlock[];
20
+ restore: (compressedText: string) => string;
21
+ }
22
+
23
+ export interface FidelityResult {
24
+ ok: boolean;
25
+ totalBlocks: number;
26
+ preservedBlocks: number;
27
+ missingBlocks: string[];
28
+ missingNumbers: string[];
29
+ }
30
+
31
+ // Regex patterns ordered by extraction precedence
32
+ const PATTERNS: Array<{
33
+ type: PreservedBlock["type"];
34
+ regex: RegExp;
35
+ }> = [
36
+ // Fenced code blocks ```...```
37
+ {
38
+ type: "code_block",
39
+ regex: /```[\s\S]*?```/g,
40
+ },
41
+ // Inline code `...`
42
+ {
43
+ type: "inline_code",
44
+ regex: /`[^`\r\n]+`/g,
45
+ },
46
+ // URLs
47
+ {
48
+ type: "url",
49
+ regex: /https?:\/\/[^\s<>"':;()[\]{}]+[^\s<>"':;()[\]{}.,?!]/gi,
50
+ },
51
+ // Stack traces / error lines (e.g., " at Module._compile (node:internal/modules/cjs/loader:1376:14)")
52
+ {
53
+ type: "stack_trace",
54
+ regex: /^\s*at\s+[\w.<>$]+\s+\([^)]+\)/gm,
55
+ },
56
+ // Absolute Unix / Windows file paths or relative paths starting with ./ or ../
57
+ {
58
+ type: "file_path",
59
+ // Keep the path body as a single character class. Nested repetitions here
60
+ // made malformed relative paths trigger exponential backtracking.
61
+ regex: /(?:\/[a-zA-Z0-9_./-]+|(?:\.\.?\/[a-zA-Z0-9_./-]+)|[a-zA-Z]:\\[a-zA-Z0-9_.\\-]+)\.[a-zA-Z0-9]+/g,
62
+ },
63
+ // Env variables ($VAR, ${VAR}, or ALL_CAPS_VAR=)
64
+ {
65
+ type: "env_var",
66
+ regex: /\$\{[A-Z0-9_]+\}|\$[A-Z0-9_]+|\b[A-Z0-9_]{3,}=(?=[^\s]+)/g,
67
+ },
68
+ // Semantic version strings (e.g. v1.2.3, v0.1.0-beta.2)
69
+ {
70
+ type: "version",
71
+ regex: /\bv?\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?\b/g,
72
+ },
73
+ ];
74
+
75
+ /**
76
+ * Extracts protected patterns from text and replaces them with unique sentinel placeholders.
77
+ */
78
+ export function extractPreservedBlocks(text: string): ExtractionResult {
79
+ if (!text || typeof text !== "string") {
80
+ return {
81
+ text: text || "",
82
+ blocks: [],
83
+ restore: (compressedText: string) => compressedText || "",
84
+ };
85
+ }
86
+
87
+ const seed = randomBytes(4).toString("hex");
88
+ const blocks: PreservedBlock[] = [];
89
+ let currentText = text;
90
+ let blockIndex = 0;
91
+
92
+ for (const { type, regex } of PATTERNS) {
93
+ currentText = currentText.replace(regex, (match) => {
94
+ // Avoid re-extracting inside an already generated sentinel placeholder
95
+ if (match.includes("\0ROTATOR_PRESERVE_")) {
96
+ return match;
97
+ }
98
+ const id = `ROTATOR_PRESERVE_${seed}_${blockIndex++}`;
99
+ const placeholder = `\0${id}\0`;
100
+ blocks.push({
101
+ id,
102
+ placeholder,
103
+ originalText: match,
104
+ type,
105
+ });
106
+ return placeholder;
107
+ });
108
+ }
109
+
110
+ const restore = (compressedText: string): string => {
111
+ return restorePreservedBlocks(compressedText, blocks);
112
+ };
113
+
114
+ return {
115
+ text: currentText,
116
+ blocks,
117
+ restore,
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Restores sentinel placeholders back to their original text.
123
+ */
124
+ export function restorePreservedBlocks(
125
+ compressedText: string,
126
+ blocks: PreservedBlock[],
127
+ ): string {
128
+ if (!compressedText || blocks.length === 0) {
129
+ return compressedText || "";
130
+ }
131
+
132
+ let restored = compressedText;
133
+ // Restore in reverse order of extraction to handle any potential nesting cleanly
134
+ for (let i = blocks.length - 1; i >= 0; i--) {
135
+ const block = blocks[i];
136
+ restored = restored.replaceAll(block.placeholder, block.originalText);
137
+ }
138
+ return restored;
139
+ }
140
+
141
+ /**
142
+ * Verifies that preserved blocks and critical literals (like numbers) survive compression.
143
+ */
144
+ export function verifyFidelity(
145
+ originalText: string,
146
+ restoredText: string,
147
+ blocks: PreservedBlock[],
148
+ minPreservedRatio = 0.95,
149
+ ): FidelityResult {
150
+ const missingBlocks: string[] = [];
151
+ let preservedCount = 0;
152
+
153
+ for (const block of blocks) {
154
+ if (restoredText.includes(block.originalText)) {
155
+ preservedCount++;
156
+ } else {
157
+ missingBlocks.push(block.originalText);
158
+ }
159
+ }
160
+
161
+ // Verify numerical literals in original survive in restored text
162
+ const missingNumbers: string[] = [];
163
+ const numbersInOriginal = originalText.match(/\b\d+(?:\.\d+)?\b/g) || [];
164
+ const uniqueNumbers = Array.from(new Set(numbersInOriginal));
165
+
166
+ for (const num of uniqueNumbers) {
167
+ if (!restoredText.includes(num)) {
168
+ missingNumbers.push(num);
169
+ }
170
+ }
171
+
172
+ const totalBlocks = blocks.length;
173
+ const ratio = totalBlocks > 0 ? preservedCount / totalBlocks : 1.0;
174
+ const ok = ratio >= minPreservedRatio && missingNumbers.length === 0;
175
+
176
+ return {
177
+ ok,
178
+ totalBlocks,
179
+ preservedBlocks: preservedCount,
180
+ missingBlocks,
181
+ missingNumbers,
182
+ };
183
+ }
@@ -0,0 +1,170 @@
1
+ export interface CommandDetectionResult {
2
+ type: string;
3
+ command: string | null;
4
+ confidence: number;
5
+ category:
6
+ | "git"
7
+ | "test"
8
+ | "build"
9
+ | "shell"
10
+ | "docker"
11
+ | "package"
12
+ | "infra"
13
+ | "cloud"
14
+ | "generic";
15
+ matchedPatterns: string[];
16
+ }
17
+
18
+ type Detector = {
19
+ type: string;
20
+ category: CommandDetectionResult["category"];
21
+ commandPatterns: RegExp[];
22
+ contentPatterns: RegExp[];
23
+ };
24
+
25
+ const DETECTORS: Detector[] = [
26
+ {
27
+ type: "git-status",
28
+ category: "git",
29
+ commandPatterns: [/^git\s+status\b/i],
30
+ contentPatterns: [
31
+ /^On branch /m,
32
+ /^Changes (?:not staged|to be committed)/m,
33
+ /^Untracked files:/m,
34
+ ],
35
+ },
36
+ {
37
+ type: "git-branch",
38
+ category: "git",
39
+ commandPatterns: [
40
+ /^git\s+branch\b/i,
41
+ /^git\s+checkout\b/i,
42
+ /^git\s+switch\b/i,
43
+ ],
44
+ contentPatterns: [
45
+ /^\*\s+\S+/m,
46
+ /Switched to (?:a new )?branch/i,
47
+ /Already on ['"][^'"]+['"]/i,
48
+ ],
49
+ },
50
+ {
51
+ type: "git-diff",
52
+ category: "git",
53
+ commandPatterns: [/^git\s+diff\b/i, /^git\s+show\b/i],
54
+ contentPatterns: [/^diff --git /m, /^index [0-9a-f]+\.\.[0-9a-f]+/m],
55
+ },
56
+ {
57
+ type: "git-log",
58
+ category: "git",
59
+ commandPatterns: [/^git\s+log\b/i],
60
+ contentPatterns: [/^commit [0-9a-f]{40}/m, /^Author:\s+/m],
61
+ },
62
+ {
63
+ type: "npm-install",
64
+ category: "package",
65
+ commandPatterns: [
66
+ /^(?:npm|pnpm|yarn|bun)\s+(?:install|i|add)\b/i,
67
+ /^bundle\s+install\b/i,
68
+ /^composer\s+install\b/i,
69
+ ],
70
+ contentPatterns: [
71
+ /added \d+ packages/i,
72
+ /packages are looking for funding/i,
73
+ /Lockfile is up to date/i,
74
+ ],
75
+ },
76
+ {
77
+ type: "build-typescript",
78
+ category: "build",
79
+ commandPatterns: [/^tsc\b/i, /^npm\s+run\s+typecheck\b/i],
80
+ contentPatterns: [/: error TS\d+:/m, /Found \d+ errors?/i],
81
+ },
82
+ {
83
+ type: "test-pytest",
84
+ category: "test",
85
+ commandPatterns: [/^pytest\b/i, /^python\s+-m\s+pytest\b/i],
86
+ contentPatterns: [
87
+ /===+ (?:test session starts|passed|failed) ===+/i,
88
+ /rootdir:/i,
89
+ ],
90
+ },
91
+ {
92
+ type: "test-jest",
93
+ category: "test",
94
+ commandPatterns: [/^jest\b/i, /^npm\s+test\b/i, /^npx\s+jest\b/i],
95
+ contentPatterns: [
96
+ /PASS\s+\S+\.test\.(?:js|ts|jsx|tsx)/i,
97
+ /FAIL\s+\S+\.test\.(?:js|ts|jsx|tsx)/i,
98
+ /Test Suites:\s+\d+/i,
99
+ ],
100
+ },
101
+ {
102
+ type: "test-vitest",
103
+ category: "test",
104
+ commandPatterns: [/vitest\b/i],
105
+ contentPatterns: [/✓\s+\S+\.\w+/m, /FAIL\s+\S+\.\w+/m, /Test Files\s+\d+/i],
106
+ },
107
+ {
108
+ type: "docker-build",
109
+ category: "docker",
110
+ commandPatterns: [/^docker\s+build\b/i, /^docker\s+compose\s+build\b/i],
111
+ contentPatterns: [
112
+ /^Step \d+\/\d+ :/m,
113
+ /^#\d+ \[internal\]/m,
114
+ /EXPORTING HASHE/i,
115
+ ],
116
+ },
117
+ ];
118
+
119
+ export function detectCommandType(
120
+ text: string,
121
+ command?: string | null,
122
+ ): CommandDetectionResult {
123
+ const matchedPatterns: string[] = [];
124
+
125
+ if (command) {
126
+ const trimmed = command.trim();
127
+ for (const detector of DETECTORS) {
128
+ if (detector.commandPatterns.some((pattern) => pattern.test(trimmed))) {
129
+ return {
130
+ type: detector.type,
131
+ command: trimmed,
132
+ confidence: 0.95,
133
+ category: detector.category,
134
+ matchedPatterns: [`command:${detector.type}`],
135
+ };
136
+ }
137
+ }
138
+ }
139
+
140
+ for (const detector of DETECTORS) {
141
+ let matched = 0;
142
+ for (const pattern of detector.contentPatterns) {
143
+ if (pattern.test(text)) {
144
+ matched++;
145
+ matchedPatterns.push(`content:${pattern.source}`);
146
+ }
147
+ }
148
+ if (matched > 0) {
149
+ const confidence = Math.min(
150
+ 0.9,
151
+ 0.5 + (matched / detector.contentPatterns.length) * 0.4,
152
+ );
153
+ return {
154
+ type: detector.type,
155
+ command: command || null,
156
+ confidence,
157
+ category: detector.category,
158
+ matchedPatterns,
159
+ };
160
+ }
161
+ }
162
+
163
+ return {
164
+ type: "generic-output",
165
+ command: command || null,
166
+ confidence: 0.1,
167
+ category: "generic",
168
+ matchedPatterns: [],
169
+ };
170
+ }
@@ -0,0 +1,39 @@
1
+ export interface DeduplicateOptions {
2
+ threshold?: number;
3
+ }
4
+
5
+ export function deduplicateRepeatedLines(
6
+ text: string,
7
+ options: DeduplicateOptions = {},
8
+ ): {
9
+ text: string;
10
+ collapsed: number;
11
+ } {
12
+ const threshold = Math.max(2, Math.floor(options.threshold ?? 3));
13
+ const lines = text.split(/\r?\n/);
14
+ const output: string[] = [];
15
+ let collapsed = 0;
16
+
17
+ for (let index = 0; index < lines.length; index++) {
18
+ const line = lines[index];
19
+ let runLength = 1;
20
+ while (
21
+ index + runLength < lines.length &&
22
+ lines[index + runLength] === line
23
+ ) {
24
+ runLength++;
25
+ }
26
+
27
+ if (line.trim() && runLength >= threshold) {
28
+ output.push(line);
29
+ output.push(`[rtk:dropped ${runLength - 1} repeated lines]`);
30
+ collapsed += runLength - 1;
31
+ index += runLength - 1;
32
+ continue;
33
+ }
34
+
35
+ output.push(line);
36
+ }
37
+
38
+ return { text: output.join("\n"), collapsed };
39
+ }