codis 1.1.1__py3-none-any.whl

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 (329) hide show
  1. codis-1.1.1.dist-info/METADATA +194 -0
  2. codis-1.1.1.dist-info/RECORD +329 -0
  3. codis-1.1.1.dist-info/WHEEL +5 -0
  4. codis-1.1.1.dist-info/entry_points.txt +5 -0
  5. codis-1.1.1.dist-info/licenses/LICENSE +21 -0
  6. codis-1.1.1.dist-info/top_level.txt +2 -0
  7. run.py +190 -0
  8. src/__init__.py +1 -0
  9. src/__main__.py +81 -0
  10. src/_app_build.py +1507 -0
  11. src/_app_editor.py +1274 -0
  12. src/_app_kui.py +825 -0
  13. src/_app_lsp.py +625 -0
  14. src/_app_recovery.py +189 -0
  15. src/_app_settings.py +1385 -0
  16. src/_app_tools.py +2471 -0
  17. src/_app_webpreview.py +126 -0
  18. src/_font_safety.py +127 -0
  19. src/_shells.py +172 -0
  20. src/app.py +1488 -0
  21. src/chat/__init__.py +1 -0
  22. src/chat/adapters/__init__.py +33 -0
  23. src/chat/adapters/base.py +209 -0
  24. src/chat/adapters/discord.py +190 -0
  25. src/chat/adapters/http.py +78 -0
  26. src/chat/adapters/irc.py +360 -0
  27. src/chat/adapters/matrix.py +219 -0
  28. src/chat/adapters/mattermost.py +178 -0
  29. src/chat/adapters/mqtt.py +165 -0
  30. src/chat/adapters/slack.py +204 -0
  31. src/chat/adapters/telegram.py +117 -0
  32. src/chat/adapters/ws.py +154 -0
  33. src/chat/adapters/xmpp.py +337 -0
  34. src/chat/history.py +76 -0
  35. src/chat/models.py +207 -0
  36. src/chat/probe.py +79 -0
  37. src/chat/session.py +446 -0
  38. src/chat/util.py +125 -0
  39. src/collab/__init__.py +1 -0
  40. src/collab/net.py +411 -0
  41. src/collab/ot.py +311 -0
  42. src/collab/session.py +141 -0
  43. src/collab/tk_adapter.py +134 -0
  44. src/config.py +335 -0
  45. src/constants.py +2552 -0
  46. src/dep_catalog.py +446 -0
  47. src/diff/__init__.py +1 -0
  48. src/diff/engine.py +247 -0
  49. src/dpi.py +30 -0
  50. src/editor/__init__.py +1 -0
  51. src/editor/_pane_lsp.py +2937 -0
  52. src/editor/_pane_utils.py +171 -0
  53. src/editor/autocomplete.py +607 -0
  54. src/editor/code_folding.py +836 -0
  55. src/editor/color_preview.py +382 -0
  56. src/editor/complexity_lens.py +281 -0
  57. src/editor/diff_pane.py +623 -0
  58. src/editor/file_watcher.py +144 -0
  59. src/editor/focus_block.py +236 -0
  60. src/editor/heatmap.py +141 -0
  61. src/editor/inlay_hints.py +366 -0
  62. src/editor/inline_blame.py +429 -0
  63. src/editor/kdocs.py +3376 -0
  64. src/editor/large_file.py +488 -0
  65. src/editor/ligatures.py +180 -0
  66. src/editor/line_numbers.py +598 -0
  67. src/editor/minimap.py +691 -0
  68. src/editor/multi_cursor.py +269 -0
  69. src/editor/pane.py +2082 -0
  70. src/editor/rhythm.py +206 -0
  71. src/editor/save_hooks.py +43 -0
  72. src/editor/smart_selection.py +425 -0
  73. src/editor/smart_tips.py +719 -0
  74. src/editor/snippets.py +411 -0
  75. src/editor/sticky_note_gutter.py +410 -0
  76. src/editor/sticky_scroll.py +385 -0
  77. src/editor/suggest.py +464 -0
  78. src/editor/text_transforms.py +310 -0
  79. src/editor/vim_mode.py +1074 -0
  80. src/events/__init__.py +84 -0
  81. src/events/bus.py +427 -0
  82. src/events/correlator.py +244 -0
  83. src/events/kinds.py +125 -0
  84. src/events/pipeline.py +264 -0
  85. src/events/stream.py +416 -0
  86. src/events/window.py +204 -0
  87. src/extcompat/__init__.py +19 -0
  88. src/extcompat/code/__init__.py +13 -0
  89. src/extcompat/code/consent.py +162 -0
  90. src/extcompat/code/host.py +353 -0
  91. src/extcompat/code/hosts/py_host.py +763 -0
  92. src/extcompat/code/locate.py +105 -0
  93. src/extcompat/code/manager.py +325 -0
  94. src/extcompat/code/permissions.py +154 -0
  95. src/extcompat/code/sandbox.py +60 -0
  96. src/extcompat/colors.py +131 -0
  97. src/extcompat/common.py +184 -0
  98. src/extcompat/cson.py +269 -0
  99. src/extcompat/formats/__init__.py +22 -0
  100. src/extcompat/formats/_tm.py +189 -0
  101. src/extcompat/formats/_util.py +31 -0
  102. src/extcompat/formats/base16.py +66 -0
  103. src/extcompat/formats/brackets.py +172 -0
  104. src/extcompat/formats/eclipse.py +193 -0
  105. src/extcompat/formats/emacs.py +361 -0
  106. src/extcompat/formats/geany.py +147 -0
  107. src/extcompat/formats/generic.py +184 -0
  108. src/extcompat/formats/gtksource.py +117 -0
  109. src/extcompat/formats/helix.py +91 -0
  110. src/extcompat/formats/jetbrains.py +343 -0
  111. src/extcompat/formats/kate.py +130 -0
  112. src/extcompat/formats/micro.py +131 -0
  113. src/extcompat/formats/nano.py +111 -0
  114. src/extcompat/formats/notepadpp.py +140 -0
  115. src/extcompat/formats/pulsar.py +165 -0
  116. src/extcompat/formats/pyides.py +163 -0
  117. src/extcompat/formats/sublime.py +340 -0
  118. src/extcompat/jsonc.py +65 -0
  119. src/extcompat/lessish.py +128 -0
  120. src/extcompat/manager.py +122 -0
  121. src/extcompat/market/__init__.py +63 -0
  122. src/extcompat/market/sources.py +211 -0
  123. src/extcompat/model.py +88 -0
  124. src/extcompat/net.py +228 -0
  125. src/extcompat/openvsx.py +63 -0
  126. src/extcompat/readers.py +362 -0
  127. src/extcompat/registry.py +73 -0
  128. src/extcompat/safexml.py +63 -0
  129. src/extcompat/sexp.py +187 -0
  130. src/extcompat/sources.py +105 -0
  131. src/extcompat/store.py +276 -0
  132. src/extcompat/textmate.py +214 -0
  133. src/extcompat/themes.py +487 -0
  134. src/extcompat/yamlite.py +294 -0
  135. src/fileio.py +94 -0
  136. src/fs_ops.py +106 -0
  137. src/i18n.py +233 -0
  138. src/ia/__init__.py +1 -0
  139. src/ia/actions.py +295 -0
  140. src/ia/approval_gate.py +672 -0
  141. src/ia/checkpoints.py +308 -0
  142. src/ia/context_builder.py +921 -0
  143. src/ia/dialdiff.py +408 -0
  144. src/ia/iaspace.py +2078 -0
  145. src/ia/pair.py +296 -0
  146. src/ia/providers.py +954 -0
  147. src/ia/session.py +335 -0
  148. src/ia/toolbox.py +2524 -0
  149. src/launcher_actions.py +204 -0
  150. src/lint/__init__.py +1 -0
  151. src/lint/manager.py +1058 -0
  152. src/locales/.translate_manifest.json +64170 -0
  153. src/locales/de.json +4936 -0
  154. src/locales/en.json +4936 -0
  155. src/locales/es.json +4936 -0
  156. src/locales/fr.json +4936 -0
  157. src/locales/it.json +4936 -0
  158. src/locales/ja.json +4936 -0
  159. src/locales/ko.json +4936 -0
  160. src/locales/nl.json +4936 -0
  161. src/locales/pl.json +4936 -0
  162. src/locales/pt-BR.json +4936 -0
  163. src/locales/ru.json +4936 -0
  164. src/locales/tr.json +4936 -0
  165. src/locales/uk.json +4936 -0
  166. src/locales/zh-CN.json +4936 -0
  167. src/lsp/__init__.py +26 -0
  168. src/lsp/client.py +2300 -0
  169. src/lsp/dap_client.py +480 -0
  170. src/lsp/edits.py +84 -0
  171. src/lsp/framing.py +73 -0
  172. src/lsp/protocol.py +931 -0
  173. src/main.py +260 -0
  174. src/memtrim.py +91 -0
  175. src/plugins/__init__.py +1 -0
  176. src/plugins/api.py +1761 -0
  177. src/plugins/loader.py +571 -0
  178. src/plugins/process_runner.py +519 -0
  179. src/plugins/registry.py +342 -0
  180. src/plugins/safety.py +367 -0
  181. src/plugins/startup.py +195 -0
  182. src/plugins/store.py +1178 -0
  183. src/proc_registry.py +278 -0
  184. src/pyexec.py +394 -0
  185. src/recovery.py +259 -0
  186. src/stall_trace.py +92 -0
  187. src/standalone.py +1070 -0
  188. src/startup_profile.py +35 -0
  189. src/syntax/__init__.py +1 -0
  190. src/syntax/highlighter.py +776 -0
  191. src/syntax/patterns.py +584 -0
  192. src/system_profile.py +430 -0
  193. src/terminal/backends.py +658 -0
  194. src/terminal/internal.py +346 -0
  195. src/terminal/keys.py +138 -0
  196. src/terminal/palette.py +67 -0
  197. src/terminal/session.py +283 -0
  198. src/terminal/shells.py +79 -0
  199. src/terminal/view.py +489 -0
  200. src/terminal/vt.py +870 -0
  201. src/textfmt.py +22 -0
  202. src/theme/__init__.py +1 -0
  203. src/theme/base.py +1281 -0
  204. src/theme/colors.py +49 -0
  205. src/theme/manager.py +602 -0
  206. src/theme/utils.py +312 -0
  207. src/toolbox.py +329 -0
  208. src/trash_core.py +531 -0
  209. src/ui/__init__.py +1 -0
  210. src/ui/_perf_utils.py +285 -0
  211. src/ui/_persistence_utils.py +93 -0
  212. src/ui/accessibility.py +843 -0
  213. src/ui/activity_bar.py +860 -0
  214. src/ui/app_embed.py +434 -0
  215. src/ui/archive_panel.py +608 -0
  216. src/ui/bookmarks.py +314 -0
  217. src/ui/breadcrumb.py +383 -0
  218. src/ui/calculator_panel.py +982 -0
  219. src/ui/calendar_panel.py +1218 -0
  220. src/ui/chat_panel.py +1271 -0
  221. src/ui/chat_profile_dialog.py +278 -0
  222. src/ui/chat_render.py +128 -0
  223. src/ui/clock_panel.py +810 -0
  224. src/ui/code_outline.py +364 -0
  225. src/ui/code_runner.py +729 -0
  226. src/ui/code_stats.py +546 -0
  227. src/ui/collab_panel.py +1009 -0
  228. src/ui/color_picker.py +547 -0
  229. src/ui/command_palette.py +452 -0
  230. src/ui/cursor_manager.py +750 -0
  231. src/ui/custom_keywords_panel.py +413 -0
  232. src/ui/debug_panel.py +1037 -0
  233. src/ui/dependency_graph.py +692 -0
  234. src/ui/diff_panel.py +381 -0
  235. src/ui/docs_panel.py +514 -0
  236. src/ui/doom_embed.py +349 -0
  237. src/ui/dropdown.py +321 -0
  238. src/ui/easter_eggs.py +979 -0
  239. src/ui/env_manager.py +666 -0
  240. src/ui/extcode_bridge.py +215 -0
  241. src/ui/extcode_dialogs.py +412 -0
  242. src/ui/extcompat_dialog.py +583 -0
  243. src/ui/file_timeline.py +319 -0
  244. src/ui/file_tree.py +1208 -0
  245. src/ui/find_in_files.py +1355 -0
  246. src/ui/flowchart_panel.py +727 -0
  247. src/ui/formatter_panel.py +490 -0
  248. src/ui/git_auth.py +763 -0
  249. src/ui/git_clone_dialog.py +487 -0
  250. src/ui/git_panel.py +1483 -0
  251. src/ui/grab_safe.py +84 -0
  252. src/ui/internal_python_dialog.py +98 -0
  253. src/ui/k_ui/__init__.py +1305 -0
  254. src/ui/k_ui/_bgrenderer.py +317 -0
  255. src/ui/k_ui/_colors.py +213 -0
  256. src/ui/k_ui/_dock.py +545 -0
  257. src/ui/k_ui/_easter.py +290 -0
  258. src/ui/k_ui/_engine.py +5448 -0
  259. src/ui/k_ui/_perf.py +333 -0
  260. src/ui/k_ui/_tkutil.py +7 -0
  261. src/ui/k_ui/_tooltip.py +365 -0
  262. src/ui/k_ui/_widgets.py +1204 -0
  263. src/ui/k_ui/_world.py +837 -0
  264. src/ui/key_remapper.py +856 -0
  265. src/ui/launcher.py +1252 -0
  266. src/ui/lazy_panel.py +73 -0
  267. src/ui/macro_recorder.py +610 -0
  268. src/ui/menu_bar.py +898 -0
  269. src/ui/output_panel.py +321 -0
  270. src/ui/paint_canvas.py +1000 -0
  271. src/ui/paint_engine.py +535 -0
  272. src/ui/paint_panel.py +888 -0
  273. src/ui/panel_detach.py +112 -0
  274. src/ui/performance_panel.py +861 -0
  275. src/ui/pip_manager.py +1758 -0
  276. src/ui/plugin_panel.py +1586 -0
  277. src/ui/pomodoro_panel.py +447 -0
  278. src/ui/problems.py +566 -0
  279. src/ui/process_manager.py +1657 -0
  280. src/ui/project_templates.py +775 -0
  281. src/ui/recovery_dialog.py +122 -0
  282. src/ui/regex_playground.py +304 -0
  283. src/ui/remote_adapters.py +1398 -0
  284. src/ui/remote_browser.py +1224 -0
  285. src/ui/remote_profile_dialog.py +342 -0
  286. src/ui/render_panel.py +1293 -0
  287. src/ui/rest_client.py +549 -0
  288. src/ui/scratchpad.py +548 -0
  289. src/ui/search_bar.py +1274 -0
  290. src/ui/settings_editor.py +3349 -0
  291. src/ui/settings_window.py +1554 -0
  292. src/ui/snippets_panel.py +597 -0
  293. src/ui/sql_studio.py +1815 -0
  294. src/ui/status_bar.py +438 -0
  295. src/ui/tab_bar.py +654 -0
  296. src/ui/task_manager.py +1773 -0
  297. src/ui/terminal.py +525 -0
  298. src/ui/theme_preview_panel.py +851 -0
  299. src/ui/thread_safe_tk.py +152 -0
  300. src/ui/time_tracker.py +574 -0
  301. src/ui/tkbind.py +43 -0
  302. src/ui/todo_panel.py +358 -0
  303. src/ui/toolbox_panels.py +658 -0
  304. src/ui/trash_manager.py +657 -0
  305. src/ui/ui_scale.py +294 -0
  306. src/ui/ux_enhancements.py +41 -0
  307. src/ui/web_preview.py +397 -0
  308. src/ui/webdev.py +630 -0
  309. src/ui/welcome.py +567 -0
  310. src/ui/window_embed.py +1500 -0
  311. src/ui/wizard.py +1550 -0
  312. src/ui/workspace_switcher.py +418 -0
  313. src/ui/workspace_trust.py +370 -0
  314. src/ui/zen_audio.py +354 -0
  315. src/ui/zen_media.py +2271 -0
  316. src/ui/zen_media_client.py +303 -0
  317. src/ui/zen_media_host.py +329 -0
  318. src/ui/zen_player.py +907 -0
  319. src/ui/zen_player_widgets.py +700 -0
  320. src/updater/__init__.py +11 -0
  321. src/updater/assets.py +145 -0
  322. src/updater/backup.py +101 -0
  323. src/updater/channel.py +221 -0
  324. src/updater/dialog.py +492 -0
  325. src/updater/integrity.py +111 -0
  326. src/updater/manager.py +727 -0
  327. src/updater/result.py +114 -0
  328. src/venv_runtime.py +531 -0
  329. src/workspace_state.py +25 -0
src/ia/toolbox.py ADDED
@@ -0,0 +1,2524 @@
1
+ """Codis IA - Toolbox Expandido (nível Cursor/Windsurf/Zed Agent).
2
+
3
+ Ferramentas disponíveis para o assistente de IA:
4
+
5
+ LEITURA (SAFE):
6
+ read_file, read_active_file, get_cursor_context, list_files,
7
+ search_in_files, find_definition, get_project_summary, read_diagnostics,
8
+ read_symbols, read_git_diff, read_git_log, find_references,
9
+ preview_rename, workspace_symbols, get_env_info, check_dependency,
10
+ diff_files, read_file_tree, get_clipboard
11
+
12
+ ESCRITA (MEDIUM):
13
+ write_file, apply_edit, insert_after_line, format_code, patch_files
14
+
15
+ EXECUÇÃO (HIGH):
16
+ run_command, run_script, run_tests, create_directory, delete_file,
17
+ move_file, copy_file, init_project, install_dependency,
18
+ git_commit, git_stage, git_branch, open_terminal_tab
19
+
20
+ CRÍTICO (CRITICAL):
21
+ delete_directory, git_reset, git_clean
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import contextlib
27
+ import logging
28
+ import os
29
+ import re
30
+ import shutil
31
+ import subprocess
32
+ import tempfile
33
+ from collections.abc import Callable
34
+ from pathlib import Path
35
+ from typing import Any
36
+
37
+ from src import proc_registry
38
+ from src.constants import SKIP_DIRS
39
+ from src.i18n import _t
40
+ from src.ia.checkpoints import CheckpointStore
41
+ from src.workspace_state import is_restricted
42
+
43
+ logger = logging.getLogger("Codis.IA.Toolbox")
44
+
45
+ def _run(*args, **kwargs):
46
+ """``subprocess.run`` registrado como tarefa da IA, para o Gerenciador de Processos poder encerrá-lo."""
47
+ return proc_registry.run(*args, kind="ia", **kwargs)
48
+
49
+
50
+ TOOL_SCHEMA: list[dict[str, Any]] = [
51
+ {
52
+ "type": "function",
53
+ "function": {
54
+ "name": "read_file",
55
+ "description": (
56
+ "Lê o conteúdo completo de um arquivo, ou um intervalo de linhas específico. "
57
+ "Use quando o usuário perguntar sobre o conteúdo, lógica ou implementação de um arquivo."
58
+ ),
59
+ "parameters": {
60
+ "type": "object",
61
+ "properties": {
62
+ "path": {
63
+ "type": "string",
64
+ "description": "Caminho relativo à raiz do workspace ou absoluto.",
65
+ },
66
+ "start_line": {
67
+ "type": "integer",
68
+ "description": "Primeira linha (base 1, inclusiva). Padrão: 1.",
69
+ },
70
+ "end_line": {
71
+ "type": "integer",
72
+ "description": "Última linha (base 1, inclusiva). Padrão: fim.",
73
+ },
74
+ },
75
+ "required": ["path"],
76
+ },
77
+ },
78
+ },
79
+ {
80
+ "type": "function",
81
+ "function": {
82
+ "name": "read_active_file",
83
+ "description": "Retorna o conteúdo completo do arquivo aberto no editor com números de linha.",
84
+ "parameters": {"type": "object", "properties": {}, "required": []},
85
+ },
86
+ },
87
+ {
88
+ "type": "function",
89
+ "function": {
90
+ "name": "get_cursor_context",
91
+ "description": "Retorna as linhas ao redor da posição atual do cursor no editor ativo.",
92
+ "parameters": {
93
+ "type": "object",
94
+ "properties": {
95
+ "window": {
96
+ "type": "integer",
97
+ "description": "Linhas acima/abaixo do cursor. Padrão 40.",
98
+ },
99
+ },
100
+ "required": [],
101
+ },
102
+ },
103
+ },
104
+ {
105
+ "type": "function",
106
+ "function": {
107
+ "name": "list_files",
108
+ "description": "Lista arquivos e diretórios de uma pasta do workspace.",
109
+ "parameters": {
110
+ "type": "object",
111
+ "properties": {
112
+ "folder": {
113
+ "type": "string",
114
+ "description": "Caminho relativo à raiz. Padrão: '.'",
115
+ },
116
+ "recursive": {
117
+ "type": "boolean",
118
+ "description": "Se true, percorre subdiretórios. Padrão: false.",
119
+ },
120
+ "extensions": {
121
+ "type": "string",
122
+ "description": "Extensões para filtrar, ex: '.py,.js'. Padrão: todos.",
123
+ },
124
+ },
125
+ "required": [],
126
+ },
127
+ },
128
+ },
129
+ {
130
+ "type": "function",
131
+ "function": {
132
+ "name": "read_file_tree",
133
+ "description": "Retorna a árvore completa do projeto em formato visual similar ao comando 'tree'.",
134
+ "parameters": {
135
+ "type": "object",
136
+ "properties": {
137
+ "max_depth": {
138
+ "type": "integer",
139
+ "description": "Profundidade máxima. Padrão: 4.",
140
+ },
141
+ "show_hidden": {
142
+ "type": "boolean",
143
+ "description": "Incluir arquivos ocultos. Padrão: false.",
144
+ },
145
+ },
146
+ "required": [],
147
+ },
148
+ },
149
+ },
150
+ {
151
+ "type": "function",
152
+ "function": {
153
+ "name": "search_in_files",
154
+ "description": "Busca por regex em todos os arquivos do workspace.",
155
+ "parameters": {
156
+ "type": "object",
157
+ "properties": {
158
+ "query": {
159
+ "type": "string",
160
+ "description": "Expressão regular ou texto.",
161
+ },
162
+ "extensions": {
163
+ "type": "string",
164
+ "description": "Extensões para buscar. Padrão: todos.",
165
+ },
166
+ "max_results": {
167
+ "type": "integer",
168
+ "description": "Máximo de matches. Padrão 30.",
169
+ },
170
+ "case_sensitive": {
171
+ "type": "boolean",
172
+ "description": "Case sensitive? Padrão: false.",
173
+ },
174
+ },
175
+ "required": ["query"],
176
+ },
177
+ },
178
+ },
179
+ {
180
+ "type": "function",
181
+ "function": {
182
+ "name": "find_definition",
183
+ "description": "Localiza a DEFINIÇÃO de um símbolo (classe, função, variável).",
184
+ "parameters": {
185
+ "type": "object",
186
+ "properties": {
187
+ "symbol": {"type": "string"},
188
+ "extensions": {"type": "string"},
189
+ },
190
+ "required": ["symbol"],
191
+ },
192
+ },
193
+ },
194
+ {
195
+ "type": "function",
196
+ "function": {
197
+ "name": "find_references",
198
+ "description": "Encontra todos os USOS de um símbolo no workspace (excluindo a definição).",
199
+ "parameters": {
200
+ "type": "object",
201
+ "properties": {
202
+ "symbol": {"type": "string"},
203
+ "extensions": {"type": "string"},
204
+ "max_results": {
205
+ "type": "integer",
206
+ "description": "Padrão 30, máx 200.",
207
+ },
208
+ },
209
+ "required": ["symbol"],
210
+ },
211
+ },
212
+ },
213
+ {
214
+ "type": "function",
215
+ "function": {
216
+ "name": "get_project_summary",
217
+ "description": "Retorna resumo completo: tipo, linguagens, dependências, git, árvore raiz.",
218
+ "parameters": {"type": "object", "properties": {}, "required": []},
219
+ },
220
+ },
221
+ {
222
+ "type": "function",
223
+ "function": {
224
+ "name": "read_diagnostics",
225
+ "description": "Retorna erros e avisos do linter/LSP para o arquivo ativo.",
226
+ "parameters": {"type": "object", "properties": {}, "required": []},
227
+ },
228
+ },
229
+ {
230
+ "type": "function",
231
+ "function": {
232
+ "name": "read_symbols",
233
+ "description": "Lista símbolos de nível superior no arquivo ativo com números de linha.",
234
+ "parameters": {"type": "object", "properties": {}, "required": []},
235
+ },
236
+ },
237
+ {
238
+ "type": "function",
239
+ "function": {
240
+ "name": "workspace_symbols",
241
+ "description": "Coleta todos os símbolos de todo o workspace, organizado por arquivo.",
242
+ "parameters": {
243
+ "type": "object",
244
+ "properties": {
245
+ "extensions": {"type": "string"},
246
+ },
247
+ "required": [],
248
+ },
249
+ },
250
+ },
251
+ {
252
+ "type": "function",
253
+ "function": {
254
+ "name": "read_git_diff",
255
+ "description": "Mostra o git diff do workspace. Use antes de commitar.",
256
+ "parameters": {
257
+ "type": "object",
258
+ "properties": {
259
+ "staged_only": {
260
+ "type": "boolean",
261
+ "description": "Se true, mostra apenas mudanças staged.",
262
+ },
263
+ "path": {
264
+ "type": "string",
265
+ "description": "Arquivo específico. Padrão: todo o workspace.",
266
+ },
267
+ },
268
+ "required": [],
269
+ },
270
+ },
271
+ },
272
+ {
273
+ "type": "function",
274
+ "function": {
275
+ "name": "read_git_log",
276
+ "description": "Mostra histórico de commits recentes.",
277
+ "parameters": {
278
+ "type": "object",
279
+ "properties": {
280
+ "count": {
281
+ "type": "integer",
282
+ "description": "Número de commits. Padrão 10.",
283
+ },
284
+ "oneline": {
285
+ "type": "boolean",
286
+ "description": "Formato condensado. Padrão: false.",
287
+ },
288
+ },
289
+ "required": [],
290
+ },
291
+ },
292
+ },
293
+ {
294
+ "type": "function",
295
+ "function": {
296
+ "name": "preview_rename",
297
+ "description": "Simula renomear um símbolo no workspace inteiro. Nenhum arquivo é modificado.",
298
+ "parameters": {
299
+ "type": "object",
300
+ "properties": {
301
+ "symbol_old": {"type": "string"},
302
+ "symbol_new": {"type": "string"},
303
+ "extensions": {"type": "string"},
304
+ },
305
+ "required": ["symbol_old", "symbol_new"],
306
+ },
307
+ },
308
+ },
309
+ {
310
+ "type": "function",
311
+ "function": {
312
+ "name": "get_env_info",
313
+ "description": "Retorna informações sobre o ambiente de desenvolvimento: versões de ferramentas, OS, workspace.",
314
+ "parameters": {"type": "object", "properties": {}, "required": []},
315
+ },
316
+ },
317
+ {
318
+ "type": "function",
319
+ "function": {
320
+ "name": "check_dependency",
321
+ "description": "Verifica se uma dependência está instalada, sua versão e localização.",
322
+ "parameters": {
323
+ "type": "object",
324
+ "properties": {
325
+ "name": {
326
+ "type": "string",
327
+ "description": "Nome da dependência/ferramenta.",
328
+ },
329
+ "manager": {
330
+ "type": "string",
331
+ "description": "pip, npm, cargo, gem. Padrão: auto-detectar.",
332
+ },
333
+ },
334
+ "required": ["name"],
335
+ },
336
+ },
337
+ },
338
+ {
339
+ "type": "function",
340
+ "function": {
341
+ "name": "diff_files",
342
+ "description": "Mostra o diff entre dois arquivos ou entre um arquivo e um conteúdo fornecido.",
343
+ "parameters": {
344
+ "type": "object",
345
+ "properties": {
346
+ "path_a": {"type": "string", "description": "Primeiro arquivo."},
347
+ "path_b": {
348
+ "type": "string",
349
+ "description": "Segundo arquivo (ou omita para usar content_b).",
350
+ },
351
+ "content_b": {
352
+ "type": "string",
353
+ "description": "Conteúdo alternativo para comparar com path_a.",
354
+ },
355
+ },
356
+ "required": ["path_a"],
357
+ },
358
+ },
359
+ },
360
+ {
361
+ "type": "function",
362
+ "function": {
363
+ "name": "get_clipboard",
364
+ "description": "Retorna o conteúdo atual da área de transferência do sistema.",
365
+ "parameters": {"type": "object", "properties": {}, "required": []},
366
+ },
367
+ },
368
+ {
369
+ "type": "function",
370
+ "function": {
371
+ "name": "write_file",
372
+ "description": "Cria ou sobrescreve um arquivo no workspace atomicamente. Um backup (.bak) é criado. Requer aprovação.",
373
+ "parameters": {
374
+ "type": "object",
375
+ "properties": {
376
+ "path": {"type": "string"},
377
+ "content": {"type": "string"},
378
+ "encoding": {"type": "string", "description": "Padrão: utf-8."},
379
+ },
380
+ "required": ["path", "content"],
381
+ },
382
+ },
383
+ },
384
+ {
385
+ "type": "function",
386
+ "function": {
387
+ "name": "apply_edit",
388
+ "description": "Realiza uma ou mais substituições precisas dentro de um arquivo. Forma preferida para mudanças cirúrgicas. Requer aprovação.",
389
+ "parameters": {
390
+ "type": "object",
391
+ "properties": {
392
+ "path": {"type": "string"},
393
+ "edits": {
394
+ "type": "array",
395
+ "items": {
396
+ "type": "object",
397
+ "properties": {
398
+ "old_text": {"type": "string"},
399
+ "new_text": {"type": "string"},
400
+ "count": {
401
+ "type": "integer",
402
+ "description": "Qual ocorrência (1=primeira, 0=todas). Padrão 1.",
403
+ },
404
+ "regex": {
405
+ "type": "boolean",
406
+ "description": "Se true, old_text é regex Python. Padrão false.",
407
+ },
408
+ },
409
+ "required": ["old_text", "new_text"],
410
+ },
411
+ },
412
+ "dry_run": {
413
+ "type": "boolean",
414
+ "description": "Se true, retorna mudanças sem salvar.",
415
+ },
416
+ },
417
+ "required": ["path", "edits"],
418
+ },
419
+ },
420
+ },
421
+ {
422
+ "type": "function",
423
+ "function": {
424
+ "name": "insert_after_line",
425
+ "description": "Insere um bloco de texto exatamente após um número de linha. Útil para adicionar imports ou novas funções.",
426
+ "parameters": {
427
+ "type": "object",
428
+ "properties": {
429
+ "path": {"type": "string"},
430
+ "line": {
431
+ "type": "integer",
432
+ "description": "Linha após a qual inserir (base 1).",
433
+ },
434
+ "text": {"type": "string"},
435
+ },
436
+ "required": ["path", "line", "text"],
437
+ },
438
+ },
439
+ },
440
+ {
441
+ "type": "function",
442
+ "function": {
443
+ "name": "format_code",
444
+ "description": "Auto-formata um arquivo (Black para Python, Prettier para JS/TS, rustfmt, gofmt).",
445
+ "parameters": {
446
+ "type": "object",
447
+ "properties": {
448
+ "path": {"type": "string"},
449
+ },
450
+ "required": ["path"],
451
+ },
452
+ },
453
+ },
454
+ {
455
+ "type": "function",
456
+ "function": {
457
+ "name": "patch_files",
458
+ "description": "Aplica edições em MÚLTIPLOS arquivos de uma vez. Ideal para refatorações grandes. Requer aprovação.",
459
+ "parameters": {
460
+ "type": "object",
461
+ "properties": {
462
+ "patches": {
463
+ "type": "array",
464
+ "items": {
465
+ "type": "object",
466
+ "properties": {
467
+ "path": {"type": "string"},
468
+ "edits": {
469
+ "type": "array",
470
+ "items": {
471
+ "type": "object",
472
+ "properties": {
473
+ "old_text": {"type": "string"},
474
+ "new_text": {"type": "string"},
475
+ "count": {"type": "integer"},
476
+ "regex": {"type": "boolean"},
477
+ },
478
+ "required": ["old_text", "new_text"],
479
+ },
480
+ },
481
+ "create_if_missing": {"type": "boolean"},
482
+ },
483
+ "required": ["path", "edits"],
484
+ },
485
+ },
486
+ "dry_run": {"type": "boolean"},
487
+ },
488
+ "required": ["patches"],
489
+ },
490
+ },
491
+ },
492
+ {
493
+ "type": "function",
494
+ "function": {
495
+ "name": "run_command",
496
+ "description": "Executa um comando shell no diretório do workspace. Requer aprovação. Use para build, lint, test, install, git, etc.",
497
+ "parameters": {
498
+ "type": "object",
499
+ "properties": {
500
+ "command": {"type": "string"},
501
+ "timeout": {
502
+ "type": "integer",
503
+ "description": "Timeout em segundos. Padrão 60.",
504
+ },
505
+ "working_dir": {
506
+ "type": "string",
507
+ "description": "Subpasta do workspace. Padrão: raiz.",
508
+ },
509
+ "env": {
510
+ "type": "object",
511
+ "description": "Variáveis de ambiente extras.",
512
+ },
513
+ },
514
+ "required": ["command"],
515
+ },
516
+ },
517
+ },
518
+ {
519
+ "type": "function",
520
+ "function": {
521
+ "name": "run_script",
522
+ "description": "Escreve código em arquivo temporário e executa com o runtime escolhido. Requer aprovação.",
523
+ "parameters": {
524
+ "type": "object",
525
+ "properties": {
526
+ "code": {"type": "string"},
527
+ "language": {
528
+ "type": "string",
529
+ "description": "python, bash, node, ruby, perl. Padrão: python.",
530
+ },
531
+ "timeout": {
532
+ "type": "integer",
533
+ "description": "Máx segundos. Padrão 30.",
534
+ },
535
+ "env": {"type": "object"},
536
+ },
537
+ "required": ["code"],
538
+ },
539
+ },
540
+ },
541
+ {
542
+ "type": "function",
543
+ "function": {
544
+ "name": "run_tests",
545
+ "description": "Detecta o framework de testes e executa. Requer aprovação.",
546
+ "parameters": {
547
+ "type": "object",
548
+ "properties": {
549
+ "target": {
550
+ "type": "string",
551
+ "description": "Arquivo ou módulo. Padrão: projeto inteiro.",
552
+ },
553
+ "extra_args": {"type": "string"},
554
+ "framework": {
555
+ "type": "string",
556
+ "description": "pytest, jest, cargo, go. Padrão: auto.",
557
+ },
558
+ },
559
+ "required": [],
560
+ },
561
+ },
562
+ },
563
+ {
564
+ "type": "function",
565
+ "function": {
566
+ "name": "create_directory",
567
+ "description": "Cria uma pasta no workspace (incluindo intermediárias). Requer aprovação.",
568
+ "parameters": {
569
+ "type": "object",
570
+ "properties": {
571
+ "path": {"type": "string"},
572
+ },
573
+ "required": ["path"],
574
+ },
575
+ },
576
+ },
577
+ {
578
+ "type": "function",
579
+ "function": {
580
+ "name": "delete_file",
581
+ "description": "Remove um arquivo do workspace. Cria backup antes. Requer aprovação.",
582
+ "parameters": {
583
+ "type": "object",
584
+ "properties": {
585
+ "path": {"type": "string"},
586
+ },
587
+ "required": ["path"],
588
+ },
589
+ },
590
+ },
591
+ {
592
+ "type": "function",
593
+ "function": {
594
+ "name": "delete_directory",
595
+ "description": "⚠️ Remove uma pasta. Com recursive=true, deleta tudo dentro. AÇÃO IRREVERSÍVEL. Requer aprovação CRÍTICA.",
596
+ "parameters": {
597
+ "type": "object",
598
+ "properties": {
599
+ "path": {"type": "string"},
600
+ "recursive": {
601
+ "type": "boolean",
602
+ "description": "Deleta conteúdo recursivamente.",
603
+ },
604
+ },
605
+ "required": ["path"],
606
+ },
607
+ },
608
+ },
609
+ {
610
+ "type": "function",
611
+ "function": {
612
+ "name": "move_file",
613
+ "description": "Move ou renomeia um arquivo/pasta no workspace. Requer aprovação.",
614
+ "parameters": {
615
+ "type": "object",
616
+ "properties": {
617
+ "src": {"type": "string"},
618
+ "dst": {"type": "string"},
619
+ },
620
+ "required": ["src", "dst"],
621
+ },
622
+ },
623
+ },
624
+ {
625
+ "type": "function",
626
+ "function": {
627
+ "name": "copy_file",
628
+ "description": "Copia um arquivo ou pasta para outro local no workspace. Requer aprovação.",
629
+ "parameters": {
630
+ "type": "object",
631
+ "properties": {
632
+ "src": {"type": "string"},
633
+ "dst": {"type": "string"},
634
+ },
635
+ "required": ["src", "dst"],
636
+ },
637
+ },
638
+ },
639
+ {
640
+ "type": "function",
641
+ "function": {
642
+ "name": "init_project",
643
+ "description": (
644
+ "Inicializa um projeto do ZERO em uma pasta: git init, npm init, estrutura de pastas, "
645
+ "arquivos base (README, .gitignore, etc). "
646
+ "Templates: 'node-ts', 'python-lib', 'react', 'fastapi', 'rust', 'vazio'. "
647
+ "Requer aprovação."
648
+ ),
649
+ "parameters": {
650
+ "type": "object",
651
+ "properties": {
652
+ "path": {
653
+ "type": "string",
654
+ "description": "Pasta onde inicializar. Padrão: workspace atual.",
655
+ },
656
+ "template": {
657
+ "type": "string",
658
+ "description": "node-ts, python-lib, react, fastapi, rust, vazio.",
659
+ },
660
+ "name": {"type": "string", "description": "Nome do projeto."},
661
+ "git": {
662
+ "type": "boolean",
663
+ "description": "Fazer git init? Padrão: true.",
664
+ },
665
+ "extra_cmds": {
666
+ "type": "array",
667
+ "items": {"type": "string"},
668
+ "description": "Comandos adicionais após inicialização.",
669
+ },
670
+ },
671
+ "required": ["template"],
672
+ },
673
+ },
674
+ },
675
+ {
676
+ "type": "function",
677
+ "function": {
678
+ "name": "install_dependency",
679
+ "description": "Instala uma dependência usando o gerenciador detectado (pip, npm, cargo, gem). Requer aprovação.",
680
+ "parameters": {
681
+ "type": "object",
682
+ "properties": {
683
+ "package": {"type": "string"},
684
+ "manager": {
685
+ "type": "string",
686
+ "description": "pip, npm, cargo, gem. Padrão: auto.",
687
+ },
688
+ "dev": {
689
+ "type": "boolean",
690
+ "description": "Dev dependency? Padrão: false.",
691
+ },
692
+ "global_": {
693
+ "type": "boolean",
694
+ "description": "Global? Padrão: false.",
695
+ },
696
+ "extra_args": {"type": "string"},
697
+ },
698
+ "required": ["package"],
699
+ },
700
+ },
701
+ },
702
+ {
703
+ "type": "function",
704
+ "function": {
705
+ "name": "git_stage",
706
+ "description": "Faz git add. Requer aprovação.",
707
+ "parameters": {
708
+ "type": "object",
709
+ "properties": {
710
+ "path": {
711
+ "type": "string",
712
+ "description": "Arquivo/pasta. Use '.' para todos. Padrão: todos.",
713
+ },
714
+ },
715
+ "required": [],
716
+ },
717
+ },
718
+ },
719
+ {
720
+ "type": "function",
721
+ "function": {
722
+ "name": "git_commit",
723
+ "description": "Faz git commit com mensagem. Requer aprovação.",
724
+ "parameters": {
725
+ "type": "object",
726
+ "properties": {
727
+ "message": {"type": "string"},
728
+ "add_all": {
729
+ "type": "boolean",
730
+ "description": "Fazer git add -A antes? Padrão: false.",
731
+ },
732
+ },
733
+ "required": ["message"],
734
+ },
735
+ },
736
+ },
737
+ {
738
+ "type": "function",
739
+ "function": {
740
+ "name": "git_branch",
741
+ "description": "Cria, muda ou lista branches git. Requer aprovação.",
742
+ "parameters": {
743
+ "type": "object",
744
+ "properties": {
745
+ "action": {
746
+ "type": "string",
747
+ "description": "create, checkout, list, delete.",
748
+ },
749
+ "name": {"type": "string"},
750
+ },
751
+ "required": ["action"],
752
+ },
753
+ },
754
+ },
755
+ {
756
+ "type": "function",
757
+ "function": {
758
+ "name": "git_reset",
759
+ "description": "⚠️ Git reset. Pode perder alterações. Requer aprovação CRÍTICA.",
760
+ "parameters": {
761
+ "type": "object",
762
+ "properties": {
763
+ "mode": {
764
+ "type": "string",
765
+ "description": "soft, mixed, hard. Padrão: mixed.",
766
+ },
767
+ "target": {
768
+ "type": "string",
769
+ "description": "Ref/commit. Padrão: HEAD.",
770
+ },
771
+ },
772
+ "required": [],
773
+ },
774
+ },
775
+ },
776
+ {
777
+ "type": "function",
778
+ "function": {
779
+ "name": "git_clean",
780
+ "description": "⚠️ Remove arquivos não rastreados. IRREVERSÍVEL. Requer aprovação CRÍTICA.",
781
+ "parameters": {
782
+ "type": "object",
783
+ "properties": {
784
+ "flags": {
785
+ "type": "string",
786
+ "description": "Flags git clean. Padrão: '-fd'.",
787
+ },
788
+ },
789
+ "required": [],
790
+ },
791
+ },
792
+ },
793
+ {
794
+ "type": "function",
795
+ "function": {
796
+ "name": "open_terminal_tab",
797
+ "description": "Abre uma nova aba no painel de terminal integrado, opcionalmente executando um comando inicial.",
798
+ "parameters": {
799
+ "type": "object",
800
+ "properties": {
801
+ "name": {
802
+ "type": "string",
803
+ "description": "Nome da aba. Padrão: 'IA Terminal'.",
804
+ },
805
+ "command": {
806
+ "type": "string",
807
+ "description": "Comando inicial. Opcional.",
808
+ },
809
+ },
810
+ "required": [],
811
+ },
812
+ },
813
+ },
814
+ ]
815
+
816
+ _BAD_REF = "Nome de branch ou referência inválido."
817
+
818
+ _TRUST_REQUIRED = frozenset(
819
+ {"run_command", "run_script", "run_tests", "init_project", "install_dependency",
820
+ "open_terminal_tab", "format_code"}
821
+ )
822
+ _RESTRICTED_MSG = (
823
+ "Workspace em modo restrito: ferramentas que executam código estão bloqueadas. "
824
+ "Marque a pasta como confiável para usá-las."
825
+ )
826
+
827
+
828
+ class ToolExecutor:
829
+ """Executa ferramentas da IA no workspace local.
830
+
831
+ O ApprovalGate intercepta as chamadas antes de chegarem aqui; o executor assume
832
+ que a permissão já foi concedida.
833
+ """
834
+
835
+ def __init__(
836
+ self,
837
+ get_editor: Any,
838
+ get_workspace: Any,
839
+ on_open_terminal: Callable[[str, str], None] | None = None,
840
+ get_root_widget: Callable[[], Any] | None = None,
841
+ get_open_editors: Callable[[], Any] | None = None,
842
+ ) -> None:
843
+ """Configura as dependências necessárias para execução das ferramentas.
844
+
845
+ Args:
846
+ get_editor: Callable que retorna o editor ativo ou None.
847
+ get_workspace: Callable que retorna o caminho raiz do workspace ou None.
848
+ on_open_terminal: Callback para abrir nova aba no terminal integrado.
849
+ get_root_widget: Callable que retorna o widget raiz Tkinter (para clipboard).
850
+ """
851
+ self._get_editor = get_editor
852
+ self._get_workspace = get_workspace
853
+ self._on_open_terminal = on_open_terminal
854
+ self._get_root_widget = get_root_widget
855
+ self._get_open_editors = get_open_editors
856
+ self.checkpoints: CheckpointStore | None = None
857
+ self._cp_session: str | None = None
858
+
859
+ def set_session(self, session_id: str | None) -> None:
860
+ """Define a sessão de IA atual (cada sessão tem seus checkpoints)."""
861
+ if session_id != self._cp_session:
862
+ self._cp_session = session_id
863
+ self.checkpoints = None
864
+
865
+ def _cps(self) -> CheckpointStore | None:
866
+ if self.checkpoints is None and self._cp_session:
867
+ root = self._workspace()
868
+ if root is not None:
869
+ self.checkpoints = CheckpointStore(root, self._cp_session)
870
+ return self.checkpoints
871
+
872
+ def begin_turn(self, label: str) -> None:
873
+ """Abre um checkpoint para o turno da IA que vai começar."""
874
+ cps = self._cps()
875
+ if cps is not None:
876
+ cps.begin(label)
877
+
878
+ def end_turn(self) -> Any:
879
+ """Fecha o checkpoint do turno; retorna-o (ou ``None`` se nada mudou)."""
880
+ cps = self.checkpoints
881
+ return cps.commit() if cps is not None else None
882
+
883
+ def undo_turn(self, cp_id: int | None = None, *, force: bool = False) -> Any:
884
+ """Desfaz um checkpoint (padrão: o mais recente)."""
885
+ cps = self._cps()
886
+ return cps.undo(cp_id, force=force) if cps is not None else None
887
+
888
+ def _open_editor_for(self, path: Path) -> Any | None:
889
+ """Editor aberto cujo arquivo é *path* (ou ``None``)."""
890
+ try:
891
+ editors = list(self._get_open_editors()) if self._get_open_editors else []
892
+ if not editors and self._get_editor:
893
+ ed = self._get_editor()
894
+ editors = [ed] if ed is not None else []
895
+ target = path.resolve()
896
+ for ed in editors:
897
+ ep = getattr(ed, "path", None)
898
+ if ep and Path(ep).resolve() == target:
899
+ return ed
900
+ except Exception:
901
+ logger.debug("busca de editor aberto falhou", exc_info=True)
902
+ return None
903
+
904
+ def _unsaved_block(self, dest: Path) -> str | None:
905
+ """Mensagem de bloqueio se *dest* tem alterações não salvas no editor.
906
+
907
+ Escrever por cima apagaria trabalho do usuário que só existe no buffer.
908
+ """
909
+ ed = self._open_editor_for(dest)
910
+ if ed is not None and getattr(ed, "modified", False):
911
+ return _t(
912
+ "ia.tool_unsaved_block", name=dest.name,
913
+ default="[Bloqueado] '{name}' tem alterações não salvas no editor. "
914
+ "Peça ao usuário para salvar (Ctrl+S) e tente de novo; "
915
+ "use read_active_file para ver o conteúdo atual do editor.",
916
+ )
917
+ return None
918
+
919
+ def execute(self, name: str, args: dict[str, Any]) -> str:
920
+ """
921
+ Retorna sempre uma string - o resultado da ferramenta ou mensagem de erro.
922
+ """
923
+ try:
924
+ method = getattr(self, f"_tool_{name}", None)
925
+ if method is None:
926
+ return _t("ia.tool_unknown", name=name)
927
+ if name in _TRUST_REQUIRED and is_restricted():
928
+ return _RESTRICTED_MSG
929
+ return method(**args)
930
+ except TypeError as exc:
931
+ return _t("ia.tool_bad_args", name=name, err=exc)
932
+ except Exception as exc:
933
+ logger.warning("Ferramenta '%s' falhou: %s",
934
+ name, exc, exc_info=True)
935
+ return f"[Erro] {exc}"
936
+
937
+ def _workspace(self) -> Path | None:
938
+ """Retorna o Path do workspace ativo, ou None se nenhum estiver aberto."""
939
+ ws = self._get_workspace()
940
+ return Path(ws) if ws else None
941
+
942
+ _SENSITIVE_NAMES = frozenset(
943
+ {".env", ".netrc", ".pgpass", ".npmrc", ".pypirc", ".git-credentials",
944
+ "id_rsa", "id_ed25519", "id_ecdsa", "id_dsa", "authorized_keys", ".gitconfig"}
945
+ )
946
+ _SENSITIVE_SUFFIXES = frozenset({".pem", ".key", ".p12", ".pfx", ".kdbx"})
947
+
948
+ def _allowed_roots(self) -> list[Path]:
949
+ """Diretórios onde a IA pode ler: workspace e pasta do arquivo ativo."""
950
+ roots: list[Path] = []
951
+ root = self._workspace()
952
+ if root:
953
+ roots.append(root.resolve())
954
+ editor = self._get_editor() if self._get_editor else None
955
+ active = getattr(editor, "path", None) if editor else None
956
+ if active:
957
+ roots.append(Path(active).resolve().parent)
958
+ return roots
959
+
960
+ @staticmethod
961
+ def _is_within(path: Path, root: Path) -> bool:
962
+ """Indica se `path`, já resolvido, está dentro de `root` (ou é igual a ele)."""
963
+ return path == root or root in path.parents
964
+
965
+ def _is_sensitive(self, path: Path) -> bool:
966
+ """Indica se o arquivo costuma guardar credenciais e não deve ser lido pela IA."""
967
+ name = path.name.lower()
968
+ return (
969
+ name in self._SENSITIVE_NAMES
970
+ or name.startswith(".env.")
971
+ or path.suffix.lower() in self._SENSITIVE_SUFFIXES
972
+ )
973
+
974
+ def _resolve(self, path: str) -> Path | None:
975
+ """Resolve `path` para um arquivo existente dentro das áreas permitidas.
976
+
977
+ Tenta, em ordem: absoluto, relativo ao workspace, relativo à pasta do
978
+ editor ativo. Caminhos fora do workspace e da pasta do arquivo ativo,
979
+ e arquivos de credenciais, resultam em None.
980
+ """
981
+ raw = Path(path)
982
+ candidates = [raw] if raw.is_absolute() else []
983
+ if not raw.is_absolute():
984
+ candidates.extend(base / raw for base in self._allowed_roots())
985
+ allowed = self._allowed_roots()
986
+ for candidate in candidates:
987
+ try:
988
+ resolved = candidate.resolve()
989
+ except (OSError, RuntimeError):
990
+ continue
991
+ if not resolved.exists() or self._is_sensitive(resolved):
992
+ continue
993
+ if any(self._is_within(resolved, root) for root in allowed):
994
+ return resolved
995
+ return None
996
+
997
+ def _confine(self, path: str) -> Path | None:
998
+ """Resolve `path` para escrita, exigindo que fique dentro do workspace.
999
+
1000
+ O arquivo não precisa existir. Retorna None se não houver workspace ou
1001
+ se o caminho, após resolver ``..`` e links simbólicos, escapar dele.
1002
+ """
1003
+ root = self._workspace()
1004
+ if root is None:
1005
+ return None
1006
+ base = root.resolve()
1007
+ try:
1008
+ target = (base / path).resolve()
1009
+ except (OSError, RuntimeError):
1010
+ return None
1011
+ return target if self._is_within(target, base) else None
1012
+
1013
+ def _read(self, fp: Path) -> str:
1014
+ """Lê um arquivo como texto UTF-8, substituindo bytes inválidos.
1015
+
1016
+ Se o arquivo está aberto com alterações não salvas, devolve o buffer do
1017
+ editor (o que o usuário realmente está vendo), não a versão antiga do disco.
1018
+ """
1019
+ ed = self._open_editor_for(fp)
1020
+ if ed is not None and getattr(ed, "modified", False):
1021
+ with contextlib.suppress(Exception):
1022
+ return ed.text.get("1.0", "end-1c")
1023
+ return fp.read_text("utf-8", errors="replace")
1024
+
1025
+ def _git(self, args: list[str], cwd: str | None = None) -> str:
1026
+ """Executa um subcomando git e retorna stdout + stderr como string.
1027
+
1028
+ Usa o workspace como diretório de trabalho se `cwd` não for fornecido.
1029
+ """
1030
+ root = self._workspace()
1031
+ c = cwd or (str(root) if root else None)
1032
+ try:
1033
+ r = _run(
1034
+ ["git"] + args,
1035
+ cwd=c,
1036
+ capture_output=True,
1037
+ text=True,
1038
+ timeout=15,
1039
+ check=False,
1040
+ )
1041
+ out = r.stdout.strip()
1042
+ err = r.stderr.strip()
1043
+ if r.returncode != 0 and err:
1044
+ return _t("ia.tool_git_error", err=err)
1045
+ return out or "(sem output)"
1046
+ except FileNotFoundError:
1047
+ return _t("ia.tool_git_unavail")
1048
+ except subprocess.TimeoutExpired:
1049
+ return _t("ia.tool_git_timeout")
1050
+
1051
+ def _safe_write(self, dest: Path, content: str, encoding: str = "utf-8") -> str:
1052
+ """Escreve `content` em `dest` atomicamente via arquivo temporário.
1053
+
1054
+ Cria um backup `.bak` se o arquivo já existir. Cria diretórios intermediários
1055
+ automaticamente. Retorna mensagem i18n de sucesso ou erro.
1056
+ """
1057
+ root = self._workspace()
1058
+ blocked = self._unsaved_block(dest)
1059
+ if blocked:
1060
+ return blocked
1061
+ cps = self._cps()
1062
+ if cps is not None and cps._current is not None:
1063
+ cps.record_write(dest)
1064
+ elif dest.exists() and dest.stat().st_size > 0:
1065
+ bak = dest.with_suffix(dest.suffix + ".bak")
1066
+ with contextlib.suppress(OSError):
1067
+ bak.write_bytes(dest.read_bytes())
1068
+ dest.parent.mkdir(parents=True, exist_ok=True)
1069
+ try:
1070
+ with tempfile.NamedTemporaryFile(
1071
+ mode="w",
1072
+ encoding=encoding,
1073
+ dir=dest.parent,
1074
+ prefix=f".tmp_{dest.name}_",
1075
+ suffix=".tmp",
1076
+ delete=False,
1077
+ ) as tmp:
1078
+ tmp.write(content)
1079
+ tmp_path = Path(tmp.name)
1080
+ tmp_path.replace(dest)
1081
+ if cps is not None and cps._current is not None:
1082
+ cps.record_after(dest)
1083
+ sz = dest.stat().st_size
1084
+ sz_str = f"{sz // 1024}KB" if sz >= 1024 else f"{sz}B"
1085
+ try:
1086
+ rel = dest.relative_to(root) if root else dest
1087
+ except ValueError:
1088
+ rel = dest
1089
+ return _t("ia.tool_write_ok", path=str(rel), size=sz_str)
1090
+ except Exception as exc:
1091
+ return _t("ia.tool_write_err", path=str(dest), err=exc)
1092
+
1093
+ def _tool_read_active_file(self) -> str:
1094
+ """Retorna o conteúdo do editor ativo com número de linhas à esquerda."""
1095
+ editor = self._get_editor()
1096
+ if editor is None:
1097
+ return _t("ia.tool_no_editor")
1098
+ fp = getattr(editor, "path", None)
1099
+ lang = getattr(editor, "lang", "")
1100
+ try:
1101
+ content = editor.text.get("1.0", "end-1c")
1102
+ except Exception:
1103
+ if fp:
1104
+ try:
1105
+ content = Path(fp).read_text("utf-8", errors="replace")
1106
+ except OSError as e:
1107
+ return _t("ia.tool_read_error", path=str(fp) if fp else "?", err=e)
1108
+ else:
1109
+ return _t("ia.tool_no_editor")
1110
+ lines = content.splitlines(keepends=True)
1111
+ total = len(lines)
1112
+ header = f"# Arquivo ativo: {fp or '(sem nome)'} | Linguagem: {lang} | Total: {total} linhas\n\n"
1113
+ return header + "".join(f"{i + 1:4d} {line}" for i, line in enumerate(lines))
1114
+
1115
+ def _tool_get_cursor_context(self, window: int = 40) -> str:
1116
+ """Retorna as `window` linhas antes e depois da posição atual do cursor.
1117
+
1118
+ A linha do cursor é marcada com `>>>`. Inclui cabeçalho com arquivo, linguagem
1119
+ e posição do cursor.
1120
+ """
1121
+ editor = self._get_editor()
1122
+ if editor is None:
1123
+ return _t("ia.tool_no_editor")
1124
+ fp = getattr(editor, "path", None)
1125
+ lang = getattr(editor, "lang", "")
1126
+ try:
1127
+ index = editor.text.index("insert")
1128
+ row, col = index.split(".")
1129
+ cur_line = int(row)
1130
+ cur_col = int(col) + 1
1131
+ except Exception:
1132
+ return _t("ia.tool_cursor_error")
1133
+ try:
1134
+ content = editor.text.get("1.0", "end-1c")
1135
+ except Exception:
1136
+ return _t("ia.tool_no_editor")
1137
+ lines = content.splitlines()
1138
+ total = len(lines)
1139
+ start = max(0, cur_line - window - 1)
1140
+ end = min(total, cur_line + window)
1141
+ region = lines[start:end]
1142
+ numbered = "\n".join(
1143
+ f"{'>>>' if start + i + 1 == cur_line else ' '} {start + i + 1:4d} {line}"
1144
+ for i, line in enumerate(region)
1145
+ )
1146
+ return (
1147
+ f"# Arquivo: {fp or '(sem nome)'} | Linguagem: {lang}\n"
1148
+ f"# Cursor: linha {cur_line}, col {cur_col}\n"
1149
+ f"# Mostrando linhas {start + 1}–{start + len(region)} de {total}\n"
1150
+ f"# (>>> = linha do cursor)\n\n{numbered}"
1151
+ )
1152
+
1153
+ def _tool_read_file(
1154
+ self, path: str, start_line: int | None = None, end_line: int | None = None
1155
+ ) -> str:
1156
+ """Lê um arquivo completo ou intervalo de linhas.
1157
+
1158
+ Args:
1159
+ path: Caminho relativo ao workspace ou absoluto.
1160
+ start_line: Primeira linha a incluir (base 1). None = início do arquivo.
1161
+ end_line: Última linha a incluir (base 1). None = fim do arquivo.
1162
+ """
1163
+ resolved = self._resolve(path)
1164
+ if resolved is None:
1165
+ return _t("ia.tool_file_not_found", path=path)
1166
+ try:
1167
+ content = self._read(resolved)
1168
+ lines = content.splitlines(keepends=True)
1169
+ lf = max(0, (start_line or 1) - 1)
1170
+ lt = end_line if end_line else len(lines)
1171
+ excerpt = "".join(lines[lf:lt])
1172
+ total = len(lines)
1173
+ return f"# Arquivo: {resolved} | Linhas {lf + 1}-{min(lt, total)} de {total}\n\n{excerpt}"
1174
+ except OSError as exc:
1175
+ return _t("ia.tool_read_error", path=path, err=exc)
1176
+
1177
+ def _tool_read_file_tree(
1178
+ self, max_depth: int = 4, show_hidden: bool = False
1179
+ ) -> str:
1180
+ """Retorna a estrutura de diretórios do workspace em formato de árvore visual.
1181
+
1182
+ Ignora pastas de artefatos gerados (node_modules, __pycache__, dist etc.).
1183
+ """
1184
+ root = self._workspace()
1185
+ if root is None:
1186
+ return _t("ia.tool_no_workspace")
1187
+ lines: list[str] = [f"# Árvore: {root.name}\n{root.name}/"]
1188
+
1189
+ def walk(path: Path, prefix: str, depth: int) -> None:
1190
+ """Percorre recursivamente o diretório e emite entradas de arquivo."""
1191
+ if depth > max_depth:
1192
+ return
1193
+ try:
1194
+ entries = sorted(
1195
+ path.iterdir(), key=lambda p: (p.is_file(), p.name.lower())
1196
+ )
1197
+ except PermissionError:
1198
+ return
1199
+ entries = [
1200
+ e
1201
+ for e in entries
1202
+ if (show_hidden or not e.name.startswith("."))
1203
+ and e.name not in SKIP_DIRS
1204
+ ]
1205
+ for i, entry in enumerate(entries):
1206
+ connector = "\\-- " if i == len(entries) - 1 else "|-- "
1207
+ ext = " " if i == len(entries) - 1 else "│ "
1208
+ if entry.is_dir():
1209
+ lines.append(f"{prefix}{connector}{entry.name}/")
1210
+ walk(entry, prefix + ext, depth + 1)
1211
+ else:
1212
+ sz = entry.stat().st_size
1213
+ lines.append(
1214
+ f"{prefix}{connector}{entry.name}"
1215
+ + (f" ({sz // 1024}KB)" if sz >= 1024 else "")
1216
+ )
1217
+
1218
+ walk(root, "", 1)
1219
+ return "\n".join(lines[:500])
1220
+
1221
+ def _tool_list_files(
1222
+ self, folder: str = ".", recursive: bool = False, extensions: str = ""
1223
+ ) -> str:
1224
+ """Lista arquivos e pastas dentro de `folder`.
1225
+
1226
+ Args:
1227
+ folder: Subpasta relativa ao workspace. Padrão: raiz.
1228
+ recursive: Se True, percorre subdiretórios.
1229
+ extensions: Filtro de extensões separadas por vírgula, ex: `.py,.ts`.
1230
+ """
1231
+ root = self._workspace()
1232
+ if root is None:
1233
+ return _t("ia.tool_no_workspace")
1234
+ target = (root / folder).resolve()
1235
+ if not target.exists():
1236
+ return _t("ia.tool_folder_missing", path=folder)
1237
+ ext_filter = (
1238
+ {e.strip() for e in extensions.split(",") if e.strip()}
1239
+ if extensions
1240
+ else set()
1241
+ )
1242
+ lines = [f"# Conteúdo de: {target.relative_to(root)}\n"]
1243
+ pattern = "**/*" if recursive else "*"
1244
+ for p in sorted(target.glob(pattern)):
1245
+ rel = p.relative_to(root)
1246
+ if p.is_dir():
1247
+ lines.append(f"📁 {rel}/")
1248
+ elif not ext_filter or p.suffix.lower() in ext_filter:
1249
+ sz = p.stat().st_size
1250
+ lines.append(
1251
+ f"📄 {rel} ({sz // 1024}KB)"
1252
+ if sz >= 1024
1253
+ else f"📄 {rel} ({sz}B)"
1254
+ )
1255
+ return "\n".join(lines[:300])
1256
+
1257
+ def _tool_search_in_files(
1258
+ self,
1259
+ query: str,
1260
+ extensions: str = "",
1261
+ max_results: int = 30,
1262
+ case_sensitive: bool = False,
1263
+ ) -> str:
1264
+ """
1265
+ Args:
1266
+ query: Expressão regular Python.
1267
+ max_results: Número máximo de correspondências retornadas.
1268
+ case_sensitive: Se False, ignora maiúsculas/minúsculas.
1269
+ """
1270
+ root = self._workspace()
1271
+ if root is None:
1272
+ return _t("ia.tool_no_workspace")
1273
+ ext_filter = (
1274
+ {e.strip() for e in extensions.split(",") if e.strip()}
1275
+ if extensions
1276
+ else set()
1277
+ )
1278
+ flags = 0 if case_sensitive else re.IGNORECASE
1279
+ try:
1280
+ pattern = re.compile(query, flags)
1281
+ except re.error as exc:
1282
+ return _t("ia.tool_bad_regex", err=exc)
1283
+ results: list[str] = []
1284
+ for fp in sorted(root.rglob("*")):
1285
+ if not fp.is_file():
1286
+ continue
1287
+ if any(p in SKIP_DIRS for p in fp.parts):
1288
+ continue
1289
+ if ext_filter and fp.suffix.lower() not in ext_filter:
1290
+ continue
1291
+ try:
1292
+ for i, line in enumerate(self._read(fp).splitlines(), 1):
1293
+ if pattern.search(line):
1294
+ results.append(
1295
+ f"{fp.relative_to(root)}:{i}: {line.strip()[:120]}"
1296
+ )
1297
+ if len(results) >= max_results:
1298
+ break
1299
+ except OSError:
1300
+ continue
1301
+ if len(results) >= max_results:
1302
+ break
1303
+ if not results:
1304
+ return f"Nenhum resultado para '{query}'."
1305
+ return f"# {len(results)} resultado(s) para '{query}'\n\n" + "\n".join(results)
1306
+
1307
+ def _tool_find_definition(self, symbol: str, extensions: str = "") -> str:
1308
+ """Localiza a definição de um símbolo (classe, função, variável) no workspace.
1309
+
1310
+ Usa padrões de regex específicos para Python, JS/TS e Rust/Go.
1311
+ Retorna até 5 ocorrências com contexto de linhas ao redor.
1312
+ """
1313
+ root = self._workspace()
1314
+ if root is None:
1315
+ return _t("ia.tool_no_workspace")
1316
+ ext_filter = (
1317
+ {e.strip() for e in extensions.split(",") if e.strip()}
1318
+ if extensions
1319
+ else set()
1320
+ )
1321
+ sym_esc = re.escape(symbol)
1322
+ def_re = re.compile(
1323
+ rf"^\s*(?:async\s+)?(?:def|class)\s+{sym_esc}\b|"
1324
+ rf"^(?:export\s+)?(?:async\s+)?(?:function|class)\s+{sym_esc}\b|"
1325
+ rf"^(?:export\s+)?(?:const|let|var)\s+{sym_esc}\s*=|"
1326
+ rf"^(?:pub\s+)?(?:fn|struct|enum|trait|impl|mod|type)\s+{sym_esc}\b",
1327
+ re.MULTILINE | re.IGNORECASE,
1328
+ )
1329
+ results: list[str] = []
1330
+ for fp in sorted(root.rglob("*")):
1331
+ if not fp.is_file():
1332
+ continue
1333
+ if any(p in SKIP_DIRS for p in fp.parts):
1334
+ continue
1335
+ if ext_filter and fp.suffix.lower() not in ext_filter:
1336
+ continue
1337
+ try:
1338
+ fl = self._read(fp).splitlines()
1339
+ for i, line in enumerate(fl, 1):
1340
+ if def_re.search(line):
1341
+ ctx = "\n".join(
1342
+ f"{'>>>' if j + 1 == i else ' '} {j + 1:4d} {fl[j]}"
1343
+ for j in range(max(0, i - 4), min(len(fl), i + 5))
1344
+ )
1345
+ results.append(
1346
+ f"## {fp.relative_to(root)} (linha {i})\n{ctx}")
1347
+ if len(results) >= 5:
1348
+ break
1349
+ except OSError:
1350
+ continue
1351
+ if len(results) >= 5:
1352
+ break
1353
+ if not results:
1354
+ return f"Nenhuma definição encontrada para '{symbol}'."
1355
+ return f"# Definições de: {symbol}\n\n" + "\n\n".join(results)
1356
+
1357
+ def _tool_find_references(
1358
+ self, symbol: str, extensions: str = "", max_results: int = 30
1359
+ ) -> str:
1360
+ """
1361
+ Retorna cada ocorrência com duas linhas de contexto acima e abaixo.
1362
+ """
1363
+ root = self._workspace()
1364
+ if root is None:
1365
+ return _t("ia.tool_no_workspace")
1366
+ ext_filter = (
1367
+ {e.strip() for e in extensions.split(",") if e.strip()}
1368
+ if extensions
1369
+ else set()
1370
+ )
1371
+ sym_esc = re.escape(symbol)
1372
+ usage_re = re.compile(rf"\b{sym_esc}\b")
1373
+ def_re = re.compile(
1374
+ rf"^\s*(?:async\s+)?(?:def|class)\s+{sym_esc}\b|"
1375
+ rf"^(?:export\s+)?(?:async\s+)?(?:function|class)\s+{sym_esc}\b|"
1376
+ rf"^(?:export\s+)?(?:const|let|var)\s+{sym_esc}\s*=",
1377
+ re.MULTILINE | re.IGNORECASE,
1378
+ )
1379
+ results: list[str] = []
1380
+ for fp in sorted(root.rglob("*")):
1381
+ if not fp.is_file():
1382
+ continue
1383
+ if any(p in SKIP_DIRS for p in fp.parts):
1384
+ continue
1385
+ if ext_filter and fp.suffix.lower() not in ext_filter:
1386
+ continue
1387
+ try:
1388
+ fl = self._read(fp).splitlines()
1389
+ for i, line in enumerate(fl, 1):
1390
+ if usage_re.search(line) and not def_re.search(line):
1391
+ ctx = fl[max(0, i - 2): i + 2]
1392
+ ctx_str = "\n".join(
1393
+ f" {j + 1:4d} {l_}"
1394
+ for j, l_ in enumerate(ctx, max(0, i - 2))
1395
+ )
1396
+ results.append(
1397
+ f"{fp.relative_to(root)}:{i}\n{ctx_str}")
1398
+ if len(results) >= max_results:
1399
+ break
1400
+ except OSError:
1401
+ continue
1402
+ if len(results) >= max_results:
1403
+ break
1404
+ if not results:
1405
+ return f"Nenhuma referência encontrada para '{symbol}'."
1406
+ return f"# Referências para '{symbol}'\n\n" + "\n\n".join(results)
1407
+
1408
+ def _tool_get_project_summary(self) -> str:
1409
+ """Retorna um resumo do projeto: tipo, linguagens, dependências, git e estrutura raiz."""
1410
+ root = self._workspace()
1411
+ if root is None:
1412
+ return _t("ia.tool_no_workspace")
1413
+ parts = [f"# Resumo: {root.name}\n**Caminho:** {root}\n"]
1414
+ markers = {
1415
+ "pyproject.toml": "Python",
1416
+ "setup.py": "Python",
1417
+ "package.json": "Node.js",
1418
+ "Cargo.toml": "Rust",
1419
+ "go.mod": "Go",
1420
+ "pom.xml": "Java",
1421
+ "Gemfile": "Ruby",
1422
+ }
1423
+ for m, label in markers.items():
1424
+ if (root / m).exists():
1425
+ parts.append(f"**Tipo:** {label}")
1426
+ break
1427
+ ext_map = {
1428
+ ".py": "Python",
1429
+ ".js": "JavaScript",
1430
+ ".ts": "TypeScript",
1431
+ ".java": "Java",
1432
+ ".rs": "Rust",
1433
+ ".go": "Go",
1434
+ ".html": "HTML",
1435
+ ".css": "CSS",
1436
+ ".cs": "C#",
1437
+ ".cpp": "C++",
1438
+ }
1439
+ counts: dict[str, int] = {}
1440
+ for p in root.rglob("*"):
1441
+ if p.is_file() and p.suffix.lower() in ext_map:
1442
+ if not any(d in SKIP_DIRS for d in p.parts):
1443
+ lang = ext_map[p.suffix.lower()]
1444
+ counts[lang] = counts.get(lang, 0) + 1
1445
+ if counts:
1446
+ top = sorted(counts.items(), key=lambda x: -x[1])[:6]
1447
+ parts.append(
1448
+ f"**Linguagens:** {', '.join(f'{l_} ({n})' for l_, n in top)}")
1449
+ branch = self._git(["branch", "--show-current"])
1450
+ if branch and "[git" not in branch:
1451
+ commit = self._git(["log", "-1", "--pretty=format:%h - %s"])
1452
+ parts.append(f"**Git:** branch `{branch}` | {commit}")
1453
+ recent = self._git(
1454
+ ["log", "-5", "--pretty=format:%h %ad %s", "--date=short"]
1455
+ )
1456
+ if recent:
1457
+ parts.append(f"**Commits recentes:**\n```\n{recent}\n```")
1458
+ with contextlib.suppress(OSError):
1459
+ entries = sorted(
1460
+ root.iterdir(), key=lambda p: (p.is_file(), p.name.lower())
1461
+ )
1462
+ tree = [
1463
+ (f" {e.name}/" if e.is_dir() else f" {e.name}")
1464
+ for e in entries
1465
+ if not e.name.startswith(".") and e.name not in SKIP_DIRS
1466
+ ]
1467
+ if tree:
1468
+ parts.append("**Estrutura raiz:**\n```\n" +
1469
+ "\n".join(tree) + "\n```")
1470
+ return "\n".join(parts)
1471
+
1472
+ def _tool_read_diagnostics(self) -> str:
1473
+ """Retorna os diagnósticos (erros e avisos) do editor ativo registrados pelo LSP."""
1474
+ editor = self._get_editor()
1475
+ if editor is None:
1476
+ return _t("ia.tool_no_editor")
1477
+ diags = getattr(editor, "_diags", [])
1478
+ if not diags:
1479
+ return _t("ia.tool_no_diags")
1480
+ lines = [f"# Diagnósticos: {getattr(editor, 'path', 'arquivo')}\n"]
1481
+ for d in diags:
1482
+ level = getattr(d, "level", "?").upper()
1483
+ line_no = getattr(d, "line", 0)
1484
+ msg = getattr(d, "message", str(d))
1485
+ source = getattr(d, "source", "")
1486
+ entry = f"[{level}] linha {line_no}: {msg}"
1487
+ if source:
1488
+ entry += f" ({source})"
1489
+ lines.append(entry)
1490
+ return "\n".join(lines)
1491
+
1492
+ def _tool_read_symbols(self) -> str:
1493
+ """Lista símbolos de nível superior (classes, funções) do arquivo ativo com números de linha."""
1494
+ editor = self._get_editor()
1495
+ if editor is None:
1496
+ return _t("ia.tool_no_editor")
1497
+ fp = getattr(editor, "path", None)
1498
+ lang = getattr(editor, "lang", "")
1499
+ if fp is None:
1500
+ return _t("ia.tool_no_editor")
1501
+ try:
1502
+ content = self._read(Path(fp))
1503
+ except OSError as exc:
1504
+ return f"Erro ao ler arquivo: {exc}"
1505
+ symbols: list[str] = []
1506
+ for i, line in enumerate(content.splitlines(), 1):
1507
+ if lang == "python":
1508
+ m = re.match(r"^(class|def|async def)\s+(\w+)", line)
1509
+ if m:
1510
+ symbols.append(f"linha {i:4d}: {m.group(1)} {m.group(2)}")
1511
+ elif lang in ("javascript", "typescript"):
1512
+ m = re.match(
1513
+ r"^\s*(?:export\s+)?(?:async\s+)?(?:function|class|const|let|var)\s+(\w+)",
1514
+ line,
1515
+ )
1516
+ if m:
1517
+ symbols.append(f"linha {i:4d}: {line.strip()[:80]}")
1518
+ else:
1519
+ if re.match(r"^\s*(?:func|function|class|def|fn)\s+\w+", line):
1520
+ symbols.append(f"linha {i:4d}: {line.strip()[:80]}")
1521
+ if not symbols:
1522
+ return f"Nenhum símbolo em {Path(fp).name}."
1523
+ return f"# Símbolos em {Path(fp).name}\n\n" + "\n".join(symbols[:100])
1524
+
1525
+ def _tool_workspace_symbols(self, extensions: str = "") -> str:
1526
+ """
1527
+ Retorna um mapa organizado por arquivo, limitado a 50 símbolos por arquivo.
1528
+ """
1529
+ root = self._workspace()
1530
+ if root is None:
1531
+ return _t("ia.tool_no_workspace")
1532
+ ext_filter = (
1533
+ {e.strip() for e in extensions.split(",") if e.strip()}
1534
+ if extensions
1535
+ else set()
1536
+ )
1537
+ symbol_map: dict[str, list[str]] = {}
1538
+ py_re = re.compile(r"^(class|def|async def)\s+(\w+)")
1539
+ js_re = re.compile(
1540
+ r"^\s*(?:export\s+)?(?:async\s+)?(?:function|class|const|let|var)\s+(\w+)"
1541
+ )
1542
+ for fp in sorted(root.rglob("*")):
1543
+ if not fp.is_file():
1544
+ continue
1545
+ if any(p in SKIP_DIRS for p in fp.parts):
1546
+ continue
1547
+ if ext_filter and fp.suffix.lower() not in ext_filter:
1548
+ continue
1549
+ try:
1550
+ rel = str(fp.relative_to(root))
1551
+ for i, line in enumerate(self._read(fp).splitlines(), 1):
1552
+ if fp.suffix == ".py":
1553
+ m = py_re.match(line)
1554
+ if m:
1555
+ symbol_map.setdefault(rel, []).append(
1556
+ f" linha {i:4d}: {m.group(1)} {m.group(2)}"
1557
+ )
1558
+ elif fp.suffix in (".js", ".ts"):
1559
+ m = js_re.match(line)
1560
+ if m:
1561
+ symbol_map.setdefault(rel, []).append(
1562
+ f" linha {i:4d}: {line.strip()[:80]}"
1563
+ )
1564
+ else:
1565
+ if re.match(r"^\s*(?:func|function|class|def|fn)\s+\w+", line):
1566
+ symbol_map.setdefault(rel, []).append(
1567
+ f" linha {i:4d}: {line.strip()[:80]}"
1568
+ )
1569
+ except OSError:
1570
+ continue
1571
+ if not symbol_map:
1572
+ return _t("ia.tool_no_workspace")
1573
+ out = ["# Símbolos do workspace\n"]
1574
+ for fname in sorted(symbol_map):
1575
+ out.append(f"## {fname}")
1576
+ out.extend(symbol_map[fname][:50])
1577
+ out.append("")
1578
+ return "\n".join(out[:600])
1579
+
1580
+ def _tool_read_git_diff(self, staged_only: bool = False, path: str = "") -> str:
1581
+ """Retorna o diff git do workspace, opcionalmente filtrado por arquivo ou staged."""
1582
+ args = ["diff"]
1583
+ if staged_only:
1584
+ args.append("--staged")
1585
+ if path:
1586
+ args.extend(["--", path])
1587
+ diff = self._git(args)
1588
+ return diff[:8000] if diff else _t("ia.tool_no_changes")
1589
+
1590
+ def _tool_read_git_log(self, count: int = 10, oneline: bool = False) -> str:
1591
+ """Retorna os últimos `count` commits em formato tabular ou condensado."""
1592
+ fmt = "%h %ad %an %s" if not oneline else "%h %s"
1593
+ result = self._git(
1594
+ ["log", f"-{count}", f"--pretty=format:{fmt}", "--date=short"]
1595
+ )
1596
+ return f"# {result}" if result else _t("ia.tool_no_commits")
1597
+
1598
+ def _tool_preview_rename(
1599
+ self, symbol_old: str, symbol_new: str, extensions: str = ""
1600
+ ) -> str:
1601
+ """Simula renomear `symbol_old` para `symbol_new` sem modificar nenhum arquivo.
1602
+
1603
+ Retorna lista de arquivos e linhas que seriam alterados.
1604
+ """
1605
+ root = self._workspace()
1606
+ if root is None:
1607
+ return _t("ia.tool_no_workspace")
1608
+ ext_filter = (
1609
+ {e.strip() for e in extensions.split(",") if e.strip()}
1610
+ if extensions
1611
+ else set()
1612
+ )
1613
+ pattern = re.compile(rf"\b{re.escape(symbol_old)}\b")
1614
+ lines: list[str] = []
1615
+ for fp in sorted(root.rglob("*")):
1616
+ if not fp.is_file():
1617
+ continue
1618
+ if any(p in SKIP_DIRS for p in fp.parts):
1619
+ continue
1620
+ if ext_filter and fp.suffix.lower() not in ext_filter:
1621
+ continue
1622
+ try:
1623
+ fl = self._read(fp).splitlines()
1624
+ changed = False
1625
+ for i, line in enumerate(fl, 1):
1626
+ if pattern.search(line):
1627
+ lines.append(
1628
+ f"{fp.relative_to(root)}:{i}: {line.strip()}")
1629
+ lines.append(
1630
+ f" -> {pattern.sub(symbol_new, line).strip()}"
1631
+ )
1632
+ changed = True
1633
+ if changed:
1634
+ lines.append("")
1635
+ except OSError:
1636
+ continue
1637
+ if len(lines) > 200:
1638
+ lines.append("... (truncado)")
1639
+ break
1640
+ if not lines:
1641
+ return f"Nenhuma ocorrência de '{symbol_old}'."
1642
+ return f"# Preview rename: {symbol_old} -> {symbol_new}\n\n" + "\n".join(lines)
1643
+
1644
+ def _tool_get_env_info(self) -> str:
1645
+ """Retorna versões de ferramentas instaladas (git, node, python etc.), OS e workspace."""
1646
+ import platform
1647
+
1648
+ parts = ["# Informações do Ambiente\n"]
1649
+ parts.append(
1650
+ f"**OS:** {platform.system()} {platform.release()} ({platform.machine()})"
1651
+ )
1652
+ parts.append(f"**Python:** {platform.python_version()}")
1653
+ tools = [
1654
+ "git",
1655
+ "node",
1656
+ "npm",
1657
+ "npx",
1658
+ "cargo",
1659
+ "go",
1660
+ "ruby",
1661
+ "java",
1662
+ "docker",
1663
+ "pip",
1664
+ "pip3",
1665
+ "black",
1666
+ "prettier",
1667
+ "ruff",
1668
+ "mypy",
1669
+ ]
1670
+ found = []
1671
+ for tool in tools:
1672
+ try:
1673
+ r = _run(
1674
+ [tool, "--version"],
1675
+ capture_output=True,
1676
+ text=True,
1677
+ timeout=3,
1678
+ check=False,
1679
+ )
1680
+ ver = (
1681
+ r.stdout.strip().splitlines()[
1682
+ 0][:60] if r.returncode == 0 else None
1683
+ )
1684
+ found.append(
1685
+ f" {'✅' if ver else '❌'} {tool}: {ver or 'não disponível'}"
1686
+ )
1687
+ except FileNotFoundError:
1688
+ found.append(f" ❌ {tool}: não encontrado")
1689
+ except Exception:
1690
+ found.append(f" ⚠️ {tool}: erro")
1691
+ parts.append("**Ferramentas:**\n" + "\n".join(found))
1692
+ root = self._workspace()
1693
+ if root:
1694
+ parts.append(f"**Workspace:** {root}")
1695
+ return "\n".join(parts)
1696
+
1697
+ def _tool_check_dependency(self, name: str, manager: str = "") -> str:
1698
+ """Verifica se uma dependência está instalada e retorna sua versão."""
1699
+ candidates = {
1700
+ "pip": ["pip", "show", name],
1701
+ "npm": ["npm", "list", name, "--depth=0"],
1702
+ "cargo": ["cargo", "search", "--limit", "1", name],
1703
+ }
1704
+ to_try = {manager: candidates[manager]
1705
+ } if manager in candidates else candidates
1706
+ results: list[str] = []
1707
+ for mgr, cmd in to_try.items():
1708
+ try:
1709
+ r = _run(
1710
+ cmd, capture_output=True, text=True, timeout=8, check=False
1711
+ )
1712
+ if r.returncode == 0 and r.stdout.strip():
1713
+ results.append(
1714
+ f"✅ {mgr}: {r.stdout.strip().splitlines()[0][:100]}"
1715
+ )
1716
+ else:
1717
+ results.append(f"❌ {mgr}: não instalado")
1718
+ except FileNotFoundError:
1719
+ results.append(f"⚠️ {mgr}: gerenciador não encontrado")
1720
+ except subprocess.TimeoutExpired:
1721
+ results.append(f"⚠️ {mgr}: timeout")
1722
+ return f"# Verificação: {name}\n\n" + "\n".join(results)
1723
+
1724
+ def _tool_diff_files(
1725
+ self, path_a: str, path_b: str = "", content_b: str = ""
1726
+ ) -> str:
1727
+ """Compara dois arquivos ou um arquivo com um conteúdo fornecido em formato unified diff."""
1728
+ import difflib
1729
+
1730
+ ra = self._resolve(path_a)
1731
+ if ra is None:
1732
+ return f"Arquivo não encontrado: {path_a}"
1733
+ try:
1734
+ lines_a = self._read(ra).splitlines(keepends=True)
1735
+ except OSError as e:
1736
+ return f"Erro ao ler {path_a}: {e}"
1737
+ if path_b:
1738
+ rb = self._resolve(path_b)
1739
+ if rb is None:
1740
+ return f"Arquivo não encontrado: {path_b}"
1741
+ try:
1742
+ lines_b = self._read(rb).splitlines(keepends=True)
1743
+ except OSError as e:
1744
+ return f"Erro ao ler {path_b}: {e}"
1745
+ label_b = path_b
1746
+ elif content_b:
1747
+ lines_b = content_b.splitlines(keepends=True)
1748
+ label_b = "(conteúdo fornecido)"
1749
+ else:
1750
+ return _t("ia.tool_bad_path")
1751
+ diff = list(
1752
+ difflib.unified_diff(
1753
+ lines_a, lines_b, fromfile=path_a, tofile=label_b, lineterm=""
1754
+ )
1755
+ )
1756
+ return "\n".join(diff[:300]) if diff else "Arquivos idênticos."
1757
+
1758
+ def _tool_get_clipboard(self) -> str:
1759
+ """Retorna o conteúdo atual da área de transferência do sistema via Tkinter."""
1760
+ rw = self._get_root_widget() if self._get_root_widget else None
1761
+ if rw is None:
1762
+ return _t("ia.tool_no_root_widget")
1763
+ try:
1764
+ return rw.clipboard_get()
1765
+ except Exception as e:
1766
+ return _t("ia.tool_clipboard_empty", err=e)
1767
+
1768
+ def _tool_write_file(self, path: str, content: str, encoding: str = "utf-8") -> str:
1769
+ """Cria ou sobrescreve `path` com `content` de forma atômica.
1770
+
1771
+ Recusa escrita em arquivos sensíveis (.env, .pem, .key etc.).
1772
+ Cria um backup `.bak` antes de sobrescrever arquivos existentes.
1773
+ """
1774
+ root = self._workspace()
1775
+ if root is None:
1776
+ return _t("ia.tool_no_workspace")
1777
+ dest = self._confine(path)
1778
+ if dest is None:
1779
+ return f"Caminho '{path}' fora do workspace."
1780
+ blocked_ext = {".pyc", ".so", ".dll", ".exe", ".bin", ".key", ".pem"}
1781
+ if self._is_sensitive(dest) or dest.suffix.lower() in blocked_ext:
1782
+ return f"Escrita em '{dest.name}' não permitida."
1783
+ return self._safe_write(dest, content, encoding)
1784
+
1785
+ def _tool_apply_edit(
1786
+ self, path: str, edits: list[dict[str, Any]], dry_run: bool = False
1787
+ ) -> str:
1788
+ """Aplica uma lista de substituições cirúrgicas em `path`.
1789
+
1790
+ Cada edição especifica `old_text` (literal ou regex) e `new_text`.
1791
+ Com `dry_run=True`, retorna o diff sem gravar em disco.
1792
+ """
1793
+ resolved = self._resolve(path) or self._confine(path)
1794
+ if resolved is None or not resolved.exists():
1795
+ return _t("ia.tool_file_not_found", path=path)
1796
+ if self._is_sensitive(resolved):
1797
+ return f"Escrita em '{resolved.name}' não permitida."
1798
+ try:
1799
+ content = self._read(resolved)
1800
+ except OSError as exc:
1801
+ return _t("ia.tool_read_error", path=path, err=exc)
1802
+ original = content
1803
+ changes: list[str] = []
1804
+ for idx, edit in enumerate(edits, 1):
1805
+ old = edit["old_text"]
1806
+ new = edit.get("new_text", "")
1807
+ count = edit.get("count", 1)
1808
+ use_re = edit.get("regex", False)
1809
+ pattern = re.compile(
1810
+ re.escape(old) if not use_re else old, re.MULTILINE)
1811
+ occ = 0
1812
+
1813
+ def repl(m: re.Match, _c: int = count, _n: str = new) -> str:
1814
+ """Executa um REPL de código via toolbox de IA e retorna a saída."""
1815
+ nonlocal occ
1816
+ occ += 1
1817
+ return (
1818
+ _n if (_c == 0 or occ == _c) else m.group(0)
1819
+ ) # pylint: disable=consider-using-in
1820
+
1821
+ content, n = pattern.subn(repl, content)
1822
+ changes.append(
1823
+ f"Edit #{idx}: {n} ocorrência(s) substituída(s)."
1824
+ if n
1825
+ else f"Edit #{idx}: padrão não encontrado: '{old[:60]}'"
1826
+ )
1827
+ if dry_run:
1828
+ import difflib
1829
+
1830
+ diff = list(
1831
+ difflib.unified_diff(
1832
+ original.splitlines(keepends=True),
1833
+ content.splitlines(keepends=True),
1834
+ fromfile=f"a/{path}",
1835
+ tofile=f"b/{path}",
1836
+ lineterm="",
1837
+ )
1838
+ )
1839
+ return (
1840
+ "# Dry-run diff\n\n"
1841
+ + "\n".join(diff[:200])
1842
+ + "\n\n"
1843
+ + "\n".join(changes)
1844
+ )
1845
+ if content == original:
1846
+ return _t("ia.tool_no_changes") + "\n" + "\n".join(changes)
1847
+ return self._safe_write(resolved, content) + "\n" + "\n".join(changes)
1848
+
1849
+ def _tool_insert_after_line(self, path: str, line: int, text: str) -> str:
1850
+ """Insere `text` imediatamente após o número de linha `line` em `path`."""
1851
+ resolved = self._resolve(path)
1852
+ if resolved is None:
1853
+ return _t("ia.tool_file_not_found", path=path)
1854
+ try:
1855
+ content = self._read(resolved)
1856
+ except OSError as exc:
1857
+ return _t("ia.tool_read_error", path=path, err=exc)
1858
+ lines = content.splitlines(keepends=True)
1859
+ if line < 0 or line > len(lines):
1860
+ return f"Linha {line} fora do intervalo (1-{len(lines)})."
1861
+ if not text.endswith("\n"):
1862
+ text += "\n"
1863
+ new_content = "".join(lines[:line]) + text + "".join(lines[line:])
1864
+ return self._safe_write(resolved, new_content)
1865
+
1866
+ def _tool_format_code(self, path: str) -> str:
1867
+ """Formata `path` com o formatador da linguagem detectada e salva o resultado.
1868
+
1869
+ Suporta: Black (.py), Prettier (.js/.ts/.json), rustfmt (.rs), gofmt (.go).
1870
+ """
1871
+ resolved = self._resolve(path)
1872
+ if resolved is None:
1873
+ return _t("ia.tool_file_not_found", path=path)
1874
+ ext = resolved.suffix.lower()
1875
+ cmds: dict[str, list[str]] = {
1876
+ ".py": ["black", "--quiet", "-"],
1877
+ ".js": ["npx", "prettier", "--stdin-filepath", str(resolved)],
1878
+ ".ts": ["npx", "prettier", "--stdin-filepath", str(resolved)],
1879
+ ".json": ["npx", "prettier", "--parser", "json"],
1880
+ ".rs": ["rustfmt", "--emit", "stdout", str(resolved)],
1881
+ ".go": ["gofmt", str(resolved)],
1882
+ }
1883
+ cmd = cmds.get(ext)
1884
+ if not cmd:
1885
+ return f"Nenhum formatador para '{ext}'."
1886
+ try:
1887
+ original = self._read(resolved)
1888
+ proc = _run(
1889
+ cmd,
1890
+ input=original if ext in (
1891
+ ".py", ".js", ".ts", ".json") else None,
1892
+ capture_output=True,
1893
+ text=True,
1894
+ timeout=15,
1895
+ check=False,
1896
+ )
1897
+ if proc.returncode != 0:
1898
+ return _t("ia.tool_formatter_err", err=proc.stderr)
1899
+ formatted = proc.stdout
1900
+ if formatted.strip() == original.strip():
1901
+ return _t("ia.tool_already_formatted")
1902
+ return self._safe_write(resolved, formatted)
1903
+ except FileNotFoundError:
1904
+ return _t("ia.tool_formatter_missing", cmd=cmd[0])
1905
+ except Exception as exc:
1906
+ return f"[Erro] {exc}"
1907
+
1908
+ def _tool_patch_files(
1909
+ self, patches: list[dict[str, Any]], dry_run: bool = False
1910
+ ) -> str:
1911
+ """Aplica edições em múltiplos arquivos em sequência.
1912
+
1913
+ Cada item de `patches` segue o mesmo formato de `apply_edit`.
1914
+ Com `dry_run=True`, simula sem gravar em disco.
1915
+ """
1916
+ results: list[str] = []
1917
+ for patch in patches:
1918
+ path = patch.get("path", "")
1919
+ edits = patch.get("edits", [])
1920
+ create = patch.get("create_if_missing", False)
1921
+ if not path:
1922
+ results.append(_t("ia.tool_no_path"))
1923
+ continue
1924
+ resolved = self._resolve(path)
1925
+ if resolved is None and create:
1926
+ resolved = self._confine(path)
1927
+ if resolved is None or self._is_sensitive(resolved):
1928
+ results.append(f"{path}: fora do workspace ou não permitido.")
1929
+ continue
1930
+ if dry_run:
1931
+ results.append(f"📄 {path}: (dry-run) seria criado.")
1932
+ continue
1933
+ cps = self._cps()
1934
+ if cps is not None and cps._current is not None:
1935
+ cps.record_write(resolved)
1936
+ resolved.parent.mkdir(parents=True, exist_ok=True)
1937
+ resolved.touch()
1938
+ if resolved is None:
1939
+ results.append(f"❌ {path}: não encontrado.")
1940
+ continue
1941
+ result = self._tool_apply_edit(path, edits, dry_run=dry_run)
1942
+ results.append(f"📄 {path}: {result.splitlines()[0]}")
1943
+ return "\n".join(results)
1944
+
1945
+ def _tool_run_command(
1946
+ self,
1947
+ command: str,
1948
+ timeout: int = 60,
1949
+ working_dir: str = "",
1950
+ env: dict[str, str] | None = None,
1951
+ ) -> str:
1952
+ """Executa `command` via shell no diretório do workspace.
1953
+
1954
+ Args:
1955
+ command: Comando shell completo.
1956
+ timeout: Segundos antes de encerrar o processo.
1957
+ working_dir: Subdiretório relativo ao workspace. Vazio = raiz.
1958
+ env: Variáveis de ambiente adicionais.
1959
+ """
1960
+ root = self._workspace()
1961
+ cwd = str(root) if root else None
1962
+ if working_dir and root:
1963
+ confined = self._confine(working_dir)
1964
+ if confined is None or not confined.is_dir():
1965
+ return f"Diretório '{working_dir}' fora do workspace ou inexistente."
1966
+ cwd = str(confined)
1967
+ run_env = os.environ.copy()
1968
+ if env:
1969
+ run_env.update(env)
1970
+ try:
1971
+ result = _run(
1972
+ command,
1973
+ shell=True,
1974
+ cwd=cwd,
1975
+ capture_output=True,
1976
+ text=True,
1977
+ timeout=timeout,
1978
+ check=False,
1979
+ env=run_env,
1980
+ )
1981
+ stdout = result.stdout.strip()
1982
+ stderr = result.stderr.strip()
1983
+ code = result.returncode
1984
+ parts = [f"# Comando: {command}\n# Código de saída: {code}\n"]
1985
+ if stdout:
1986
+ parts.append(f"## stdout\n{stdout[:5000]}")
1987
+ if stderr:
1988
+ parts.append(f"## stderr\n{stderr[:2000]}")
1989
+ return "\n\n".join(parts)
1990
+ except subprocess.TimeoutExpired:
1991
+ return f"Comando expirou após {timeout}s."
1992
+ except Exception as exc:
1993
+ return f"[Erro] {exc}"
1994
+
1995
+ def _tool_run_script(
1996
+ self,
1997
+ code: str,
1998
+ language: str = "python",
1999
+ timeout: int = 30,
2000
+ env: dict[str, str] | None = None,
2001
+ ) -> str:
2002
+ """Grava `code` em arquivo temporário e executa com o runtime da linguagem.
2003
+
2004
+ Suporta: python, bash, node, ruby, perl.
2005
+ """
2006
+ runtimes = {
2007
+ "python": ("python3", ".py"),
2008
+ "py": ("python3", ".py"),
2009
+ "bash": ("bash", ".sh"),
2010
+ "sh": ("sh", ".sh"),
2011
+ "node": ("node", ".js"),
2012
+ "js": ("node", ".js"),
2013
+ "javascript": ("node", ".js"),
2014
+ "ruby": ("ruby", ".rb"),
2015
+ "perl": ("perl", ".pl"),
2016
+ }
2017
+ lang_key = language.lower().strip()
2018
+ if lang_key not in runtimes:
2019
+ return _t("ia.tool_script_lang", lang=language)
2020
+ runtime, ext = runtimes[lang_key]
2021
+ root = self._workspace()
2022
+ cwd = str(root) if root else None
2023
+ sp: Path | None = None
2024
+ try:
2025
+ with tempfile.NamedTemporaryFile(
2026
+ mode="w", encoding="utf-8", suffix=ext, prefix="codis_ia_", delete=False
2027
+ ) as tmp:
2028
+ sp = Path(tmp.name)
2029
+ tmp.write(code)
2030
+ run_env = os.environ.copy()
2031
+ if cwd:
2032
+ run_env["PYTHONPATH"] = cwd
2033
+ if env:
2034
+ run_env.update(env)
2035
+ r = _run(
2036
+ [runtime, str(sp)],
2037
+ cwd=cwd,
2038
+ capture_output=True,
2039
+ text=True,
2040
+ timeout=timeout,
2041
+ check=False,
2042
+ env=run_env,
2043
+ )
2044
+ stdout = r.stdout.strip()
2045
+ stderr = r.stderr.strip()
2046
+ status = "✅ sucesso" if r.returncode == 0 else f"❌ saída {r.returncode}"
2047
+ parts = [f"# Script ({runtime}) – {status}"]
2048
+ parts.append(
2049
+ f"## stdout\n{stdout[:5000]}" if stdout else "## stdout\n(vazio)"
2050
+ )
2051
+ if stderr:
2052
+ parts.append(f"## stderr\n{stderr[:2000]}")
2053
+ return "\n\n".join(parts)
2054
+ except subprocess.TimeoutExpired:
2055
+ return _t("ia.tool_script_timeout", timeout=timeout)
2056
+ except FileNotFoundError:
2057
+ return f"Runtime '{runtime}' não encontrado."
2058
+ except Exception as exc:
2059
+ return f"[Erro] {exc}"
2060
+ finally:
2061
+ if sp and sp.exists():
2062
+ with contextlib.suppress(OSError):
2063
+ sp.unlink()
2064
+
2065
+ def _tool_run_tests(
2066
+ self, target: str = "", extra_args: str = "", framework: str = ""
2067
+ ) -> str:
2068
+ """Executa a suite de testes do projeto com auto-detecção de framework.
2069
+
2070
+ Detecta automaticamente pytest, jest, cargo test ou go test pela presença de
2071
+ arquivos de configuração. Timeout fixo de 120 segundos.
2072
+ """
2073
+ root = self._workspace()
2074
+ if not root:
2075
+ return _t("ia.tool_no_workspace")
2076
+ fw_map = {
2077
+ "pytest": ["pytest"],
2078
+ "jest": ["npx", "jest"],
2079
+ "cargo": ["cargo", "test"],
2080
+ "go": ["go", "test", "./..."],
2081
+ }
2082
+ if framework and framework in fw_map:
2083
+ selected = fw_map[framework]
2084
+ else:
2085
+ selected = None
2086
+ for cmd in [["pytest", "--version"]]:
2087
+ with contextlib.suppress(FileNotFoundError):
2088
+ _run(cmd, capture_output=True,
2089
+ timeout=5, check=False)
2090
+ selected = ["pytest"]
2091
+ break
2092
+ if not selected:
2093
+ if (root / "package.json").exists():
2094
+ selected = ["npm", "test"]
2095
+ elif (root / "go.mod").exists():
2096
+ selected = ["go", "test", "./..."]
2097
+ elif (root / "Cargo.toml").exists():
2098
+ selected = ["cargo", "test"]
2099
+ if not selected:
2100
+ return _t("ia.tool_tests_no_fw")
2101
+ full_cmd = selected + ([target] if target else [])
2102
+ if extra_args:
2103
+ full_cmd.extend(extra_args.split())
2104
+ try:
2105
+ result = _run(
2106
+ full_cmd,
2107
+ cwd=str(root),
2108
+ capture_output=True,
2109
+ text=True,
2110
+ timeout=120,
2111
+ check=False,
2112
+ )
2113
+ stdout = result.stdout.strip()
2114
+ stderr = result.stderr.strip()
2115
+ status = (
2116
+ "PASSOU"
2117
+ if result.returncode == 0
2118
+ else f"FALHOU (saída {result.returncode})"
2119
+ )
2120
+ parts = [f"# Testes: {status}"]
2121
+ if stdout:
2122
+ parts.append(stdout[:6000])
2123
+ if stderr:
2124
+ parts.append(f"stderr:\n{stderr[:2000]}")
2125
+ return "\n".join(parts)
2126
+ except subprocess.TimeoutExpired:
2127
+ return _t("ia.tool_tests_timeout")
2128
+ except Exception as exc:
2129
+ return f"[Erro] {exc}"
2130
+
2131
+ def _tool_create_directory(self, path: str) -> str:
2132
+ """Cria o diretório no caminho especificado, incluindo pais necessários."""
2133
+ root = self._workspace()
2134
+ if root is None:
2135
+ return _t("ia.tool_no_workspace")
2136
+ dest = self._confine(path)
2137
+ if dest is None:
2138
+ return _t("ia.tool_outside_ws")
2139
+ try:
2140
+ cps = self._cps()
2141
+ if cps is not None and cps._current is not None:
2142
+ cps.record_created_dir(dest)
2143
+ dest.mkdir(parents=True, exist_ok=True)
2144
+ return _t("ia.tool_dir_created", path=str(dest.relative_to(root.resolve())))
2145
+ except Exception as exc:
2146
+ return _t("ia.tool_dir_err", err=exc)
2147
+
2148
+ def _tool_delete_file(self, path: str) -> str:
2149
+ """Remove `path` do workspace, criando um backup `.deleted.bak` antes."""
2150
+ resolved = self._confine(path)
2151
+ if resolved is None:
2152
+ return _t("ia.tool_outside_ws")
2153
+ if not resolved.exists():
2154
+ return _t("ia.tool_file_not_found", path=path)
2155
+ if not resolved.is_file():
2156
+ return f"'{path}' não é um arquivo."
2157
+ blocked = self._unsaved_block(resolved)
2158
+ if blocked:
2159
+ return blocked
2160
+ try:
2161
+ rel = resolved.relative_to(self._workspace().resolve())
2162
+ self._remove_reversibly(resolved)
2163
+ return f"✅ Arquivo movido para a lixeira do projeto: {rel} (reversível)"
2164
+ except Exception as exc:
2165
+ return f"[Erro ao deletar] {exc}"
2166
+
2167
+ def _remove_reversibly(self, target: Path) -> None:
2168
+ """Remove *target* mandando-o para a lixeira do projeto (``rename`` atômico).
2169
+
2170
+ Nunca ``rmtree``/``unlink`` direto: o usuário pode restaurar pelo painel da
2171
+ lixeira ou desfazendo o turno da IA. Se a lixeira não estiver disponível
2172
+ (ex.: volume diferente), recusa em vez de apagar de forma irreversível.
2173
+ """
2174
+ from src.trash_core import TrashStore, trash_root_for
2175
+
2176
+ cps = self._cps()
2177
+ if cps is not None and cps._current is not None:
2178
+ cps.trash(target)
2179
+ else:
2180
+ TrashStore.for_root(trash_root_for(target, self._workspace())).put(target)
2181
+
2182
+ def _tool_delete_directory(self, path: str, recursive: bool = False) -> str:
2183
+ """Remove o diretório `path`. Com `recursive=True`, remove conteúdo recursivamente.
2184
+
2185
+ Recusa deletar fora do workspace. Operação irreversível.
2186
+ """
2187
+ root = self._workspace()
2188
+ if root is None:
2189
+ return _t("ia.tool_no_workspace")
2190
+ dest = (root / path).resolve()
2191
+ if not dest.exists():
2192
+ return _t("ia.tool_folder_missing", path=path)
2193
+ if not dest.is_dir():
2194
+ return f"'{path}' não é uma pasta."
2195
+ try:
2196
+ dest.relative_to(root.resolve())
2197
+ except ValueError:
2198
+ return _t("ia.tool_outside_ws")
2199
+ if dest == root.resolve():
2200
+ return _t("ia.tool_outside_ws")
2201
+ try:
2202
+ if recursive:
2203
+ self._remove_reversibly(dest)
2204
+ return f"✅ Pasta movida para a lixeira do projeto: {dest.relative_to(root)} (reversível)"
2205
+ dest.rmdir()
2206
+ return f"✅ Pasta deletada: {dest.relative_to(root)}"
2207
+ except OSError as exc:
2208
+ return f"[Erro ao deletar pasta] {exc}"
2209
+
2210
+ def _tool_move_file(self, src: str, dst: str) -> str:
2211
+ """Move ou renomeia `src` para `dst`, criando diretórios de destino se necessário."""
2212
+ root = self._workspace()
2213
+ if root is None:
2214
+ return _t("ia.tool_no_workspace")
2215
+ src_path = self._confine(src)
2216
+ dst_path = self._confine(dst)
2217
+ if src_path is None or dst_path is None:
2218
+ return _t("ia.tool_outside_ws")
2219
+ if not src_path.exists():
2220
+ return _t("ia.tool_file_not_found", path=src)
2221
+ dst_path.parent.mkdir(parents=True, exist_ok=True)
2222
+ if dst_path.exists():
2223
+ return f"[Erro] destino já existe: {dst}"
2224
+ try:
2225
+ shutil.move(str(src_path), str(dst_path))
2226
+ cps = self._cps()
2227
+ if cps is not None and cps._current is not None:
2228
+ cps.record_move(src_path, dst_path)
2229
+ return _t("ia.tool_moved", src=src, dst=dst)
2230
+ except Exception as exc:
2231
+ return _t("ia.tool_dir_err", err=exc)
2232
+
2233
+ def _tool_copy_file(self, src: str, dst: str) -> str:
2234
+ """Copia `src` para `dst`. Funciona com arquivos e diretórios."""
2235
+ root = self._workspace()
2236
+ if root is None:
2237
+ return _t("ia.tool_no_workspace")
2238
+ src_path = self._confine(src)
2239
+ dst_path = self._confine(dst)
2240
+ if src_path is None or dst_path is None:
2241
+ return _t("ia.tool_outside_ws")
2242
+ if not src_path.exists():
2243
+ return _t("ia.tool_file_not_found", path=src)
2244
+ dst_path.parent.mkdir(parents=True, exist_ok=True)
2245
+ if dst_path.exists():
2246
+ return f"[Erro] destino já existe: {dst}"
2247
+ try:
2248
+ cps = self._cps()
2249
+ if cps is not None and cps._current is not None:
2250
+ cps.record_write(dst_path)
2251
+ (shutil.copytree if src_path.is_dir() else shutil.copy2)(
2252
+ str(src_path), str(dst_path)
2253
+ )
2254
+ return _t("ia.tool_copied", src=src, dst=dst)
2255
+ except Exception as exc:
2256
+ return _t("ia.tool_dir_err", err=exc)
2257
+
2258
+ def _tool_init_project(
2259
+ self,
2260
+ template: str,
2261
+ path: str = ".",
2262
+ name: str = "",
2263
+ git: bool = True,
2264
+ extra_cmds: list[str] | None = None,
2265
+ ) -> str:
2266
+ """Inicializa um novo projeto a partir de um template.
2267
+
2268
+ Templates disponíveis: node-ts, react, python-lib, fastapi, rust, vazio.
2269
+ Cria README, .gitignore e executa comandos de inicialização do template.
2270
+ Com `git=True`, faz git init e commit inicial.
2271
+ """
2272
+ root = self._workspace()
2273
+ if root is None:
2274
+ return _t("ia.tool_no_workspace")
2275
+ dest = self._confine(path)
2276
+ if dest is None:
2277
+ return _t("ia.tool_outside_ws")
2278
+ dest.mkdir(parents=True, exist_ok=True)
2279
+ project_name = re.sub(r"[^A-Za-z0-9_.-]+", "-", name or dest.name).strip("-.") or "project"
2280
+ module_name = re.sub(r"\W+", "_", project_name).strip("_") or "project"
2281
+ if module_name[0].isdigit():
2282
+ module_name = f"_{module_name}"
2283
+ results = [
2284
+ f"# Inicializando projeto '{project_name}' (template: {template})\n"]
2285
+
2286
+ def run(cmd: str) -> None:
2287
+ """Executa a ferramenta de IA e retorna o resultado."""
2288
+ r = _run(
2289
+ cmd,
2290
+ shell=True,
2291
+ cwd=str(dest),
2292
+ capture_output=True,
2293
+ text=True,
2294
+ timeout=60,
2295
+ check=False,
2296
+ )
2297
+ out = (r.stdout + r.stderr).strip()
2298
+ results.append(f"$ {cmd}\n{out[:500]}")
2299
+
2300
+ def write(rel: str, content: str) -> None:
2301
+ """Escreve conteúdo no arquivo especificado via toolbox de IA."""
2302
+ fp = dest / rel
2303
+ fp.parent.mkdir(parents=True, exist_ok=True)
2304
+ fp.write_text(content, "utf-8")
2305
+ results.append(f"✅ Criado: {rel}")
2306
+
2307
+ if git:
2308
+ run("git init")
2309
+ write(".gitignore", _GITIGNORE.get(template, _GITIGNORE["vazio"]))
2310
+
2311
+ write("README.md", f"# {project_name}\n\n> Criado com Codis IA.\n")
2312
+
2313
+ if template == "node-ts":
2314
+ run("npm init -y")
2315
+ run(
2316
+ "npm install --save-dev typescript ts-node @types/node --ignore-scripts"
2317
+ )
2318
+ write("tsconfig.json", _TSCONFIG)
2319
+ write("src/index.ts", "console.log('Hello, TypeScript!');\n")
2320
+ elif template == "react":
2321
+ run("npx create-react-app . --template typescript --yes")
2322
+ elif template == "python-lib":
2323
+ write("pyproject.toml", _PYPROJECT.replace("PROJNAME", project_name))
2324
+ write(
2325
+ f"src/{module_name}/__init__.py",
2326
+ f'"""Package {project_name}."""\n__version__ = "0.1.0"\n',
2327
+ )
2328
+ write("tests/__init__.py", "")
2329
+ write(
2330
+ "tests/test_basic.py",
2331
+ f"def test_version():\n from {module_name} import __version__\n assert __version__ == '0.1.0'\n",
2332
+ )
2333
+ elif template == "fastapi":
2334
+ run("pip install fastapi uvicorn --quiet")
2335
+ write("main.py", _FASTAPI)
2336
+ write("requirements.txt", "fastapi\nuvicorn[standard]\n")
2337
+ elif template == "rust":
2338
+ run(f"cargo init . --name {project_name}")
2339
+
2340
+ for cmd in extra_cmds or []:
2341
+ run(cmd)
2342
+
2343
+ if git:
2344
+ run("git add -A")
2345
+ run(f'git commit -m "chore: init {project_name} via Codis IA"')
2346
+
2347
+ results.append(f"\n✅ Projeto '{project_name}' pronto em {dest}")
2348
+ return "\n".join(results)
2349
+
2350
+ def _tool_install_dependency(
2351
+ self,
2352
+ package: str,
2353
+ manager: str = "",
2354
+ dev: bool = False,
2355
+ global_: bool = False,
2356
+ extra_args: str = "",
2357
+ ) -> str:
2358
+ """Instala `package` com o gerenciador especificado ou auto-detectado.
2359
+
2360
+ Auto-detecção: package.json -> npm, Cargo.toml -> cargo, senão -> pip.
2361
+ """
2362
+ root = self._workspace()
2363
+ cwd = str(root) if root else None
2364
+ if not manager:
2365
+ if root and (root / "package.json").exists():
2366
+ manager = "npm"
2367
+ elif root and (root / "Cargo.toml").exists():
2368
+ manager = "cargo"
2369
+ else:
2370
+ manager = "pip"
2371
+ cmds: dict[str, list[str]] = {
2372
+ "pip": ["pip", "install", package],
2373
+ "pip3": ["pip3", "install", package],
2374
+ "npm": ["npm", "install"]
2375
+ + (["--save-dev"] if dev else [])
2376
+ + (["-g"] if global_ else [])
2377
+ + [package],
2378
+ "yarn": ["yarn", "add"] + (["--dev"] if dev else []) + [package],
2379
+ "cargo": ["cargo", "add", package],
2380
+ "gem": ["gem", "install", package],
2381
+ }
2382
+ cmd = cmds.get(manager)
2383
+ if not cmd:
2384
+ return _t("ia.tool_mgr_unknown", mgr=manager)
2385
+ if package.startswith("-") or not package.strip():
2386
+ return f"Nome de pacote inválido: {package!r}"
2387
+ if extra_args:
2388
+ cmd.extend(extra_args.split())
2389
+ try:
2390
+ r = _run(
2391
+ cmd, cwd=cwd, capture_output=True, text=True, timeout=120, check=False
2392
+ )
2393
+ out = (r.stdout + r.stderr).strip()
2394
+ return f"{'✅' if r.returncode == 0 else '❌'} {manager} install {package}\n\n{out[:3000]}"
2395
+ except FileNotFoundError:
2396
+ return f"'{manager}' não encontrado."
2397
+ except subprocess.TimeoutExpired:
2398
+ return _t("ia.tool_install_timeout")
2399
+ except Exception as exc:
2400
+ return f"[Erro] {exc}"
2401
+
2402
+ def _tool_git_stage(self, path: str = ".") -> str:
2403
+ """Adiciona o caminho ao staging area do Git (git add)."""
2404
+ return self._git(["add", "--", path or "."])
2405
+
2406
+ def _tool_git_commit(self, message: str, add_all: bool = False) -> str:
2407
+ """Executa `git commit -m <message>`. Com `add_all=True`, faz `git add -A` antes."""
2408
+ if add_all:
2409
+ self._git(["add", "-A"])
2410
+ return self._git(["commit", "-m", message])
2411
+
2412
+ @staticmethod
2413
+ def _valid_ref(name: str) -> bool:
2414
+ """Aceita nomes de refs não vazios que não possam ser lidos como opção do git."""
2415
+ return bool(name) and not name.startswith("-") and not any(c.isspace() for c in name)
2416
+
2417
+ def _tool_git_branch(self, action: str, name: str = "") -> str:
2418
+ """Gerencia branches git. `action` aceita: list, create, checkout, delete."""
2419
+ actions = {
2420
+ "list": lambda: self._git(["branch", "-a"]),
2421
+ "create": lambda: (
2422
+ self._git(["checkout", "-b", name]) if self._valid_ref(name) else _BAD_REF
2423
+ ),
2424
+ "checkout": lambda: (
2425
+ self._git(["checkout", name]) if self._valid_ref(name) else _BAD_REF
2426
+ ),
2427
+ "delete": lambda: (
2428
+ self._git(["branch", "-d", name]) if self._valid_ref(name) else _BAD_REF
2429
+ ),
2430
+ }
2431
+ fn = actions.get(action)
2432
+ return fn() if fn else f"Ação desconhecida: {action}"
2433
+
2434
+ def _tool_git_reset(self, mode: str = "mixed", target: str = "HEAD") -> str:
2435
+ """Executa `git reset --<mode> <target>`. Operação potencialmente destrutiva."""
2436
+ if mode not in ("soft", "mixed", "hard"):
2437
+ return f"Modo inválido: {mode}. Use: soft, mixed, hard."
2438
+ if not self._valid_ref(target):
2439
+ return _BAD_REF
2440
+ return self._git(["reset", f"--{mode}", target])
2441
+
2442
+ def _tool_git_clean(self, flags: str = "-fd") -> str:
2443
+ """Remove arquivos não rastreados com `git clean`. Sempre inclui -f."""
2444
+ if "-f" not in flags:
2445
+ flags = "-f" + flags.lstrip("-")
2446
+ return self._git(["clean"] + flags.split())
2447
+
2448
+ def _tool_open_terminal_tab(
2449
+ self, name: str = "IA Terminal", command: str = ""
2450
+ ) -> str:
2451
+ """Abre nova aba no terminal integrado do Codis via callback `on_open_terminal`."""
2452
+ if self._on_open_terminal:
2453
+ self._on_open_terminal(name, command)
2454
+ suffix = f"\nComando: {command}" if command else ""
2455
+ return _t("ia.tool_term_opened", name=name) + suffix
2456
+ return _t("ia.tool_no_terminal")
2457
+
2458
+
2459
+ _GITIGNORE: dict[str, str] = {
2460
+ "node-ts": "__pycache__/\nnode_modules/\ndist/\n.env\n*.log\n",
2461
+ "react": "node_modules/\nbuild/\n.env\n*.log\n",
2462
+ "python-lib": "__pycache__/\n*.pyc\n.venv/\nvenv/\ndist/\nbuild/\n*.egg-info/\n.env\n",
2463
+ "fastapi": "__pycache__/\n*.pyc\n.venv/\n.env\n",
2464
+ "rust": "target/\nCargo.lock\n.env\n",
2465
+ "vazio": ".env\n*.log\n",
2466
+ }
2467
+
2468
+ _TSCONFIG = """{
2469
+ "compilerOptions": {
2470
+ "target": "ES2022",
2471
+ "module": "commonjs",
2472
+ "lib": ["ES2022"],
2473
+ "outDir": "dist",
2474
+ "rootDir": "src",
2475
+ "strict": true,
2476
+ "esModuleInterop": true,
2477
+ "skipLibCheck": true,
2478
+ "forceConsistentCasingInFileNames": true
2479
+ },
2480
+ "include": ["src/**/*"],
2481
+ "exclude": ["node_modules", "dist"]
2482
+ }
2483
+ """
2484
+
2485
+ _PYPROJECT = """[build-system]
2486
+ requires = ["hatchling"]
2487
+ build-backend = "hatchling.build"
2488
+
2489
+ [project]
2490
+ name = "PROJNAME"
2491
+ version = "0.1.0"
2492
+ description = ""
2493
+ requires-python = ">=3.12"
2494
+ dependencies = []
2495
+
2496
+ [project.optional-dependencies]
2497
+ dev = ["pytest", "black", "ruff", "mypy"]
2498
+ """
2499
+
2500
+ _FASTAPI = '''"""FastAPI application."""
2501
+ from fastapi import FastAPI
2502
+
2503
+ app = FastAPI(title=_t("ia.my_api"))
2504
+
2505
+
2506
+ @app.get("/")
2507
+ async def root() -> dict:
2508
+ return {"message": "Olá, mundo!"}
2509
+
2510
+
2511
+ @app.get("/health")
2512
+ async def health() -> dict:
2513
+ return {"status": "ok"}
2514
+ '''
2515
+
2516
+
2517
+ def extract_code_blocks(text: str) -> list[tuple[str, str]]:
2518
+ """Extrai blocos de código Markdown e retorna lista de (linguagem, conteúdo)."""
2519
+ return [
2520
+ (m.group(1).lower(), m.group(2))
2521
+ for m in re.compile(r"```(\w*)\n(.*?)```", re.DOTALL).finditer(text)
2522
+ if not m.group(2).startswith("# File:")
2523
+ and m.group(1).lower() not in ("json", "tool_call")
2524
+ ]