@yahyahammad/venastine 0.3.8 → 0.3.10

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 (130) hide show
  1. package/.env.example +19 -19
  2. package/CONFIG_ARCHITECTURE.md +2139 -2002
  3. package/LICENSE +201 -201
  4. package/README.md +1043 -1034
  5. package/agents/builtin/compactor.md +75 -75
  6. package/agents/builtin/explore.md +77 -77
  7. package/agents/builtin/pipeline-reviewer.md +100 -100
  8. package/agents/builtin/plan.md +106 -106
  9. package/agents/builtin/review.md +74 -74
  10. package/agents/manager.py +261 -261
  11. package/agents/subagent_tool.py +472 -472
  12. package/agents/tui_commands.py +238 -146
  13. package/bin/venastine.mjs +584 -528
  14. package/bin/venastine.py +73 -71
  15. package/cli_commands.py +848 -835
  16. package/config.yaml +64 -0
  17. package/config_edit.py +1301 -1301
  18. package/config_schema.py +987 -966
  19. package/config_update.py +749 -749
  20. package/core/agent_activity.py +256 -256
  21. package/core/ansi.py +452 -452
  22. package/core/approval.py +137 -137
  23. package/core/call_view.py +364 -364
  24. package/core/cancel.py +121 -121
  25. package/core/chatgpt_auth.py +747 -747
  26. package/core/claims_view.py +107 -107
  27. package/core/client.py +2756 -2715
  28. package/core/commands.py +464 -454
  29. package/core/compaction.py +1735 -1735
  30. package/core/config_loader.py +1982 -1982
  31. package/core/connect.py +686 -686
  32. package/core/events.py +123 -123
  33. package/core/file_mentions.py +280 -280
  34. package/core/interaction.py +411 -411
  35. package/core/loop.py +2566 -2566
  36. package/core/memory.py +482 -482
  37. package/core/pipeline_models.py +190 -190
  38. package/core/provider_errors.py +274 -234
  39. package/core/reasoning/authorization.py +130 -130
  40. package/core/reasoning/base.py +219 -219
  41. package/core/reasoning/confidence_scoring.py +484 -484
  42. package/core/reasoning/events.py +149 -149
  43. package/core/reasoning/orchestrator.py +1561 -1561
  44. package/core/reasoning/output_writer.py +345 -345
  45. package/core/reasoning/payload_validation.py +524 -524
  46. package/core/reasoning/pipeline_storage.py +427 -427
  47. package/core/reasoning/scholar.py +467 -458
  48. package/core/reasoning/source_corpus.py +433 -433
  49. package/core/reasoning/source_scoring.py +855 -855
  50. package/core/replay.py +315 -315
  51. package/core/shell_sessions.py +1553 -1553
  52. package/credentials.py +307 -307
  53. package/database.py +333 -333
  54. package/docs/PRIVACY.md +78 -78
  55. package/docs/SECURITY.md +114 -108
  56. package/docs/THIRD_PARTY_NOTICES.md +148 -148
  57. package/env_secrets.py +118 -118
  58. package/json_store.py +343 -343
  59. package/logging_setup.py +295 -295
  60. package/main.py +3433 -3433
  61. package/mcp_client/client.py +780 -733
  62. package/mcp_client/config.py +484 -484
  63. package/mcp_client/registration.py +343 -343
  64. package/memories/manager.py +147 -147
  65. package/memories/tui_commands.py +319 -239
  66. package/package.json +303 -303
  67. package/project_init/config_files.py +282 -282
  68. package/project_init/generator.py +728 -728
  69. package/project_init/manifest.py +418 -418
  70. package/project_init/tui_commands.py +147 -147
  71. package/prompts/critic_pass.md +24 -24
  72. package/prompts/revalidate.md +25 -25
  73. package/prompts/revise.md +17 -17
  74. package/prompts/source_grounding.md +66 -66
  75. package/prompts/system_prompts.py +316 -316
  76. package/providers.json.example +94 -94
  77. package/pyproject.toml +149 -149
  78. package/requirements.txt +314 -295
  79. package/safety/policy_enforcement.py +1082 -1082
  80. package/security/askpass.py +419 -419
  81. package/security/capability.py +207 -207
  82. package/security/confine.py +484 -484
  83. package/security/hosted.py +182 -182
  84. package/security/permissions.py +237 -237
  85. package/security/protected_paths.py +501 -501
  86. package/security/sandbox.py +4108 -4108
  87. package/skills/builtin/math/formal-specification.md +67 -67
  88. package/skills/builtin/math/numerical-methods.md +66 -66
  89. package/skills/builtin/research/experiment-design.md +62 -62
  90. package/skills/builtin/research/reproducibility.md +55 -55
  91. package/skills/builtin/research/source-evaluation.md +70 -70
  92. package/skills/builtin/research/statistical-inference.md +63 -63
  93. package/skills/builtin/research/technical-writing.md +59 -59
  94. package/skills/builtin/software/code-review.md +61 -61
  95. package/skills/builtin/software/debugging.md +61 -61
  96. package/skills/builtin/software/test-design.md +67 -67
  97. package/skills/tui_commands.py +110 -110
  98. package/storage.py +1338 -1338
  99. package/tools/base.py +465 -465
  100. package/tools/builtin/_math_common.py +667 -667
  101. package/tools/builtin/_net_common.py +1145 -267
  102. package/tools/builtin/_page_text.py +490 -0
  103. package/tools/builtin/_pdf_text.py +113 -0
  104. package/tools/builtin/arxiv.py +685 -681
  105. package/tools/builtin/fetch_url.py +639 -371
  106. package/tools/builtin/file_ops.py +720 -720
  107. package/tools/builtin/geometry.py +184 -184
  108. package/tools/builtin/load_skill.py +76 -76
  109. package/tools/builtin/pin.py +227 -227
  110. package/tools/builtin/probability_stats.py +224 -224
  111. package/tools/builtin/project_docs.py +464 -464
  112. package/tools/builtin/remember.py +175 -175
  113. package/tools/builtin/shell.py +980 -980
  114. package/tools/builtin/todo.py +149 -149
  115. package/tools/builtin/web_search.py +402 -328
  116. package/tools/context.py +159 -159
  117. package/tools/isolation.py +387 -387
  118. package/tools/registry.py +1252 -1242
  119. package/tui/app.py +8372 -8307
  120. package/tui/app.tcss +754 -739
  121. package/tui/commands.py +26 -26
  122. package/tui/diffs.py +286 -286
  123. package/tui/history.py +128 -128
  124. package/tui/hosted_driver.py +102 -102
  125. package/tui/markdown.py +1329 -1329
  126. package/tui/meters.py +364 -364
  127. package/tui/ravens.py +146 -146
  128. package/tui/screens.py +1255 -1197
  129. package/tui/themes.py +599 -599
  130. package/tui/widgets.py +3861 -3796
package/tui/themes.py CHANGED
@@ -1,599 +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 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
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