synth-code 0.0.1__py3-none-macosx_15_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. synth_code/__init__.py +0 -0
  2. synth_code/account.py +551 -0
  3. synth_code/account_http.py +86 -0
  4. synth_code/account_refusal.py +80 -0
  5. synth_code/accounting.py +148 -0
  6. synth_code/activity_grouping.py +149 -0
  7. synth_code/agent_panels.py +127 -0
  8. synth_code/approvals.py +397 -0
  9. synth_code/blobs.py +31 -0
  10. synth_code/cli.py +734 -0
  11. synth_code/client.py +413 -0
  12. synth_code/composer_delivery.py +139 -0
  13. synth_code/conversation.py +949 -0
  14. synth_code/daemon.py +34 -0
  15. synth_code/edition.py +306 -0
  16. synth_code/enrollment.py +304 -0
  17. synth_code/file_edit_facts.py +10 -0
  18. synth_code/freeze.py +234 -0
  19. synth_code/grant.py +59 -0
  20. synth_code/history.py +140 -0
  21. synth_code/history_generated.py +219 -0
  22. synth_code/history_wire.py +166 -0
  23. synth_code/image_input.py +109 -0
  24. synth_code/image_preview.py +105 -0
  25. synth_code/legacy_history.py +161 -0
  26. synth_code/live_turns.py +171 -0
  27. synth_code/model_picker.py +311 -0
  28. synth_code/native/manifest.json +1 -0
  29. synth_code/native/synth-code-runtime +0 -0
  30. synth_code/native.py +95 -0
  31. synth_code/oauth.py +284 -0
  32. synth_code/operator.py +116 -0
  33. synth_code/pack_source.py +65 -0
  34. synth_code/panel_request.py +291 -0
  35. synth_code/panels.py +40 -0
  36. synth_code/plugin_host.py +459 -0
  37. synth_code/protocol.py +35 -0
  38. synth_code/provider.py +313 -0
  39. synth_code/provider_fault.py +173 -0
  40. synth_code/provider_frames.py +571 -0
  41. synth_code/recommendation.py +324 -0
  42. synth_code/report.py +72 -0
  43. synth_code/research_events.py +44 -0
  44. synth_code/research_trace.py +449 -0
  45. synth_code/rex_view.py +58 -0
  46. synth_code/runtime_refusal.py +108 -0
  47. synth_code/schema/budgets.json +17 -0
  48. synth_code/schema/history-v2.json +1002 -0
  49. synth_code/session.py +291 -0
  50. synth_code/shoal.py +564 -0
  51. synth_code/side_panel.py +309 -0
  52. synth_code/skills.py +269 -0
  53. synth_code/slash.py +425 -0
  54. synth_code/source_view.py +135 -0
  55. synth_code/starter.json +13 -0
  56. synth_code/stdio.py +75 -0
  57. synth_code/stream.py +142 -0
  58. synth_code/subscriptions.py +267 -0
  59. synth_code/synth_authority.py +362 -0
  60. synth_code/synth_extra.py +32 -0
  61. synth_code/terminal.py +817 -0
  62. synth_code/terminal_journal.py +284 -0
  63. synth_code/terminal_layout.py +643 -0
  64. synth_code/terminal_surfaces.py +470 -0
  65. synth_code/terminal_viewport.py +125 -0
  66. synth_code/tool_render.py +86 -0
  67. synth_code/transcript_frames.py +212 -0
  68. synth_code/transcript_placement.py +63 -0
  69. synth_code/transcript_rows.py +456 -0
  70. synth_code/transport.py +243 -0
  71. synth_code/v001_history.py +468 -0
  72. synth_code/view.py +854 -0
  73. synth_code/views/__init__.py +93 -0
  74. synth_code/views/charts.py +196 -0
  75. synth_code/views/curses_adapter.py +116 -0
  76. synth_code/views/engine.py +170 -0
  77. synth_code/views/model.py +226 -0
  78. synth_code/views/primitives.py +270 -0
  79. synth_code/views/tiling.py +124 -0
  80. synth_code-0.0.1.dist-info/METADATA +50 -0
  81. synth_code-0.0.1.dist-info/RECORD +110 -0
  82. synth_code-0.0.1.dist-info/WHEEL +5 -0
  83. synth_code-0.0.1.dist-info/entry_points.txt +6 -0
  84. synth_code-0.0.1.dist-info/licenses/temper/LICENSE-APACHE +190 -0
  85. synth_code-0.0.1.dist-info/licenses/temper/LICENSE-MIT +21 -0
  86. synth_code-0.0.1.dist-info/licenses/temper/SOURCE.json +433 -0
  87. synth_code-0.0.1.dist-info/top_level.txt +2 -0
  88. synth_code_plugins/_sdk/__init__.py +19 -0
  89. synth_code_plugins/_sdk/callback_wire.py +240 -0
  90. synth_code_plugins/_sdk/callbacks.py +317 -0
  91. synth_code_plugins/_sdk/compliance.py +51 -0
  92. synth_code_plugins/_sdk/contracts.py +236 -0
  93. synth_code_plugins/_sdk/discovery.py +75 -0
  94. synth_code_plugins/_sdk/job_binding.py +71 -0
  95. synth_code_plugins/_sdk/lifecycle.py +50 -0
  96. synth_code_plugins/_sdk/lifecycle_generated.py +15 -0
  97. synth_code_plugins/_sdk/manifest.py +269 -0
  98. synth_code_plugins/_sdk/pack.py +332 -0
  99. synth_code_plugins/_sdk/push.py +98 -0
  100. synth_code_plugins/_sdk/records.py +26 -0
  101. synth_code_plugins/_sdk/registry.py +491 -0
  102. synth_code_plugins/_sdk/schemas.py +210 -0
  103. synth_code_plugins/_sdk/sources.py +230 -0
  104. synth_code_plugins/_sdk/surfaces.py +54 -0
  105. synth_code_plugins/_sdk/tools.py +172 -0
  106. synth_code_plugins/_sdk/worker_memory.py +49 -0
  107. synth_code_plugins/core/SKILL.md +6 -0
  108. synth_code_plugins/core/__init__.py +21 -0
  109. synth_code_plugins/core/plugin.toml +44 -0
  110. synth_code_plugins/core/source.py +18 -0
@@ -0,0 +1,949 @@
1
+ """Project the durable run history into terminal conversation rows."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from bisect import bisect_left, bisect_right
7
+ from collections.abc import Iterator
8
+ from dataclasses import dataclass
9
+ from functools import lru_cache
10
+ from itertools import repeat
11
+ from time import perf_counter
12
+ from unicodedata import category
13
+
14
+ from markdown_it import MarkdownIt
15
+ from rich.console import Console
16
+ from rich.markdown import Markdown
17
+ from rich.segment import Segment
18
+ from rich.style import Style
19
+ from rich.theme import Theme
20
+
21
+ from . import approvals
22
+ from .activity_grouping import ToolAnchor, ToolRows
23
+ from .file_edit_facts import is_file_edit
24
+ from .tool_render import tool_rows, width_cells
25
+ from .transcript_frames import MessageCompleted, ToolKind, ToolOutcome
26
+ from .transcript_placement import StreamAnchors, committed_key, live_key, message_key
27
+ from .transcript_rows import Frame, RowPrefix, grouped_frame
28
+ from .view import render_char, sanitize_text
29
+
30
+
31
+ def turn_failure_label(data):
32
+ fault = data.get("fault")
33
+ if fault is not None:
34
+ return fault["label"]
35
+ # Older journals stored only the reason. Their cancellation label is kept
36
+ # so replay preserves the status row shown when the turn originally stopped.
37
+ reason = data.get("reason") or data.get("outcome")
38
+ if reason == "cancel_requested":
39
+ return "Turn stopped"
40
+ return reason or "Turn did not complete"
41
+
42
+
43
+ _MARKDOWN_SYNTAX = re.compile(
44
+ r"[`*_]|~~|\]\(|^ {0,3}(?:\||#{1,6} |[>+-] |\d+[.)] )",
45
+ re.MULTILINE,
46
+ )
47
+ _MARKDOWN_CONSOLE = Console(
48
+ theme=Theme(
49
+ {
50
+ "markdown.code": Style(meta={"code": True}),
51
+ "markdown.table.header": Style(bold=True),
52
+ }
53
+ )
54
+ )
55
+
56
+
57
+ @lru_cache(maxsize=128)
58
+ def _markdown_rows(text: str, width: int) -> tuple[tuple[Segment, ...], ...]:
59
+ """Render styled Markdown and fit every row to the curses cell budget."""
60
+ reply = Markdown(sanitize_text(text), hyperlinks=False)
61
+ options = _MARKDOWN_CONSOLE.options.update(width=width)
62
+ return tuple(
63
+ fitted
64
+ for line in _MARKDOWN_CONSOLE.render_lines(reply, options, pad=False)
65
+ for fitted in _fit_markdown_line(line, width)
66
+ )
67
+
68
+
69
+ def _fit_markdown_line(line: list[Segment], width: int) -> Iterator[tuple[Segment, ...]]:
70
+ # Rich measures grapheme clusters, while curses lays out scalar cells.
71
+ # Reflow any overflow without dropping characters or styles at the edge.
72
+ visible = tuple(segment for segment in line if not segment.control and segment.text)
73
+ if sum(width_cells(segment.text) for segment in visible) <= width:
74
+ yield visible
75
+ return
76
+ row = []
77
+ used = 0
78
+ for text, style, _ in visible:
79
+ chunk = []
80
+ for char in text:
81
+ cells = _cells(char)
82
+ if cells > width:
83
+ char, cells = "\N{REPLACEMENT CHARACTER}", 1
84
+ if used + cells > width:
85
+ if chunk:
86
+ row.append(Segment("".join(chunk), style))
87
+ yield tuple(row)
88
+ row, chunk, used = [], [], 0
89
+ chunk.append(char)
90
+ used += cells
91
+ if chunk:
92
+ row.append(Segment("".join(chunk), style))
93
+ yield tuple(row)
94
+
95
+
96
+ def _cells(char):
97
+ """Terminal cells for one character, measured exactly as the curses painter does."""
98
+ return render_char(char)[1]
99
+
100
+
101
+ def _cells_of(text):
102
+ return sum(_cells(char) for char in text)
103
+
104
+
105
+ def _wrapped(text, width):
106
+ """Preserve explicit line breaks and indentation while wrapping to cells."""
107
+ for line in sanitize_text(text, expand_tabs=False).split("\n"):
108
+ row = []
109
+ used = 0
110
+ for segment in re.findall(r"[^ ]+|[ ]+", line):
111
+ segment_width = sum(map(_cells, segment))
112
+ if (
113
+ row
114
+ and not segment.isspace()
115
+ and segment_width <= width
116
+ and used + segment_width > width
117
+ ):
118
+ yield "".join(row)
119
+ row = []
120
+ used = 0
121
+ for char in segment:
122
+ if char == "\t":
123
+ chunk = " " * (4 - used % 4)
124
+ elif category(char) in {"Cc", "Cs", "Zl", "Zp"}:
125
+ chunk = "\N{REPLACEMENT CHARACTER}"
126
+ else:
127
+ chunk = char
128
+ for item in chunk:
129
+ cells = _cells(item)
130
+ if used + cells > width:
131
+ if row:
132
+ yield "".join(row)
133
+ row = []
134
+ used = 0
135
+ if cells > width:
136
+ item, cells = "�", 1
137
+ row.append(item)
138
+ used += cells
139
+ yield "".join(row)
140
+
141
+
142
+ class UnsequencedEvent(ValueError):
143
+ """A history event arrived without the integer `seq` that history-v2 DurableEvent requires."""
144
+
145
+ code = "conversation.event_unsequenced"
146
+
147
+ def __init__(self, kind: object) -> None:
148
+ self.kind = kind
149
+ super().__init__(f"{self.code}: {kind!r} event has no integer seq")
150
+
151
+
152
+ @dataclass(frozen=True, slots=True)
153
+ class TurnPresentation:
154
+ role: str | None
155
+ structured_output: bool
156
+ owner_input: bool
157
+
158
+
159
+ @dataclass(frozen=True, slots=True)
160
+ class NodePresentation:
161
+ node_class: str
162
+ opened_by: ToolAnchor | None
163
+
164
+
165
+ def _actor(role, node: NodePresentation | None):
166
+ normalized = role.casefold() if isinstance(role, str) else ""
167
+ if normalized == "side":
168
+ return "side", "Side agent"
169
+ if normalized in {"", "core"}:
170
+ return "core", "Agent"
171
+ if node is not None and node.node_class == "side":
172
+ return "side", f"Side agent · {role}"
173
+ if normalized == "swarm-dispatch":
174
+ return "agent", "Hosted swarm"
175
+ return "agent", f"Subagent · {role}"
176
+
177
+
178
+ class ConversationProjection:
179
+ """Resumable fold of an ordered run history into transcript blocks.
180
+
181
+ `observe` folds one event. `rows` reuses width-specific rows of unchanged blocks.
182
+ """
183
+
184
+ def __init__(self, *, core_only: bool = False, stream_anchors: StreamAnchors | None = None) -> None:
185
+ self.core_only = core_only
186
+ # A projection built from history alone has no live streams to anchor to.
187
+ self.stream_anchors = stream_anchors if stream_anchors is not None else StreamAnchors()
188
+ self.blocks = []
189
+ self._block_sequences = []
190
+ # Ascending placement key per block (see transcript_placement).
191
+ self._block_keys = []
192
+ self.completed_messages = set()
193
+ self._next_message_index = {}
194
+ self.tool_indices = {}
195
+ self._tool_keys = {}
196
+ self.tool_rows = {}
197
+ self.activity_group_rows = {}
198
+ self.block_rows = {}
199
+ self.tool_links = {}
200
+ self.tools_by_block = {}
201
+ self.tool_files = {}
202
+ self.protected_tools = set()
203
+ self.nodes: dict[str, NodePresentation] = {}
204
+ self.turns: dict[str, TurnPresentation] = {}
205
+ self.effect_targets = {}
206
+ self.slash_steers = set()
207
+ self._rendered: dict[int, _RenderedBlock] = {}
208
+ # Blocks on stand-in rows (or no rows) the viewport needs soon; drives frames.
209
+ self._stale = 0
210
+ self._retained = False
211
+ # Every block on stand-in rows or none; old ones wait until the viewport nears.
212
+ self._pending = 0
213
+ self._dirty = 0
214
+ self._live_start = None
215
+ # First block whose frame rows are final at the frame's width (None: unknown).
216
+ self._seam = None
217
+ self._frame = Frame()
218
+ self._overlay = None
219
+
220
+ def _add(self, style, speaker, text):
221
+ if isinstance(text, str) and text.strip():
222
+ self.blocks.append((style, speaker, [text]))
223
+
224
+ def _actor_for(self, role):
225
+ return _actor(role, self.nodes.get(role))
226
+
227
+ def _show_turn(self, identity, role):
228
+ turn = self.turns.get(identity)
229
+ return not self.core_only or self._actor_for(role)[0] == "core" or bool(turn and turn.owner_input)
230
+
231
+ def observe(self, event) -> None:
232
+ sequence = event.get("seq")
233
+ if not isinstance(sequence, int) or isinstance(sequence, bool):
234
+ raise UnsequencedEvent(event.get("kind"))
235
+ before = len(self.blocks)
236
+ self._observe(event)
237
+ if added := len(self.blocks) - before:
238
+ self._block_sequences.extend([sequence] * added)
239
+ self._block_keys.extend([committed_key(sequence)] * added)
240
+ if event["kind"] == "message.completed":
241
+ anchor = self.stream_anchors.anchor(event["turn"], event["payload"]["message_id"])
242
+ self._place_last(message_key(anchor, sequence))
243
+
244
+ def _place_last(self, key: int) -> None:
245
+ """Move the newest block to `key`'s place among the blocks committed since."""
246
+ last = len(self.blocks) - 1
247
+ self._block_keys[last] = key
248
+ position = bisect_right(self._block_keys, key, 0, last)
249
+ if position == last:
250
+ return
251
+ for items in (self.blocks, self._block_sequences, self._block_keys):
252
+ items.insert(position, items.pop())
253
+
254
+ def moved(index: int) -> int:
255
+ if index == last:
256
+ return position
257
+ return index + 1 if index >= position else index
258
+
259
+ self.tool_indices = {tool: moved(block) for tool, block in self.tool_indices.items()}
260
+ self._tool_keys = {moved(block): tool for block, tool in self._tool_keys.items()}
261
+ self.tools_by_block = {moved(block): tool for block, tool in self.tools_by_block.items()}
262
+ self.tool_links = {moved(block): link for block, link in self.tool_links.items()}
263
+ self.tool_files = {moved(block): paths for block, paths in self.tool_files.items()}
264
+ self._rendered = {moved(block): rendered for block, rendered in self._rendered.items()}
265
+ self.protected_tools = {moved(block) for block in self.protected_tools}
266
+ self._dirty = min(self._dirty, position)
267
+
268
+ def _observe(self, event) -> None:
269
+ kind = event["kind"]
270
+ data = event["payload"]
271
+ identity = event.get("turn") or data.get("id")
272
+ turn = self.turns.get(identity)
273
+ role = data.get("role") or (turn.role if turn is not None else event.get("actor"))
274
+ if kind in {"message.completed", "reasoning.summary", "tool.started", "tool.finished", "file.changed", "turn.finished"}:
275
+ self._observe_transcript(event)
276
+ elif kind == "node.opened":
277
+ node = data["node"]
278
+ opened_by = None
279
+ if data.get("opened_by_turn") and data.get("tool_id"):
280
+ opened_by = ToolAnchor(event["run"], data["opened_by_turn"], data["tool_id"])
281
+ self.nodes[node] = NodePresentation(data["class"], opened_by)
282
+ elif kind == "turn.reserved":
283
+ cause = event.get("cause_ref") or {}
284
+ self.turns[identity] = TurnPresentation(
285
+ role,
286
+ data.get("output_contract") in {"advice_json", "file_json"},
287
+ cause.get("kind") == "input",
288
+ )
289
+ elif self.core_only and kind == "terminal.command":
290
+ return
291
+ elif kind == "terminal.command" and data.get("summary", "").split(" ", 1)[
292
+ 0
293
+ ] in ("/model", "/providers"):
294
+ text = data["summary"] + (
295
+ " " + data["outcome"] if data.get("outcome") else ""
296
+ )
297
+ self._add("setting", "", text)
298
+ elif (
299
+ kind == "core.steer.requested"
300
+ and not data.get("source")
301
+ and data.get("operation") not in self.slash_steers
302
+ ):
303
+ self._add("user", "You", data.get("summary"))
304
+ elif kind == "input.received":
305
+ if data.get("delivery") == "turn_only" and (
306
+ data.get("from") != "owner" or data.get("operation") in self.slash_steers
307
+ ):
308
+ return
309
+ change = event.get("history_change")
310
+ block = change["upsert"] if change else data
311
+ text = "\n".join(part["text"] for part in block["parts"] if part["type"] == "text")
312
+ self._add("user", "You", text)
313
+ elif kind in {
314
+ "terminal.command",
315
+ "user.message",
316
+ "user.steer",
317
+ }:
318
+ if kind == "terminal.command" and data.get("summary", "").startswith(
319
+ "/steer "
320
+ ):
321
+ self.slash_steers.add(data.get("operation"))
322
+ self._add("user", "You", data.get("summary"))
323
+ elif kind == "side.recommendation" and not self.core_only:
324
+ self._add("side", "Side agent", data.get("summary"))
325
+ elif kind == "agent.message":
326
+ style, sender = self._actor_for(data.get("from"))
327
+ recipient = data.get("to")
328
+ addressed_to_you = recipient in {"owner", "user"}
329
+ if style == "side" and (not self.core_only or addressed_to_you):
330
+ destination = "You" if addressed_to_you else self._actor_for(recipient)[1]
331
+ self._add(style, f"{sender} → {destination}", data.get("summary"))
332
+ elif self.core_only and kind in {
333
+ "core.notification.requested", "notification.requested",
334
+ "core.user.notified",
335
+ }:
336
+ self._add("side", "Side agent → You", data.get("summary"))
337
+ elif kind == "config.changed" and data["field"] == "model" and not self.core_only:
338
+ scope, model = data["scope"], data["to"]
339
+ self._add(
340
+ "status",
341
+ self._actor_for(scope["role"])[1],
342
+ "Model · " + " ".join(filter(None, (model["model"] or "provider default", model["effort"]))),
343
+ )
344
+ elif kind == "context.compacted" and (
345
+ not self.core_only or self._actor_for(role)[0] == "core"
346
+ ):
347
+ before, after = data["estimated_tokens_before"], data["estimated_tokens_after"]
348
+ self._add("divider", "", f"Context compacted · {before:,}→{after:,} tokens")
349
+ elif is_file_edit(event):
350
+ if kind == "effect.proposed":
351
+ self._add("user", "You", data.get("summary"))
352
+ elif self._show_turn(identity, role):
353
+ self._add("error", "Edit rejected", data.get("fault"))
354
+ elif kind == "effect.proposed":
355
+ effect = data.get("effect")
356
+ target = data.get("target")
357
+ if effect and target:
358
+ self.effect_targets[effect] = target
359
+ self._add("approval", "Approval required", target or effect)
360
+ elif kind in {"effect.approved", "effect.denied"} or (
361
+ kind in approvals.DECISION_EVENT_KINDS and self._show_turn(identity, role)
362
+ ):
363
+ decision = approvals.decision(event, self.effect_targets)
364
+ self._add("status", decision.verdict, decision.detail())
365
+ elif kind in {
366
+ "effect.succeeded",
367
+ "effect.refused",
368
+ "effect.in_doubt",
369
+ "effect.reconciled",
370
+ }:
371
+ effect = data.get("effect")
372
+ status = {
373
+ "effect.succeeded": "Effect completed",
374
+ "effect.refused": "Effect refused",
375
+ "effect.in_doubt": "Effect unresolved",
376
+ "effect.reconciled": {
377
+ "succeeded": "Effect completed",
378
+ "refused": "Effect refused",
379
+ "definitely_absent": "Approved",
380
+ }.get(data.get("result"), "Effect unresolved"),
381
+ }[kind]
382
+ self._add("status", status, self.effect_targets.get(effect, effect))
383
+ elif (
384
+ kind == "side.intervention.unresolved"
385
+ and not self.core_only
386
+ and self._show_turn(identity, role)
387
+ ):
388
+ reason = data.get("reason") or data.get("outcome")
389
+ self._add("error", "Side agent intervention unresolved", reason)
390
+
391
+
392
+ def _observe_transcript(self, event) -> None:
393
+ kind, identity, data = event["kind"], event["turn"], event["payload"]
394
+ change = event.get("history_change")
395
+ row = change["upsert"] if change else None
396
+ turn = self.turns.get(identity)
397
+ role = data.get("role") or (turn.role if turn is not None else event.get("actor"))
398
+ if kind == "turn.finished":
399
+ self._next_message_index.pop(identity, None)
400
+ if not self._show_turn(identity, role):
401
+ return
402
+ if kind == "message.completed":
403
+ message = MessageCompleted.decode(row if row is not None else data)
404
+ expected = self._next_message_index.get(identity, message.index)
405
+ key = (identity, message.message_id)
406
+ if message.index != expected or key in self.completed_messages:
407
+ raise ValueError(f"Out-of-order completed message {message.message_id} in turn {identity}")
408
+ self._next_message_index[identity] = expected + 1
409
+ self.completed_messages.add(key)
410
+ if turn is None or not turn.structured_output:
411
+ self._add(*self._actor_for(role), message.text)
412
+ elif kind == "reasoning.summary":
413
+ self._add("activity", "", (row if row is not None else data)["text"])
414
+ elif kind == "tool.started":
415
+ start = row if row is not None else data
416
+ tool_id = start["tool_id"]
417
+ kind = ToolKind(start["tool_kind"] if row is not None else start["kind"])
418
+ block = self._start_tool(identity, tool_id, start["target"], event["seq"])
419
+ run = event.get("run")
420
+ if run is not None:
421
+ anchor = ToolAnchor(run, identity, tool_id)
422
+ parent_tool_id = start.get("parent_tool_id")
423
+ node = self.nodes.get(role)
424
+ parent = (
425
+ ToolAnchor(run, identity, parent_tool_id)
426
+ if parent_tool_id else (node.opened_by if node is not None else None)
427
+ )
428
+ self.tool_links[block] = (anchor, kind, parent)
429
+ if data.get("pin"):
430
+ self.protected_tools.add(block)
431
+ if row is not None and row["finish"] is not None:
432
+ self._finish_tool(block, row["finish"], event["seq"])
433
+ elif kind == "tool.finished":
434
+ key = (identity, data["tool_id"])
435
+ block = self.tool_indices.get(key)
436
+ if block is None:
437
+ # A settled tool can start before the display page.
438
+ if row is None:
439
+ raise ValueError(f"Tool {key[1]} finished without a start in turn {identity}")
440
+ return
441
+ self._finish_tool(block, row["finish"] if row is not None else data, event["seq"])
442
+ elif kind == "file.changed":
443
+ block = self.tool_indices.get((identity, data.get("tool_id")))
444
+ if block is not None:
445
+ paths = self.tool_files.get(block, ())
446
+ path = data["path"]
447
+ if data.get("rename_to"):
448
+ path = f"{path} → {data['rename_to']}"
449
+ if len(paths) < 8 and path not in paths:
450
+ self.tool_files[block] = (*paths, path)
451
+ self._dirty = min(self._dirty, block)
452
+ elif kind == "turn.finished":
453
+ outcome = data["outcome"]
454
+ match outcome["kind"]:
455
+ case "cancelled":
456
+ self._add("status", self._actor_for(role)[1], (data.get("fault") or {}).get("label", "Turn stopped"))
457
+ case "failed":
458
+ self._add("error", self._actor_for(role)[1], turn_failure_label(data))
459
+
460
+ def _start_tool(self, identity, tool_id, target, sequence):
461
+ key = (identity, tool_id)
462
+ if key in self.tool_indices:
463
+ raise ValueError(f"Duplicate tool start {tool_id} in turn {identity}")
464
+ block = len(self.blocks)
465
+ self.tool_indices[key] = block
466
+ self._tool_keys[block] = key
467
+ self.blocks.append(("tool", "", [target]))
468
+ self.tools_by_block[block] = identity, {
469
+ "target": target, "state": "running", "exit_code": None,
470
+ "duration_ms": None, "preview": (), "omitted_lines": 0,
471
+ }, sequence
472
+ return block
473
+
474
+ def _finish_tool(self, block, finish, sequence) -> None:
475
+ self._dirty = min(self._dirty, block)
476
+ identity, tool, _ = self.tools_by_block[block]
477
+ state = ToolOutcome(finish["outcome"])
478
+ if finish.get("pin") or finish.get("touched"):
479
+ self.protected_tools.add(block)
480
+ self.tools_by_block[block] = identity, {
481
+ "target": tool["target"], "state": state,
482
+ "exit_code": finish.get("exit_code"), "duration_ms": finish.get("duration_ms"),
483
+ "preview": finish["preview"], "omitted_lines": finish["omitted_lines"],
484
+ }, sequence
485
+
486
+ def _live_rows(self, live_transcript, width):
487
+ pending = {}
488
+ if live_transcript is None:
489
+ return pending
490
+ streams = [
491
+ (stream.order, identity, stream, "message")
492
+ for (identity, _), stream in live_transcript.messages.items()
493
+ ] + [
494
+ (stream.order, identity, stream, "reasoning")
495
+ for (identity, _), stream in live_transcript.reasoning.items()
496
+ ]
497
+ for _, identity, stream, kind in sorted(streams):
498
+ turn = self.turns.get(identity)
499
+ role = turn.role if turn else None
500
+ if not live_transcript.visible(identity) or not self._show_turn(identity, role):
501
+ continue
502
+ if kind == "message" and turn is not None and turn.structured_output:
503
+ continue
504
+ style, speaker = self._actor_for(role) if kind == "message" else ("activity", "")
505
+ for index, parts in self._live_segments(stream):
506
+ block = (style, speaker, parts)
507
+ pending.setdefault(index, []).append(self._render_block(index, block, True, width))
508
+ return pending
509
+
510
+ def _live_segments(self, stream):
511
+ """Split a live stream at every committed block that arrived while it grew."""
512
+ segments = []
513
+ for text, after in zip(stream.parts, stream.part_after):
514
+ index = bisect_right(self._block_keys, live_key(max(after, stream.after)))
515
+ if segments and segments[-1][0] == index:
516
+ segments[-1][1].append(text)
517
+ else:
518
+ segments.append((index, [text]))
519
+ return segments
520
+
521
+ @property
522
+ def rewrapping(self) -> bool:
523
+ """True while some blocks still show rows wrapped for an earlier width."""
524
+ return self._stale > 0
525
+
526
+ @property
527
+ def retained(self) -> bool:
528
+ """True when the last `rows()` call cold-painted or caught up old blocks.
529
+
530
+ Those rows stay held across frames; the frame-loop owner may exempt them from
531
+ full GC passes (`terminal_viewport.retain_rows`). `rows()` itself never does.
532
+ """
533
+ return self._retained
534
+
535
+ def rows(
536
+ self, width: int, rewrap_limit: int | None = None, *, live_transcript=None,
537
+ activity_groups=(), rewrap_from: int | None = None, viewport_rows: int | None = None,
538
+ ):
539
+ """Styled rows for every visible block, reusing rows of unchanged blocks.
540
+
541
+ After a width change, re-wrapping a long history at once stalls the frame,
542
+ and so does the first paint of a long session. With `rewrap_limit`, at most
543
+ that many blocks whose content is unchanged, or never rendered, are rendered
544
+ per call, visible blocks first; deferred ones keep their earlier-width rows, or
545
+ a cheap unstyled draft of their text (the painter clips both), until later calls
546
+ catch up. Never-rendered blocks older than a draft window take no rows at all
547
+ until then, so the first paint does not visit the whole history. Blocks whose content changed always render. Without a limit the result is exact.
548
+
549
+ Only blocks within `_DEMAND_SCREENS` screens of `viewport_rows` around the
550
+ viewport (the bottom, or the `rewrap_from` block) catch up; older stand-ins wait
551
+ until the viewport nears them, so idle frames render nothing.
552
+ """
553
+ screen = viewport_rows or _VIEWPORT_ROWS
554
+ width = max(1, width)
555
+ frame = self._frame
556
+ groups = tuple(activity_groups)
557
+ overlays = self._live_rows(live_transcript, width)
558
+ active_tools = {
559
+ self.tool_indices[key]: stream
560
+ for key, stream in live_transcript.tools.items()
561
+ if key in self.tool_indices and live_transcript.visible(key[0])
562
+ } if live_transcript else {}
563
+ live_start = min(min(overlays, default=len(self.blocks)), min(active_tools, default=len(self.blocks)))
564
+ start = min(self._dirty, frame.count, live_start)
565
+ if self._live_start is not None:
566
+ start = min(start, self._live_start)
567
+ reusable = start
568
+ resizing = frame.width != width or self._pending
569
+ if resizing:
570
+ start = 0
571
+ anchor = (
572
+ None if rewrap_from is None
573
+ else bisect_left(self._block_keys, committed_key(rewrap_from))
574
+ )
575
+ demand = self._demand(frame, anchor, screen)
576
+ # Catch-up renders (blocks the previous frame already held, content unchanged)
577
+ # run in viewport-priority order and stop once the frame has spent its catch-up
578
+ # time; appended or changed blocks always render.
579
+ self._catch_up = (frame.count, perf_counter() + _CATCH_UP_SECONDS)
580
+ self._caught_up = 0
581
+ cold, deferred = self._deferred(width, rewrap_limit, anchor, demand) if resizing else (0, ())
582
+ deferred = set(deferred)
583
+ if cold > live_start:
584
+ # Live rows anchor inside the cold range: those blocks draft as before.
585
+ deferred = {*deferred, *range(live_start, cold)}
586
+ cold = live_start
587
+ self._live_start = live_start if overlays or active_tools else None
588
+ seam = max(cold, max(deferred, default=-1) + 1)
589
+ # Catch-up at an unchanged width renders only the head below the seam; the
590
+ # blocks from the seam up keep their rows, spliced back in when the state the
591
+ # seam block's rows depend on (rows above it, previous style) is unchanged.
592
+ splice = (
593
+ max(seam, self._seam) if resizing and not groups and self._seam is not None
594
+ and frame.width == width else None
595
+ )
596
+ if splice is not None and not (
597
+ 0 < splice < reusable and frame.checkpoints[splice][0] > 0
598
+ and self._block_sequences[splice - 1] != self._block_sequences[splice]
599
+ ):
600
+ splice = None
601
+ self._seam = seam
602
+ if splice is not None:
603
+ earlier = frame.detach()
604
+ previous_style = frame.checkpoints[0][1]
605
+ else:
606
+ row_start, previous_style = frame.checkpoints[start]
607
+ frame.rewind(start, row_start)
608
+ frame.width = width
609
+ rows = frame.rows
610
+ if start < cold:
611
+ # Never-rendered blocks below the budget take no rows and no per-block work
612
+ # this frame: positions are recorded in bulk, rows arrive as frames catch up.
613
+ frame.blocks.extend(zip(self._block_sequences[start:cold], repeat(None)))
614
+ frame.checkpoints.extend(repeat((len(rows), previous_style), cold - start))
615
+ start = cold
616
+ # The first rendered block keeps the separator a cold predecessor will need.
617
+ lead = not rows and any(block[2] and "".join(block[2]).strip() for block in self.blocks[max(0, cold - 1):cold])
618
+ previous_style = self.blocks[cold - 1][0] if lead else previous_style
619
+ else:
620
+ lead = False
621
+ stop = len(self.blocks) if splice is None else splice
622
+ for index in range(start, stop):
623
+ previous_style, lead = self._emit_block(
624
+ index, frame, width, previous_style, lead, overlays, deferred, active_tools,
625
+ )
626
+ if splice is not None:
627
+ row, style = earlier.checkpoints[splice]
628
+ resume = splice
629
+ if len(rows) and style == previous_style:
630
+ frame.splice(earlier, splice, reusable)
631
+ previous_style = frame.checkpoints[-1][1]
632
+ resume = reusable
633
+ for index in range(resume, len(self.blocks)):
634
+ previous_style, lead = self._emit_block(
635
+ index, frame, width, previous_style, lead, overlays, deferred, active_tools,
636
+ )
637
+ for style, live_rows in overlays.get(len(self.blocks), ()):
638
+ previous_style = _extend_rows(rows, previous_style, style, live_rows)
639
+ self._dirty = len(self.blocks)
640
+ self._pending = cold + len(deferred)
641
+ low, high = self._demand(frame, anchor, screen)
642
+ self._stale = sum(low <= index < high for index in deferred) + max(0, min(cold, high) - low)
643
+ self._retained = bool(cold or self._caught_up)
644
+
645
+ if groups:
646
+ projected, self.block_rows, self.tool_rows, self.activity_group_rows = grouped_frame(
647
+ frame, groups, width,
648
+ )
649
+ self._overlay = projected
650
+ return projected
651
+ self._overlay = None
652
+ self.block_rows, self.tool_rows = frame.block_rows, frame.tool_rows
653
+ self.activity_group_rows = {}
654
+ return RowPrefix(rows)
655
+
656
+ def _emit_block(self, index, frame, width, previous_style, lead, overlays, deferred, active_tools):
657
+ """Append block `index`'s rows and position records to `frame`."""
658
+ rows = frame.rows
659
+ block = self.blocks[index]
660
+ for style, live_rows in overlays.get(index, ()):
661
+ previous_style = _extend_rows(rows, previous_style, style, live_rows)
662
+ parts = block[2]
663
+ rendered = self._rendered.get(index)
664
+ token = self._validity(index, block)
665
+ if index in deferred:
666
+ if rendered is None:
667
+ rendered = _RenderedBlock(
668
+ block, len(parts), False, None, token, *_draft_block(block),
669
+ )
670
+ self._rendered[index] = rendered
671
+ elif rendered is None or not rendered.matches(block, len(parts), False, width, token):
672
+ rendered = _RenderedBlock(
673
+ block, len(parts), False, width, token,
674
+ *self._render_block(index, block, False, width),
675
+ )
676
+ self._rendered[index] = rendered
677
+ start_row = len(rows)
678
+ if (active := active_tools.get(index)) is not None:
679
+ _, tool, sequence = self.tools_by_block[index]
680
+ preview_rows = tool_rows(
681
+ {**tool, "preview": "".join(active.parts).splitlines()},
682
+ width, sequence, self.tool_files.get(index, ()),
683
+ )
684
+ previous_style = _extend_rows(rows, previous_style, "tool", preview_rows, lead)
685
+ else:
686
+ previous_style = _extend_rows(rows, previous_style, rendered.style, rendered.rows, lead)
687
+ lead = lead and start_row == len(rows)
688
+ sequence = self._block_sequences[index]
689
+ key = self._tool_keys.get(index)
690
+ if start_row < len(rows):
691
+ frame.set_block(sequence, start_row, len(rows))
692
+ if key is not None:
693
+ if rows[start_row][0] == "blank":
694
+ start_row += 1
695
+ frame.tool_rows[key] = start_row
696
+ if link := self.tool_links.get(index):
697
+ anchor, kind, parent = link
698
+ _, tool, _ = self.tools_by_block[index]
699
+ success = (
700
+ tool["state"] == ToolOutcome.COMPLETED and tool["exit_code"] in (None, 0)
701
+ and index not in self.tool_files and index not in self.protected_tools
702
+ )
703
+ frame.set_tool(index, ToolRows(anchor, parent, kind, success, start_row, len(rows)))
704
+ frame.blocks.append((sequence, key))
705
+ frame.checkpoints.append((len(rows), previous_style))
706
+ return previous_style, lead
707
+
708
+ def viewport_anchor(self, offset):
709
+ index = self._overlay.base_index(offset) if self._overlay is not None else offset
710
+ while (sequence := self._frame.anchor_at(index)) is not None:
711
+ if (span := self.block_rows.get(sequence)) is not None:
712
+ start, stop = span
713
+ return sequence, min(offset, stop - 1) - start
714
+ original_start, _ = self._frame.block_rows[sequence]
715
+ index = self._overlay.previous_visible_base(original_start - 1)
716
+ return None
717
+
718
+ def _demand(self, frame, anchor, screen):
719
+ """Block range `[low, high)` within `_DEMAND_SCREENS` screens of the viewport.
720
+
721
+ Positions come from `frame`; blocks past its end are new and in demand when the
722
+ range reaches the end. Leading blocks without rows join only once the range
723
+ reaches the top row.
724
+ """
725
+ count = len(self.blocks)
726
+ marks = frame.checkpoints
727
+ known = min(frame.count, count)
728
+ if known == 0:
729
+ return 0, count
730
+ total = marks[known][0]
731
+ top = marks[anchor][0] if anchor is not None and anchor < known else max(0, total - screen)
732
+ reach = _DEMAND_SCREENS * screen
733
+ ends = [mark[0] for mark in marks[1 : known + 1]]
734
+ low = bisect_right(ends, top - reach)
735
+ high = bisect_left([mark[0] for mark in marks[:known]], top + screen + reach)
736
+ return low, count if high >= known else high
737
+
738
+ def _deferred(self, width, budget, anchor, demand):
739
+ """Blocks kept on stand-in rows this frame: `(cold, deferred)`.
740
+
741
+ `cold` counts the leading blocks never rendered that miss both the budget and the
742
+ draft window; they are left out of the frame whole, so a first paint costs the
743
+ budget plus the window, not the history.
744
+ `deferred` holds the other blocks that keep earlier-width or draft rows.
745
+ """
746
+ if budget is None:
747
+ return 0, ()
748
+ deferred = set()
749
+ count = len(self.blocks)
750
+ # Every block below the lowest rendered index has never been rendered.
751
+ floor = min(self._rendered, default=count)
752
+ low, high = demand
753
+ if anchor is None:
754
+ ascending, descending = (), range(count - 1, -1, -1)
755
+ else:
756
+ ascending, descending = range(anchor, count), range(anchor - 1, -1, -1)
757
+ for index in ascending:
758
+ if index >= high:
759
+ self._defer(index, width, 0, deferred)
760
+ else:
761
+ budget = self._defer(index, width, budget, deferred)
762
+ window = _DRAFT_WINDOW
763
+ for index in descending:
764
+ if index < low:
765
+ # Out of the viewport's reach: never-rendered blocks stay cold, the rest
766
+ # keep their stand-in rows, and none of them cost render work.
767
+ if index < floor:
768
+ return index + 1, deferred
769
+ self._defer(index, width, 0, deferred)
770
+ continue
771
+ if budget <= 0 and index < floor:
772
+ # Draft a screenful-plus below the rendered tail so a short tail still
773
+ # fills the viewport; everything older stays cold.
774
+ if window <= 0:
775
+ return index + 1, deferred
776
+ window -= 1
777
+ budget = self._defer(index, width, budget, deferred)
778
+ return 0, deferred
779
+
780
+ def _defer(self, index, width, budget, deferred):
781
+ block = self.blocks[index]
782
+ rendered = self._rendered.get(index)
783
+ if rendered is not None and (
784
+ rendered.width == width
785
+ or not rendered.same_content(block, len(block[2]), False, self._validity(index, block))
786
+ ):
787
+ return budget
788
+ # Never rendered (a first paint), or unchanged content wrapped for another width.
789
+ if budget > 0:
790
+ held, deadline = self._catch_up
791
+ if index < held and self._caught_up and perf_counter() > deadline:
792
+ deferred.add(index)
793
+ return 0
794
+ # Render now, in priority order; the frame below reuses these rows.
795
+ token = self._validity(index, block)
796
+ self._rendered[index] = _RenderedBlock(
797
+ block, len(block[2]), False, width, token,
798
+ *self._render_block(index, block, False, width),
799
+ )
800
+ self._caught_up += 1
801
+ return budget - 1
802
+ deferred.add(index)
803
+ return budget
804
+
805
+ def _validity(self, index, block):
806
+ """Inputs besides the block itself that its rows depend on."""
807
+ if block[0] == "tool":
808
+ _, tool, sequence = self.tools_by_block[index]
809
+ return sequence, tool, self.tool_files.get(index)
810
+ return None
811
+
812
+ def _render_block(self, index, block, live, width):
813
+ """Return style and rows for one block."""
814
+ style, speaker, parts = block
815
+ text = "".join(parts)
816
+ if not text.strip():
817
+ return style, ()
818
+ if style == "tool":
819
+ _, tool, sequence = self.tools_by_block[index]
820
+ return style, tuple(tool_rows(tool, width, sequence, self.tool_files.get(index, ())))
821
+ if style == "divider":
822
+ label = f"── {text} "
823
+ if _cells_of(label) >= width:
824
+ return style, tuple(("muted", line) for line in _wrapped(text, width))
825
+ return style, (("muted", label + "─" * (width - _cells_of(label))),)
826
+ if style == "activity":
827
+ prefix = "· "
828
+ elif self.core_only:
829
+ prefix = f"{speaker} · " if style in {"approval", "status", "error"} and speaker else ""
830
+ else:
831
+ prefix = f"{speaker} › " if speaker else "› "
832
+ plain = "muted" if style in {"setting", "activity"} else style
833
+ if self.core_only and style in {"core", "side", "agent"}:
834
+ settled, tail = _settled_markdown(text) if live else (text, "")
835
+ if _MARKDOWN_SYNTAX.search(settled):
836
+ rows = [(style, line) for line in _markdown_rows(settled, width)]
837
+ if tail.strip():
838
+ if rows:
839
+ rows.append((style, ""))
840
+ rows.extend((plain, line) for line in _wrapped(prefix + tail, width))
841
+ return style, tuple(rows)
842
+ return style, tuple((plain, line) for line in _wrapped(prefix + text, width))
843
+
844
+
845
+ # Never-rendered blocks below the frame budget that still get a one-row draft, so a
846
+ # tail of short blocks fills any terminal height on the first frame (one row each).
847
+ _DRAFT_WINDOW = 256
848
+ # Screens above and below the viewport whose blocks catch up; farther ones wait.
849
+ _DEMAND_SCREENS = 2
850
+ # Wall-clock spent on catch-up renders per frame; at least one block always renders.
851
+ _CATCH_UP_SECONDS = 0.05
852
+ # Viewport height assumed when the caller does not say.
853
+ _VIEWPORT_ROWS = 50
854
+
855
+
856
+ def _draft_block(block):
857
+ """One unstyled row standing in for a block until its first render.
858
+
859
+ Only blocks outside the viewport are drafted, so a cold paint costs one short
860
+ row per older block, not a Markdown render; the painter clips the row.
861
+ """
862
+ style, _, parts = block
863
+ text = "".join(parts).strip()
864
+ if not text:
865
+ return style, ()
866
+ plain = "muted" if style in {"setting", "activity", "divider"} else style
867
+ return style, ((plain, sanitize_text(text[:512].split("\n", 1)[0], expand_tabs=False)),)
868
+
869
+
870
+ def _extend_rows(rows, previous_style, style, block_rows, lead=False):
871
+ if not block_rows:
872
+ return previous_style
873
+ if (rows or lead) and not (style == previous_style and style in {"setting", "activity", "tool"}):
874
+ rows.append(("blank", ""))
875
+ rows.extend(block_rows)
876
+ return style
877
+
878
+
879
+ class _RenderedBlock:
880
+ """Rows rendered for one block, valid while the block and its inputs are unchanged."""
881
+
882
+ __slots__ = ("block", "live", "part_count", "rows", "style", "token", "width")
883
+
884
+ def __init__(self, block, part_count, live, width, token, style, rows):
885
+ self.block = block
886
+ self.part_count = part_count
887
+ self.live = live
888
+ self.width = width
889
+ self.token = token
890
+ self.style = style
891
+ self.rows = rows
892
+
893
+ def matches(self, block, part_count, live, width, token):
894
+ return self.width == width and self.same_content(block, part_count, live, token)
895
+
896
+ def same_content(self, block, part_count, live, token):
897
+ """True when only the width may differ: the rows are a stale wrap of current content."""
898
+ return (
899
+ self.block is block
900
+ and self.part_count == part_count
901
+ and self.live == live
902
+ and self.token == token
903
+ )
904
+
905
+
906
+ _BLANK_LINE = re.compile(r"^[ \t]*\n", re.MULTILINE)
907
+ _MARKDOWN_PARSER = MarkdownIt().enable("strikethrough").enable("table")
908
+
909
+
910
+ def _settled_markdown(text: str) -> tuple[str, str]:
911
+ """Split after the last completed blank line outside a CommonMark fence."""
912
+ text = sanitize_text(text, expand_tabs=False)
913
+ blank_lines = tuple(_BLANK_LINE.finditer(text))
914
+ if not blank_lines:
915
+ return "", text
916
+ if "```" not in text and "~~~" not in text:
917
+ boundary = blank_lines[-1].end()
918
+ return text[:boundary], text[boundary:]
919
+
920
+ # The parser knows the enclosing list/quote indentation and opener length.
921
+ # A blank line inside a fence belongs to its token's source range.
922
+ fences = [
923
+ token.map
924
+ for token in _MARKDOWN_PARSER.parse(text)
925
+ if token.type == "fence" and token.map is not None
926
+ ]
927
+ line_number = 0
928
+ last_offset = 0
929
+ boundary = 0
930
+ fence_index = 0
931
+ for blank in blank_lines:
932
+ line_number += text.count("\n", last_offset, blank.start())
933
+ last_offset = blank.start()
934
+ while fence_index < len(fences) and fences[fence_index][1] <= line_number:
935
+ fence_index += 1
936
+ if fence_index == len(fences) or line_number < fences[fence_index][0]:
937
+ boundary = blank.end()
938
+ return text[:boundary], text[boundary:]
939
+
940
+
941
+ def conversation_rows(events, width, *, core_only=False, live_transcript=None):
942
+ """Return styled text or Markdown segments for an ordered run history."""
943
+ projection = ConversationProjection(
944
+ core_only=core_only,
945
+ stream_anchors=live_transcript.stream_anchors if live_transcript is not None else None,
946
+ )
947
+ for event in events:
948
+ projection.observe(event)
949
+ return list(projection.rows(width, live_transcript=live_transcript))