tokensafe 1.3.4 → 1.3.5

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/src/compactor.py CHANGED
@@ -1,7 +1,8 @@
1
1
  """
2
- Semantic Compactor: Converts verbose natural language prompts (Russian/English)
3
- into ultra-dense Token-Optimized Communication Protocol (TOCP) S-Expressions.
4
- Supports 3-Tier Routing: Pass-through -> Regex Compactor -> DeepSeek-V3 Distiller.
2
+ Semantic Compactor: Converts verbose natural language prompts (English, Spanish,
3
+ German, French, Portuguese, Italian, Chinese, Japanese, Russian) into ultra-dense
4
+ Token-Optimized Communication Protocol (TOCP) S-Expressions.
5
+ Supports 3-Tier Routing: Pass-through -> Multilingual Regex Compactor -> Universal Distiller.
5
6
  """
6
7
 
7
8
  import os
@@ -13,60 +14,309 @@ from src.distiller import UniversalDistiller
13
14
  from src.secret_redactor import SecretRedactor
14
15
 
15
16
  class PromptCompactor:
16
- """Transforms verbose natural language requests into compact Intent IR."""
17
+ """Transforms verbose natural language requests into compact Intent IR across major world languages."""
17
18
 
18
19
  STOP_PHRASES = [
19
- # Russian courtesy, prepositions & fillers
20
+ # English courtesy, prepositions, fillers & directives
21
+ r"\b(please|kindly|could you please|could you|would you mind|would you|thank you|thanks in advance|thanks)\b",
22
+ r"\b(hello|hi there|hi|hey|good morning|good evening|good afternoon)\b",
23
+ r"\b(listen|look|basically|anyway|actually|to be honest|just)\b",
24
+ r"\b(can you help me with|can you help me|can you|help me to|help me|i want you to|i would like you to|i need to|i want to|we need to|lets|let's)\b",
25
+ r"\b(make sure to|make sure that|tell me how to|show me how to|what is the reason|how can i)\b",
26
+ r"\b(in file|inside file|the function|the method|the class|file|function|method|class|project|code)\b",
27
+ r"\b(add to it|make it|so that it)\b",
28
+ r"\b(and|with|on|at|for|from|to|the|a|an|in|of|is|are|it|its|this|that|these|those)\b",
29
+
30
+ # Spanish (Español)
31
+ r"\b(por\s+favor|muchas\s+gracias|gracias|te\s+agradecer[ií]a|agradezco)\b",
32
+ r"\b(hola|buenos\s+d[ií]as|buenas\s+tardes|buenas\s+noches|saludos)\b",
33
+ r"\b(mira|oye|b[aá]sicamente|en\s+realidad|de\s+hecho|a\s+ver)\b",
34
+ r"\b(puedes\s+ayudarme|puedes|podr[ií]as|ay[uú]dame|necesito\s+que|quiero\s+que|vamos\s+a)\b",
35
+ r"\b(aseg[uú]rate\s+de|dime\s+c[oó]mo|mu[eé]strame|cu[aá]l\s+es\s+el\s+problema|c[oó]mo\s+puedo)\b",
36
+ r"\b(en\s+el\s+archivo|del\s+archivo|el\s+archivo|archivo|la\s+funci[oó]n|funci[oó]n|el\s+m[eé]todo|m[eé]todo|la\s+clase|clase|el\s+c[oó]digo|c[oó]digo|proyecto)\b",
37
+ r"\b(para\s+que|de\s+modo\s+que|y|con|en|de|a|el|la|los|las|un|una|unos|unas|este|esta|esto|es|son|por)\b",
38
+
39
+ # German (Deutsch)
40
+ r"\b(bitte|vielen\s+dank|danke\s+im\s+voraus|danke\s+schön|danke)\b",
41
+ r"\b(hallo|guten\s+tag|guten\s+morgen|guten\s+abend|grüß\s+gott)\b",
42
+ r"\b(schau\s+mal|eigentlich|im\s+grunde|übrigens|quasi)\b",
43
+ r"\b(kannst\s+du\s+mir\s+helfen|kannst\s+du|könntest\s+du|hilf\s+mir|ich\s+brauche|ich\s+möchte|wir\s+müssen|lass\s+uns)\b",
44
+ r"\b(stelle\s+sicher|sag\s+mir|zeige\s+mir|was\s+ist\s+der\s+grund|wie\s+kann\s+ich)\b",
45
+ r"\b(in\s+der\s+datei|aus\s+der\s+datei|die\s+datei|datei|die\s+funktion|funktion|die\s+methode|methode|die\s+klasse|klasse|der\s+code|code|projekt)\b",
46
+ r"\b(damit|sodass|und|mit|auf|für|von|zu|der|die|das|den|dem|ein|eine|dies|diese|ist|sind)\b",
47
+
48
+ # French (Français)
49
+ r"\b(s'il\s+vous\s+pla[iî]t|s'il\s+te\s+pla[iî]t|svp|stp|merci\s+d'avance|merci\s+beaucoup|merci)\b",
50
+ r"\b(bonjour|bonsoir|salut|coucou|bienvenue)\b",
51
+ r"\b([eé]coute|regarde|en\s+fait|fondamentalement|au\s+fait|bref)\b",
52
+ r"\b(peux-tu\s+m'aider|peux-tu|pourrais-tu|aide-moi|j'ai\s+besoin\s+de|je\s+veux\s+que|il\s+faut\s+que)\b",
53
+ r"\b(assure-toi\s+de|dis-moi\s+comment|montre-moi|quelle\s+est\s+la\s+raison|comment\s+faire)\b",
54
+ r"\b(dans\s+le\s+fichier|du\s+fichier|le\s+fichier|fichier|la\s+fonction|fonction|la\s+m[eé]thode|m[eé]thode|la\s+classe|classe|le\s+code|code|projet)\b",
55
+ r"\b(pour\s+que|afin\s+que|et|avec|sur|dans|pour|de|le|la|les|un|une|des|ce|cette|ces|est|sont)\b",
56
+
57
+ # Portuguese (Português)
58
+ r"\b(por\s+favor|muito\s+obrigado|obrigado|obrigada|valeu|grato)\b",
59
+ r"\b(ol[aá]|bom\s+dia|boa\s+tarde|boa\s+noite|fala|e\s+a[ií])\b",
60
+ r"\b(olha|veja|basicamente|na\s+verdade|ent[aã]o)\b",
61
+ r"\b(voc[eê]\s+pode|poderia|ajude-me|me\s+ajuda|preciso\s+que|quero\s+que|vamos)\b",
62
+ r"\b(certifique-se\s+de|me\s+diga\s+como|me\s+mostre|qual\s+[eé]\s+o\s+motivo|como\s+posso)\b",
63
+ r"\b(no\s+arquivo|do\s+arquivo|o\s+arquivo|arquivo|a\s+funç[aã]o|funç[aã]o|o\s+m[eé]todo|m[eé]todo|a\s+classe|classe|o\s+c[oó]digo|c[oó]digo|projeto)\b",
64
+ r"\b(para\s+que|de\s+modo\s+que|e|com|em|de|a|o|a|os|as|um|uma|este|esta|isso|isto|[eé]|s[aã]o)\b",
65
+
66
+ # Italian (Italiano)
67
+ r"\b(per\s+favore|per\s+cortesia|grazie\s+mille|grazie)\b",
68
+ r"\b(ciao|buongiorno|buonasera|salve)\b",
69
+ r"\b(puoi|potresti|aiutami|ho\s+bisogno\s+di|voglio\s+che)\b",
70
+ r"\b(nel\s+file|dal\s+file|il\s+file|file|la\s+funzione|funzione|il\s+metodo|metodo|la\s+classe|classe|il\s+codice|codice|progetto)\b",
71
+ r"\b(in\s+modo\s+che|affinch[eé]|e|con|su|in|di|a|il|lo|la|i|gli|le|un|uno|una|questo|questa|[eè]|sono)\b",
72
+
73
+ # Russian (Русский)
20
74
  r"\b(пожалуйста|будь добр|будь любезен|если не трудно|заранее спасибо|спасибо|благодарю)\b",
21
75
  r"\b(привет|здравствуй|здравствуйте|добрый день|добрый вечер|доброе утро|хай|салют)\b",
22
76
  r"\b(слушай|смотри|короче|кстати|в общем|в общем-то|дело в том что)\b",
23
- r"\b(можешь ли ты|можешь|не мог бы ты|помоги мне|помоги пожалуйста|мне нужно|я хочу чтобы ты|я хочу|нужно чтобы)\b",
24
- r"\b(подскажи как|подскажи пожалуйста|расскажи как|сделай так чтобы|сделай пожалуйста|попробуй)\b",
25
- r"\b(как думаешь|как считаешь|по твоему мнению)\b",
26
- r"\b(в файле|из файла|внутри файла|функцию|метод|класс|код|строку)\b",
27
- r"\b(добавь туда|сделай её|сделай его|чтобы было|для этого)\b",
28
- r"\b(и|в|на|с|при|по|к|из|у|о|об|от|под|над|для)\b",
29
-
30
- # English courtesy, prepositions & fillers
31
- r"\b(please|kindly|could you please|could you|would you mind|would you|thank you|thanks in advance)\b",
32
- r"\b(hello|hi there|hi|hey|good morning|good evening|good afternoon)\b",
33
- r"\b(listen|look|basically|anyway|actually|to be honest)\b",
34
- r"\b(can you help me with|can you help me|can you|help me to|help me|i want you to|i would like you to|i need to|i want to)\b",
35
- r"\b(make sure to|make sure that|tell me how to|show me how to)\b",
36
- r"\b(in file|inside file|the function|the method|the class)\b",
37
- r"\b(add to it|make it|so that it)\b",
38
- r"\b(and|with|on|at|for|from|to|the|a|an|in|of)\b",
77
+ r"\b(можешь ли ты|можешь|не мог бы ты|помоги мне|помоги пожалуйста|мне нужно|я хочу чтобы ты|я хочу|нужно чтобы|надо чтобы|надо|нужно|давай)\b",
78
+ r"\b(подскажи как|подскажи пожалуйста|подскажи|расскажи как|сделай так чтобы|сделай пожалуйста|попробуй|попробуем)\b",
79
+ r"\b(как думаешь|как считаешь|по твоему мнению|в чем проблема|почему|почему падает|не работает)\b",
80
+ r"\b(в файле|из файла|внутри файла|файле|файл|функцию|функция|функции|метод|методе|метода|класс|классе|класса|код|кода|строку|строка|проект|проекта|проекте|описани\w*|пояснени\w*|информаци\w*|баз\w*\s+данных|баз[аеуоы]|бд|database)\b",
81
+ r"\b(добавь туда|сделай её|сделай его|сделай их|чтобы было|чтобы он|чтобы она|чтобы оно|для этого|для того чтобы)\b",
82
+ r"\b(и|в|на|с|при|по|к|из|у|о|об|от|под|над|для|не|бы|ли|же|то|это|этот|эта|эти|он|она|оно|они|ему|ей|им|их|его|ее)\b",
83
+
84
+ # Chinese (中文)
85
+ r"(请|麻烦|谢谢|多谢|你好|您好|早上好|晚上好)",
86
+ r"(你看|其实|基本上|你能|可以帮我|帮我|我需要|我想|我们要|让我们)",
87
+ r"(请问|为什么|怎么做|如何|看一下)",
88
+ r"(在文件|文件里|文件|中的|函数|方法|类|代码|项目)",
89
+ r"(为了|以便|并且|和|与|在|从|把|将|使|让|的|了|是|这|那)",
90
+
91
+ # Japanese (日本語)
92
+ r"(お願いします|お願い|ありがとう|よろしく|こんにちは|おはよう|こんばんは)",
93
+ r"(できますか|手伝って|必要があります|したい|しましょう|教えて|どうやって|なぜ)",
94
+ r"(ファイル内|ファイル|関数|メソッド|クラス|コード|プロジェクト)",
95
+ r"(のために|ように|そして|で|に|を|は|が|の|と|から|へ|これ|それ)",
39
96
  ]
40
97
 
41
98
  ACTION_PATTERNS = [
42
- ("REFACTOR", re.compile(r"\b(refactor|rewrite|restructure|перепиши|отрефактори|отрефакторить|переделай|модернизируй)\b", re.I)),
43
- ("DEBUG", re.compile(r"\b(fix|debug|resolve|error|bug|issue|broken|failing|crash|почини|исправь|баг|ошибка|ошибку|не работает|падает|падение)\b", re.I)),
44
- ("OPTIMIZE", re.compile(r"\b(optimize|speed up|perf|memory leak|latency|ускори|оптимизируй|утечка памяти|быстрее)\b", re.I)),
45
- ("CREATE", re.compile(r"\b(create|add|implement|build|write|new|generate|создай|добавь|напиши|реализуй|сделай|напиши новый)\b", re.I)),
46
- ("TEST", re.compile(r"\b(test|spec|assert|coverage|unit test|тест|тесты|протестируй|покрыть тестами)\b", re.I)),
47
- ("EXPLAIN", re.compile(r"\b(explain|why|how does|what is|clarify|объясни|почему|как работает|что делает|поясни)\b", re.I)),
48
- ("AUDIT", re.compile(r"\b(audit|review|check|security|analyze|проверь|проанализируй|аудит|ревью)\b", re.I)),
49
- ("RUN", re.compile(r"\b(run|execute|start|launch|запусти|выполни|стартуй)\b", re.I)),
99
+ ("TEST", re.compile(
100
+ r"\b(test|spec|assert|coverage|unit[\s_-]?test|e2e|"
101
+ r"probar|prueba\w*|testear\w*|"
102
+ r"testen\w*|"
103
+ r"tester\w*|"
104
+ r"testar\w*|teste\w*|"
105
+ r"collaudar\w*|"
106
+ r"тест\w*|протестируй\w*|покрыт\w*\s+тест\w*)\b|"
107
+ r"(测试|单测|断言|テスト|単体テスト)",
108
+ re.I
109
+ )),
110
+ ("DEPLOY", re.compile(
111
+ r"\b(deploy|release|publish|ship|"
112
+ r"despleg\w*|public\w*|lanz\w*|"
113
+ r"bereitstell\w*|veröffentlich\w*|releas\w*|"
114
+ r"déploy\w*|"
115
+ r"implant\w*|"
116
+ r"rilasci\w*|"
117
+ r"выкат\w*|задепло\w*|опублику\w*|релиз\w*)\b|"
118
+ r"(部署|发布|上线|デプロイ|リリース|公開)",
119
+ re.I
120
+ )),
121
+ ("BENCHMARK", re.compile(
122
+ r"\b(benchmark|bench|profil\w*|"
123
+ r"evaluar|medir\s+rendimiento|"
124
+ r"profiling|leistungsmessung|"
125
+ r"analyser\s+la\s+performance|"
126
+ r"замер\w*|бенчмарк\w*|профайлинг\w*)\b|"
127
+ r"(基准测试|压测|性能分析|ベンチマーク|性能測定)",
128
+ re.I
129
+ )),
130
+ ("DOCS", re.compile(
131
+ r"\b(document\w*|readme|docs?|docstring|swagger|"
132
+ r"documentar|documento\w*|documentaci[oó]n|"
133
+ r"dokumentier\w*|dokumentation|"
134
+ r"documentaç[aã]o|"
135
+ r"documentare|"
136
+ r"документ\w*|доку\b|дока\b|документаци\w*|комментар\w*)\b|"
137
+ r"(文档|说明文档|注释|ドキュメント|文書化|コメント)",
138
+ re.I
139
+ )),
140
+ ("CLEAN", re.compile(
141
+ r"\b(clean(?:up)?|remove|delete|prune|vacuum|"
142
+ r"limpi\w*|elimin\w*|borr\w*|quit\w*|"
143
+ r"bereinig\w*|lösch\w*|entfern\w*|aufräum\w*|"
144
+ r"nettoy\w*|supprim\w*|effac\w*|"
145
+ r"remov\w*|exclu\w*|apag\w*|"
146
+ r"pulir\w*|"
147
+ r"удал\w*|почист\w*|очист\w*|сотри)\b|"
148
+ r"(清理|清除|删除|クリーンアップ|削除|クリーン)",
149
+ re.I
150
+ )),
151
+ ("CONFIG", re.compile(
152
+ r"\b(config(?:ure)?|setup|env|"
153
+ r"configur\w*|ajust\w*|"
154
+ r"einricht\w*|"
155
+ r"настро\w*|конфигур\w*|сконфигурируй)\b|"
156
+ r"(配置|设置|环境|設定|構成|セットアップ)",
157
+ re.I
158
+ )),
159
+ ("UPDATE", re.compile(
160
+ r"\b(update|upgrade|bump|"
161
+ r"actualiz\w*|"
162
+ r"updat\w*|"
163
+ r"mettre\s+à\s+jour|"
164
+ r"atualiz\w*|"
165
+ r"aggiorn\w*|"
166
+ r"обнов\w*|актуализируй\w*|подними\s+верси\w*)\b|"
167
+ r"(更新|升级|アップグレード)",
168
+ re.I
169
+ )),
170
+ ("OPTIMIZE", re.compile(
171
+ r"\b(optimize|speed\s*up|perf|memory\s*leak|latency|"
172
+ r"optimiz\w*|aceler\w*|"
173
+ r"beschleunig\w*|"
174
+ r"accélér\w*|"
175
+ r"otimiz\w*|"
176
+ r"ottimizz\w*|"
177
+ r"ускор\w*|оптимизируй\w*|быстрее)\b|"
178
+ r"(优化|加速|性能提升|最適化|高速化)",
179
+ re.I
180
+ )),
181
+ ("REFACTOR", re.compile(
182
+ r"\b(refactor|rewrite|restructure|"
183
+ r"refactoriz\w*|reescrib\w*|reestructur\w*|"
184
+ r"refaktorisier\w*|umschreib\w*|umstrukturier\w*|"
185
+ r"refactoris\w*|réécr\w*|restructur\w*|"
186
+ r"refator\w*|reescrev\w*|"
187
+ r"rifattorizz\w*|"
188
+ r"перепиш\w*|отрефактор\w*|передела\w*|модернизируй\w*)\b|"
189
+ r"(重构|重写|改构|リファクタリング|再構築|書き直し)",
190
+ re.I
191
+ )),
192
+ ("DEBUG", re.compile(
193
+ r"\b(fix|debug|resolve|error|bug|issue|broken|failing|crash|build\s*fail\w*|"
194
+ r"arregl\w*|correg\w*|repar\w*|depur\w*|fall\w*|"
195
+ r"beheb\w*|reparier\w*|fehlschlag\w*|fehler\w*|korrigier\w*|"
196
+ r"corrig\w*|répar\w*|débogu\w*|bogue\w*|"
197
+ r"consert\w*|falha\w*|"
198
+ r"risolv\w*|guast\w*|"
199
+ r"почин\w*|исправ\w*|баг\w*|ошибк\w*|не\s*работает|пада\w*|падени\w*|не\s*собирается|собирается|не\s*компилируется|сборк\w*|билд\w*)\b|"
200
+ r"(修复|修好|调试|报错|错误|崩溃|修正|デバッグ|バグ|エラー|不具合)",
201
+ re.I
202
+ )),
203
+ ("CREATE", re.compile(
204
+ r"\b(create|add|implement|build|write|new|generate|"
205
+ r"cre\w*|añad\w*|agreg\w*|implement\w*|escrib\w*|gener\w*|"
206
+ r"erstell\w*|hinzufüg\w*|bau\w*|"
207
+ r"cré\w*|ajout\w*|écr\w*|"
208
+ r"adicion\w*|escrev\w*|"
209
+ r"creare|aggiung\w*|"
210
+ r"созда\w*|добав\w*|напиш\w*|реализу\w*|сдела\w*)\b|"
211
+ r"(创建|添加|实现|编写|新建|生成|作成|追加|実装|書く|新規)",
212
+ re.I
213
+ )),
214
+ ("AUDIT", re.compile(
215
+ r"\b(audit|review|check|security|analyze|verify|"
216
+ r"auditar|revisar|verificar|analizar|"
217
+ r"überprüf\w*|prüf\w*|analysier\w*|auditier\w*|"
218
+ r"auditer|inspect\w*|vérifi\w*|"
219
+ r"ispezion\w*|"
220
+ r"провер\w*|проанализируй\w*|аудит\w*|ревью)\b|"
221
+ r"(审查|审核|检查|分析|验证|監査|レビュー|確認|診断|解析|検証)",
222
+ re.I
223
+ )),
224
+ ("RUN", re.compile(
225
+ r"\b(run|execute|start|launch|"
226
+ r"ejecutar|iniciar|lanzar|"
227
+ r"ausführen|starten|"
228
+ r"exécuter|démarrer|"
229
+ r"rodar|"
230
+ r"eseguire|"
231
+ r"запуст\w*|выполн\w*|старту\w*)\b|"
232
+ r"(运行|执行|启动|実行|起動|開始)",
233
+ re.I
234
+ )),
235
+ ("EXPLAIN", re.compile(
236
+ r"\b(explain|why|how\s+does|what\s+is|clarify|"
237
+ r"explicar|por\s+qu[eé]|c[oó]mo\s+funciona|qu[eé]\s+es|"
238
+ r"erklären|warum|wie\s+funktioniert|was\s+ist|"
239
+ r"expliquer|pourquoi|comment\s+fonctionne|"
240
+ r"spiegare|perch[eé]|come\s+funziona|"
241
+ r"объясн\w*|почему|как\s+работает|что\s+делает|поясн\w*)\b|"
242
+ r"(解释|为什么|如何工作|什么作用|说明|説明|なぜ|どう動く|どういうこと|解説)",
243
+ re.I
244
+ )),
50
245
  ]
51
246
 
52
- FILE_REGEX = re.compile(r"[\w\-\./\\]+\.(?:ts|js|tsx|jsx|py|go|rs|java|c|cpp|h|json|yaml|yml|md|proto|toml|sql|html|css|sh)", re.I)
247
+ FILE_REGEX = re.compile(
248
+ r'(?:'
249
+ r'(?:[\w\-\./\\]+[\/\\])?[\w\-\.]+\.(?:ts|js|tsx|jsx|py|go|rs|java|c|cpp|h|hpp|json|yaml|yml|md|proto|toml|sql|html|css|scss|sh|bash|zsh|lock|vue|svelte|graphql|prisma)'
250
+ r'|(?:\.env(?:\.[\w\-]+)?|\.gitignore|\.dockerignore|\.prettierrc[\w\.\-]*|\.eslintrc[\w\.\-]*|\.npmignore|\.npmrc|\.yarnrc)'
251
+ r'|\b(?:Dockerfile(?:\.[\w\-]+)?|Makefile|Procfile|Gemfile|Vagrantfile|Containerfile)\b'
252
+ r'|\b(?:README(?:\.md)?|LICENSE|CHANGELOG(?:\.md)?)\b'
253
+ r')',
254
+ re.I
255
+ )
53
256
 
54
257
  TRAIT_MAPPINGS = [
55
- (re.compile(r"\b(async|асинхронн\w*)\b", re.I), "async"),
56
- (re.compile(r"\b(sync|синхронн\w*)\b", re.I), "sync"),
258
+ (re.compile(r"\b(async|асинхронн\w*|as[ií]ncron\w*|asynchrone|asynchron)\b|(异步|非同期)", re.I), "async"),
259
+ (re.compile(r"\b(sync|синхронн\w*|s[ií]ncron\w*|synchrone|synchron)\b|(同步)", re.I), "sync"),
57
260
  (re.compile(r"\b(redis|редис)\b", re.I), "redis"),
58
- (re.compile(r"\b(cache|кэш|кеш|кэширован\w*|кеширован\w*)\b", re.I), "cache"),
261
+ (re.compile(r"\b(cache|кэш\w*|кеш\w*|cach[eé]|speicher)\b|(缓存|キャッシュ)", re.I), "cache"),
262
+ (re.compile(r"\b(lru)\b", re.I), "lru"),
59
263
  (re.compile(r"\b(postgres|postgresql|постгрес)\b", re.I), "postgres"),
60
264
  (re.compile(r"\b(sqlite)\b", re.I), "sqlite"),
265
+ (re.compile(r"\b(mysql)\b", re.I), "mysql"),
61
266
  (re.compile(r"\b(prisma|призма)\b", re.I), "prisma"),
62
267
  (re.compile(r"\b(docker|докер)\b", re.I), "docker"),
63
- (re.compile(r"\b(jwt|токен\w*|auth|авторизац\w*)\b", re.I), "jwt"),
64
- (re.compile(r"\b(zero_alloc|без аллокаций)\b", re.I), "zero_alloc"),
65
- (re.compile(r"\b(typesafe|типизац\w*|типобезопасн\w*)\b", re.I), "typesafe"),
268
+ (re.compile(r"\b(bunny|банни)\b", re.I), "bunny"),
269
+ (re.compile(r"\b(jwt|токен\w*|auth|авторизац\w*|autenticaci[oó]n|authentification|token)\b|(认证|認証)", re.I), "jwt"),
270
+ (re.compile(r"\b(oauth)\b", re.I), "oauth"),
271
+ (re.compile(r"\b(zero_alloc|без\s+аллокаций|sin\s+asignaciones|ohne\s+allokation)\b", re.I), "zero_alloc"),
272
+ (re.compile(r"\b(typesafe|типизац\w*|типобезопасн\w*|типами|типы|tipado|typesécurisé|typsicher)\b|(类型安全|型安全)", re.I), "typesafe"),
66
273
  (re.compile(r"\b(tailwind)\b", re.I), "tailwind"),
67
- (re.compile(r"\b(unit_test|юнит\w*)\b", re.I), "unit_test"),
274
+ (re.compile(r"\b(unit[\s_-]?test|юнит\w*|prueba\s+unitaria|test\s+unitaire)\b|(单测|単体テスト)", re.I), "unit_test"),
275
+ (re.compile(r"\b(e2e)\b", re.I), "e2e"),
276
+ (re.compile(r"\b(mock|мок\w*)\b", re.I), "mock"),
277
+ (re.compile(r"\b(npm)\b", re.I), "npm"),
278
+ (re.compile(r"\b(pypi)\b", re.I), "pypi"),
279
+ (re.compile(r"\b(gemini|гемини)\b", re.I), "gemini"),
280
+ (re.compile(r"\b(deepseek|дипсик)\b", re.I), "deepseek"),
281
+ (re.compile(r"\b(swagger|openapi)\b", re.I), "swagger"),
282
+ (re.compile(r"\b(rest|api)\b", re.I), "rest"),
283
+ (re.compile(r"\b(graphql)\b", re.I), "graphql"),
284
+ (re.compile(r"\b(grpc)\b", re.I), "grpc"),
285
+ (re.compile(r"\b(websocket|ws)\b", re.I), "websocket"),
286
+ (re.compile(r"\b(sse)\b", re.I), "sse"),
287
+ (re.compile(r"\b(react)\b", re.I), "react"),
288
+ (re.compile(r"\b(vite)\b", re.I), "vite"),
289
+ (re.compile(r"\b(nextjs|next\.js)\b", re.I), "nextjs"),
290
+ (re.compile(r"\b(git|github)\b", re.I), "git"),
291
+ (re.compile(r"\b(ci|github_actions|action)\b", re.I), "ci"),
292
+ (re.compile(r"\b(mcp)\b", re.I), "mcp"),
293
+ (re.compile(r"\b(crypto|ed25519|aes|cripto|krypto|cryptographie)\b|(加密|暗号化)", re.I), "crypto"),
68
294
  ]
69
295
 
296
+ SYMBOL_KEYWORDS = (
297
+ r"(?:function|función|funcion|funktion|fonction|função|funcao|funzione|функци[яиейюь]*|"
298
+ r"method|método|metodo|methode|méthode|метод[аеуомы]*|"
299
+ r"class|clase|klasse|classe|класс[аеуомы]*|"
300
+ r"handler|gestionnaire|gestore|хэндлер\w*|"
301
+ r"endpoint|эндпоинт\w*|enrutador|"
302
+ r"component|componente|composant|komponente|компонент\w*|"
303
+ r"route|ruta|роут\w*|"
304
+ r"hook|хук\w*|"
305
+ r"service|servicio|serviço|servizio|dienst|сервис\w*|"
306
+ r"controller|controlador|contrôleur|controleur|контроллер\w*|"
307
+ r"variable|variável|variavel|variabile|переменн[уюаяые]+|"
308
+ r"interface|interfaz|schnittstelle|interfaccia|интерфейс\w*|"
309
+ r"type|tipo|typ|тип\w*|"
310
+ r"struct|estructura|struktur|structure|struttura|структур\w*|"
311
+ r"symbol|símbolo|simbolo|symbole|символ\w*)"
312
+ )
313
+ SYMBOL_REGEX_KEYWORD = re.compile(SYMBOL_KEYWORDS + r"\s+[`'\"\(]?([a-zA-Z_][a-zA-Z0-9_]*)", re.I)
314
+ SYMBOL_CJK_KW = r"(?:函数|方法|类|接口|类型|结构体|变量|端点|组件|関数|メソッド|クラス|ハンドラー|エンドポイント|コンポーネント|変数|型|構造体)"
315
+ SYMBOL_REGEX_CJK_PREFIX = re.compile(SYMBOL_CJK_KW + r"[\s`'\"\(]*([a-zA-Z_][a-zA-Z0-9_]*)")
316
+ SYMBOL_REGEX_CJK_SUFFIX = re.compile(r"([a-zA-Z_][a-zA-Z0-9_]*)[\s`'\"\)]*" + SYMBOL_CJK_KW)
317
+ SYMBOL_REGEX_BACKTICK = re.compile(r"`([a-zA-Z_][a-zA-Z0-9_]*)`")
318
+ SYMBOL_REGEX_CALL = re.compile(r"\b([a-zA-Z_][a-zA-Z0-9_]*)\(\)")
319
+
70
320
  DEFAULT_MIN_DISTILL_TOKENS = 100
71
321
 
72
322
  @classmethod
@@ -84,6 +334,26 @@ class PromptCompactor:
84
334
  pass
85
335
  return cls.DEFAULT_MIN_DISTILL_TOKENS
86
336
 
337
+ @classmethod
338
+ def extract_symbol(cls, text: str, target_file: str = "") -> str:
339
+ """Extracts identifier/symbol name from text across supported languages."""
340
+ m_sym = cls.SYMBOL_REGEX_KEYWORD.search(text)
341
+ if m_sym and m_sym.group(1) != target_file:
342
+ return m_sym.group(1)
343
+ m_cjk_pre = cls.SYMBOL_REGEX_CJK_PREFIX.search(text)
344
+ if m_cjk_pre and m_cjk_pre.group(1) != target_file:
345
+ return m_cjk_pre.group(1)
346
+ m_cjk_suf = cls.SYMBOL_REGEX_CJK_SUFFIX.search(text)
347
+ if m_cjk_suf and m_cjk_suf.group(1) != target_file:
348
+ return m_cjk_suf.group(1)
349
+ m_backtick = cls.SYMBOL_REGEX_BACKTICK.search(text)
350
+ if m_backtick and m_backtick.group(1) != target_file:
351
+ return m_backtick.group(1)
352
+ m_call = cls.SYMBOL_REGEX_CALL.search(text)
353
+ if m_call and m_call.group(1) != target_file:
354
+ return m_call.group(1)
355
+ return ""
356
+
87
357
  @classmethod
88
358
  def compact(
89
359
  cls,
@@ -94,8 +364,8 @@ class PromptCompactor:
94
364
  """
95
365
  Compresses input prompt via 3-Tier Architecture:
96
366
  - Tier 0: Pass-through for very short inputs (< 6 tokens)
97
- - Tier 1: Local Regex Compactor (0ms, 0 external tokens) for inputs < 100 tokens
98
- - Tier 2: LLM Distiller (DeepSeek / Gemini / OpenAI) for long/complex prompts (>= 100 tokens)
367
+ - Tier 1: Multilingual Regex Compactor (0ms, 0 external tokens) for inputs < 100 tokens
368
+ - Tier 2: Universal Distiller (DeepSeek / Gemini / OpenAI) for long/complex prompts (>= 100 tokens)
99
369
  """
100
370
  if not raw_text or not raw_text.strip():
101
371
  return {
@@ -153,13 +423,8 @@ class PromptCompactor:
153
423
  files = cls.FILE_REGEX.findall(distilled)
154
424
  target_file = files[0] if files else ""
155
425
 
156
- # Extract symbol if present in raw_text
157
- sym_match = re.search(
158
- r"(?:функци[юяие]|function|method|метод|class|класс|handler|хэндлер|symbol|переменн[уюая]+)\s+[`'\"]?([a-zA-Z0-9_]+)[`'\"]?",
159
- raw_text,
160
- re.I
161
- )
162
- symbol = sym_match.group(1) if sym_match else ""
426
+ # Extract symbol
427
+ symbol = cls.extract_symbol(raw_text, target_file)
163
428
 
164
429
  # Extract traits if present in distilled S-Expression: e.g. [async redis ...]
165
430
  trait_match = re.search(r"\[(.*?)\]", distilled)
@@ -179,7 +444,7 @@ class PromptCompactor:
179
444
  "tier": "DEEPSEEK_V3"
180
445
  }
181
446
 
182
- # Tier 1: Local Regex Compactor
447
+ # Tier 1: Multilingual Local Regex Compactor
183
448
  files = cls.FILE_REGEX.findall(raw_text)
184
449
  target_file = files[0] if files else ""
185
450
 
@@ -195,20 +460,14 @@ class PromptCompactor:
195
460
  if tag not in traits:
196
461
  traits.append(tag)
197
462
 
198
- symbol = ""
199
- symbol_match = re.search(
200
- r"(?:функци[юяие]|function|method|метод|class|класс|handler|хэндлер|symbol|переменн[уюая]+)\s+[`'\"]?([a-zA-Z0-9_]+)[`'\"]?",
201
- raw_text,
202
- re.I
203
- )
204
- if symbol_match:
205
- symbol = symbol_match.group(1)
463
+ symbol = cls.extract_symbol(raw_text, target_file)
206
464
 
207
465
  delta = raw_text
208
466
  if target_file:
209
467
  delta = delta.replace(target_file, " ")
210
468
  if symbol:
211
469
  delta = re.sub(r"\b" + re.escape(symbol) + r"\b", " ", delta)
470
+ delta = delta.replace(f"`{symbol}`", " ")
212
471
 
213
472
  for pattern in cls.STOP_PHRASES:
214
473
  delta = re.sub(pattern, " ", delta, flags=re.I)
@@ -219,10 +478,10 @@ class PromptCompactor:
219
478
  for regex, _ in cls.TRAIT_MAPPINGS:
220
479
  delta = regex.sub(" ", delta)
221
480
 
222
- delta = re.sub(r"[,\.:;\"'\(\)\[\]\{\}]", " ", delta)
481
+ delta = re.sub(r"[\.,:;\"'\(\)\[\]\{\}`\?¿¡!。,:;“”‘’「」『』、]", " ", delta)
223
482
  delta = re.sub(r"\s+", " ", delta).strip()
224
483
 
225
- parts = [f"({action}"]
484
+ parts = [action]
226
485
  if target_file:
227
486
  parts.append(target_file)
228
487
  if symbol:
@@ -231,12 +490,11 @@ class PromptCompactor:
231
490
  parts.append(f"[{' '.join(traits)}]")
232
491
  if delta and len(delta) > 2:
233
492
  parts.append(f'"{delta}"')
234
- parts.append(")")
235
493
 
236
- compact_expr = " ".join(parts)
494
+ compact_expr = f"({' '.join(parts)})"
237
495
  compact_tokens = count_tokens(compact_expr)
238
496
 
239
- if compact_tokens >= original_tokens:
497
+ if compact_tokens > original_tokens:
240
498
  compact_expr = raw_text.strip()
241
499
  compact_tokens = original_tokens
242
500
 
package/src/dashboard.py CHANGED
@@ -14,6 +14,7 @@ if BASE_DIR not in sys.path:
14
14
  sys.path.insert(0, BASE_DIR)
15
15
 
16
16
  from src.metrics import MetricsTracker
17
+ from src.license_manager import LicenseManager
17
18
  try:
18
19
  from src.version_checker import VersionChecker
19
20
  except ImportError:
@@ -24,6 +25,7 @@ BOLD = "\033[1m"
24
25
  GREEN = "\033[32m"
25
26
  CYAN = "\033[36m"
26
27
  YELLOW = "\033[33m"
28
+ RED = "\033[31m"
27
29
  MAGENTA = "\033[35m"
28
30
  BLUE = "\033[34m"
29
31
  DIM = "\033[2m"
@@ -72,6 +74,23 @@ class Dashboard:
72
74
  out.append(f"{BOLD}{CYAN}╚════════════════════════════════════════════════════════════════════╝{RESET}\n")
73
75
 
74
76
  # Top summary cards
77
+ tier, payload = LicenseManager.get_active_license()
78
+ tier_upper = tier.upper()
79
+ if tier == "free":
80
+ monthly_saved = self.tracker.get_monthly_saved_tokens()
81
+ limit = 500_000
82
+ q_pct = min(100.0, (monthly_saved / limit * 100.0))
83
+ if monthly_saved >= limit:
84
+ out.append(f" {BOLD}Subscription Tier:{RESET} {YELLOW}COMMUNITY (Free){RESET} • {RED}{BOLD}500k Monthly Quota Reached{RESET}")
85
+ out.append(f" {BOLD}Quota Usage:{RESET} {RED}{render_bar(q_pct)}{RESET} (Upgrade to Solo for Unlimited: {CYAN}https://tokensafe.dev/#pricing{RESET})")
86
+ else:
87
+ out.append(f" {BOLD}Subscription Tier:{RESET} {YELLOW}COMMUNITY (Free){RESET} • {monthly_saved:,} / {limit:,} tokens this month")
88
+ out.append(f" {BOLD}Quota Usage:{RESET} {YELLOW}{render_bar(q_pct)}{RESET} (Upgrade to Solo for Unlimited)")
89
+ else:
90
+ email_info = f" ({payload.get('email', '')})" if payload.get('email') else ""
91
+ out.append(f" {BOLD}Subscription Tier:{RESET} {GREEN}{BOLD}{tier_upper} (Unlimited){RESET}{email_info}")
92
+ out.append("")
93
+
75
94
  out.append(f" {BOLD}Total Tokens Saved:{RESET} {GREEN}{BOLD}{total_saved:,}{RESET} tokens")
76
95
  out.append(f" {BOLD}Efficiency Gain:{RESET} {YELLOW}{BOLD}{render_bar(pct)}{RESET}")
77
96
  out.append(f" {BOLD}Estimated Savings:{RESET} {GREEN}${usd:.4f} USD{RESET}")
@@ -105,8 +124,8 @@ class Dashboard:
105
124
 
106
125
  out.append(f" [{DIM}{t_str}{RESET}] {CYAN}{ev_type:<15}{RESET} {detail_desc:<20} ➔ {GREEN}+{saved:,} saved{RESET} ({pct_ev:.1f}%)")
107
126
 
108
- out.append(f"\n{DIM}Run `tokensafe test \"<prompt>\"` (or `agy-tokens`) to test compression on custom input.{RESET}")
109
- out.append(f"{DIM}Run `tokensafe html` (or `agy-tokens html`) to view interactive browser dashboard.{RESET}")
127
+ out.append(f"\n{DIM}Run `tokensafe test \"<prompt>\"` to test compression on custom input.{RESET}")
128
+ out.append(f"{DIM}Run `tokensafe html` to view interactive browser dashboard.{RESET}")
110
129
 
111
130
  if VersionChecker:
112
131
  banner = VersionChecker.get_banner()
@@ -203,6 +222,29 @@ class Dashboard:
203
222
  </tr>
204
223
  """
205
224
 
225
+ tier, payload = LicenseManager.get_active_license()
226
+ if tier == "free":
227
+ monthly_saved = self.tracker.get_monthly_saved_tokens()
228
+ limit = 500_000
229
+ q_pct = min(100.0, round(monthly_saved / limit * 100.0, 1))
230
+ banner_html = f"""
231
+ <div style="background: rgba(234, 179, 8, 0.1); border: 1px solid rgba(234, 179, 8, 0.3); border-radius: 12px; padding: 14px 18px; margin-bottom: 24px; display: flex; justify-content: space-between; align-items: center; font-size: 13px;">
232
+ <div>
233
+ <strong style="color: #eab308;">⚡ Community Edition:</strong> {monthly_saved:,} / {limit:,} free tokens saved this month ({q_pct}%).
234
+ </div>
235
+ <a href="https://tokensafe.dev/#pricing" target="_blank" style="background: #10b981; color: #090a0f; font-weight: 700; padding: 6px 14px; border-radius: 8px; text-decoration: none; font-size: 12px;">Upgrade to Solo (Unlimited)</a>
236
+ </div>
237
+ """
238
+ else:
239
+ banner_html = f"""
240
+ <div style="background: rgba(16, 185, 129, 0.1); border: 1px solid rgba(16, 185, 129, 0.3); border-radius: 12px; padding: 14px 18px; margin-bottom: 24px; display: flex; justify-content: space-between; align-items: center; font-size: 13px;">
241
+ <div>
242
+ <strong style="color: #10b981;">⚡ License Active:</strong> TokenSafe {tier.upper()} Plan (Unlimited Tokens).
243
+ </div>
244
+ <span style="color: #9ca3af; font-size: 12px;">{payload.get('email', '')}</span>
245
+ </div>
246
+ """
247
+
206
248
  html = f"""<!DOCTYPE html>
207
249
  <html lang="en">
208
250
  <head>
@@ -267,6 +309,8 @@ class Dashboard:
267
309
  </div>
268
310
  </div>
269
311
 
312
+ {banner_html}
313
+
270
314
  <div class="stats-grid">
271
315
  <div class="stat-card">
272
316
  <div class="stat-label">Total Tokens Saved</div>
@@ -19,18 +19,21 @@ class DeepSeekDistiller:
19
19
  DEFAULT_MODEL = "deepseek-flash"
20
20
  DEFAULT_TIMEOUT = 3.5
21
21
 
22
- SYSTEM_PROMPT = """You are a semantic code intent compiler for the Token-Optimized Communication Protocol (TOCP). Your task is to compress verbose, conversational developer requests into an ultra-dense S-Expression with this exact syntax:
22
+ SYSTEM_PROMPT = """You are a multilingual semantic code intent compiler for the Token-Optimized Communication Protocol (TOCP). Your task is to compress verbose, conversational developer requests into an ultra-dense S-Expression with this exact syntax:
23
23
  (ACTION [filepath] [symbol] [[traits...]] ["minimal_intent"])
24
24
 
25
25
  Available ACTIONS: REFACTOR, DEBUG, CREATE, OPTIMIZE, EXPLAIN, AUDIT, TEST, RUN.
26
26
 
27
27
  Examples:
28
- Input: "Слушай, перепиши пожалуйста функцию get_balance в файле wallet.ts, добавь туда redis cache и сделай её асинхронной"
28
+ Input: "Could you please rewrite the get_balance function in wallet.ts, add redis caching to it and make it async?"
29
29
  Output: (REFACTOR wallet.ts get_balance [async redis] "add caching and async")
30
30
 
31
- Input: "У меня в auth.controller.ts при логине через гугл если нет аватарки промис зависает на 30 сек и падает 504"
31
+ Input: "In auth.controller.ts during Google login, if user has no avatar the promise hangs for 30s and throws 504"
32
32
  Output: (DEBUG auth.controller.ts [oauth google timeout_504 missing_avatar] "fix 30s hang on no avatar")
33
33
 
34
+ Input: "Por favor arregla la función validate_token en auth.py para que verifique jwt y devuelva boolean"
35
+ Output: (DEBUG auth.py validate_token [jwt] "verify jwt and return boolean")
36
+
34
37
  Rules:
35
38
  1. Output ONLY the S-Expression starting with ( and ending with ).
36
39
  2. No markdown code blocks, no preamble, no explanations.
package/src/distiller.py CHANGED
@@ -18,18 +18,21 @@ class UniversalDistiller:
18
18
 
19
19
  DEFAULT_TIMEOUT = 3.5
20
20
 
21
- SYSTEM_PROMPT = """You are a semantic code intent compiler for the Token-Optimized Communication Protocol (TOCP). Your task is to compress verbose, conversational developer requests into an ultra-dense S-Expression with this exact syntax:
21
+ SYSTEM_PROMPT = """You are a multilingual semantic code intent compiler for the Token-Optimized Communication Protocol (TOCP). Your task is to compress verbose, conversational developer requests into an ultra-dense S-Expression with this exact syntax:
22
22
  (ACTION [filepath] [symbol] [[traits...]] ["minimal_intent"])
23
23
 
24
24
  Available ACTIONS: REFACTOR, DEBUG, CREATE, OPTIMIZE, EXPLAIN, AUDIT, TEST, RUN.
25
25
 
26
26
  Examples:
27
- Input: "Слушай, перепиши пожалуйста функцию get_balance в файле wallet.ts, добавь туда redis cache и сделай её асинхронной"
27
+ Input: "Could you please rewrite the get_balance function in wallet.ts, add redis caching to it and make it async?"
28
28
  Output: (REFACTOR wallet.ts get_balance [async redis] "add caching and async")
29
29
 
30
- Input: "У меня в auth.controller.ts при логине через гугл если нет аватарки промис зависает на 30 сек и падает 504"
30
+ Input: "In auth.controller.ts during Google login, if user has no avatar the promise hangs for 30s and throws 504"
31
31
  Output: (DEBUG auth.controller.ts [oauth google timeout_504 missing_avatar] "fix 30s hang on no avatar")
32
32
 
33
+ Input: "Por favor arregla la función validate_token en auth.py para que verifique jwt y devuelva boolean"
34
+ Output: (DEBUG auth.py validate_token [jwt] "verify jwt and return boolean")
35
+
33
36
  Rules:
34
37
  1. Output ONLY the S-Expression starting with ( and ending with ).
35
38
  2. No markdown code blocks, no preamble, no explanations.