@yahyahammad/venastine 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +14 -0
- package/LICENSE +201 -0
- package/NOTICE +14 -0
- package/PRIVACY.md +66 -0
- package/README.md +878 -0
- package/SECURITY.md +88 -0
- package/THIRD_PARTY_NOTICES.md +100 -0
- package/agents/builtin/compactor.md +75 -0
- package/agents/builtin/explore.md +77 -0
- package/agents/builtin/grill-me.md +27 -0
- package/agents/builtin/initializer.md +94 -0
- package/agents/builtin/pipeline-reviewer.md +100 -0
- package/agents/builtin/plan.md +88 -0
- package/agents/builtin/review.md +74 -0
- package/agents/manager.py +195 -0
- package/agents/subagent_tool.py +215 -0
- package/agents/tui_commands.py +136 -0
- package/bin/venastine.mjs +382 -0
- package/config.py +1198 -0
- package/core/__init__.py +0 -0
- package/core/approval.py +115 -0
- package/core/client.py +1548 -0
- package/core/compaction.py +959 -0
- package/core/config_loader.py +1563 -0
- package/core/events.py +61 -0
- package/core/interaction.py +328 -0
- package/core/loop.py +1353 -0
- package/core/memory.py +370 -0
- package/core/model_windows.py +175 -0
- package/core/pipeline_models.py +176 -0
- package/core/reasoning/__init__.py +0 -0
- package/core/reasoning/authorization.py +130 -0
- package/core/reasoning/base.py +219 -0
- package/core/reasoning/confidence_scoring.py +468 -0
- package/core/reasoning/events.py +149 -0
- package/core/reasoning/json_retry.py +219 -0
- package/core/reasoning/orchestrator.py +1382 -0
- package/core/reasoning/output_writer.py +286 -0
- package/core/reasoning/payload_validation.py +398 -0
- package/core/reasoning/pipeline_storage.py +361 -0
- package/core/reasoning/review.py +615 -0
- package/core/reasoning/scholar.py +434 -0
- package/core/reasoning/source_corpus.py +327 -0
- package/core/reasoning/source_scoring.py +855 -0
- package/core/replay.py +167 -0
- package/core/session.py +153 -0
- package/core/workspace_trust.py +207 -0
- package/credentials.py +180 -0
- package/database.py +252 -0
- package/env_secrets.py +77 -0
- package/json_store.py +123 -0
- package/logging_setup.py +185 -0
- package/main.py +1959 -0
- package/mcp_client/__init__.py +15 -0
- package/mcp_client/client.py +499 -0
- package/mcp_client/config.py +379 -0
- package/mcp_client/registration.py +182 -0
- package/memories/manager.py +132 -0
- package/memories/tui_commands.py +232 -0
- package/package.json +73 -0
- package/project_init/config_files.py +278 -0
- package/project_init/doc_sets.py +330 -0
- package/project_init/generator.py +564 -0
- package/project_init/manifest.py +406 -0
- package/project_init/tui_commands.py +144 -0
- package/prompts/__init__.py +0 -0
- package/prompts/annotate.md +14 -0
- package/prompts/assumption_audit.md +27 -0
- package/prompts/claim_extraction.md +34 -0
- package/prompts/completeness.md +18 -0
- package/prompts/confidence_tiers.md +23 -0
- package/prompts/critic_pass.md +24 -0
- package/prompts/final_synthesis.md +13 -0
- package/prompts/initial_generation.md +14 -0
- package/prompts/preliminary_plan.md +23 -0
- package/prompts/revalidate.md +25 -0
- package/prompts/revise.md +15 -0
- package/prompts/source_grounding.md +66 -0
- package/prompts/system_prompts.py +262 -0
- package/prompts/universal_system_prompt +7 -0
- package/prompts/untrusted_content +1 -0
- package/providers.json.example +92 -0
- package/pyproject.toml +100 -0
- package/requirements.txt +72 -0
- package/safety/__init__.py +0 -0
- package/safety/policy_enforcement.py +682 -0
- package/security/__init__.py +0 -0
- package/security/capability.py +177 -0
- package/security/permissions.py +190 -0
- package/security/posture.py +302 -0
- package/security/protected_paths.py +309 -0
- package/security/sandbox.py +985 -0
- package/skills/builtin/crypto/cryptography-verification.md +66 -0
- package/skills/builtin/math/formal-specification.md +67 -0
- package/skills/builtin/math/numerical-methods.md +66 -0
- package/skills/builtin/math/proof-writing.md +61 -0
- package/skills/builtin/research/experiment-design.md +62 -0
- package/skills/builtin/research/literature-review.md +65 -0
- package/skills/builtin/research/reproducibility.md +55 -0
- package/skills/builtin/research/source-evaluation.md +70 -0
- package/skills/builtin/research/statistical-inference.md +63 -0
- package/skills/builtin/research/technical-writing.md +59 -0
- package/skills/builtin/security/cybersecurity-research.md +63 -0
- package/skills/builtin/software/code-review.md +61 -0
- package/skills/builtin/software/debugging.md +61 -0
- package/skills/builtin/software/test-design.md +67 -0
- package/skills/manager.py +138 -0
- package/skills/tui_commands.py +111 -0
- package/storage.py +1005 -0
- package/tools/base.py +305 -0
- package/tools/builtin/__init__.py +0 -0
- package/tools/builtin/_math_common.py +377 -0
- package/tools/builtin/_net_common.py +61 -0
- package/tools/builtin/arxiv.py +223 -0
- package/tools/builtin/ask_user.py +213 -0
- package/tools/builtin/discrete_math.py +134 -0
- package/tools/builtin/fetch_url.py +153 -0
- package/tools/builtin/file_ops.py +412 -0
- package/tools/builtin/geometry.py +148 -0
- package/tools/builtin/get_time.py +20 -0
- package/tools/builtin/linear_algebra.py +155 -0
- package/tools/builtin/load_skill.py +66 -0
- package/tools/builtin/logic.py +96 -0
- package/tools/builtin/pin.py +193 -0
- package/tools/builtin/probability_stats.py +228 -0
- package/tools/builtin/project_docs.py +405 -0
- package/tools/builtin/remember.py +158 -0
- package/tools/builtin/shell.py +461 -0
- package/tools/builtin/symbolic_math.py +119 -0
- package/tools/builtin/todo.py +147 -0
- package/tools/builtin/web_search.py +151 -0
- package/tools/context.py +136 -0
- package/tools/isolation.py +314 -0
- package/tools/registry.py +897 -0
- package/tui/app.py +3423 -0
- package/tui/app.tcss +458 -0
- package/tui/commands.py +61 -0
- package/tui/diffs.py +265 -0
- package/tui/preferences.py +182 -0
- package/tui/ravens.py +146 -0
- package/tui/screens.py +943 -0
- package/tui/themes.py +366 -0
- package/tui/widgets.py +1239 -0
package/tui/widgets.py
ADDED
|
@@ -0,0 +1,1239 @@
|
|
|
1
|
+
"""
|
|
2
|
+
tui/widgets.py
|
|
3
|
+
|
|
4
|
+
ROADMAP_v2 §16 widgets. Presentation only -- nothing here imports core/
|
|
5
|
+
or reaches into harness state; tui/app.py feeds them.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from rich.syntax import Syntax
|
|
9
|
+
from rich.text import Text
|
|
10
|
+
from textual.reactive import reactive
|
|
11
|
+
from textual.widgets import RichLog, Static
|
|
12
|
+
|
|
13
|
+
from prompts.system_prompts import pass_label
|
|
14
|
+
|
|
15
|
+
from tui import diffs, ravens, themes
|
|
16
|
+
|
|
17
|
+
# Animation cadence. Slow enough to read, and paused outright while tokens
|
|
18
|
+
# are streaming -- a redraw loop competing with token deltas is the one
|
|
19
|
+
# place the mascot can cost responsiveness rather than just effort.
|
|
20
|
+
ANIMATION_INTERVAL = 0.4
|
|
21
|
+
|
|
22
|
+
# §38. The thinking block's furniture. A bar down the left is how chat
|
|
23
|
+
# interfaces mark quoted reasoning, and it has to be applied per RENDERED
|
|
24
|
+
# row rather than once per block -- which is why Transcript pre-wraps
|
|
25
|
+
# instead of letting RichLog soft-wrap.
|
|
26
|
+
THINKING_OPEN = "╭ thinking…"
|
|
27
|
+
THINKING_BAR = "│ "
|
|
28
|
+
THINKING_CLOSE = "╰ …done thinking"
|
|
29
|
+
THINKING_INDENT = " "
|
|
30
|
+
|
|
31
|
+
# Below this many usable columns nothing is pre-wrapped and the newline
|
|
32
|
+
# rule alone decides when a chunk is committable. A transcript that narrow
|
|
33
|
+
# has bigger problems than streaming cadence, and an unmeasurable width
|
|
34
|
+
# (a bare-built test widget, a widget before mount) reads as 0.
|
|
35
|
+
MIN_WRAP_WIDTH = 20
|
|
36
|
+
|
|
37
|
+
# §41. The inline diff's furniture, owned by the renderer for the same
|
|
38
|
+
# reason the thinking bar is: `_entries` keeps the canonical block, so
|
|
39
|
+
# /copy hands back a diff rather than a decorated string and a replay
|
|
40
|
+
# under a new theme re-derives the painting.
|
|
41
|
+
#
|
|
42
|
+
# One column deeper than a plain transcript line (five), so the block
|
|
43
|
+
# reads as belonging to the `▸ edit` line above it.
|
|
44
|
+
DIFF_INDENT = " "
|
|
45
|
+
|
|
46
|
+
# A tab is one CELL to Rich and a jump to the next tab stop in the
|
|
47
|
+
# terminal, so a tabbed source line would break the padding that
|
|
48
|
+
# carries the row's background and leave the rectangle ragged.
|
|
49
|
+
# Expanded at render time only -- the stored block keeps the file's
|
|
50
|
+
# own bytes.
|
|
51
|
+
DIFF_TAB = " "
|
|
52
|
+
|
|
53
|
+
_DIFF_ROLES = {
|
|
54
|
+
diffs.CONTEXT: "diff_context",
|
|
55
|
+
diffs.DELETED: "diff_del",
|
|
56
|
+
diffs.ADDED: "diff_add",
|
|
57
|
+
diffs.ELIDED: "diff_context",
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
# The elided-rows notice takes the gutter column rather than a row of
|
|
61
|
+
# its own: it is a statement about line numbers, so it belongs where
|
|
62
|
+
# the line numbers are.
|
|
63
|
+
_ELIDE_GUTTER = "…"
|
|
64
|
+
|
|
65
|
+
_DIFF_MARKS = {
|
|
66
|
+
diffs.CONTEXT: " ",
|
|
67
|
+
diffs.DELETED: "-",
|
|
68
|
+
diffs.ADDED: "+",
|
|
69
|
+
diffs.ELIDED: " ",
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
# Batch 41 (X3). The checklist vocabulary, in ONE place because two
|
|
73
|
+
# panels render it and they were already spelling it differently: the
|
|
74
|
+
# todo list used `x` for done where the research panel used `x` for a
|
|
75
|
+
# finished pass and · for a code stage, so `·` meant
|
|
76
|
+
# "not started" in one widget and "already finished" in the other.
|
|
77
|
+
#
|
|
78
|
+
# Checkboxes rather than punctuation: a reader should not have to
|
|
79
|
+
# remember which mark means what, and ☐/☑/☒ carry it in the
|
|
80
|
+
# glyph. All three measure ONE CELL under the pinned Rich
|
|
81
|
+
# (tests/test_todo.py pins that) -- a two-cell glyph would shear the
|
|
82
|
+
# 22-column sidebar on every row it appears in.
|
|
83
|
+
MARK_PENDING = "☐" # U+2610 BALLOT BOX
|
|
84
|
+
MARK_DONE = "☑" # U+2611 BALLOT BOX WITH CHECK
|
|
85
|
+
MARK_FAILED = "☒" # U+2612 BALLOT BOX WITH X
|
|
86
|
+
|
|
87
|
+
# NOT a fourth checkbox. An item being worked on right now is the one
|
|
88
|
+
# state a box cannot express -- an empty box says "nothing has
|
|
89
|
+
# happened here", which is exactly what a running pass is not, and
|
|
90
|
+
# telling the live pass from the queued ones is the whole job of the
|
|
91
|
+
# research panel. It borrows the transcript's own tool marker, so the
|
|
92
|
+
# same glyph means "in flight" in both places.
|
|
93
|
+
MARK_RUNNING = "▸"
|
|
94
|
+
|
|
95
|
+
# Also not a checklist state. A zero-LLM stage (Pass 5, gate D1) is
|
|
96
|
+
# done the moment it is announced because it made no model call, so it
|
|
97
|
+
# has no pending form and no running form to check off -- §26 marked
|
|
98
|
+
# it apart from a pass for that reason and this keeps the distinction.
|
|
99
|
+
MARK_STAGE = "·"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
# Batch 48. Which transcript roles are the CONVERSATION, and which are
|
|
103
|
+
# the harness talking about itself. `/copy all` reads neither -- it is a
|
|
104
|
+
# superset by decision (#140), and the harness lines are exactly what
|
|
105
|
+
# reconstructs what happened -- but `/copy conversation` promises that
|
|
106
|
+
# none of them are in it, and that promise needs a list.
|
|
107
|
+
#
|
|
108
|
+
# An ALLOWLIST, because it fails in the safe direction: a role added
|
|
109
|
+
# later is meta until someone classifies it, so the worst a forgotten
|
|
110
|
+
# role can do is go missing from `conversation` rather than leak a
|
|
111
|
+
# harness line into it. tests/test_themes.py holds both halves against
|
|
112
|
+
# MESSAGE_ROLES, so a new role has to be classified rather than land in
|
|
113
|
+
# one target or the other by accident.
|
|
114
|
+
CONVERSATION_ROLES = frozenset({
|
|
115
|
+
"user", "assistant", "thinking", "tool", "tool_error", "diff"})
|
|
116
|
+
|
|
117
|
+
# `pass` and `pass_done` are here rather than above deliberately: a
|
|
118
|
+
# ten-pass run's boundaries are progress reporting about the harness,
|
|
119
|
+
# not the exchange, so a research run copies as the query, the tool
|
|
120
|
+
# lines and the report.
|
|
121
|
+
META_ROLES = frozenset({
|
|
122
|
+
"system", "warning", "error", "pass", "pass_done", "success"})
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class RavenPanel(Static):
|
|
126
|
+
"""Corner raven: what the harness is doing right now."""
|
|
127
|
+
|
|
128
|
+
# NOT always_update=True. Every token_delta reassigns state to
|
|
129
|
+
# THINKING, so always_update fired watch_state once per token for the
|
|
130
|
+
# whole stream -- resetting the frame, calling Static.update() and
|
|
131
|
+
# re-pausing the timer -- which is exactly the per-token redraw loop
|
|
132
|
+
# pause_animation exists to eliminate. Genuine transitions still fire.
|
|
133
|
+
state = reactive(ravens.IDLE)
|
|
134
|
+
|
|
135
|
+
def __init__(self, animations: bool = True, **kwargs):
|
|
136
|
+
super().__init__(**kwargs)
|
|
137
|
+
self._animations = animations
|
|
138
|
+
self._frame = 0
|
|
139
|
+
self._timer = None
|
|
140
|
+
|
|
141
|
+
def on_mount(self) -> None:
|
|
142
|
+
if self._animations:
|
|
143
|
+
self._timer = self.set_interval(ANIMATION_INTERVAL, self._advance)
|
|
144
|
+
self._render_state()
|
|
145
|
+
|
|
146
|
+
def _advance(self) -> None:
|
|
147
|
+
self._frame += 1
|
|
148
|
+
self._render_state()
|
|
149
|
+
|
|
150
|
+
def watch_state(self) -> None:
|
|
151
|
+
self._frame = 0
|
|
152
|
+
self._render_state()
|
|
153
|
+
|
|
154
|
+
def _render_state(self) -> None:
|
|
155
|
+
frames = self.state.frames
|
|
156
|
+
art = frames[self._frame % len(frames)] if self._animations else frames[0]
|
|
157
|
+
self.update(f"{art}\n{self.state.label}")
|
|
158
|
+
|
|
159
|
+
def pause_animation(self) -> None:
|
|
160
|
+
"""Called while a token stream is active. Idempotent."""
|
|
161
|
+
if self._timer is not None:
|
|
162
|
+
self._timer.pause()
|
|
163
|
+
|
|
164
|
+
def resume_animation(self) -> None:
|
|
165
|
+
if self._timer is not None:
|
|
166
|
+
self._timer.resume()
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class ThinkingIndicator(Static):
|
|
170
|
+
"""The collapsed form of a thinking span (§38 O8), for
|
|
171
|
+
`tui.show_thinking: false`.
|
|
172
|
+
|
|
173
|
+
A Static rather than a transcript line, because RichLog cannot rewrite
|
|
174
|
+
a row it has drawn and an ellipsis that does not move is not an
|
|
175
|
+
indicator. Docked directly under the transcript, so it reads as the
|
|
176
|
+
bottom of the conversation rather than as sidebar furniture.
|
|
177
|
+
|
|
178
|
+
`tui.animations` is honoured (RavenPanel's rule): with animations off
|
|
179
|
+
it renders the last frame, static. The timer is created PAUSED and
|
|
180
|
+
resumed only while a span is live -- a 0.4s tick against a hidden
|
|
181
|
+
widget is exactly the idle redraw loop RavenPanel.pause_animation
|
|
182
|
+
exists to avoid.
|
|
183
|
+
"""
|
|
184
|
+
|
|
185
|
+
FRAMES = ("thinking.", "thinking..", "thinking...")
|
|
186
|
+
|
|
187
|
+
def __init__(self, animations: bool = True, **kwargs):
|
|
188
|
+
super().__init__(**kwargs)
|
|
189
|
+
self._animations = animations
|
|
190
|
+
self._frame = 0
|
|
191
|
+
self._timer = None
|
|
192
|
+
self.display = False
|
|
193
|
+
|
|
194
|
+
def on_mount(self) -> None:
|
|
195
|
+
if self._animations:
|
|
196
|
+
self._timer = self.set_interval(ANIMATION_INTERVAL, self._advance)
|
|
197
|
+
self._timer.pause()
|
|
198
|
+
|
|
199
|
+
def _advance(self) -> None:
|
|
200
|
+
self._frame = (self._frame + 1) % len(self.FRAMES)
|
|
201
|
+
self._redraw()
|
|
202
|
+
|
|
203
|
+
def _redraw(self) -> None:
|
|
204
|
+
# Same guard as Transcript._styles: self.app RAISES outside a
|
|
205
|
+
# running app, and this widget is built bare in the suite.
|
|
206
|
+
try:
|
|
207
|
+
style = themes.styles_for(self.app).get("thinking", "")
|
|
208
|
+
except Exception: # noqa: BLE001 -- no running app; render unstyled
|
|
209
|
+
style = ""
|
|
210
|
+
frame = self.FRAMES[self._frame] if self._animations else self.FRAMES[-1]
|
|
211
|
+
self.update(Text(f"{THINKING_INDENT}{frame}", style))
|
|
212
|
+
|
|
213
|
+
def start(self) -> None:
|
|
214
|
+
"""Idempotent -- called on every thinking delta."""
|
|
215
|
+
if self.display:
|
|
216
|
+
return
|
|
217
|
+
self._frame = 0
|
|
218
|
+
self.display = True
|
|
219
|
+
self._redraw()
|
|
220
|
+
if self._timer is not None:
|
|
221
|
+
self._timer.resume()
|
|
222
|
+
|
|
223
|
+
def stop(self) -> None:
|
|
224
|
+
"""Idempotent -- called by every non-thinking event."""
|
|
225
|
+
if self._timer is not None:
|
|
226
|
+
self._timer.pause()
|
|
227
|
+
self.display = False
|
|
228
|
+
self.update("")
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
class EffortRaven(Static):
|
|
232
|
+
"""One-line raven showing the current reasoning-effort level."""
|
|
233
|
+
|
|
234
|
+
effort = reactive(None, always_update=True)
|
|
235
|
+
|
|
236
|
+
def watch_effort(self) -> None:
|
|
237
|
+
self.update(ravens.effort_raven(self.effort))
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
class PostureBadge(Static):
|
|
241
|
+
"""Which shipped protections are OFF, shown for the whole session.
|
|
242
|
+
|
|
243
|
+
§40 (UN3). The startup banner scrolls away; a posture does not. The
|
|
244
|
+
case this exists for is not the researcher who just typed a flag --
|
|
245
|
+
it is the user who set `ALLOW_INSECURE_SANDBOX_FALLBACK` months ago
|
|
246
|
+
and forgot, or who inherited a config.py from somewhere. Neither of
|
|
247
|
+
them reads app.log.
|
|
248
|
+
|
|
249
|
+
Hidden when the posture is the shipped one, GoalBanner-style, so it
|
|
250
|
+
costs no sidebar rows in the case that needs nothing said. It takes
|
|
251
|
+
the lines rather than reading the posture itself, because
|
|
252
|
+
`Posture.unsafe_reasons()` is the single source all three surfaces
|
|
253
|
+
share and a widget that re-derived the question would be the second.
|
|
254
|
+
"""
|
|
255
|
+
|
|
256
|
+
def __init__(self, reasons: list[tuple[str, str]], **kwargs) -> None:
|
|
257
|
+
super().__init__(**kwargs)
|
|
258
|
+
self._reasons = list(reasons)
|
|
259
|
+
|
|
260
|
+
def on_mount(self) -> None:
|
|
261
|
+
if not self._reasons:
|
|
262
|
+
self.display = False
|
|
263
|
+
return
|
|
264
|
+
# The full sentences live in the banner and the log; the sidebar
|
|
265
|
+
# is twenty columns, so this shows the LABEL half of each pair.
|
|
266
|
+
# `unsafe_reasons()` carries both for exactly this reason -- a
|
|
267
|
+
# second method deriving short names would put the conditions in
|
|
268
|
+
# two places, and the raw constant name (31 characters for
|
|
269
|
+
# ALLOW_INSECURE_SANDBOX_FALLBACK) wraps mid-identifier here.
|
|
270
|
+
# No `style=` here, and that is §26's rule (#116) rather than an
|
|
271
|
+
# oversight: a widget must not paint a literal, because half the
|
|
272
|
+
# shipped themes disagree with any ANSI slot it could pick. The
|
|
273
|
+
# colour and the weight come from `#posture-badge` in app.tcss,
|
|
274
|
+
# which resolves `$error` against the ACTIVE theme -- so this
|
|
275
|
+
# badge recolours with `/theme` like everything else.
|
|
276
|
+
body = Text("!! REDUCED SECURITY\n")
|
|
277
|
+
for label, _detail in self._reasons:
|
|
278
|
+
body.append("- " + label + "\n")
|
|
279
|
+
self.update(body)
|
|
280
|
+
self.display = True
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
class UsageLine(Static):
|
|
284
|
+
"""Session usage, batch 27 (#4): billed-since-resume and the thread's
|
|
285
|
+
current context size, one sidebar line.
|
|
286
|
+
|
|
287
|
+
TWO DIFFERENT INSTRUMENTS, labelled so nobody repeats item 9's
|
|
288
|
+
misreading. `ctx` is the provider's own count of what the last call
|
|
289
|
+
was SENT -- the size figure compaction acts on. `billed` accumulates
|
|
290
|
+
every input+output on this thread since it was (re)opened in this
|
|
291
|
+
session; it grows quadratically in a tool-using turn because that is
|
|
292
|
+
what the provider charges, and it is deliberately NOT persisted
|
|
293
|
+
(memory.record_billed for that decision). Neither figure is a price.
|
|
294
|
+
|
|
295
|
+
Hidden until the first turn puts numbers behind it, GoalBanner-style.
|
|
296
|
+
"""
|
|
297
|
+
|
|
298
|
+
def __init__(self, **kwargs):
|
|
299
|
+
super().__init__(**kwargs)
|
|
300
|
+
self.display = False
|
|
301
|
+
self._last = None
|
|
302
|
+
|
|
303
|
+
def _styles(self) -> dict:
|
|
304
|
+
# TodoPanel/Transcript shape (#116): resolve per draw against the
|
|
305
|
+
# active theme; bare-built widgets render unstyled.
|
|
306
|
+
try:
|
|
307
|
+
app = self.app
|
|
308
|
+
except Exception: # noqa: BLE001 -- no running app; render unstyled
|
|
309
|
+
return {}
|
|
310
|
+
return themes.styles_for(app)
|
|
311
|
+
|
|
312
|
+
def _reset(self) -> None:
|
|
313
|
+
"""A thread switch: hide until the new thread's first turn.
|
|
314
|
+
Session billing restarts at zero by construction; showing the
|
|
315
|
+
PREVIOUS thread's totals here would be §27's stale-state bug in
|
|
316
|
+
miniature."""
|
|
317
|
+
self._last = None
|
|
318
|
+
self.display = False
|
|
319
|
+
self.update("")
|
|
320
|
+
|
|
321
|
+
def update_usage(self, billed: int, ctx: int,
|
|
322
|
+
ceiling: int = 0, overridden: bool = False) -> None:
|
|
323
|
+
"""`ceiling` is the compaction trigger this thread is measured
|
|
324
|
+
against, shown as a denominator so `ctx` has a scale. `overridden`
|
|
325
|
+
marks it with a `*` when a session /trigger set it -- ephemeral
|
|
326
|
+
state that changes when compaction fires should not be invisible,
|
|
327
|
+
which is the same rule M14 states for injected memories.
|
|
328
|
+
|
|
329
|
+
Both are optional so a caller that has no threshold to hand still
|
|
330
|
+
gets the batch-27 two-instrument line unchanged.
|
|
331
|
+
"""
|
|
332
|
+
key = (billed, ctx, ceiling, overridden)
|
|
333
|
+
if key == self._last or not (billed or ctx):
|
|
334
|
+
# Change-guard: on_loop_event fires per token delta during a
|
|
335
|
+
# stream; both figures only move at step boundaries, so this
|
|
336
|
+
# makes per-event calls nearly free.
|
|
337
|
+
return
|
|
338
|
+
self._last = key
|
|
339
|
+
|
|
340
|
+
def _k(n: int) -> str:
|
|
341
|
+
return f"{n / 1000:.0f}k" if n >= 1000 else str(n)
|
|
342
|
+
|
|
343
|
+
self.display = True
|
|
344
|
+
scale = f"/{_k(ceiling)}{'*' if overridden else ''}" if ceiling else ""
|
|
345
|
+
# `system` is the harness-talking-about-itself role -- the right
|
|
346
|
+
# meaning for a usage line, and the palette route the batch-26
|
|
347
|
+
# guard test demands (it caught this line as a literal within one
|
|
348
|
+
# commit of the widget existing).
|
|
349
|
+
self.update(Text(f"usage · ctx {_k(ctx)}{scale} · billed {_k(billed)}",
|
|
350
|
+
style=self._styles().get("system", "")))
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
class GoalBanner(Static):
|
|
354
|
+
"""Persistent-objective banner (§18 goal mode). Hidden when the
|
|
355
|
+
thread has no goal; a one-line reminder of what the session is
|
|
356
|
+
oriented toward, fed by app.py from ConversationThread.extra_data."""
|
|
357
|
+
|
|
358
|
+
goal = reactive(None, always_update=True)
|
|
359
|
+
|
|
360
|
+
def _styles(self) -> dict:
|
|
361
|
+
# TodoPanel's shape, and Transcript._styles' guard: resolved per
|
|
362
|
+
# update rather than cached, and bare-built test widgets render
|
|
363
|
+
# unstyled rather than raising (self.app raises NoActiveAppError).
|
|
364
|
+
try:
|
|
365
|
+
app = self.app
|
|
366
|
+
except Exception: # noqa: BLE001 -- no running app; render unstyled
|
|
367
|
+
return {}
|
|
368
|
+
return themes.styles_for(app)
|
|
369
|
+
|
|
370
|
+
def watch_goal(self) -> None:
|
|
371
|
+
if self.goal:
|
|
372
|
+
self.display = True
|
|
373
|
+
# The palette, not a literal (#116): `warning` is one of the
|
|
374
|
+
# three theme-invariant roles, so the hue means the same thing
|
|
375
|
+
# on every theme. The WEIGHT is carried by the role itself
|
|
376
|
+
# since batch 41 (X2) -- this used to compose `bold {colour}`
|
|
377
|
+
# over a plain hue, which now yields "bold bold #d9a441" and
|
|
378
|
+
# is the second place a weight would be decided. Guarded still,
|
|
379
|
+
# because a bare-built widget has no styles dict at all.
|
|
380
|
+
style = self._styles().get("warning", "") or "bold"
|
|
381
|
+
self.update(Text(f"goal {self.goal}", style=style))
|
|
382
|
+
else:
|
|
383
|
+
self.display = False
|
|
384
|
+
self.update("")
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
class TodoPanel(Static):
|
|
388
|
+
"""The model's checklist for this thread (ROADMAP_v2 §23 slice 2, AC4).
|
|
389
|
+
|
|
390
|
+
GoalBanner's reactive-and-hide shape rather than ResearchProgress's
|
|
391
|
+
one-way reveal, because a todo list EMPTIES as well as fills: clearing
|
|
392
|
+
it must take the panel away again, and `display = True` set once cannot.
|
|
393
|
+
|
|
394
|
+
Re-rendered from an EVENT, never polled (§23 AC4). app.py sets `todos` when
|
|
395
|
+
a `todo_changed` notice arrives, reading the list from thread state --
|
|
396
|
+
the event says when, the thread says what. That split is why this widget
|
|
397
|
+
holds no authoritative copy of anything: the panel cannot disagree with
|
|
398
|
+
the conversation about what the list is.
|
|
399
|
+
|
|
400
|
+
Statuses are mapped with a local table defaulting to the pending marker,
|
|
401
|
+
so a list persisted under an older vocabulary renders rather than
|
|
402
|
+
raising. Same instinct as storage.py keeping THREAD_KIND_* a plain string
|
|
403
|
+
-- and the reason this file still imports nothing from core/ or config.
|
|
404
|
+
"""
|
|
405
|
+
|
|
406
|
+
MARKERS = {"completed": MARK_DONE,
|
|
407
|
+
"in_progress": MARK_RUNNING,
|
|
408
|
+
"pending": MARK_PENDING}
|
|
409
|
+
|
|
410
|
+
# A window, for ResearchProgress's reason: a Static does not scroll
|
|
411
|
+
# itself to the bottom, so an unbounded list would push the newest item
|
|
412
|
+
# out of view -- the opposite of the problem being solved.
|
|
413
|
+
ROWS = 12
|
|
414
|
+
|
|
415
|
+
todos = reactive(None, always_update=True)
|
|
416
|
+
|
|
417
|
+
def __init__(self, **kwargs):
|
|
418
|
+
super().__init__(**kwargs)
|
|
419
|
+
# EXPLICIT, not left to the watcher. A reactive's watch method does
|
|
420
|
+
# not fire for its initial value, so without this the panel is a
|
|
421
|
+
# visible empty box until something first sets `todos` -- which on
|
|
422
|
+
# a fresh thread may be never. ResearchProgress does the same for
|
|
423
|
+
# the same reason; GoalBanner gets away without it only because
|
|
424
|
+
# app.py refreshes it during on_mount.
|
|
425
|
+
self.display = False
|
|
426
|
+
|
|
427
|
+
def _styles(self) -> dict:
|
|
428
|
+
try:
|
|
429
|
+
app = self.app
|
|
430
|
+
except Exception: # noqa: BLE001 -- see Transcript._styles
|
|
431
|
+
return {}
|
|
432
|
+
return themes.styles_for(app)
|
|
433
|
+
|
|
434
|
+
def watch_todos(self) -> None:
|
|
435
|
+
items = self.todos or []
|
|
436
|
+
if not items:
|
|
437
|
+
self.display = False
|
|
438
|
+
self.update("")
|
|
439
|
+
return
|
|
440
|
+
|
|
441
|
+
styles = self._styles()
|
|
442
|
+
done = sum(1 for i in items if i.get("status") == "completed")
|
|
443
|
+
body = Text()
|
|
444
|
+
body.append(f"todo {done}/{len(items)}\n\n")
|
|
445
|
+
for item in items[-self.ROWS:]:
|
|
446
|
+
status = item.get("status", "pending")
|
|
447
|
+
marker = self.MARKERS.get(status, self.MARKERS["pending"])
|
|
448
|
+
# Only the three theme-invariant roles are safe across all eight
|
|
449
|
+
# themes (tui/themes.py), so a completed item uses `success` and
|
|
450
|
+
# everything else stays unstyled rather than reaching for a hue
|
|
451
|
+
# that means something different in half the palettes.
|
|
452
|
+
role = "success" if status == "completed" else ""
|
|
453
|
+
body.append(f"{marker} {item.get('content', '')}\n",
|
|
454
|
+
styles.get(role, "") if role else "")
|
|
455
|
+
if len(items) > self.ROWS:
|
|
456
|
+
body.append(f"(+{len(items) - self.ROWS} earlier)\n",
|
|
457
|
+
styles.get("system", ""))
|
|
458
|
+
self.display = True
|
|
459
|
+
self.update(body)
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
class ResearchProgress(Static):
|
|
463
|
+
"""Live state of a /research run (ROADMAP_v2 §22).
|
|
464
|
+
|
|
465
|
+
Fed by PipelineEvents, never polled -- the database checkpoints the
|
|
466
|
+
pipeline writes are for durability, not for a UI to read back.
|
|
467
|
+
|
|
468
|
+
The pass sequence is NOT a fixed ten-row checklist, because the
|
|
469
|
+
pipeline's shape depends on its own findings: 3a/3b are skipped
|
|
470
|
+
outright when no claim is factual, and 6a/6c repeat once per retry
|
|
471
|
+
round. A pre-drawn list would show rows that never run and hide rows
|
|
472
|
+
that run three times. So passes are appended as they start.
|
|
473
|
+
|
|
474
|
+
Hidden until a run begins and left visible afterwards, so the last
|
|
475
|
+
run's shape stays readable while its report is being read.
|
|
476
|
+
"""
|
|
477
|
+
|
|
478
|
+
# Labels, not a slice of the tier name: the sidebar is 22 columns, and
|
|
479
|
+
# truncating produced "unverifie 1" and would have made
|
|
480
|
+
# UNVERIFIED_COVERAGE indistinguishable from UNVERIFIED.
|
|
481
|
+
TIERS = (
|
|
482
|
+
("HIGH", "high"),
|
|
483
|
+
("MEDIUM", "medium"),
|
|
484
|
+
("LOW", "low"),
|
|
485
|
+
("UNVERIFIED", "unverified"),
|
|
486
|
+
("UNVERIFIED_COVERAGE", "uncovered"),
|
|
487
|
+
)
|
|
488
|
+
|
|
489
|
+
# §26. Code stages roughly double the row count, so the §22 window of 8
|
|
490
|
+
# would push Pass 0 off before the run reached its own claims. Still a
|
|
491
|
+
# WINDOW rather than the whole list: #research-progress scrolls, but a
|
|
492
|
+
# Static does not scroll itself to the bottom, so an unbounded list
|
|
493
|
+
# would leave the newest row out of view -- the opposite of the
|
|
494
|
+
# problem being fixed.
|
|
495
|
+
ROWS = 16
|
|
496
|
+
|
|
497
|
+
def __init__(self, **kwargs):
|
|
498
|
+
super().__init__(**kwargs)
|
|
499
|
+
self.display = False
|
|
500
|
+
self.reset()
|
|
501
|
+
|
|
502
|
+
def reset(self) -> None:
|
|
503
|
+
# [pass_id, done?, failed?, code_stage?, tool_calls, chars]
|
|
504
|
+
self._passes: list = []
|
|
505
|
+
self._tiers: dict = {} # claim_id -> tier
|
|
506
|
+
self._claims = 0
|
|
507
|
+
self._retries = 0
|
|
508
|
+
|
|
509
|
+
def start_run(self) -> None:
|
|
510
|
+
self.reset()
|
|
511
|
+
self.display = True
|
|
512
|
+
self._redraw()
|
|
513
|
+
|
|
514
|
+
def pass_started(self, pass_id: str) -> None:
|
|
515
|
+
self._passes.append([pass_id, False, False, False, 0, 0])
|
|
516
|
+
self._redraw()
|
|
517
|
+
|
|
518
|
+
def pass_completed(self, pass_id: str, *, ok: bool) -> None:
|
|
519
|
+
"""`ok` is REQUIRED and keyword-only (#115/E14): a caller that
|
|
520
|
+
cannot say whether the pass succeeded or died is exactly the
|
|
521
|
+
caller this parameter exists to make think. With a default, an
|
|
522
|
+
old call site would tick a FAILED row as done -- the one
|
|
523
|
+
outcome worse than the stale row this batch fixes.
|
|
524
|
+
|
|
525
|
+
Correlates to the most recent unresolved row with this label,
|
|
526
|
+
the same scan pass_completed always used. Correct under ensemble
|
|
527
|
+
mode's overlapping Pass 1 rows because candidates start and
|
|
528
|
+
finish sequentially."""
|
|
529
|
+
for entry in reversed(self._passes):
|
|
530
|
+
if entry[0] == pass_id and not entry[1]:
|
|
531
|
+
entry[1] = True
|
|
532
|
+
entry[2] = not ok
|
|
533
|
+
break
|
|
534
|
+
self._redraw()
|
|
535
|
+
|
|
536
|
+
def stage_completed(self, pass_id: str) -> None:
|
|
537
|
+
"""A zero-LLM stage (§26). Recorded as already done, because it
|
|
538
|
+
was: it made no model call, so it has no observable running
|
|
539
|
+
state."""
|
|
540
|
+
self._passes.append([pass_id, True, False, True, 0, 0])
|
|
541
|
+
self._redraw()
|
|
542
|
+
|
|
543
|
+
def restyle(self) -> None:
|
|
544
|
+
"""Re-render under the current theme (#183).
|
|
545
|
+
|
|
546
|
+
Public wrapper over _redraw: the panel renders through Rich
|
|
547
|
+
styles resolved per draw, so a /theme switch cannot reach it via
|
|
548
|
+
tcss -- the same reason Transcript needs rerender()."""
|
|
549
|
+
self._redraw()
|
|
550
|
+
|
|
551
|
+
def tool_called(self, pass_id: str) -> None:
|
|
552
|
+
"""Counted here rather than carried on an event of its own -- see
|
|
553
|
+
the note in core/reasoning/events.py about why there is no step
|
|
554
|
+
kind. The count is what proves a quiet pass is working."""
|
|
555
|
+
entry = self._current(pass_id)
|
|
556
|
+
if entry is not None:
|
|
557
|
+
entry[4] += 1
|
|
558
|
+
self._redraw()
|
|
559
|
+
|
|
560
|
+
def activity(self, pass_id: str, chars: int) -> None:
|
|
561
|
+
entry = self._current(pass_id)
|
|
562
|
+
if entry is not None:
|
|
563
|
+
entry[5] = chars or 0
|
|
564
|
+
self._redraw()
|
|
565
|
+
|
|
566
|
+
def _current(self, pass_id: str):
|
|
567
|
+
for entry in reversed(self._passes):
|
|
568
|
+
if entry[0] == pass_id and not entry[1]:
|
|
569
|
+
return entry
|
|
570
|
+
return None
|
|
571
|
+
|
|
572
|
+
def claim_extracted(self) -> None:
|
|
573
|
+
self._claims += 1
|
|
574
|
+
self._redraw()
|
|
575
|
+
|
|
576
|
+
def claim_tiered(self, claim_id: str, tier) -> None:
|
|
577
|
+
# Keyed by claim, not counted: a claim is re-tiered on every 6c
|
|
578
|
+
# round, so counting would inflate the tally by one per round and
|
|
579
|
+
# end up reporting more claims than the run has.
|
|
580
|
+
self._tiers[claim_id] = tier
|
|
581
|
+
self._redraw()
|
|
582
|
+
|
|
583
|
+
def retried(self) -> None:
|
|
584
|
+
self._retries += 1
|
|
585
|
+
self._redraw()
|
|
586
|
+
|
|
587
|
+
def _styles(self) -> dict:
|
|
588
|
+
try:
|
|
589
|
+
app = self.app
|
|
590
|
+
except Exception: # noqa: BLE001 -- see Transcript._styles
|
|
591
|
+
return {}
|
|
592
|
+
return themes.styles_for(app)
|
|
593
|
+
|
|
594
|
+
def _redraw(self) -> None:
|
|
595
|
+
styles = self._styles()
|
|
596
|
+
body = Text()
|
|
597
|
+
body.append("research\n\n")
|
|
598
|
+
for pass_id, done, failed, is_stage, tools, chars in self._passes[-self.ROWS:]:
|
|
599
|
+
if is_stage:
|
|
600
|
+
marker, role = MARK_STAGE, "pass_done"
|
|
601
|
+
elif failed:
|
|
602
|
+
# #115/E14. A row that ended badly must not share a
|
|
603
|
+
# glyph with one that finished. This used to be the
|
|
604
|
+
# transcript's own ✗; since batch 41 it is the ballot
|
|
605
|
+
# box's failed form, which keeps E14's constraint and
|
|
606
|
+
# puts the three pass outcomes in one visual family.
|
|
607
|
+
marker, role = MARK_FAILED, "error"
|
|
608
|
+
else:
|
|
609
|
+
marker, role = (MARK_DONE, "pass_done") if done \
|
|
610
|
+
else (MARK_RUNNING, "pass")
|
|
611
|
+
body.append(f"{marker} {pass_label(pass_id)}\n", styles.get(role, ""))
|
|
612
|
+
if not done:
|
|
613
|
+
detail = []
|
|
614
|
+
if tools:
|
|
615
|
+
detail.append(f"{tools} tool{'s' if tools > 1 else ''}")
|
|
616
|
+
if chars:
|
|
617
|
+
detail.append(f"{chars // 1000}k")
|
|
618
|
+
if detail:
|
|
619
|
+
body.append(f" {' · '.join(detail)}\n",
|
|
620
|
+
styles.get("tool", ""))
|
|
621
|
+
if self._claims:
|
|
622
|
+
body.append(f"\n{self._claims} claim(s)\n")
|
|
623
|
+
for tier, label in self.TIERS:
|
|
624
|
+
count = sum(1 for v in self._tiers.values() if v == tier)
|
|
625
|
+
if count:
|
|
626
|
+
body.append(f" {label} {count}\n", styles.get(tier, ""))
|
|
627
|
+
if self._retries:
|
|
628
|
+
body.append(f"{self._retries} revision(s)\n")
|
|
629
|
+
self.update(body)
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
class Transcript(RichLog):
|
|
633
|
+
"""The conversation. Code fences render highlighted via Rich's Syntax.
|
|
634
|
+
|
|
635
|
+
Token deltas are buffered and committed AT LINE BOUNDARIES THIS WIDGET
|
|
636
|
+
COMPUTES (§38 O7), so an answer appears as it is written. RichLog
|
|
637
|
+
appends and cannot rewrite a row it has already drawn, so a delta
|
|
638
|
+
cannot simply be painted: a chunk is only committable once it ends
|
|
639
|
+
where a rendered row ends.
|
|
640
|
+
|
|
641
|
+
Two rules decide that, in order:
|
|
642
|
+
|
|
643
|
+
- everything up to and including the last newline is committable;
|
|
644
|
+
- past that, a tail longer than one rendered row is committed up to
|
|
645
|
+
its last space. That second rule is what makes a single long
|
|
646
|
+
paragraph stream rather than arriving whole at the end of the
|
|
647
|
+
turn, and it is why the wrap has to be ours: Rich would soft-wrap
|
|
648
|
+
the row we are still appending to.
|
|
649
|
+
|
|
650
|
+
A chunk is held back while a ``` fence is open, and the check is
|
|
651
|
+
against `_stream_text + chunk` rather than the whole pending buffer --
|
|
652
|
+
a block whose closing fence has no newline after it yet puts the last
|
|
653
|
+
newline INSIDE the fence, so an otherwise-committable prefix would
|
|
654
|
+
render an unterminated opener as plain text and leave _split_fences
|
|
655
|
+
counting from the wrong place for the rest of the answer. Holding is
|
|
656
|
+
what keeps §26's syntax highlighting working: a fence rendered plain
|
|
657
|
+
now cannot be restyled when it closes.
|
|
658
|
+
|
|
659
|
+
This USED to buffer everything until flush_stream(), and the docstring
|
|
660
|
+
here said so: "a plain answer with no tool calls shows nothing until
|
|
661
|
+
the turn ends... this is not progressive rendering, and anyone chasing
|
|
662
|
+
streaming latency should look here first." They should still look
|
|
663
|
+
here first; the answer is now the two rules above.
|
|
664
|
+
|
|
665
|
+
Known edge, stated rather than fixed: a terminal resize mid-answer
|
|
666
|
+
leaves already-drawn rows wrapped to the old width. `_entries` keeps
|
|
667
|
+
the unwrapped source, so rerender() puts it right, and a resize
|
|
668
|
+
handler for the seconds an answer is in flight is machinery with no
|
|
669
|
+
user.
|
|
670
|
+
|
|
671
|
+
§26 adds two things and one obligation.
|
|
672
|
+
|
|
673
|
+
COLOUR, by role rather than by call site. tui/themes.role_styles()
|
|
674
|
+
resolves them against the active theme; see the note there about why a
|
|
675
|
+
RichLog cannot use app.tcss's variables.
|
|
676
|
+
|
|
677
|
+
AN ENTRY LOG. `_entries` keeps (role, raw_text) for everything written,
|
|
678
|
+
and it earns its place twice: RichLog cannot restyle what it has
|
|
679
|
+
already rendered, so a /theme switch mid-session needs rerender() to
|
|
680
|
+
replay; and /copy needs the session's text, which RichLog stores only
|
|
681
|
+
as rendered segments. One list rather than two mechanisms.
|
|
682
|
+
|
|
683
|
+
The obligation: every write path must go through _emit(), or a line
|
|
684
|
+
lands on screen and is absent from both the replay and the copy. That
|
|
685
|
+
is the same "two writers of related data" shape §22 spent a section
|
|
686
|
+
removing from the trace. §38 keeps it by a different route for a
|
|
687
|
+
streamed span: the rows go out in pieces, but `_entries` holds ONE
|
|
688
|
+
entry per span, updated in place. Appending per chunk would split a
|
|
689
|
+
copied answer across as_text()'s "\\n\\n" joins and make rerender()
|
|
690
|
+
draw a "venastine ›" label per fragment.
|
|
691
|
+
|
|
692
|
+
§43 moves that label. It belongs to the TURN, not to an answer span:
|
|
693
|
+
one "venastine ›" above the model's first output of the turn,
|
|
694
|
+
whether that output is reasoning or text, retired by the next
|
|
695
|
+
"you ›". See _open_label for why, and note the property that makes
|
|
696
|
+
it safe -- placement is a pure function of the role sequence in
|
|
697
|
+
`_entries`, so rerender() reproduces it rather than approximating
|
|
698
|
+
it. A re-render that moves a label is the same defect as one that
|
|
699
|
+
reflows a paragraph.
|
|
700
|
+
"""
|
|
701
|
+
|
|
702
|
+
def __init__(self, **kwargs):
|
|
703
|
+
super().__init__(wrap=True, markup=False, **kwargs)
|
|
704
|
+
self._pending = ""
|
|
705
|
+
self._entries: list[tuple[str, str]] = []
|
|
706
|
+
# §38. An assistant span with rows already on screen: its label is
|
|
707
|
+
# drawn and its single entry is open at _entries[-1].
|
|
708
|
+
self._stream_open = False
|
|
709
|
+
self._stream_text = ""
|
|
710
|
+
# The same pair for a thinking span, tracked separately because
|
|
711
|
+
# the two interleave -- thinking, text, a tool call, thinking
|
|
712
|
+
# again -- and opening either closes the other.
|
|
713
|
+
self._thinking_pending = ""
|
|
714
|
+
self._thinking_open = False
|
|
715
|
+
self._thinking_text = ""
|
|
716
|
+
# §43 (RM1). Whether this turn's `venastine ›` has been drawn.
|
|
717
|
+
# ONE label per turn, above the model's first output of it
|
|
718
|
+
# whether that output is reasoning or text -- see _open_label.
|
|
719
|
+
self._label_in_force = False
|
|
720
|
+
|
|
721
|
+
# -- styling -----------------------------------------------------------
|
|
722
|
+
|
|
723
|
+
def _styles(self) -> dict:
|
|
724
|
+
# Resolved per write rather than cached at mount: /theme switches
|
|
725
|
+
# the palette under a live widget, and a cache would leave every
|
|
726
|
+
# subsequent line in the old theme's colours.
|
|
727
|
+
#
|
|
728
|
+
# self.app RAISES (NoActiveAppError) rather than returning None
|
|
729
|
+
# outside a running app, and widgets are built bare in tests, so
|
|
730
|
+
# the guard is around the attribute access itself.
|
|
731
|
+
try:
|
|
732
|
+
app = self.app
|
|
733
|
+
except Exception: # noqa: BLE001 -- no running app; render unstyled
|
|
734
|
+
return {}
|
|
735
|
+
return themes.styles_for(app)
|
|
736
|
+
|
|
737
|
+
def _style(self, role: str) -> str:
|
|
738
|
+
return self._styles().get(role, "")
|
|
739
|
+
|
|
740
|
+
def _syntax_theme(self) -> str:
|
|
741
|
+
# The guard is at the attribute access, like _styles: self.app
|
|
742
|
+
# RAISES outside a running app, and syntax_theme_for can only help
|
|
743
|
+
# once it has been handed one.
|
|
744
|
+
try:
|
|
745
|
+
return themes.syntax_theme_for(self.app)
|
|
746
|
+
except Exception: # noqa: BLE001 -- no running app; default dark
|
|
747
|
+
return "ansi_dark"
|
|
748
|
+
|
|
749
|
+
# -- writing -----------------------------------------------------------
|
|
750
|
+
|
|
751
|
+
def _emit(self, role: str, text: str, record: bool = True) -> None:
|
|
752
|
+
"""Render one entry and remember it. THE single write path."""
|
|
753
|
+
if record:
|
|
754
|
+
self._entries.append((role, text))
|
|
755
|
+
self._render_entry(role, text)
|
|
756
|
+
|
|
757
|
+
def _render_entry(self, role: str, text: str) -> None:
|
|
758
|
+
if role == "user":
|
|
759
|
+
# §43 (RM1). The turn's label is retired HERE and nowhere
|
|
760
|
+
# else, so where the labels land is a pure function of the
|
|
761
|
+
# role sequence in `_entries` -- which is what lets
|
|
762
|
+
# rerender() put them exactly where the live render did.
|
|
763
|
+
self._label_in_force = False
|
|
764
|
+
self.write(Text.assemble(
|
|
765
|
+
("\nyou › ", self._style("user_label")),
|
|
766
|
+
(text, self._style("user"))))
|
|
767
|
+
elif role == "assistant":
|
|
768
|
+
self._open_label()
|
|
769
|
+
# One trailing newline is dropped, exactly as a committed
|
|
770
|
+
# stream chunk drops it. Rich renders a trailing newline as an
|
|
771
|
+
# extra empty row, so without this a REPLAYED answer carried a
|
|
772
|
+
# blank line the live render never had -- and a /theme
|
|
773
|
+
# mid-session would reflow the transcript it was only meant to
|
|
774
|
+
# recolour. Stripped HERE and not inside _render_blocks, which
|
|
775
|
+
# is also called per committed chunk, where a second strip
|
|
776
|
+
# would eat the blank line between paragraphs.
|
|
777
|
+
self._render_blocks(text[:-1] if text.endswith("\n") else text)
|
|
778
|
+
elif role == "diff":
|
|
779
|
+
self._render_diff(text)
|
|
780
|
+
elif role == "thinking":
|
|
781
|
+
# §38. The furniture is OWNED by the renderer, not stored in
|
|
782
|
+
# the entry: `_entries` keeps the model's raw reasoning, so
|
|
783
|
+
# /copy gets prose rather than box-drawing characters, and a
|
|
784
|
+
# replay under a new theme re-derives the bar rather than
|
|
785
|
+
# replaying a string that was decorated once.
|
|
786
|
+
self._open_label()
|
|
787
|
+
self._write_thinking_open()
|
|
788
|
+
self._write_thinking_lines(text)
|
|
789
|
+
self._write_thinking_close()
|
|
790
|
+
else:
|
|
791
|
+
self.write(Text(f" {text}", self._style(role)))
|
|
792
|
+
|
|
793
|
+
def _open_label(self) -> None:
|
|
794
|
+
"""Draw this turn's `venastine ›`, once (§43, RM1).
|
|
795
|
+
|
|
796
|
+
The label used to belong to an ANSWER span, drawn by
|
|
797
|
+
_write_stream_chunk when the first committable chunk arrived. On
|
|
798
|
+
a turn that thinks first -- the normal shape since §38 -- that
|
|
799
|
+
put the reasoning ABOVE the label and therefore under `you ›`,
|
|
800
|
+
so the transcript read as if the user had done the thinking and
|
|
801
|
+
the model had answered without any.
|
|
802
|
+
|
|
803
|
+
It is now the TURN's, opened by whichever of reasoning or text
|
|
804
|
+
comes first and retired only by the next `you ›`. A tool line, a
|
|
805
|
+
diff or a system notice inside the turn does NOT re-open one:
|
|
806
|
+
they are part of the turn the label already announced. The cost,
|
|
807
|
+
accepted rather than fixed: an answer resuming after a tool line
|
|
808
|
+
starts directly under it, where the suppressed label used to
|
|
809
|
+
supply a blank row. A separator drawn instead would be a second
|
|
810
|
+
thing the live path and rerender() must agree about.
|
|
811
|
+
"""
|
|
812
|
+
if self._label_in_force:
|
|
813
|
+
return
|
|
814
|
+
self.write(Text("\nvenastine ›", self._style("assistant_label")))
|
|
815
|
+
self._label_in_force = True
|
|
816
|
+
|
|
817
|
+
def _render_diff(self, block: str) -> None:
|
|
818
|
+
"""One `write`/`edit` diff (§41, X5).
|
|
819
|
+
|
|
820
|
+
Every rendered row is PADDED to the full width and written with an
|
|
821
|
+
explicit `width=`, and both halves are load-bearing. RichLog
|
|
822
|
+
otherwise raises the render width to `min_width` and
|
|
823
|
+
`Strip.adjust_cell_length` pads the tail with an UNSTYLED segment,
|
|
824
|
+
so the background would stop at the last character of the source
|
|
825
|
+
line instead of at the edge of the row -- which is the difference
|
|
826
|
+
between a marked line and a coloured word.
|
|
827
|
+
|
|
828
|
+
Wrapping is ours for §38's reason: Rich would soft-wrap the row and
|
|
829
|
+
the padding would reach the first rendered line only, leaving a
|
|
830
|
+
wrapped addition half green.
|
|
831
|
+
"""
|
|
832
|
+
path, rows = diffs.parse(block)
|
|
833
|
+
if not path and not rows:
|
|
834
|
+
return
|
|
835
|
+
styles = self._styles()
|
|
836
|
+
total = self._wrap_width()
|
|
837
|
+
gutter_width = max((len(gutter) for _k, gutter, _t in rows), default=0)
|
|
838
|
+
|
|
839
|
+
self._write_padded(f"{DIFF_INDENT} {path}",
|
|
840
|
+
styles.get("diff_header", ""), total)
|
|
841
|
+
for kind, gutter, text in rows:
|
|
842
|
+
column = (_ELIDE_GUTTER if kind == diffs.ELIDED else gutter)
|
|
843
|
+
prefix = (f"{DIFF_INDENT}{_DIFF_MARKS[kind]} "
|
|
844
|
+
f"{column.rjust(gutter_width)}{diffs.GUTTER_SEP}")
|
|
845
|
+
blank = " " * len(prefix)
|
|
846
|
+
style = styles.get(_DIFF_ROLES[kind], "")
|
|
847
|
+
body = text.replace("\t", DIFF_TAB)
|
|
848
|
+
for index, chunk in enumerate(
|
|
849
|
+
diffs.wrap_source(body, total - len(prefix) if total else 0)):
|
|
850
|
+
self._write_padded((prefix if index == 0 else blank) + chunk,
|
|
851
|
+
style, total)
|
|
852
|
+
|
|
853
|
+
def _write_padded(self, text: str, style: str, total: int) -> None:
|
|
854
|
+
"""One rendered row, filled to `total` columns so its background
|
|
855
|
+
covers the whole line. `total` of 0 means the widget could not be
|
|
856
|
+
measured (unmounted, or built bare in the suite), where the row is
|
|
857
|
+
written as it stands rather than raising -- `_styles`' guard rule
|
|
858
|
+
applied to geometry."""
|
|
859
|
+
if not total:
|
|
860
|
+
self.write(Text(text, style))
|
|
861
|
+
return
|
|
862
|
+
self.write(Text(text.ljust(total), style), width=total)
|
|
863
|
+
|
|
864
|
+
def _render_blocks(self, text: str) -> None:
|
|
865
|
+
"""The assistant body: fenced code highlighted, everything else
|
|
866
|
+
plain. Shared by a replayed entry and a committed stream chunk, so
|
|
867
|
+
the two cannot render the same text differently.
|
|
868
|
+
|
|
869
|
+
The newline trimming around a fence is what makes that sharing
|
|
870
|
+
exact rather than approximate. A `Syntax` renderable occupies its own
|
|
871
|
+
rows, so the newline that ends the ``` line is structural, not a
|
|
872
|
+
blank line -- but Rich renders it as an extra empty row when it
|
|
873
|
+
lands at the edge of an adjacent plain block. A streamed answer
|
|
874
|
+
never sees those newlines (they are consumed as the committed
|
|
875
|
+
chunk's own terminator), so without this a replay of the same
|
|
876
|
+
answer grew a blank row per code block, and a /theme mid-session
|
|
877
|
+
reflowed a transcript it was only meant to recolour.
|
|
878
|
+
"""
|
|
879
|
+
blocks = _split_fences(text)
|
|
880
|
+
for index, block in enumerate(blocks):
|
|
881
|
+
if isinstance(block, tuple):
|
|
882
|
+
language, code = block
|
|
883
|
+
self.write(Syntax(code, language or "text",
|
|
884
|
+
theme=self._syntax_theme(),
|
|
885
|
+
word_wrap=True,
|
|
886
|
+
indent_guides=False))
|
|
887
|
+
continue
|
|
888
|
+
body = block
|
|
889
|
+
if index and isinstance(blocks[index - 1], tuple) \
|
|
890
|
+
and body.startswith("\n"):
|
|
891
|
+
body = body[1:]
|
|
892
|
+
if index + 1 < len(blocks) and isinstance(blocks[index + 1], tuple) \
|
|
893
|
+
and body.endswith("\n"):
|
|
894
|
+
body = body[:-1]
|
|
895
|
+
self.write(Text(body, self._style("assistant")))
|
|
896
|
+
|
|
897
|
+
def write_user(self, text: str) -> None:
|
|
898
|
+
self.flush_stream()
|
|
899
|
+
self._emit("user", text)
|
|
900
|
+
|
|
901
|
+
def write_system(self, text: str) -> None:
|
|
902
|
+
self.flush_stream()
|
|
903
|
+
self._emit("system", text)
|
|
904
|
+
|
|
905
|
+
def write_error(self, text: str) -> None:
|
|
906
|
+
self.flush_stream()
|
|
907
|
+
self._emit("error", text)
|
|
908
|
+
|
|
909
|
+
def write_role(self, role: str, text: str) -> None:
|
|
910
|
+
"""Write a line in an arbitrary palette role (§26).
|
|
911
|
+
|
|
912
|
+
Exists so the research view can style a pass boundary, a tool call
|
|
913
|
+
and a failed tool differently without Transcript growing a method
|
|
914
|
+
per event kind -- the roles already live in one table, and this is
|
|
915
|
+
the accessor for it.
|
|
916
|
+
"""
|
|
917
|
+
self.flush_stream()
|
|
918
|
+
self._emit(role, text)
|
|
919
|
+
|
|
920
|
+
def write_answer(self, text: str) -> None:
|
|
921
|
+
"""A model answer that did not arrive as a stream (a one-shot turn,
|
|
922
|
+
a research report). Same rendering as a flushed stream, so the two
|
|
923
|
+
do not diverge in label, colour or fence handling."""
|
|
924
|
+
self.flush_stream()
|
|
925
|
+
self._emit("assistant", text)
|
|
926
|
+
|
|
927
|
+
# -- streaming ---------------------------------------------------------
|
|
928
|
+
|
|
929
|
+
def _wrap_width(self, prefix: str = "") -> int:
|
|
930
|
+
"""Usable text columns for one rendered row, or 0 when there is
|
|
931
|
+
nothing to measure.
|
|
932
|
+
|
|
933
|
+
RichLog.write's OWN computation, reproduced rather than
|
|
934
|
+
approximated: it shrinks a renderable to
|
|
935
|
+
`scrollable_content_region.width` and then raises the result to
|
|
936
|
+
`min_width`, which defaults to 78 and is therefore the number that
|
|
937
|
+
actually decides where a line breaks in a sidebar-narrowed
|
|
938
|
+
transcript. Guessing instead (`content_size.width`, minus a column
|
|
939
|
+
for safety) wrapped a streamed answer ~15 columns narrower than the
|
|
940
|
+
same text replayed by rerender() -- so a /theme mid-session visibly
|
|
941
|
+
reflowed the conversation, which is the one thing a pre-wrap must
|
|
942
|
+
not do.
|
|
943
|
+
|
|
944
|
+
A widget has no size before mount and is built bare throughout the
|
|
945
|
+
suite, so the guard is around the measurement itself, for the same
|
|
946
|
+
reason _styles' is.
|
|
947
|
+
"""
|
|
948
|
+
try:
|
|
949
|
+
width = max(self.scrollable_content_region.width, self.min_width)
|
|
950
|
+
except Exception: # noqa: BLE001 -- unmounted; the newline rule alone
|
|
951
|
+
return 0
|
|
952
|
+
width -= len(prefix)
|
|
953
|
+
return width if width >= MIN_WRAP_WIDTH else 0
|
|
954
|
+
|
|
955
|
+
@staticmethod
|
|
956
|
+
def _fence_is_open(text: str) -> bool:
|
|
957
|
+
"""An odd number of ``` means a code fence is still open."""
|
|
958
|
+
return text.count("```") % 2 == 1
|
|
959
|
+
|
|
960
|
+
@staticmethod
|
|
961
|
+
def _split_committable(pending: str, width: int) -> tuple[str, str]:
|
|
962
|
+
"""Split `pending` into (commit now, keep buffered).
|
|
963
|
+
|
|
964
|
+
The two rules from the class docstring. The over-long-token branch
|
|
965
|
+
is the third case they imply: a run of more than one row with no
|
|
966
|
+
space in it (a URL) would otherwise be held until a newline
|
|
967
|
+
arrived, so it is cut at the row boundary -- which is what Rich's
|
|
968
|
+
own wrapping does with a word too long for the line.
|
|
969
|
+
"""
|
|
970
|
+
cut = pending.rfind("\n")
|
|
971
|
+
if cut != -1:
|
|
972
|
+
return pending[:cut + 1], pending[cut + 1:]
|
|
973
|
+
if width and len(pending) > width:
|
|
974
|
+
space = pending.rfind(" ", 0, width + 1)
|
|
975
|
+
if space > 0:
|
|
976
|
+
return pending[:space + 1], pending[space + 1:]
|
|
977
|
+
return pending[:width], pending[width:]
|
|
978
|
+
return "", pending
|
|
979
|
+
|
|
980
|
+
def stream_delta(self, delta: str) -> None:
|
|
981
|
+
self._pending += delta
|
|
982
|
+
self._commit_ready()
|
|
983
|
+
|
|
984
|
+
def _commit_ready(self) -> None:
|
|
985
|
+
"""Write whatever of the pending stream can safely be drawn now.
|
|
986
|
+
|
|
987
|
+
Loops because one delta can make several rows committable at once
|
|
988
|
+
-- a paragraph arriving in one chunk, or a buffer that has been
|
|
989
|
+
held back behind a closing fence.
|
|
990
|
+
"""
|
|
991
|
+
width = self._wrap_width()
|
|
992
|
+
while True:
|
|
993
|
+
chunk, rest = self._split_committable(self._pending, width)
|
|
994
|
+
if not chunk or self._fence_is_open(self._stream_text + chunk):
|
|
995
|
+
return
|
|
996
|
+
self._pending = rest
|
|
997
|
+
self._write_stream_chunk(chunk)
|
|
998
|
+
|
|
999
|
+
def _write_stream_chunk(self, chunk: str) -> None:
|
|
1000
|
+
if not self._stream_open:
|
|
1001
|
+
self.end_thinking()
|
|
1002
|
+
self._open_label()
|
|
1003
|
+
self._entries.append(("assistant", ""))
|
|
1004
|
+
self._stream_open = True
|
|
1005
|
+
self._stream_text += chunk
|
|
1006
|
+
self._entries[-1] = ("assistant", self._stream_text)
|
|
1007
|
+
# Exactly one trailing newline is dropped: the chunk ENDS at a row
|
|
1008
|
+
# boundary, and RichLog already starts a new row per write, so
|
|
1009
|
+
# keeping it would insert a blank row per committed chunk. A chunk
|
|
1010
|
+
# that is only a newline is the blank line between paragraphs and
|
|
1011
|
+
# still has to draw one.
|
|
1012
|
+
body = chunk[:-1] if chunk.endswith("\n") else chunk
|
|
1013
|
+
if body:
|
|
1014
|
+
self._render_blocks(body)
|
|
1015
|
+
else:
|
|
1016
|
+
self.write(Text("", self._style("assistant")))
|
|
1017
|
+
|
|
1018
|
+
def flush_stream(self) -> str:
|
|
1019
|
+
"""Commit whatever is left of the stream and close the span.
|
|
1020
|
+
|
|
1021
|
+
Returns everything the span committed (empty when there was
|
|
1022
|
+
nothing), so the app can track the last response for /copy without
|
|
1023
|
+
keeping a second buffer beside this one. Closes an open thinking
|
|
1024
|
+
span first, which is what gives every write_* path below the right
|
|
1025
|
+
ordering for free.
|
|
1026
|
+
"""
|
|
1027
|
+
self.end_thinking()
|
|
1028
|
+
return self._close_answer()
|
|
1029
|
+
|
|
1030
|
+
def _close_answer(self) -> str:
|
|
1031
|
+
"""flush_stream without the thinking half.
|
|
1032
|
+
|
|
1033
|
+
The split is not cosmetic: _write_thinking_chunk has to close an
|
|
1034
|
+
open ANSWER before it draws, and routing that through flush_stream
|
|
1035
|
+
would re-enter end_thinking at a point where _thinking_pending
|
|
1036
|
+
already holds the remainder of the chunk being committed -- which
|
|
1037
|
+
emits that remainder as a second, standalone thinking entry and
|
|
1038
|
+
then drops it.
|
|
1039
|
+
"""
|
|
1040
|
+
if not self._pending and not self._stream_open:
|
|
1041
|
+
return ""
|
|
1042
|
+
residual, self._pending = self._pending, ""
|
|
1043
|
+
if not self._stream_open:
|
|
1044
|
+
# Nothing reached the screen -- an answer short enough that no
|
|
1045
|
+
# commit boundary was ever crossed. Rendered through _emit so
|
|
1046
|
+
# it is byte-identical to write_answer's one-shot path.
|
|
1047
|
+
self._emit("assistant", residual)
|
|
1048
|
+
return residual
|
|
1049
|
+
if residual:
|
|
1050
|
+
self._stream_text += residual
|
|
1051
|
+
self._entries[-1] = ("assistant", self._stream_text)
|
|
1052
|
+
self._render_blocks(residual)
|
|
1053
|
+
text = self._stream_text
|
|
1054
|
+
self._stream_open = False
|
|
1055
|
+
self._stream_text = ""
|
|
1056
|
+
return text
|
|
1057
|
+
|
|
1058
|
+
# -- thinking (§38) ----------------------------------------------------
|
|
1059
|
+
|
|
1060
|
+
def _write_thinking_open(self) -> None:
|
|
1061
|
+
self.write(Text(f"{THINKING_INDENT}{THINKING_OPEN}",
|
|
1062
|
+
self._style("thinking")))
|
|
1063
|
+
|
|
1064
|
+
def _write_thinking_close(self) -> None:
|
|
1065
|
+
self.write(Text(f"{THINKING_INDENT}{THINKING_CLOSE}",
|
|
1066
|
+
self._style("thinking")))
|
|
1067
|
+
|
|
1068
|
+
def _write_thinking_lines(self, text: str) -> None:
|
|
1069
|
+
"""One bar-prefixed row per source line. The rows are pre-wrapped
|
|
1070
|
+
by the time they arrive here (that is what _wrap_width's prefix
|
|
1071
|
+
argument is for), because RichLog's own soft wrap would put the
|
|
1072
|
+
bar on the first row of a wrapped line and nothing on the rest."""
|
|
1073
|
+
lines = text.split("\n")
|
|
1074
|
+
if lines and lines[-1] == "":
|
|
1075
|
+
lines.pop()
|
|
1076
|
+
for line in lines:
|
|
1077
|
+
self.write(Text(f"{THINKING_INDENT}{THINKING_BAR}{line}",
|
|
1078
|
+
self._style("thinking")))
|
|
1079
|
+
|
|
1080
|
+
def thinking_delta(self, delta: str) -> None:
|
|
1081
|
+
self._thinking_pending += delta
|
|
1082
|
+
width = self._wrap_width(THINKING_INDENT + THINKING_BAR)
|
|
1083
|
+
while True:
|
|
1084
|
+
chunk, rest = self._split_committable(self._thinking_pending, width)
|
|
1085
|
+
if not chunk:
|
|
1086
|
+
return
|
|
1087
|
+
self._thinking_pending = rest
|
|
1088
|
+
self._write_thinking_chunk(chunk)
|
|
1089
|
+
|
|
1090
|
+
def _write_thinking_chunk(self, chunk: str) -> None:
|
|
1091
|
+
if not self._thinking_open:
|
|
1092
|
+
self._close_answer()
|
|
1093
|
+
# §43 (RM1). ABOVE the opening delimiter: on a turn that
|
|
1094
|
+
# thinks before it answers this is where the label is drawn,
|
|
1095
|
+
# and it is the whole point of the change.
|
|
1096
|
+
self._open_label()
|
|
1097
|
+
self._write_thinking_open()
|
|
1098
|
+
self._entries.append(("thinking", ""))
|
|
1099
|
+
self._thinking_open = True
|
|
1100
|
+
self._thinking_text += chunk
|
|
1101
|
+
self._entries[-1] = ("thinking", self._thinking_text)
|
|
1102
|
+
self._write_thinking_lines(chunk)
|
|
1103
|
+
|
|
1104
|
+
def end_thinking(self) -> str:
|
|
1105
|
+
"""Close the thinking span, if one is open. Idempotent: every
|
|
1106
|
+
non-thinking event calls it, and most of them find nothing."""
|
|
1107
|
+
if not self._thinking_open and not self._thinking_pending:
|
|
1108
|
+
return ""
|
|
1109
|
+
residual, self._thinking_pending = self._thinking_pending, ""
|
|
1110
|
+
if not self._thinking_open:
|
|
1111
|
+
self._emit("thinking", residual)
|
|
1112
|
+
self._thinking_text = ""
|
|
1113
|
+
return residual
|
|
1114
|
+
if residual:
|
|
1115
|
+
self._thinking_text += residual
|
|
1116
|
+
self._entries[-1] = ("thinking", self._thinking_text)
|
|
1117
|
+
self._write_thinking_lines(residual)
|
|
1118
|
+
self._write_thinking_close()
|
|
1119
|
+
text = self._thinking_text
|
|
1120
|
+
self._thinking_open = False
|
|
1121
|
+
self._thinking_text = ""
|
|
1122
|
+
return text
|
|
1123
|
+
|
|
1124
|
+
# -- replay ------------------------------------------------------------
|
|
1125
|
+
|
|
1126
|
+
def reset(self) -> None:
|
|
1127
|
+
"""Empty the transcript — screen AND entry log (§27).
|
|
1128
|
+
|
|
1129
|
+
NOT rerender()'s clear(): that one deliberately keeps `_entries` so
|
|
1130
|
+
it can redraw them under a new theme. Resuming a thread has to drop
|
|
1131
|
+
them, or the previous conversation stays on screen (bug 1) and,
|
|
1132
|
+
less visibly, `/copy all` and the next `/theme` replay both keep
|
|
1133
|
+
handing back a thread the session has left.
|
|
1134
|
+
|
|
1135
|
+
The pending stream buffer goes too. A resume cannot happen mid-turn
|
|
1136
|
+
(`_busy` refuses), so anything buffered here belongs to the thread
|
|
1137
|
+
being left. §38's open-span flags go with it for the same reason:
|
|
1138
|
+
a span left open would put the next thread's first chunk into the
|
|
1139
|
+
previous thread's entry.
|
|
1140
|
+
"""
|
|
1141
|
+
self._pending = ""
|
|
1142
|
+
self._stream_open = False
|
|
1143
|
+
self._stream_text = ""
|
|
1144
|
+
self._thinking_pending = ""
|
|
1145
|
+
self._thinking_open = False
|
|
1146
|
+
self._thinking_text = ""
|
|
1147
|
+
# §43 (RM1). Same reasoning as the open-span flags: a label left
|
|
1148
|
+
# in force would make the next thread's first turn the only one
|
|
1149
|
+
# in the session with no `venastine ›`.
|
|
1150
|
+
self._label_in_force = False
|
|
1151
|
+
self._entries.clear()
|
|
1152
|
+
self.clear()
|
|
1153
|
+
|
|
1154
|
+
def rerender(self) -> None:
|
|
1155
|
+
"""Redraw every entry under the current theme.
|
|
1156
|
+
|
|
1157
|
+
RichLog stores rendered segments, not source, so a theme switch
|
|
1158
|
+
cannot restyle what is already on screen -- without this, /theme
|
|
1159
|
+
would leave the session split between two palettes at the exact
|
|
1160
|
+
line the command was typed.
|
|
1161
|
+
"""
|
|
1162
|
+
self.flush_stream()
|
|
1163
|
+
self.clear()
|
|
1164
|
+
# §43 (RM1). The screen is empty, so no label is in force; the
|
|
1165
|
+
# loop below re-derives every one of them from the role sequence
|
|
1166
|
+
# exactly as the live path did.
|
|
1167
|
+
self._label_in_force = False
|
|
1168
|
+
for role, text in self._entries:
|
|
1169
|
+
self._render_entry(role, text)
|
|
1170
|
+
|
|
1171
|
+
def last_answer(self) -> str:
|
|
1172
|
+
"""The most recent answer in this session, or "" (for /copy last).
|
|
1173
|
+
|
|
1174
|
+
DERIVED, not tracked. `_last_response` used to shadow this list
|
|
1175
|
+
from the app, fed by whichever flush site happened to keep
|
|
1176
|
+
flush_stream()'s return value -- and the one that mattered did
|
|
1177
|
+
not: on_loop_event_message flushes at the terminal `final_response`
|
|
1178
|
+
event and discards, so the flush in on_turn_finished found the
|
|
1179
|
+
span already closed and returned "" on every streamed turn. The
|
|
1180
|
+
field then held whatever had last been assigned by another route
|
|
1181
|
+
(a replayed thread's newest answer, a research report) or nothing
|
|
1182
|
+
at all, which is what /copy last handed back.
|
|
1183
|
+
|
|
1184
|
+
Every route already writes its answer here -- a streamed span as
|
|
1185
|
+
one entry updated in place, a one-shot and a report through
|
|
1186
|
+
write_answer, a replay through write_answer per entry -- so
|
|
1187
|
+
reading the entry log is the same answer with no second writer to
|
|
1188
|
+
keep in step. `reset()` is what clears it, which is the per-thread
|
|
1189
|
+
reset §27 AC4 and §43 RM2 already call.
|
|
1190
|
+
|
|
1191
|
+
An empty string when the last answer WAS empty, matching what the
|
|
1192
|
+
field did: /copy then says there is nothing to copy rather than
|
|
1193
|
+
skipping back to an older answer the session has moved past.
|
|
1194
|
+
"""
|
|
1195
|
+
for role, text in reversed(self._entries):
|
|
1196
|
+
if role == "assistant":
|
|
1197
|
+
return text
|
|
1198
|
+
return ""
|
|
1199
|
+
|
|
1200
|
+
def as_text(self, roles: "frozenset[str] | None" = None) -> str:
|
|
1201
|
+
"""The session as plain text, for /copy all and /copy conversation.
|
|
1202
|
+
|
|
1203
|
+
`roles` filters the entry log; None keeps everything, which is
|
|
1204
|
+
what /copy all wants. A parameter rather than a second method, so
|
|
1205
|
+
the label table below stays the only copy -- two renderers of one
|
|
1206
|
+
entry log is the shape §22 spent a section removing from the
|
|
1207
|
+
trace.
|
|
1208
|
+
"""
|
|
1209
|
+
# `diff` is deliberately absent: the canonical block already
|
|
1210
|
+
# opens with the path it describes, so a label would announce
|
|
1211
|
+
# the file twice.
|
|
1212
|
+
labels = {"user": "you", "assistant": "venastine",
|
|
1213
|
+
"thinking": "thinking"}
|
|
1214
|
+
out = []
|
|
1215
|
+
for role, text in self._entries:
|
|
1216
|
+
if roles is not None and role not in roles:
|
|
1217
|
+
continue
|
|
1218
|
+
label = labels.get(role)
|
|
1219
|
+
out.append(f"{label}: {text}" if label else text)
|
|
1220
|
+
return "\n\n".join(out)
|
|
1221
|
+
|
|
1222
|
+
|
|
1223
|
+
def _split_fences(text: str):
|
|
1224
|
+
"""Split markdown into plain strings and (language, code) tuples.
|
|
1225
|
+
|
|
1226
|
+
Deliberately small: this is a renderer, not a markdown parser. An
|
|
1227
|
+
unterminated fence is treated as running to the end of the text, which
|
|
1228
|
+
is the common case mid-stream.
|
|
1229
|
+
"""
|
|
1230
|
+
out = []
|
|
1231
|
+
parts = text.split("```")
|
|
1232
|
+
for i, part in enumerate(parts):
|
|
1233
|
+
if i % 2 == 0:
|
|
1234
|
+
if part:
|
|
1235
|
+
out.append(part)
|
|
1236
|
+
else:
|
|
1237
|
+
language, _, code = part.partition("\n")
|
|
1238
|
+
out.append((language.strip() or None, code))
|
|
1239
|
+
return out
|