@yahyahammad/venastine 0.2.0 → 0.3.9

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 (152) hide show
  1. package/.env.example +9 -4
  2. package/CONFIG_ARCHITECTURE.md +2030 -0
  3. package/LICENSE +201 -201
  4. package/NOTICE +1 -1
  5. package/README.md +1034 -895
  6. package/agents/builtin/build.md +73 -0
  7. package/agents/builtin/compactor.md +75 -75
  8. package/agents/builtin/explore.md +77 -77
  9. package/agents/builtin/general.md +80 -0
  10. package/agents/builtin/pipeline-reviewer.md +100 -100
  11. package/agents/builtin/plan.md +106 -88
  12. package/agents/builtin/review.md +74 -74
  13. package/agents/builtin/test.md +65 -0
  14. package/agents/builtin/writer.md +67 -0
  15. package/agents/manager.py +68 -2
  16. package/agents/subagent_tool.py +472 -238
  17. package/agents/tui_commands.py +238 -151
  18. package/bin/venastine.mjs +150 -4
  19. package/bin/venastine.py +71 -0
  20. package/cli_commands.py +838 -0
  21. package/config.py +95 -1198
  22. package/config.yaml +1103 -0
  23. package/config_edit.py +1301 -0
  24. package/config_schema.py +971 -0
  25. package/config_update.py +749 -0
  26. package/core/agent_activity.py +256 -118
  27. package/core/ansi.py +452 -0
  28. package/core/approval.py +137 -115
  29. package/core/call_view.py +364 -0
  30. package/core/cancel.py +121 -0
  31. package/core/chatgpt_auth.py +747 -0
  32. package/core/claims_view.py +107 -0
  33. package/core/client.py +2715 -1559
  34. package/core/commands.py +460 -0
  35. package/core/compaction.py +1735 -971
  36. package/core/config_loader.py +1982 -1563
  37. package/core/connect.py +686 -0
  38. package/core/events.py +123 -61
  39. package/core/file_mentions.py +280 -0
  40. package/core/interaction.py +411 -328
  41. package/core/line_pattern.py +128 -0
  42. package/core/loop.py +2566 -1490
  43. package/core/memory.py +482 -370
  44. package/core/pipeline_models.py +190 -176
  45. package/core/provider_errors.py +234 -0
  46. package/core/reasoning/authorization.py +130 -130
  47. package/core/reasoning/base.py +219 -219
  48. package/core/reasoning/confidence_scoring.py +484 -468
  49. package/core/reasoning/events.py +149 -149
  50. package/core/reasoning/json_retry.py +19 -1
  51. package/core/reasoning/orchestrator.py +1561 -1382
  52. package/core/reasoning/output_writer.py +345 -286
  53. package/core/reasoning/payload_validation.py +524 -398
  54. package/core/reasoning/pipeline_storage.py +88 -22
  55. package/core/reasoning/review.py +659 -615
  56. package/core/reasoning/scholar.py +458 -434
  57. package/core/reasoning/source_corpus.py +433 -327
  58. package/core/reasoning/source_scoring.py +855 -855
  59. package/core/replay.py +315 -183
  60. package/core/session.py +36 -12
  61. package/core/session_view.py +259 -0
  62. package/core/session_wake.py +259 -0
  63. package/core/shell_sessions.py +1553 -0
  64. package/core/workspace_trust.py +1 -1
  65. package/credentials.py +148 -20
  66. package/database.py +333 -252
  67. package/{PRIVACY.md → docs/PRIVACY.md} +78 -66
  68. package/docs/SECURITY.md +108 -0
  69. package/docs/THIRD_PARTY_NOTICES.md +148 -0
  70. package/env_secrets.py +50 -9
  71. package/json_store.py +343 -123
  72. package/logging_setup.py +295 -185
  73. package/main.py +3433 -1961
  74. package/mcp_client/client.py +733 -499
  75. package/mcp_client/config.py +126 -21
  76. package/mcp_client/registration.py +343 -182
  77. package/memories/manager.py +147 -132
  78. package/memories/tui_commands.py +319 -244
  79. package/package.json +303 -73
  80. package/project_init/config_files.py +282 -278
  81. package/project_init/generator.py +728 -564
  82. package/project_init/manifest.py +18 -6
  83. package/project_init/tui_commands.py +147 -144
  84. package/prompts/critic_pass.md +24 -24
  85. package/prompts/revalidate.md +25 -25
  86. package/prompts/revise.md +2 -0
  87. package/prompts/source_grounding.md +66 -66
  88. package/prompts/system_prompts.py +316 -262
  89. package/providers.json.example +4 -2
  90. package/pyproject.toml +149 -100
  91. package/requirements.txt +295 -72
  92. package/safety/policy_enforcement.py +1082 -746
  93. package/security/askpass.py +419 -0
  94. package/security/capability.py +207 -177
  95. package/security/confine.py +484 -0
  96. package/security/hosted.py +182 -0
  97. package/security/permissions.py +237 -190
  98. package/security/posture.py +124 -12
  99. package/security/protected_paths.py +501 -309
  100. package/security/sandbox.py +4108 -985
  101. package/security/secrets.py +855 -0
  102. package/skills/builtin/math/formal-specification.md +67 -67
  103. package/skills/builtin/math/numerical-methods.md +66 -66
  104. package/skills/builtin/research/experiment-design.md +62 -62
  105. package/skills/builtin/research/reproducibility.md +55 -55
  106. package/skills/builtin/research/source-evaluation.md +70 -70
  107. package/skills/builtin/research/statistical-inference.md +63 -63
  108. package/skills/builtin/research/technical-writing.md +59 -59
  109. package/skills/builtin/software/code-review.md +61 -61
  110. package/skills/builtin/software/debugging.md +61 -61
  111. package/skills/builtin/software/test-design.md +67 -67
  112. package/skills/tui_commands.py +110 -111
  113. package/storage.py +1338 -1005
  114. package/tools/base.py +161 -1
  115. package/tools/builtin/_math_common.py +667 -377
  116. package/tools/builtin/_net_common.py +225 -19
  117. package/tools/builtin/arxiv.py +497 -39
  118. package/tools/builtin/ask_user.py +231 -213
  119. package/tools/builtin/discrete_math.py +35 -4
  120. package/tools/builtin/fetch_url.py +371 -153
  121. package/tools/builtin/file_ops.py +720 -412
  122. package/tools/builtin/geometry.py +48 -12
  123. package/tools/builtin/get_time.py +2 -2
  124. package/tools/builtin/linear_algebra.py +66 -23
  125. package/tools/builtin/load_skill.py +76 -66
  126. package/tools/builtin/logic.py +171 -12
  127. package/tools/builtin/pin.py +227 -193
  128. package/tools/builtin/probability_stats.py +12 -16
  129. package/tools/builtin/project_docs.py +464 -405
  130. package/tools/builtin/remember.py +175 -158
  131. package/tools/builtin/shell.py +980 -461
  132. package/tools/builtin/shell_sessions.py +613 -0
  133. package/tools/builtin/symbolic_math.py +80 -10
  134. package/tools/builtin/todo.py +149 -147
  135. package/tools/builtin/web_search.py +191 -13
  136. package/tools/context.py +159 -136
  137. package/tools/isolation.py +107 -34
  138. package/tools/registry.py +1242 -925
  139. package/tui/app.py +8318 -4100
  140. package/tui/app.tcss +747 -556
  141. package/tui/commands.py +26 -170
  142. package/tui/diffs.py +34 -13
  143. package/tui/history.py +128 -128
  144. package/tui/hosted_driver.py +102 -0
  145. package/tui/markdown.py +1329 -1279
  146. package/tui/meters.py +364 -268
  147. package/tui/ravens.py +146 -146
  148. package/tui/screens.py +1255 -943
  149. package/tui/themes.py +599 -559
  150. package/tui/widgets.py +3813 -2332
  151. package/SECURITY.md +0 -88
  152. package/THIRD_PARTY_NOTICES.md +0 -100
package/tui/themes.py CHANGED
@@ -1,559 +1,599 @@
1
- """
2
- tui/themes.py
3
-
4
- Fourteen themes: the eight-theme neutral grid (dark/light x
5
- plain/red/green/blue) plus six standalone tinted themes (matrix,
6
- nightmare, ember, midnight, glassy-lapis, paper) whose PANELS carry the
7
- identity -- background/surface/panel are theirs, not the grid's shared
8
- neutrals.
9
-
10
- Pure presentation -- no import of core/, no harness state, with one
11
- narrowing batch 64 wrote down rather than hid: `styles_for` keeps the
12
- set of theme names it has already complained about, because it runs
13
- once per rendered line and the complaint must not. Two things
14
- outside this module carry a theme name: the persisted `tui.theme` setting,
15
- validated by core/config_loader.py's _KNOWN_TUI, and tui/preferences.py's
16
- remembered choice. The second deliberately does NOT validate against
17
- THEME_NAMES -- it stores an opaque string and lets the App decide whether
18
- it still resolves, because ctrl+p's command palette can select one of
19
- Textual's own built-in themes and a whitelist here would silently forget
20
- it.
21
-
22
- Built on textual.theme.Theme (verified against the pinned textual 1.0.0,
23
- per D22's rule about not assuming a dependency's API shape). Textual
24
- derives the full variable set from these anchors, so each theme only
25
- declares the colours that actually differ.
26
- """
27
-
28
- import logging
29
-
30
- from textual.color import Color
31
- from textual.theme import Theme
32
-
33
- logger = logging.getLogger(__name__)
34
-
35
- # Shared neutrals. The accent variants below change only the three hue
36
- # slots (primary/secondary/accent), so a colour tweak to the base surfaces
37
- # lands in all eight grid themes at once rather than eight near-copies
38
- # drifting.
39
- _DARK_BASE = {
40
- "background": "#0f1115",
41
- "surface": "#171a21",
42
- "panel": "#1e222b",
43
- "foreground": "#e4e6eb",
44
- "warning": "#d9a441",
45
- "error": "#cf5c4a",
46
- "success": "#5aa86f",
47
- "dark": True,
48
- }
49
-
50
- _LIGHT_BASE = {
51
- "background": "#f7f7f5",
52
- "surface": "#ffffff",
53
- "panel": "#eceae6",
54
- "foreground": "#1b1c1e",
55
- "warning": "#9a6d10",
56
- "error": "#a63a2a",
57
- "success": "#2f7343",
58
- "dark": False,
59
- }
60
-
61
- # (primary, secondary, accent) per variant. Dark and light get separate
62
- # values because a hue readable on #0f1115 is usually too pale on #f7f7f5.
63
- #
64
- # The four DARK secondaries were lifted in batch 29 (#14): the pass role
65
- # renders in `secondary`, and every original value sat below 3.5:1 against
66
- # the shared dark background -- plain at 3.37 was the filed defect, red
67
- # ~2.7 and blue ~3.0 were the same defect nobody had measured. The floor
68
- # is pinned in tests/test_themes.py; these are the minimal luminance moves
69
- # that clear it.
70
- _ACCENTS_DARK = {
71
- # dark-plain's ACCENT was lifted in batch 41 (X1), for batch 29's
72
- # reason applied to a different axis. #14 measured contrast against
73
- # the BACKGROUND; this is separation between two roles that sit on
74
- # adjacent lines. `tool` renders in accent and `thinking` in
75
- # secondary, and on a deliberately monochrome theme hue cannot
76
- # separate them -- only lightness can. #a9b2c3 was 98.5 redmean
77
- # units from #8792a2, the tightest secondary/accent pair of all
78
- # fourteen themes (the next is paper at 143.8). #b8c1d1 is 142.7,
79
- # which clears that floor while staying 111 units off the
80
- # foreground -- go lighter and the assistant label melts into the
81
- # body text it introduces, which is the same defect facing the
82
- # other way.
83
- "plain": ("#8a93a3", "#8792a2", "#b8c1d1"),
84
- "red": ("#d4674f", "#b0513c", "#e8917b"),
85
- "green": ("#5fa876", "#4d8f63", "#8ecba1"),
86
- "blue": ("#5b90cc", "#4a76b3", "#8bb6e6"),
87
- }
88
-
89
- _ACCENTS_LIGHT = {
90
- "plain": ("#5a6273", "#3c4252", "#7d8595"),
91
- "red": ("#b04a33", "#7d3423", "#c9705a"),
92
- "green": ("#3f7f57", "#2b5a3c", "#5d9c74"),
93
- "blue": ("#3f6fa8", "#2b4d76", "#6091c7"),
94
- }
95
-
96
- # Standalone tinted themes (batch 29). Each OVERRIDES the shared base
97
- # outright -- that is their identity: the panels themselves carry the
98
- # palette, not just borders and text. Severity slots default to the grid
99
- # trio and are overridden ONLY where contrast against the theme's own
100
- # tint demands it, keeping the semantic hue family (danger stays
101
- # red-ish); every override carries its reason, and the floors live in
102
- # tests/test_themes.py (foreground >= 7:1, severity >= 4:1, identity
103
- # >= 3.5:1, all against the theme's own background).
104
- _STANDALONE = [
105
- dict(
106
- name="matrix", dark=True,
107
- background="#0a120c", surface="#0f1a12", panel="#14231a",
108
- foreground="#c8e6d0",
109
- primary="#3dd968", secondary="#2f9e52", accent="#7dffb0",
110
- # success overridden: the shared #5aa86f dissolves into matrix's
111
- # own green-dark background.
112
- success="#4ee08a",
113
- ),
114
- dict(
115
- name="nightmare", dark=True,
116
- background="#140b0e", surface="#1c0f14", panel="#251318",
117
- foreground="#e8d5d8",
118
- primary="#c94f5f", secondary="#a8556a", accent="#e88a96",
119
- # error overridden: red-on-red -- the shared #cf5c4a loses the
120
- # alarm against nightmare's blood background.
121
- error="#ff7b6b",
122
- ),
123
- dict(
124
- name="ember", dark=True,
125
- background="#16100a", surface="#1f1610", panel="#291d13",
126
- foreground="#ecdfd0",
127
- primary="#e08a3c", secondary="#a86228", accent="#f2b06a",
128
- # warning overridden yellower: the shared amber sat on top of
129
- # ember's primary orange and read as emphasis, not as caution.
130
- warning="#d9b83f",
131
- ),
132
- dict(
133
- name="midnight", dark=True,
134
- background="#0a0f1e", surface="#101830", panel="#16203c",
135
- foreground="#d5dcea",
136
- primary="#6f9fe8", secondary="#4a6fb0", accent="#9dbdf2",
137
- ),
138
- dict(
139
- name="glassy-lapis", dark=True,
140
- background="#14243f", surface="#1c2f52", panel="#243a63",
141
- foreground="#e2ecf8",
142
- primary="#7fb4ff", secondary="#5a8ac9", accent="#a8ccff",
143
- # error overridden: lapis is the lightest dark background, and
144
- # the shared #cf5c4a fell just under the severity floor on it.
145
- error="#e06a58",
146
- ),
147
- dict(
148
- name="paper", dark=False,
149
- background="#f4efe6", surface="#fbf8f2", panel="#eae3d5",
150
- foreground="#2b2620",
151
- primary="#7a5c2e", secondary="#5c4a32", accent="#9c7b45",
152
- ),
153
- ]
154
-
155
-
156
- def _build(variant: str, dark: bool) -> Theme:
157
- base = _DARK_BASE if dark else _LIGHT_BASE
158
- primary, secondary, accent = (
159
- _ACCENTS_DARK if dark else _ACCENTS_LIGHT
160
- )[variant]
161
- return Theme(
162
- name=f"{'dark' if dark else 'light'}-{variant}",
163
- primary=primary,
164
- secondary=secondary,
165
- accent=accent,
166
- **base,
167
- )
168
-
169
-
170
- def _build_standalone(spec: dict) -> Theme:
171
- base = _DARK_BASE if spec["dark"] else _LIGHT_BASE
172
- merged = {**base, **{k: v for k, v in spec.items() if k != "name"}}
173
- return Theme(name=spec["name"], **merged)
174
-
175
-
176
- ALL_THEMES = (
177
- [
178
- _build(variant, dark)
179
- for dark in (True, False)
180
- for variant in ("plain", "red", "green", "blue")
181
- ]
182
- + [_build_standalone(spec) for spec in _STANDALONE]
183
- )
184
-
185
- THEME_NAMES = [t.name for t in ALL_THEMES]
186
- DEFAULT_THEME = "dark-plain"
187
-
188
-
189
- def register_all(app) -> None:
190
- """Register every theme on the app. Call before setting app.theme."""
191
- for theme in ALL_THEMES:
192
- app.register_theme(theme)
193
-
194
-
195
- # ---------------------------------------------------------------------------
196
- # ---- Role palette (ROADMAP_v2 §26) ----------------------------------------
197
- # ---------------------------------------------------------------------------
198
- #
199
- # The transcript was uniformly white: a user message, the model's answer, a
200
- # pipeline trace line and a tool call were the same colour, and the "you"
201
- # label read as the first word of the message it introduced.
202
- #
203
- # WHY THIS IS A FUNCTION OF A THEME rather than a table of colour names.
204
- # Everything else in the TUI styles itself through app.tcss, which uses
205
- # theme variables ($panel, $primary) and so restyles across all fourteen
206
- # themes without edits. A RichLog cannot do that -- it renders Rich Text
207
- # objects, and a Rich style needs a concrete colour, not a variable to
208
- # resolve later. So the resolution happens here, against the Theme
209
- # object, and the same property holds: no literal appears below, and a
210
- # new theme needs no change in this section.
211
- #
212
- # Severity colours. Across the eight GRID themes, warning/error/success
213
- # are shared by _DARK_BASE and _LIGHT_BASE and mean the same thing
214
- # everywhere; primary/secondary/accent are the per-variant hues. A
215
- # STANDALONE theme may override a severity slot when its own panel tint
216
- # would swallow the shared value (matrix's success, nightmare's error,
217
- # ember's warning, glassy-lapis's error -- each with its reason above),
218
- # keeping the semantic hue family. Either way severity uses the
219
- # theme-resolved trio and identity uses the hues, rather than the
220
- # reverse. Floors are pinned in tests/test_themes.py.
221
-
222
- #: How far a diff row's background is blended TOWARD the theme's own
223
- #: background (batch 41, X7). 0.8 leaves a band that stands off the
224
- #: page by 1.22-1.53 across the fourteen themes while the foreground
225
- #: still reads on it at 9.3:1 or better -- a highlight rather than a
226
- #: slab. Both floors are pinned in tests/test_themes.py.
227
- DIFF_TINT = 0.8
228
-
229
-
230
- #: The eight Theme slots `role_styles` reads. Every one of them but
231
- #: `primary` is Optional[str] on textual's own Theme, and three of the
232
- #: twelve built-ins the command palette offers do leave one blank or
233
- #: fill it with a vocabulary Rich cannot read: textual-dark has no
234
- #: `background`, textual-light no `foreground`, textual-ansi nothing
235
- #: but `ansi_*` names. Reading them raw is what made selecting
236
- #: textual-dark kill the harness AT MOUNT -- and keep killing it,
237
- #: since watch_theme had already remembered the name (batch 64).
238
- _SLOTS = ("primary", "secondary", "accent", "warning", "error",
239
- "success", "foreground", "background")
240
-
241
- #: Filled palettes, keyed on the RAW SLOT VALUES rather than on
242
- #: theme.name. Theme is a plain mutable dataclass and
243
- #: App.register_theme overwrites by name, so a name key would hand a
244
- #: re-registered theme the colours of the one it replaced; a value key
245
- #: cannot. Memoisation of a pure function of its input, which is why
246
- #: it costs this module nothing the docstring claims -- and it earns
247
- #: its place because the fallback below is 0.194ms against
248
- #: role_styles' own 0.004ms, on a function called once per drawn line.
249
- _RESOLVED: dict[tuple, dict[str, str]] = {}
250
-
251
-
252
- def _rich(colour: str) -> str:
253
- """Textual's `ansi_*` colour names in Rich's vocabulary.
254
-
255
- textual-ansi fills every slot with `ansi_blue`/`ansi_default` --
256
- the terminal's own sixteen, which is the entire point of that
257
- theme -- and Rich's Style.parse does not know the prefix. It knows
258
- the names underneath it: textual.color.ANSI_COLORS is exactly the
259
- ANSI subset of rich.color.ANSI_COLOR_NAMES (verified by set
260
- difference against the pinned 1.0.0, per D22), and `ansi_default`
261
- is Rich's `default`. A translation, then, rather than a guess.
262
-
263
- Not doing it was never a crash, which is why it lasted: Rich's
264
- Text.render resolves a style string with `default=Style.null()`,
265
- so an unparseable one renders PLAIN and says nothing. Twenty-five
266
- of the thirty-four roles were silently unstyled on textual-ansi --
267
- the uniformly white transcript this section exists to fix, reached
268
- by a different road.
269
- """
270
- return colour[5:] if colour.startswith("ansi_") else colour
271
-
272
-
273
- def _palette(theme: Theme) -> dict[str, str]:
274
- """`_SLOTS`, every one of them filled, in Rich's vocabulary.
275
-
276
- A blank slot is filled from textual's OWN derivation --
277
- to_color_system().generate() is what it builds app.tcss's
278
- $background and $foreground out of -- rather than from a constant
279
- invented here, which would be a second opinion about a colour the
280
- rest of the screen already has.
281
-
282
- A FALLBACK and never a replacement, for two measured reasons.
283
- generate() is lossy: the base shade comes back as
284
- `color.lighten(0).hex`, an HSL round trip, which moves #d9a441 to
285
- #D8A441 and differs from the raw slot on 41 values across the
286
- fourteen shipped themes. And it is 48x slower than role_styles
287
- itself. Reaching for it only where a slot is actually None leaves
288
- all fourteen byte-identical and costs the other twenty-four themes
289
- eight getattrs.
290
- """
291
- raw = tuple(getattr(theme, slot) for slot in _SLOTS)
292
- if all(raw):
293
- return {slot: _rich(value) for slot, value in zip(_SLOTS, raw)}
294
- key = raw + (theme.dark,)
295
- if key not in _RESOLVED:
296
- generated = theme.to_color_system().generate()
297
- _RESOLVED[key] = {slot: _rich(value or generated[slot])
298
- for slot, value in zip(_SLOTS, raw)}
299
- return _RESOLVED[key]
300
-
301
-
302
- def _tint(colour: str, background: str,
303
- factor: float = DIFF_TINT) -> str | None:
304
- """`colour` faded toward `background`, as a hex string -- or None.
305
-
306
- Derived from the theme's own slots rather than written down, for
307
- the reason the whole of this section exists (#116): a literal pair
308
- of green and red backgrounds would be designed against one of the
309
- fourteen palettes and wrong on the other thirteen -- and on the six
310
- standalone themes, whose panels carry the identity, visibly so.
311
-
312
- None when either end is one of the terminal's own sixteen, which
313
- is textual-ansi and nothing else: there is no RGB there to blend,
314
- so there is no band to draw. Not a hypothetical guard -- textual's
315
- Color.parse raises on Rich's `default`, and blending two ANSI
316
- colours in textual hands back one of them unchanged, so both
317
- answers were wrong before this said so.
318
- """
319
- if not (colour.startswith("#") and background.startswith("#")):
320
- return None
321
- return Color.parse(colour).blend(Color.parse(background), factor).hex
322
-
323
-
324
- def role_styles(theme: Theme) -> dict[str, str]:
325
- """Rich style strings keyed by transcript role, for one theme.
326
-
327
- Roles are what a line MEANS, not where it came from: `pass` covers a
328
- research pass boundary whether the CLI or the TUI produced it, and
329
- `tool_error` is a failed tool call rather than "amber".
330
-
331
- Reads the RESOLVED palette rather than the Theme's own slots,
332
- which is batch 64: three of the twenty-six themes ctrl+p offers
333
- leave a slot at None or fill it with textual's `ansi_*` names,
334
- and one of them took the whole app down at mount. `_palette`
335
- fills and translates; nothing below can see the difference.
336
- """
337
- palette = _palette(theme)
338
- add = _tint(palette["success"], palette["background"])
339
- delete = _tint(palette["error"], palette["background"])
340
- return {
341
- # Who is speaking. The hues, because these distinguish identity.
342
- "user": f"bold {palette['primary']}",
343
- "user_label": f"bold {palette['primary']}",
344
- "assistant_label": f"bold {palette['accent']}",
345
- # The answer itself stays plain foreground DELIBERATELY. It is the
346
- # longest text on screen and the thing most often actually read;
347
- # tinting it costs contrast to say something the label already said.
348
- "assistant": "",
349
- # The harness talking about itself.
350
- "system": "dim italic",
351
- # §38: the model's reasoning, when tui.show_thinking renders it
352
- # inline. `secondary` because thinking is the answer's quieter
353
- # sibling rather than a severity or an identity -- it already
354
- # clears the identity floor on every theme, so no theme constant
355
- # moves for this. Italic separates it from `pass`/`pass_done`,
356
- # which share the hue in the research view.
357
- "thinking": f"italic {palette['secondary']}",
358
- "pass": f"bold {palette['secondary']}",
359
- "pass_done": palette["secondary"],
360
- # PLAIN accent, not `dim` (batch 41, X1). Two reasons, and the
361
- # second is the one that generalises. `dim {accent}` sat a
362
- # measured 98.5 redmean units from `thinking`'s
363
- # `italic {secondary}` on dark-plain -- the shipped default,
364
- # and the tightest pair of any theme (every other theme is
365
- # >= 143) -- so a tool call and a reasoning line were one
366
- # colour on the palette most people actually see. And `dim` is
367
- # a Rich ATTRIBUTE, not a colour: tests/test_themes.py's
368
- # contrast floors measure the undimmed hue and cannot see what
369
- # the terminal paints, so the style on EVERY tool call was the
370
- # one style whose real contrast nothing measured. Plain accent
371
- # moves it up, away from secondary, into a number the floors
372
- # can see.
373
- "tool": palette["accent"],
374
- # How bad it is. The three shared colours.
375
- "tool_error": palette["warning"],
376
- # BOLD, where tool_error is plain (X2). Both are non-fatal and
377
- # keep the hue family; the weight separates the harness raising
378
- # its voice from a tool that failed. They were the same string
379
- # outright until batch 41, which was survivable only because
380
- # nothing routed a WARNING here at all -- see
381
- # TranscriptLogHandler, where that was the actual defect.
382
- "warning": f"bold {palette['warning']}",
383
- "error": f"bold {palette['error']}",
384
- "success": palette["success"],
385
- # Confidence tiers, ordered worst-to-best in meaning rather than in
386
- # this dict. UNVERIFIED_COVERAGE is a gap in what was asked, not a
387
- # claim that failed, so it reads as absent rather than as wrong.
388
- "HIGH": palette["success"],
389
- "MEDIUM": palette["foreground"],
390
- "LOW": palette["warning"],
391
- "UNVERIFIED": palette["error"],
392
- "UNVERIFIED_COVERAGE": f"dim {palette['error']}",
393
- # §41's inline diff for `write` and `edit`. The only roles in
394
- # this table that set a BACKGROUND, because the whole point is
395
- # that a changed row is marked across its full width rather
396
- # than at the one character that carries the sign.
397
- #
398
- # Unless there is no background to set. `_tint` answers None on
399
- # a theme whose colours are the terminal's own sixteen --
400
- # textual-ansi and nothing else -- and the row then takes the
401
- # severity colour as its FOREGROUND, which is what git, diff
402
- # and patch all do in a sixteen-colour terminal. A solid band
403
- # was the alternative, and DIFF_TINT's comment above turns that
404
- # down for every theme that CAN be measured; picking it for the
405
- # one that cannot would be backwards.
406
- "diff_add": (f"{palette['foreground']} on {add}" if add
407
- else palette["success"]),
408
- "diff_del": (f"{palette['foreground']} on {delete}" if delete
409
- else palette["error"]),
410
- # Unchanged context recedes: it is there to place the change,
411
- # not to be read. `secondary` rather than a dimmed foreground
412
- # for X1's reason -- `dim` is an attribute no floor can
413
- # measure.
414
- "diff_context": palette["secondary"],
415
- # The file being changed. Bold foreground takes no hue at all,
416
- # which is what keeps it out of the identity roles the same
417
- # batch just separated -- a path is not a speaker.
418
- "diff_header": f"bold {palette['foreground']}",
419
- # Batch 53's markdown marks. These are marks INSIDE an entry rather
420
- # than kinds of line, which is why they sit outside MESSAGE_ROLES
421
- # exactly as the diff roles above do: the pairwise-distinctness and
422
- # separation floors ask whether two LINES can be told apart, and a
423
- # bold word never sits on the line below a tool call.
424
- #
425
- # This does narrow `assistant`'s "stays plain foreground
426
- # DELIBERATELY" a few lines up, and the narrowing is the decision:
427
- # that rule is about the BODY, whose length is the reason tinting it
428
- # costs more contrast than it buys. A heading and a bold run are
429
- # marks the model asked for, on a few cells at a time.
430
- #
431
- # A heading takes weight and no hue, `diff_header`'s reasoning --
432
- # a section title is not a speaker either. Strong takes the
433
- # attribute alone, because the one thing `**` means is emphasis
434
- # within body text and a colour would make it a different KIND of
435
- # line. Inline code borrows `secondary`, the transcript's quieter
436
- # slot, so an identifier reads as set apart from the prose without
437
- # competing with the accent a tool call uses.
438
- "md_heading": f"bold {palette['foreground']}",
439
- "md_strong": "bold",
440
- "md_code": palette["secondary"],
441
- # Batch 58's three additions, and the shape of the first two is
442
- # `md_strong`'s: an inline mark says something about the WORDS it
443
- # covers, so it takes the attribute and no hue -- a colour would
444
- # make it a different kind of line rather than a stressed one.
445
- "md_em": "italic",
446
- "md_strike": "strike",
447
- # A link takes UNDERLINE and no hue either, and here the reason is
448
- # the palette rather than the principle: `accent` is already the
449
- # assistant's own label and every tool call, and `secondary` is
450
- # reasoning and inline code. Underline is the one link convention
451
- # every terminal shares, and it costs no slot to say it.
452
- "md_link": "underline",
453
- # A list marker recedes for `diff_context`'s reason -- it is there
454
- # to place the text, not to be read -- so the eye lands on the
455
- # first word rather than on the hyphen the model happened to type.
456
- "md_bullet": palette["secondary"],
457
- # The table's own furniture. The border recedes for
458
- # `diff_context`'s reason -- it is there to place the cells, not to
459
- # be read -- and the header row is the heading rule applied inside
460
- # the grid, so a table and a `##` above it agree about what a title
461
- # looks like.
462
- "table_border": palette["secondary"],
463
- "table_header": f"bold {palette['foreground']}",
464
- }
465
-
466
-
467
- #: Theme names already complained about, so the warning below is said
468
- #: once each rather than once per line drawn.
469
- _UNSTYLABLE: set[str] = set()
470
-
471
-
472
- def styles_for(app) -> dict[str, str]:
473
- """The active theme's role styles, or unstyled when there is no app.
474
-
475
- A widget is constructed before it is mounted and tests build them bare
476
- (`ResearchProgress()` in test_pipeline_events.py), where `self.app`
477
- RAISES rather than returning None. Falling back to empty strings keeps
478
- a widget renderable in both cases -- Rich treats "" as no style -- so
479
- presentation degrades instead of a NoActiveAppError reaching a test
480
- that is not about theming at all.
481
-
482
- The SECOND guard is batch 64's, and it is the one that had to be
483
- learned. role_styles used to be able to RAISE -- a theme with a
484
- slot at None reached Color.parse(None) -- and this function is on
485
- the path of every transcript line, the session banner in on_mount
486
- included. So a theme the command palette offered took the app down
487
- at startup and kept taking it down, because watch_theme had
488
- already written the name to a preference store that lives at the
489
- USER tier, outside the install tree, where reinstalling cannot
490
- reach it. _palette makes that particular fault impossible; this
491
- makes the CLASS of it non-fatal, which is Section 27's rule that a
492
- display failure is contained rather than fatal. An uncoloured
493
- transcript is unhelpful; a harness that will not start is not a
494
- harness.
495
-
496
- It warns, ONCE per theme. That is the opposite of
497
- preferences._remember's deliberate non-latching, and for the
498
- reason that module states: a warning fires there on a human's own
499
- action, and fires here on every line drawn. Silence is precisely
500
- what let textual-light and textual-ansi render unstyled for as
501
- long as they did -- Rich resolves an unparseable style with
502
- `default=Style.null()` and says nothing -- so a contained failure
503
- that reported nothing would be the same defect wearing a better
504
- exception story.
505
- """
506
- try:
507
- theme = app.get_theme(app.theme)
508
- except Exception: # noqa: BLE001 -- no app, or a theme name we lost
509
- theme = None
510
- if theme is None:
511
- return {}
512
- try:
513
- return role_styles(theme)
514
- except Exception: # noqa: BLE001 -- a theme this build cannot resolve
515
- name = getattr(theme, "name", "?")
516
- if name not in _UNSTYLABLE:
517
- _UNSTYLABLE.add(name)
518
- logger.warning(
519
- "Theme %r could not be resolved into transcript "
520
- "colours, so the transcript will render unstyled. Pick "
521
- "another with /theme or ctrl+p.", name)
522
- return {}
523
-
524
-
525
- def syntax_theme_for(app) -> str:
526
- """Which Rich token theme code blocks highlight against (#116).
527
-
528
- Rich ships exactly two: ansi_dark for dark backgrounds, ansi_light for
529
- light ones. Half the shipped themes are light, and every one of them
530
- was rendering every code block in a palette designed against the
531
- opposite background -- on the one transcript element a reader is most
532
- likely to read character by character.
533
-
534
- Resolved here, against the Theme object's own `dark` flag, for the same
535
- reason role_styles is: a RichLog cannot reach app.tcss variables, so
536
- the lookup happens where the Theme object already is. No running app
537
- (bare-built test widgets) defaults to dark, which preserves what the
538
- unconditional version did.
539
- """
540
- try:
541
- theme = app.get_theme(app.theme)
542
- except Exception: # noqa: BLE001 -- no app, or a theme name we lost
543
- theme = None
544
- if theme is not None and not theme.dark:
545
- return "ansi_light"
546
- return "ansi_dark"
547
-
548
-
549
- def resolve(name: str | None) -> str:
550
- """Theme name to apply, falling back to the default.
551
-
552
- Returns the default rather than raising: config_loader already
553
- type-checks `tui.theme` as a string, but it cannot know the valid
554
- names without importing this module, and a stale name in a settings
555
- file should not stop the app from starting.
556
- """
557
- if name in THEME_NAMES:
558
- return name
559
- return DEFAULT_THEME
1
+ """
2
+ tui/themes.py
3
+
4
+ Fourteen themes: the eight-theme neutral grid (dark/light x
5
+ plain/red/green/blue) plus six standalone tinted themes (matrix,
6
+ nightmare, ember, midnight, glassy-lapis, paper) whose PANELS carry the
7
+ identity -- background/surface/panel are theirs, not the grid's shared
8
+ neutrals.
9
+
10
+ Pure presentation -- no import of core/, no harness state, with one
11
+ narrowing batch 64 wrote down rather than hid: `styles_for` keeps the
12
+ set of theme names it has already complained about, because it runs
13
+ once per rendered line and the complaint must not. Two things
14
+ outside this module carry a theme name: the persisted `tui.theme` setting,
15
+ validated by core/config_loader.py's _KNOWN_TUI, and tui/preferences.py's
16
+ remembered choice. The second deliberately does NOT validate against
17
+ THEME_NAMES -- it stores an opaque string and lets the App decide whether
18
+ it still resolves, because ctrl+p's command palette can select one of
19
+ Textual's own built-in themes and a whitelist here would silently forget
20
+ it.
21
+
22
+ Built on textual.theme.Theme (verified against the installed textual,
23
+ per D22's rule about not assuming a dependency's API shape). Textual
24
+ derives the full variable set from these anchors, so each theme only
25
+ declares the colours that actually differ.
26
+
27
+ `Theme` gained an `ansi: bool` when the pin moved to 8.2.8, and nothing
28
+ here sets it: these fourteen are RGB palettes, which is the whole
29
+ premise of the contrast floors they are held to.
30
+ """
31
+
32
+ import logging
33
+
34
+ from textual.color import Color
35
+ from textual.theme import Theme
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+ # Shared neutrals. The accent variants below change only the three hue
40
+ # slots (primary/secondary/accent), so a colour tweak to the base surfaces
41
+ # lands in all eight grid themes at once rather than eight near-copies
42
+ # drifting.
43
+ _DARK_BASE = {
44
+ "background": "#0f1115",
45
+ "surface": "#171a21",
46
+ "panel": "#1e222b",
47
+ "foreground": "#e4e6eb",
48
+ "warning": "#d9a441",
49
+ "error": "#cf5c4a",
50
+ "success": "#5aa86f",
51
+ "dark": True,
52
+ }
53
+
54
+ _LIGHT_BASE = {
55
+ "background": "#f7f7f5",
56
+ "surface": "#ffffff",
57
+ "panel": "#eceae6",
58
+ "foreground": "#1b1c1e",
59
+ "warning": "#9a6d10",
60
+ "error": "#a63a2a",
61
+ "success": "#2f7343",
62
+ "dark": False,
63
+ }
64
+
65
+ # (primary, secondary, accent) per variant. Dark and light get separate
66
+ # values because a hue readable on #0f1115 is usually too pale on #f7f7f5.
67
+ #
68
+ # The four DARK secondaries were lifted in batch 29 (#14): the pass role
69
+ # renders in `secondary`, and every original value sat below 3.5:1 against
70
+ # the shared dark background -- plain at 3.37 was the filed defect, red
71
+ # ~2.7 and blue ~3.0 were the same defect nobody had measured. The floor
72
+ # is pinned in tests/test_themes.py; these are the minimal luminance moves
73
+ # that clear it.
74
+ _ACCENTS_DARK = {
75
+ # dark-plain's ACCENT was lifted in batch 41 (X1), for batch 29's
76
+ # reason applied to a different axis. #14 measured contrast against
77
+ # the BACKGROUND; this is separation between two roles that sit on
78
+ # adjacent lines. `tool` renders in accent and `thinking` in
79
+ # secondary, and on a deliberately monochrome theme hue cannot
80
+ # separate them -- only lightness can. #a9b2c3 was 98.5 redmean
81
+ # units from #8792a2, the tightest secondary/accent pair of all
82
+ # fourteen themes (the next is paper at 143.8). #b8c1d1 is 142.7,
83
+ # which clears that floor while staying 111 units off the
84
+ # foreground -- go lighter and the assistant label melts into the
85
+ # body text it introduces, which is the same defect facing the
86
+ # other way.
87
+ "plain": ("#8a93a3", "#8792a2", "#b8c1d1"),
88
+ "red": ("#d4674f", "#b0513c", "#e8917b"),
89
+ "green": ("#5fa876", "#4d8f63", "#8ecba1"),
90
+ "blue": ("#5b90cc", "#4a76b3", "#8bb6e6"),
91
+ }
92
+
93
+ _ACCENTS_LIGHT = {
94
+ "plain": ("#5a6273", "#3c4252", "#7d8595"),
95
+ "red": ("#b04a33", "#7d3423", "#c9705a"),
96
+ "green": ("#3f7f57", "#2b5a3c", "#5d9c74"),
97
+ "blue": ("#3f6fa8", "#2b4d76", "#6091c7"),
98
+ }
99
+
100
+ # Standalone tinted themes (batch 29). Each OVERRIDES the shared base
101
+ # outright -- that is their identity: the panels themselves carry the
102
+ # palette, not just borders and text. Severity slots default to the grid
103
+ # trio and are overridden ONLY where contrast against the theme's own
104
+ # tint demands it, keeping the semantic hue family (danger stays
105
+ # red-ish); every override carries its reason, and the floors live in
106
+ # tests/test_themes.py (foreground >= 7:1, severity >= 4:1, identity
107
+ # >= 3.5:1, all against the theme's own background).
108
+ _STANDALONE = [
109
+ dict(
110
+ name="matrix", dark=True,
111
+ background="#0a120c", surface="#0f1a12", panel="#14231a",
112
+ foreground="#c8e6d0",
113
+ primary="#3dd968", secondary="#2f9e52", accent="#7dffb0",
114
+ # success overridden: the shared #5aa86f dissolves into matrix's
115
+ # own green-dark background.
116
+ success="#4ee08a",
117
+ ),
118
+ dict(
119
+ name="nightmare", dark=True,
120
+ background="#140b0e", surface="#1c0f14", panel="#251318",
121
+ foreground="#e8d5d8",
122
+ primary="#c94f5f", secondary="#a8556a", accent="#e88a96",
123
+ # error overridden: red-on-red -- the shared #cf5c4a loses the
124
+ # alarm against nightmare's blood background.
125
+ error="#ff7b6b",
126
+ ),
127
+ dict(
128
+ name="ember", dark=True,
129
+ background="#16100a", surface="#1f1610", panel="#291d13",
130
+ foreground="#ecdfd0",
131
+ primary="#e08a3c", secondary="#a86228", accent="#f2b06a",
132
+ # warning overridden yellower: the shared amber sat on top of
133
+ # ember's primary orange and read as emphasis, not as caution.
134
+ warning="#d9b83f",
135
+ ),
136
+ dict(
137
+ name="midnight", dark=True,
138
+ background="#0a0f1e", surface="#101830", panel="#16203c",
139
+ foreground="#d5dcea",
140
+ primary="#6f9fe8", secondary="#4a6fb0", accent="#9dbdf2",
141
+ ),
142
+ dict(
143
+ name="glassy-lapis", dark=True,
144
+ background="#14243f", surface="#1c2f52", panel="#243a63",
145
+ foreground="#e2ecf8",
146
+ primary="#7fb4ff", secondary="#5a8ac9", accent="#a8ccff",
147
+ # error overridden: lapis is the lightest dark background, and
148
+ # the shared #cf5c4a fell just under the severity floor on it.
149
+ error="#e06a58",
150
+ ),
151
+ dict(
152
+ name="paper", dark=False,
153
+ background="#f4efe6", surface="#fbf8f2", panel="#eae3d5",
154
+ foreground="#2b2620",
155
+ primary="#7a5c2e", secondary="#5c4a32", accent="#9c7b45",
156
+ ),
157
+ ]
158
+
159
+
160
+ def _build(variant: str, dark: bool) -> Theme:
161
+ base = _DARK_BASE if dark else _LIGHT_BASE
162
+ primary, secondary, accent = (
163
+ _ACCENTS_DARK if dark else _ACCENTS_LIGHT
164
+ )[variant]
165
+ return Theme(
166
+ name=f"{'dark' if dark else 'light'}-{variant}",
167
+ primary=primary,
168
+ secondary=secondary,
169
+ accent=accent,
170
+ **base,
171
+ )
172
+
173
+
174
+ def _build_standalone(spec: dict) -> Theme:
175
+ base = _DARK_BASE if spec["dark"] else _LIGHT_BASE
176
+ merged = {**base, **{k: v for k, v in spec.items() if k != "name"}}
177
+ return Theme(name=spec["name"], **merged)
178
+
179
+
180
+ ALL_THEMES = (
181
+ [
182
+ _build(variant, dark)
183
+ for dark in (True, False)
184
+ for variant in ("plain", "red", "green", "blue")
185
+ ]
186
+ + [_build_standalone(spec) for spec in _STANDALONE]
187
+ )
188
+
189
+ THEME_NAMES = [t.name for t in ALL_THEMES]
190
+ DEFAULT_THEME = "dark-plain"
191
+
192
+
193
+ def register_all(app) -> None:
194
+ """Register every theme on the app. Call before setting app.theme."""
195
+ for theme in ALL_THEMES:
196
+ app.register_theme(theme)
197
+
198
+
199
+ # ---------------------------------------------------------------------------
200
+ # ---- Role palette (ROADMAP_v2 §26) ----------------------------------------
201
+ # ---------------------------------------------------------------------------
202
+ #
203
+ # The transcript was uniformly white: a user message, the model's answer, a
204
+ # pipeline trace line and a tool call were the same colour, and the "you"
205
+ # label read as the first word of the message it introduced.
206
+ #
207
+ # WHY THIS IS A FUNCTION OF A THEME rather than a table of colour names.
208
+ # Everything else in the TUI styles itself through app.tcss, which uses
209
+ # theme variables ($panel, $primary) and so restyles across all fourteen
210
+ # themes without edits. A RichLog cannot do that -- it renders Rich Text
211
+ # objects, and a Rich style needs a concrete colour, not a variable to
212
+ # resolve later. So the resolution happens here, against the Theme
213
+ # object, and the same property holds: no literal appears below, and a
214
+ # new theme needs no change in this section.
215
+ #
216
+ # Severity colours. Across the eight GRID themes, warning/error/success
217
+ # are shared by _DARK_BASE and _LIGHT_BASE and mean the same thing
218
+ # everywhere; primary/secondary/accent are the per-variant hues. A
219
+ # STANDALONE theme may override a severity slot when its own panel tint
220
+ # would swallow the shared value (matrix's success, nightmare's error,
221
+ # ember's warning, glassy-lapis's error -- each with its reason above),
222
+ # keeping the semantic hue family. Either way severity uses the
223
+ # theme-resolved trio and identity uses the hues, rather than the
224
+ # reverse. Floors are pinned in tests/test_themes.py.
225
+
226
+ #: How far a diff row's background is blended TOWARD the theme's own
227
+ #: background (batch 41, X7). 0.8 leaves a band that stands off the
228
+ #: page by 1.22-1.53 across the fourteen themes while the foreground
229
+ #: still reads on it at 9.3:1 or better -- a highlight rather than a
230
+ #: slab. Both floors are pinned in tests/test_themes.py.
231
+ DIFF_TINT = 0.8
232
+
233
+
234
+ #: The eight Theme slots `role_styles` reads. Every one of them but
235
+ #: `primary` is Optional[str] on textual's own Theme, and four of the
236
+ #: twenty-one built-ins the command palette offers do leave one blank
237
+ #: or fill it with a vocabulary Rich cannot read: textual-dark has no
238
+ #: `background`, textual-light no `foreground`, and ansi-dark and
239
+ #: ansi-light nothing but `ansi_*` names. Reading them raw is what made
240
+ #: selecting textual-dark kill the harness AT MOUNT -- and keep killing
241
+ #: it, since watch_theme had already remembered the name (batch 64).
242
+ _SLOTS = ("primary", "secondary", "accent", "warning", "error",
243
+ "success", "foreground", "background")
244
+
245
+ #: Filled palettes, keyed on the RAW SLOT VALUES rather than on
246
+ #: theme.name. Theme is a plain mutable dataclass and
247
+ #: App.register_theme overwrites by name, so a name key would hand a
248
+ #: re-registered theme the colours of the one it replaced; a value key
249
+ #: cannot. Memoisation of a pure function of its input, which is why
250
+ #: it costs this module nothing the docstring claims -- and it earns
251
+ #: its place because the fallback below is 0.194ms against
252
+ #: role_styles' own 0.004ms, on a function called once per drawn line.
253
+ _RESOLVED: dict[tuple, dict[str, str]] = {}
254
+
255
+
256
+ def _rich(colour: str) -> str:
257
+ """Textual's `ansi_*` colour names in Rich's vocabulary.
258
+
259
+ An ANSI theme fills every slot with `ansi_blue`/`ansi_default` --
260
+ the terminal's own sixteen, which is the entire point of those
261
+ themes -- and Rich's Style.parse does not know the prefix. It knows
262
+ the names underneath it: textual.color.ANSI_COLORS is exactly the
263
+ ANSI subset of rich.color.ANSI_COLOR_NAMES (verified by set
264
+ difference against the installed package -- 16 of 235, re-checked
265
+ when the pin moved to 8.2.8), and `ansi_default` is Rich's
266
+ `default`. A translation, then, rather than a guess.
267
+
268
+ There was ONE such theme (`textual-ansi`) until 8.2.5 replaced it
269
+ with `ansi-dark` and `ansi-light`, and `Theme` grew an `ansi` flag
270
+ in the same release. Nothing here reads the flag: a name can be
271
+ renamed again and the `ansi_` prefix is the thing this function is
272
+ actually about.
273
+
274
+ Not doing it was never a crash, which is why it lasted: Rich's
275
+ Text.render resolves a style string with `default=Style.null()`,
276
+ so an unparseable one renders PLAIN and says nothing. Twenty-five
277
+ of the thirty-four roles were silently unstyled on the ANSI theme --
278
+ the uniformly white transcript this section exists to fix, reached
279
+ by a different road.
280
+ """
281
+ return colour[5:] if colour.startswith("ansi_") else colour
282
+
283
+
284
+ def _palette(theme: Theme) -> dict[str, str]:
285
+ """`_SLOTS`, every one of them filled, in Rich's vocabulary.
286
+
287
+ A blank slot is filled from textual's OWN derivation --
288
+ to_color_system().generate() is what it builds app.tcss's
289
+ $background and $foreground out of -- rather than from a constant
290
+ invented here, which would be a second opinion about a colour the
291
+ rest of the screen already has.
292
+
293
+ A FALLBACK and never a replacement, for two measured reasons.
294
+ generate() is lossy: the base shade comes back as
295
+ `color.lighten(0).hex`, an HSL round trip, which moves #d9a441 to
296
+ #D8A441 and differs from the raw slot on 41 values across the
297
+ fourteen shipped themes. And it is 48x slower than role_styles
298
+ itself. Reaching for it only where a slot is actually None leaves
299
+ all fourteen byte-identical and costs the other twenty-one built-ins
300
+ eight getattrs.
301
+ """
302
+ raw = tuple(getattr(theme, slot) for slot in _SLOTS)
303
+ if all(raw):
304
+ return {slot: _rich(value) for slot, value in zip(_SLOTS, raw)}
305
+ key = raw + (theme.dark,)
306
+ if key not in _RESOLVED:
307
+ generated = theme.to_color_system().generate()
308
+ _RESOLVED[key] = {slot: _rich(value or generated[slot])
309
+ for slot, value in zip(_SLOTS, raw)}
310
+ return _RESOLVED[key]
311
+
312
+
313
+ def _tint(colour: str, background: str,
314
+ factor: float = DIFF_TINT) -> str | None:
315
+ """`colour` faded toward `background`, as a hex string -- or None.
316
+
317
+ Derived from the theme's own slots rather than written down, for
318
+ the reason the whole of this section exists (#116): a literal pair
319
+ of green and red backgrounds would be designed against one of the
320
+ fourteen palettes and wrong on the other thirteen -- and on the six
321
+ standalone themes, whose panels carry the identity, visibly so.
322
+
323
+ None when either end is one of the terminal's own sixteen, which
324
+ is the ANSI themes and nothing else: there is no RGB there to blend,
325
+ so there is no band to draw. Not a hypothetical guard -- textual's
326
+ Color.parse raises on Rich's `default`, and blending two ANSI
327
+ colours in textual hands back one of them unchanged, so both
328
+ answers were wrong before this said so.
329
+ """
330
+ if not (colour.startswith("#") and background.startswith("#")):
331
+ return None
332
+ return Color.parse(colour).blend(Color.parse(background), factor).hex
333
+
334
+
335
+ def role_styles(theme: Theme) -> dict[str, str]:
336
+ """Rich style strings keyed by transcript role, for one theme.
337
+
338
+ Roles are what a line MEANS, not where it came from: `pass` covers a
339
+ research pass boundary whether the CLI or the TUI produced it, and
340
+ `tool_error` is a failed tool call rather than "amber".
341
+
342
+ Reads the RESOLVED palette rather than the Theme's own slots,
343
+ which is batch 64: four of the thirty-five themes ctrl+p offers
344
+ leave a slot at None or fill it with textual's `ansi_*` names,
345
+ and one of them took the whole app down at mount. `_palette`
346
+ fills and translates; nothing below can see the difference.
347
+ """
348
+ palette = _palette(theme)
349
+ add = _tint(palette["success"], palette["background"])
350
+ delete = _tint(palette["error"], palette["background"])
351
+ return {
352
+ # Who is speaking. The hues, because these distinguish identity.
353
+ "user": f"bold {palette['primary']}",
354
+ "user_label": f"bold {palette['primary']}",
355
+ "assistant_label": f"bold {palette['accent']}",
356
+ # The answer itself stays plain foreground DELIBERATELY. It is the
357
+ # longest text on screen and the thing most often actually read;
358
+ # tinting it costs contrast to say something the label already said.
359
+ "assistant": "",
360
+ # ROADMAP_v3 §49 (SS14): a line of a background session's own
361
+ # output, quoted into a session view. PLAIN, for `assistant`'s
362
+ # reason and one better: it is not the harness's voice and not
363
+ # the model's, it is what a program printed, and a view of a
364
+ # failing test run is read line by line rather than skimmed.
365
+ # `system` was the alternative and is wrong twice -- dimmed and
366
+ # italic is the worst possible treatment for forty lines of
367
+ # output, and it would claim the harness said them.
368
+ #
369
+ # `foreground` EXPLICITLY, not `""` like `assistant`. The empty
370
+ # slot means "inherit", which is right for the body text of a
371
+ # pane that has no other colour in force and wrong for a block
372
+ # quoted inside a frame of `system` lines. It is also the one
373
+ # deliberately unstyled slot, and tests/test_themes.py says so.
374
+ "output": palette["foreground"],
375
+ # The harness talking about itself.
376
+ "system": "dim italic",
377
+ # ROADMAP_v3 §49 (SS5): the harness starting a turn with a
378
+ # background session's result. In the tool call's hue, since it is
379
+ # the far end of one, and bold italic so it is neither that call
380
+ # (plain accent) nor the reply's label (bold accent). Not `dim`:
381
+ # this line opens a turn the reader did not ask for, and `system`
382
+ # alone is dimmed (test_dim_is_the_system_role_alone).
383
+ "wake": f"bold italic {palette['accent']}",
384
+ # Batch 199, the owner's request and choice: the hosted banner's
385
+ # star line, the harness asking the reader to do something outside
386
+ # it. The success hue because it is the inviting colour every theme
387
+ # has -- dark-plain, the hosted default, is grey but for its three
388
+ # severities -- and BOLD, where `success` is plain, so it is not a
389
+ # line reporting that something went well.
390
+ "invite": f"bold {palette['success']}",
391
+ # §38: the model's reasoning, when tui.show_thinking renders it
392
+ # inline. `secondary` because thinking is the answer's quieter
393
+ # sibling rather than a severity or an identity -- it already
394
+ # clears the identity floor on every theme, so no theme constant
395
+ # moves for this. Italic separates it from `pass`/`pass_done`,
396
+ # which share the hue in the research view.
397
+ "thinking": f"italic {palette['secondary']}",
398
+ "pass": f"bold {palette['secondary']}",
399
+ "pass_done": palette["secondary"],
400
+ # PLAIN accent, not `dim` (batch 41, X1). Two reasons, and the
401
+ # second is the one that generalises. `dim {accent}` sat a
402
+ # measured 98.5 redmean units from `thinking`'s
403
+ # `italic {secondary}` on dark-plain -- the shipped default,
404
+ # and the tightest pair of any theme (every other theme is
405
+ # >= 143) -- so a tool call and a reasoning line were one
406
+ # colour on the palette most people actually see. And `dim` is
407
+ # a Rich ATTRIBUTE, not a colour: tests/test_themes.py's
408
+ # contrast floors measure the undimmed hue and cannot see what
409
+ # the terminal paints, so the style on EVERY tool call was the
410
+ # one style whose real contrast nothing measured. Plain accent
411
+ # moves it up, away from secondary, into a number the floors
412
+ # can see.
413
+ "tool": palette["accent"],
414
+ # How bad it is. The three shared colours.
415
+ "tool_error": palette["warning"],
416
+ # BOLD, where tool_error is plain (X2). Both are non-fatal and
417
+ # keep the hue family; the weight separates the harness raising
418
+ # its voice from a tool that failed. They were the same string
419
+ # outright until batch 41, which was survivable only because
420
+ # nothing routed a WARNING here at all -- see
421
+ # TranscriptLogHandler, where that was the actual defect.
422
+ "warning": f"bold {palette['warning']}",
423
+ "error": f"bold {palette['error']}",
424
+ "success": palette["success"],
425
+ # Confidence tiers, ordered worst-to-best in meaning rather than in
426
+ # this dict. UNVERIFIED_COVERAGE is a gap in what was asked, not a
427
+ # claim that failed, so it reads as absent rather than as wrong.
428
+ "HIGH": palette["success"],
429
+ "MEDIUM": palette["foreground"],
430
+ "LOW": palette["warning"],
431
+ "UNVERIFIED": palette["error"],
432
+ "UNVERIFIED_COVERAGE": f"dim {palette['error']}",
433
+ # §41's inline diff for `write` and `edit`. The only roles in
434
+ # this table that set a BACKGROUND, because the whole point is
435
+ # that a changed row is marked across its full width rather
436
+ # than at the one character that carries the sign.
437
+ #
438
+ # Unless there is no background to set. `_tint` answers None on
439
+ # a theme whose colours are the terminal's own sixteen --
440
+ # an ANSI theme and nothing else -- and the row then takes the
441
+ # severity colour as its FOREGROUND, which is what git, diff
442
+ # and patch all do in a sixteen-colour terminal. A solid band
443
+ # was the alternative, and DIFF_TINT's comment above turns that
444
+ # down for every theme that CAN be measured; picking it for the
445
+ # one that cannot would be backwards.
446
+ "diff_add": (f"{palette['foreground']} on {add}" if add
447
+ else palette["success"]),
448
+ "diff_del": (f"{palette['foreground']} on {delete}" if delete
449
+ else palette["error"]),
450
+ # Unchanged context recedes: it is there to place the change,
451
+ # not to be read. `secondary` rather than a dimmed foreground
452
+ # for X1's reason -- `dim` is an attribute no floor can
453
+ # measure.
454
+ "diff_context": palette["secondary"],
455
+ # The file being changed. Bold foreground takes no hue at all,
456
+ # which is what keeps it out of the identity roles the same
457
+ # batch just separated -- a path is not a speaker.
458
+ "diff_header": f"bold {palette['foreground']}",
459
+ # Batch 53's markdown marks. These are marks INSIDE an entry rather
460
+ # than kinds of line, which is why they sit outside MESSAGE_ROLES
461
+ # exactly as the diff roles above do: the pairwise-distinctness and
462
+ # separation floors ask whether two LINES can be told apart, and a
463
+ # bold word never sits on the line below a tool call.
464
+ #
465
+ # This does narrow `assistant`'s "stays plain foreground
466
+ # DELIBERATELY" a few lines up, and the narrowing is the decision:
467
+ # that rule is about the BODY, whose length is the reason tinting it
468
+ # costs more contrast than it buys. A heading and a bold run are
469
+ # marks the model asked for, on a few cells at a time.
470
+ #
471
+ # A heading takes weight and no hue, `diff_header`'s reasoning --
472
+ # a section title is not a speaker either. Strong takes the
473
+ # attribute alone, because the one thing `**` means is emphasis
474
+ # within body text and a colour would make it a different KIND of
475
+ # line. Inline code borrows `secondary`, the transcript's quieter
476
+ # slot, so an identifier reads as set apart from the prose without
477
+ # competing with the accent a tool call uses.
478
+ "md_heading": f"bold {palette['foreground']}",
479
+ "md_strong": "bold",
480
+ "md_code": palette["secondary"],
481
+ # Batch 58's three additions, and the shape of the first two is
482
+ # `md_strong`'s: an inline mark says something about the WORDS it
483
+ # covers, so it takes the attribute and no hue -- a colour would
484
+ # make it a different kind of line rather than a stressed one.
485
+ "md_em": "italic",
486
+ "md_strike": "strike",
487
+ # A link takes UNDERLINE and no hue either, and here the reason is
488
+ # the palette rather than the principle: `accent` is already the
489
+ # assistant's own label and every tool call, and `secondary` is
490
+ # reasoning and inline code. Underline is the one link convention
491
+ # every terminal shares, and it costs no slot to say it.
492
+ "md_link": "underline",
493
+ # A list marker recedes for `diff_context`'s reason -- it is there
494
+ # to place the text, not to be read -- so the eye lands on the
495
+ # first word rather than on the hyphen the model happened to type.
496
+ "md_bullet": palette["secondary"],
497
+ # The table's own furniture. The border recedes for
498
+ # `diff_context`'s reason -- it is there to place the cells, not to
499
+ # be read -- and the header row is the heading rule applied inside
500
+ # the grid, so a table and a `##` above it agree about what a title
501
+ # looks like.
502
+ "table_border": palette["secondary"],
503
+ "table_header": f"bold {palette['foreground']}",
504
+ }
505
+
506
+
507
+ #: Theme names already complained about, so the warning below is said
508
+ #: once each rather than once per line drawn.
509
+ _UNSTYLABLE: set[str] = set()
510
+
511
+
512
+ def styles_for(app) -> dict[str, str]:
513
+ """The active theme's role styles, or unstyled when there is no app.
514
+
515
+ A widget is constructed before it is mounted and tests build them bare
516
+ (`ResearchProgress()` in test_pipeline_events.py), where `self.app`
517
+ RAISES rather than returning None. Falling back to empty strings keeps
518
+ a widget renderable in both cases -- Rich treats "" as no style -- so
519
+ presentation degrades instead of a NoActiveAppError reaching a test
520
+ that is not about theming at all.
521
+
522
+ The SECOND guard is batch 64's, and it is the one that had to be
523
+ learned. role_styles used to be able to RAISE -- a theme with a
524
+ slot at None reached Color.parse(None) -- and this function is on
525
+ the path of every transcript line, the session banner in on_mount
526
+ included. So a theme the command palette offered took the app down
527
+ at startup and kept taking it down, because watch_theme had
528
+ already written the name to a preference store that lives at the
529
+ USER tier, outside the install tree, where reinstalling cannot
530
+ reach it. _palette makes that particular fault impossible; this
531
+ makes the CLASS of it non-fatal, which is Section 27's rule that a
532
+ display failure is contained rather than fatal. An uncoloured
533
+ transcript is unhelpful; a harness that will not start is not a
534
+ harness.
535
+
536
+ It warns, ONCE per theme. That is the opposite of
537
+ preferences._remember's deliberate non-latching, and for the
538
+ reason that module states: a warning fires there on a human's own
539
+ action, and fires here on every line drawn. Silence is precisely
540
+ what let textual-light and the ANSI themes render unstyled for as
541
+ long as they did -- Rich resolves an unparseable style with
542
+ `default=Style.null()` and says nothing -- so a contained failure
543
+ that reported nothing would be the same defect wearing a better
544
+ exception story.
545
+ """
546
+ try:
547
+ theme = app.get_theme(app.theme)
548
+ except Exception: # noqa: BLE001 -- no app, or a theme name we lost
549
+ theme = None
550
+ if theme is None:
551
+ return {}
552
+ try:
553
+ return role_styles(theme)
554
+ except Exception: # noqa: BLE001 -- a theme this build cannot resolve
555
+ name = getattr(theme, "name", "?")
556
+ if name not in _UNSTYLABLE:
557
+ _UNSTYLABLE.add(name)
558
+ logger.warning(
559
+ "Theme %r could not be resolved into transcript "
560
+ "colours, so the transcript will render unstyled. Pick "
561
+ "another with /theme or ctrl+p.", name)
562
+ return {}
563
+
564
+
565
+ def syntax_theme_for(app) -> str:
566
+ """Which Rich token theme code blocks highlight against (#116).
567
+
568
+ Rich ships exactly two: ansi_dark for dark backgrounds, ansi_light for
569
+ light ones. Half the shipped themes are light, and every one of them
570
+ was rendering every code block in a palette designed against the
571
+ opposite background -- on the one transcript element a reader is most
572
+ likely to read character by character.
573
+
574
+ Resolved here, against the Theme object's own `dark` flag, for the same
575
+ reason role_styles is: a RichLog cannot reach app.tcss variables, so
576
+ the lookup happens where the Theme object already is. No running app
577
+ (bare-built test widgets) defaults to dark, which preserves what the
578
+ unconditional version did.
579
+ """
580
+ try:
581
+ theme = app.get_theme(app.theme)
582
+ except Exception: # noqa: BLE001 -- no app, or a theme name we lost
583
+ theme = None
584
+ if theme is not None and not theme.dark:
585
+ return "ansi_light"
586
+ return "ansi_dark"
587
+
588
+
589
+ def resolve(name: str | None) -> str:
590
+ """Theme name to apply, falling back to the default.
591
+
592
+ Returns the default rather than raising: config_loader already
593
+ type-checks `tui.theme` as a string, but it cannot know the valid
594
+ names without importing this module, and a stale name in a settings
595
+ file should not stop the app from starting.
596
+ """
597
+ if name in THEME_NAMES:
598
+ return name
599
+ return DEFAULT_THEME