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/session.py ADDED
@@ -0,0 +1,335 @@
1
+ """Codis IA - Sessões de conversa (sem dependência de Tkinter).
2
+
3
+ Problemas que este módulo resolve em relação ao histórico antigo (uma lista de
4
+ ``{role, content}`` que só crescia):
5
+
6
+ * **Contexto fresco, histórico enxuto.** O código anexado (arquivo/seleção/
7
+ menções) vale só para a mensagem em que foi enviado; nos turnos seguintes
8
+ ele vira uma nota ("anexado: a.py") em vez de ser repetido inteiro a cada
9
+ turno - o maior desperdício de tokens do chat.
10
+ * **Orçamento de tokens.** :meth:`ChatSession.messages_for_model` encolhe
11
+ blocos de código antigos, condensa os turnos mais velhos e, em último caso,
12
+ trunca no meio, sempre preservando a mensagem atual e a alternância de
13
+ papéis exigida pelos provedores.
14
+ * **Memória de ações.** O que a IA *fez* (ferramentas) fica registrado no turno
15
+ e é lembrado nas mensagens seguintes.
16
+ * **Persistência.** Várias conversas, salvas de forma atômica.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import contextlib
22
+ import json
23
+ import logging
24
+ import os
25
+ import re
26
+ import time
27
+ import uuid
28
+ from dataclasses import dataclass, field
29
+ from pathlib import Path
30
+ from typing import Any
31
+
32
+ logger = logging.getLogger("Codis.IA.Session")
33
+
34
+ MODES = ("ask", "edit", "agent")
35
+ KEEP_RECENT_TURNS = 6
36
+ OLD_CODE_KEEP_LINES = 4
37
+ OLD_CODE_MIN_LINES = 12
38
+ MAX_SESSIONS = 100
39
+
40
+ _FENCE = re.compile(r"```([^\n`]*)\n(.*?)```", re.S)
41
+
42
+
43
+ def estimate_tokens(text: str) -> int:
44
+ """Estimativa barata (~3,5 caracteres por token; conservadora para código)."""
45
+ return max(1, int(len(text) / 3.5)) if text else 0
46
+
47
+
48
+ def shrink_code_blocks(text: str, keep: int = OLD_CODE_KEEP_LINES, min_lines: int = OLD_CODE_MIN_LINES) -> str:
49
+ """Reduz blocos de código longos a ``keep`` linhas + marcador de omissão."""
50
+
51
+ def repl(m: re.Match[str]) -> str:
52
+ lang, body = m.group(1), m.group(2)
53
+ lines = body.split("\n")
54
+ if len(lines) <= min_lines:
55
+ return m.group(0)
56
+ head = "\n".join(lines[:keep])
57
+ return f"```{lang}\n{head}\n# … {len(lines) - keep} linhas omitidas do histórico …\n```"
58
+
59
+ return _FENCE.sub(repl, text)
60
+
61
+
62
+ def middle_truncate(text: str, max_tokens: int) -> str:
63
+ """Mantém início e fim, corta o meio (o início/fim costumam ser o mais útil)."""
64
+ max_chars = int(max_tokens * 3.5)
65
+ if len(text) <= max_chars or max_chars < 200:
66
+ return text if len(text) <= max_chars else text[:max_chars]
67
+ half = (max_chars - 40) // 2
68
+ return f"{text[:half]}\n[… {len(text) - 2 * half} caracteres omitidos …]\n{text[-half:]}"
69
+
70
+
71
+ @dataclass
72
+ class Turn:
73
+ """Uma mensagem da conversa."""
74
+
75
+ role: str
76
+ content: str
77
+ ts: float = field(default_factory=time.time)
78
+ actions: list[str] = field(default_factory=list)
79
+ attached: list[str] = field(default_factory=list)
80
+ checkpoint: int | None = None
81
+ attachment: str = ""
82
+ lead: str = ""
83
+
84
+ def model_text(self, *, with_attachment: bool) -> str:
85
+ if self.role == "user":
86
+ parts = [(self.lead if with_attachment else "") + self.content]
87
+ if with_attachment and self.attachment:
88
+ parts.append("\n\n" + self.attachment)
89
+ elif self.attached:
90
+ parts.append(f"\n\n[anexado antes: {', '.join(self.attached)}]")
91
+ return "".join(parts)
92
+ if self.actions:
93
+ return self.content + "\n\n[Ações executadas neste turno: " + "; ".join(self.actions[:25]) + "]"
94
+ return self.content
95
+
96
+ def to_json(self) -> dict[str, Any]:
97
+ d: dict[str, Any] = {"role": self.role, "content": self.content, "ts": self.ts}
98
+ if self.actions:
99
+ d["actions"] = self.actions
100
+ if self.attached:
101
+ d["attached"] = self.attached
102
+ if self.checkpoint is not None:
103
+ d["checkpoint"] = self.checkpoint
104
+ return d
105
+
106
+ @classmethod
107
+ def from_json(cls, d: dict[str, Any]) -> Turn:
108
+ return cls(role=str(d["role"]), content=str(d.get("content", "")), ts=float(d.get("ts", 0)),
109
+ actions=[str(a) for a in d.get("actions", [])],
110
+ attached=[str(a) for a in d.get("attached", [])], checkpoint=d.get("checkpoint"))
111
+
112
+
113
+ @dataclass
114
+ class ModelView:
115
+ """Resultado de :meth:`ChatSession.messages_for_model`."""
116
+
117
+ messages: list[dict[str, str]]
118
+ tokens: int
119
+ condensed_turns: int = 0
120
+ truncated: bool = False
121
+
122
+
123
+ class ChatSession:
124
+ """Uma conversa com a IA."""
125
+
126
+ def __init__(self, workspace: str | None = None, mode: str = "ask") -> None:
127
+ self.id = uuid.uuid4().hex[:10]
128
+ self.title = ""
129
+ self.created = self.updated = time.time()
130
+ self.workspace = workspace
131
+ self.mode = mode if mode in MODES else "ask"
132
+ self.provider = ""
133
+ self.model = ""
134
+ self.turns: list[Turn] = []
135
+
136
+ def add_user(self, text: str, *, attachment: str = "", attached: list[str] | None = None,
137
+ lead: str = "") -> Turn:
138
+ for t in self.turns:
139
+ t.attachment = ""
140
+ t.lead = ""
141
+ turn = Turn("user", text, attachment=attachment, attached=list(attached or []), lead=lead)
142
+ self.turns.append(turn)
143
+ if not self.title:
144
+ self.title = re.sub(r"\s+", " ", text).strip()[:60] or "Nova conversa"
145
+ self._touch()
146
+ return turn
147
+
148
+ def add_assistant(self, text: str, actions: list[str] | None = None, checkpoint: int | None = None) -> Turn:
149
+ turn = Turn("assistant", text, actions=list(actions or []), checkpoint=checkpoint)
150
+ self.turns.append(turn)
151
+ self._touch()
152
+ return turn
153
+
154
+ def drop_last_exchange(self) -> str | None:
155
+ """Remove a última pergunta (e a resposta, se houver). Retorna o texto do usuário."""
156
+ while self.turns and self.turns[-1].role == "assistant":
157
+ self.turns.pop()
158
+ if self.turns and self.turns[-1].role == "user":
159
+ text = self.turns.pop().content
160
+ self._touch()
161
+ return text
162
+ return None
163
+
164
+ def last_user_text(self) -> str | None:
165
+ return next((t.content for t in reversed(self.turns) if t.role == "user"), None)
166
+
167
+ def clear(self) -> None:
168
+ self.turns.clear()
169
+ self.title = ""
170
+ self._touch()
171
+
172
+ def _touch(self) -> None:
173
+ self.updated = time.time()
174
+
175
+ def messages_for_model(self, budget_tokens: int = 24_000, reserve_tokens: int = 0) -> ModelView:
176
+ """Mensagens dentro do orçamento, prontas para ``provider.send``.
177
+
178
+ *reserve_tokens* desconta o que já será gasto fora do histórico
179
+ (system prompt + contexto do projeto).
180
+ """
181
+ budget = max(1000, budget_tokens - reserve_tokens)
182
+ turns = [t for t in self.turns if t.content or t.attachment]
183
+ if not turns:
184
+ return ModelView([], 0)
185
+ last_idx = len(turns) - 1
186
+ recent_from = max(0, len(turns) - KEEP_RECENT_TURNS)
187
+
188
+ texts: list[tuple[str, str]] = []
189
+ for i, t in enumerate(turns):
190
+ body = t.model_text(with_attachment=(i == last_idx and t.role == "user"))
191
+ if i < recent_from:
192
+ body = shrink_code_blocks(body)
193
+ texts.append((t.role, body))
194
+
195
+ def total(items: list[tuple[str, str]]) -> int:
196
+ return sum(estimate_tokens(b) + 4 for _, b in items)
197
+
198
+ condensed = 0
199
+ current = texts
200
+ while total(current) > budget and condensed < recent_from:
201
+ condensed += 1
202
+ current = [("user", self._condense_note(turns[:condensed]))] + texts[condensed:]
203
+ texts = current
204
+
205
+ truncated = False
206
+ guard = 0
207
+ while total(texts) > budget and guard < 50:
208
+ guard += 1
209
+ idx = max(range(len(texts)), key=lambda k: len(texts[k][1]) if k != len(texts) - 1 else len(texts[k][1]) // 2)
210
+ role, body = texts[idx]
211
+ cur = estimate_tokens(body)
212
+ if cur <= 200:
213
+ break
214
+ texts[idx] = (role, middle_truncate(body, int(cur * 0.6)))
215
+ truncated = True
216
+
217
+ msgs = _normalize_roles(texts)
218
+ return ModelView(msgs, sum(estimate_tokens(m["content"]) for m in msgs), condensed, truncated)
219
+
220
+ @staticmethod
221
+ def _condense_note(dropped: list[Turn]) -> str:
222
+ topics = []
223
+ for t in dropped:
224
+ if t.role == "user":
225
+ first = re.sub(r"\s+", " ", t.content).strip()[:90]
226
+ if first:
227
+ topics.append(f"- {first}")
228
+ acts = [a for t in dropped for a in t.actions][:10]
229
+ note = "[Conversa anterior condensada para economizar contexto]\nO usuário pediu antes:\n"
230
+ note += "\n".join(topics[-12:]) or "- (sem detalhes)"
231
+ if acts:
232
+ note += "\nAções já realizadas: " + "; ".join(acts)
233
+ return note
234
+
235
+ def to_json(self) -> dict[str, Any]:
236
+ return {"version": 1, "id": self.id, "title": self.title, "created": self.created,
237
+ "updated": self.updated, "workspace": self.workspace, "mode": self.mode,
238
+ "provider": self.provider, "model": self.model,
239
+ "turns": [t.to_json() for t in self.turns]}
240
+
241
+ @classmethod
242
+ def from_json(cls, d: dict[str, Any]) -> ChatSession:
243
+ s = cls(d.get("workspace"), d.get("mode", "ask"))
244
+ s.id = str(d["id"])
245
+ s.title = str(d.get("title", ""))
246
+ s.created = float(d.get("created", time.time()))
247
+ s.updated = float(d.get("updated", s.created))
248
+ s.provider = str(d.get("provider", ""))
249
+ s.model = str(d.get("model", ""))
250
+ s.turns = [Turn.from_json(t) for t in d.get("turns", []) if isinstance(t, dict) and "role" in t]
251
+ return s
252
+
253
+
254
+ def _normalize_roles(pairs: list[tuple[str, str]]) -> list[dict[str, str]]:
255
+ """Garante: começa com *user*, papéis alternados (funde vizinhos iguais)."""
256
+ out: list[dict[str, str]] = []
257
+ for role, body in pairs:
258
+ if out and out[-1]["role"] == role:
259
+ out[-1]["content"] += "\n\n" + body
260
+ else:
261
+ out.append({"role": role, "content": body})
262
+ while out and out[0]["role"] != "user":
263
+ out.pop(0)
264
+ return out
265
+
266
+
267
+ @dataclass
268
+ class SessionInfo:
269
+ id: str
270
+ title: str
271
+ updated: float
272
+ workspace: str | None
273
+ turns: int
274
+
275
+
276
+ class SessionStore:
277
+ """Várias conversas em ``<dir>/<id>.json`` (escrita atômica)."""
278
+
279
+ def __init__(self, directory: Path | str) -> None:
280
+ self.dir = Path(directory)
281
+
282
+ def _path(self, sid: str) -> Path:
283
+ if not re.fullmatch(r"[0-9a-f]{6,32}", sid):
284
+ raise ValueError(f"id de sessão inválido: {sid!r}")
285
+ return self.dir / f"{sid}.json"
286
+
287
+ def save(self, session: ChatSession) -> None:
288
+ if not session.turns:
289
+ return
290
+ self.dir.mkdir(parents=True, exist_ok=True)
291
+ path = self._path(session.id)
292
+ tmp = path.with_suffix(".json.tmp")
293
+ tmp.write_text(json.dumps(session.to_json(), ensure_ascii=False), encoding="utf-8")
294
+ os.replace(tmp, path)
295
+ self._prune()
296
+
297
+ def load(self, sid: str) -> ChatSession | None:
298
+ try:
299
+ return ChatSession.from_json(json.loads(self._path(sid).read_text(encoding="utf-8")))
300
+ except (OSError, ValueError, KeyError, TypeError):
301
+ return None
302
+
303
+ def delete(self, sid: str) -> bool:
304
+ try:
305
+ self._path(sid).unlink()
306
+ return True
307
+ except (OSError, ValueError):
308
+ return False
309
+
310
+ def list(self, workspace: str | None = None) -> list[SessionInfo]:
311
+ """Conversas mais recentes primeiro; as do *workspace* informado vêm antes."""
312
+ infos: list[SessionInfo] = []
313
+ for p in self.dir.glob("*.json") if self.dir.is_dir() else []:
314
+ try:
315
+ d = json.loads(p.read_text(encoding="utf-8"))
316
+ infos.append(SessionInfo(str(d["id"]), str(d.get("title", "")), float(d.get("updated", 0)),
317
+ d.get("workspace"), len(d.get("turns", []))))
318
+ except (OSError, ValueError, KeyError, TypeError):
319
+ continue
320
+ infos.sort(key=lambda i: (workspace is not None and i.workspace != workspace, -i.updated))
321
+ return infos
322
+
323
+ def rename(self, sid: str, title: str) -> bool:
324
+ s = self.load(sid)
325
+ if s is None:
326
+ return False
327
+ s.title = title.strip()[:80] or s.title
328
+ self.save(s)
329
+ return True
330
+
331
+ def _prune(self) -> None:
332
+ infos = self.list()
333
+ for info in infos[MAX_SESSIONS:]:
334
+ with contextlib.suppress(Exception):
335
+ self.delete(info.id)