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,470 @@
1
+ """Bounded push-to-curses coordination for mounted and inline plugin views."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import curses
6
+ from collections.abc import Callable
7
+ from concurrent.futures import Future
8
+ from enum import Enum
9
+
10
+ from .approvals import ApprovalQueue, ApprovalsUnavailable
11
+ from .edition import Edition, side_agents_available
12
+ from .file_edit_facts import is_file_edit
13
+ from .live_turns import submit, wake_after
14
+ from .plugin_host import SurfaceHost
15
+ from .views import Extent, Slot, ViewFrame
16
+ from .views.tiling import WIDE_COLUMNS
17
+
18
+ _LAYOUT_EVENTS = {
19
+ "approval.requested",
20
+ "approval.resolved",
21
+ "approval.closed",
22
+ "effect.proposed",
23
+ "effect.approved",
24
+ "effect.refused",
25
+ "effect.settled",
26
+ "turn.finished",
27
+ }
28
+ _SOURCE_REQUESTS_MAX = 4
29
+
30
+
31
+ def _approval_event(kind: str) -> bool:
32
+ """Every effect lifecycle step re-syncs the card queue, not just proposals and decisions.
33
+
34
+ A sync that lands between `approve` and `execute` still sees the effect pending (phase
35
+ `approved`); only a later lifecycle event (dispatching/succeeded/settled/...) or the turn's
36
+ end can retract that card, so those must re-sync too.
37
+ """
38
+ return kind.startswith(("effect.", "approval.")) or kind == "turn.finished"
39
+
40
+
41
+ def _fetch_approvals(client) -> ApprovalQueue:
42
+ queue = ApprovalQueue()
43
+ queue.sync(client)
44
+ return queue
45
+
46
+
47
+ class TerminalExit(Enum):
48
+ RELOAD = "reload"
49
+
50
+
51
+ class TerminalSurfaces:
52
+ def __init__(
53
+ self, client, wake: Callable[[], None], host: SurfaceHost | None = None
54
+ ):
55
+ self.client = client
56
+ self.host = (
57
+ SurfaceHost(run=getattr(client, "run", None)) if host is None else host
58
+ )
59
+ self.wake = wake
60
+ self._observe: Future | None = None
61
+ self._write: Future | None = None
62
+ self._sources: dict[str, tuple[int, Future]] = {}
63
+ self._hydrated: set[str] = set()
64
+ self._dirty = False
65
+ self._online = False
66
+ self._epoch = 0
67
+ self._focus_generation = 0
68
+ self._observe_focus_generation = 0
69
+ self._write_focus_generation = 0
70
+ self.frame: ViewFrame | None = None
71
+ self.status = ""
72
+ self.side_panel_requested = False
73
+ self.group_focus: str | None = None
74
+ self.approvals = ApprovalQueue()
75
+ self._approvals_dirty = False
76
+ self._approvals_sync: Future | None = None
77
+ # Local decisions made; a sync launched before the latest one may predate it.
78
+ self._approvals_decided = 0
79
+ self._approvals_sync_decided = 0
80
+ self.approvals_unavailable: ApprovalsUnavailable | None = None
81
+
82
+ @property
83
+ def edition(self) -> Edition:
84
+ # Scripted test clients predate the edition capability and are full beta clients.
85
+ return getattr(self.client, "edition", Edition.BETA)
86
+
87
+ def _request(self, op: str, **fields) -> Future:
88
+ return wake_after(submit(self.client.send, op, **fields), self.wake)
89
+
90
+ def observe(self, frame) -> None:
91
+ kind = frame["type"]
92
+ if kind in {"resyncing", "refused", "disconnected"}:
93
+ self.host.disconnected()
94
+ self._hydrated.clear()
95
+ self._online = False
96
+ self._epoch += 1
97
+ elif kind == "history":
98
+ metadata = frame.get("state") or frame["history"]
99
+ if (view_state := metadata.get("view_state")) is not None:
100
+ self.host.set_layout(view_state)
101
+ self._approvals_dirty = True
102
+ if frame["history"].get("approvals"):
103
+ self.host.approval_pending = True
104
+ self._focus_generation += 1
105
+ self.host.seed_receipt_pins(metadata.get("tool_pins", ()))
106
+ for source in metadata.get("sources", ()):
107
+ self.host.registration(source)
108
+ elif kind == "caught_up":
109
+ self._dirty = self._online = True
110
+ elif kind == "event":
111
+ event = frame["event"]
112
+ if _approval_event(event["kind"]):
113
+ self._approvals_dirty = True
114
+ if is_file_edit(event):
115
+ return
116
+ self.host.event(event)
117
+ if (
118
+ event["kind"] == "agent.panel_requested"
119
+ and event["payload"]["panel"] == "side_agent"
120
+ and self._online
121
+ and side_agents_available(self.edition)
122
+ ):
123
+ self.side_panel_requested = True
124
+ if event["kind"] in _LAYOUT_EVENTS:
125
+ self._focus_generation += 1
126
+ self._dirty = True
127
+ if event["kind"] in {"approval.requested", "effect.proposed"}:
128
+ self.host.approval_pending = True
129
+ elif kind == "live":
130
+ body = frame["frame"]
131
+ if body.get("kind") == "view.changed":
132
+ if "layout" in body:
133
+ self.host.set_layout(body)
134
+ elif body["revision"] >= self.host.layout.revision:
135
+ self._dirty = True
136
+ else:
137
+ self.host.live(body)
138
+
139
+ @property
140
+ def approval_pending(self) -> bool:
141
+ """A card is queued, or the daemon focused an approval surface."""
142
+ return bool(self.approvals.cards) or self.host.approval_pending
143
+
144
+ def approval_key(self, key: str) -> str | None:
145
+ """Route a/d/v to the focused card; None when no card or not a card key."""
146
+ if not self.approvals.cards:
147
+ return None
148
+ before = len(self.approvals.cards)
149
+ message = self.approvals.handle_key(self.client, key)
150
+ if len(self.approvals.cards) != before:
151
+ self._approvals_decided += 1
152
+ self._approvals_dirty = True
153
+ return message
154
+
155
+ def _update_approvals(self) -> None:
156
+ if self._approvals_sync is not None and self._approvals_sync.done():
157
+ future, self._approvals_sync = self._approvals_sync, None
158
+ try:
159
+ queue = future.result()
160
+ if self._approvals_sync_decided != self._approvals_decided:
161
+ # Read before a local decision: it would resurrect the decided card.
162
+ # The decision marked the queue dirty, so a fresh sync follows below.
163
+ queue = None
164
+ except ApprovalsUnavailable as error:
165
+ # Keep the last good cards and the shared status; the queue reports its own outage.
166
+ self.approvals_unavailable = error
167
+ else:
168
+ self.approvals_unavailable = None
169
+ if queue is not None and [c.digest for c in queue.cards] != [c.digest for c in self.approvals.cards]:
170
+ self.approvals = queue
171
+ if self._approvals_dirty and self._approvals_sync is None:
172
+ self._approvals_dirty = False
173
+ self._approvals_sync_decided = self._approvals_decided
174
+ self._approvals_sync = wake_after(
175
+ submit(_fetch_approvals, self.client), self.wake
176
+ )
177
+
178
+ def update(self) -> None:
179
+ self._update_approvals()
180
+ if self._write is not None and self._write.done():
181
+ future, self._write = self._write, None
182
+ self._accept_layout(
183
+ future, report=True, focus_generation=self._write_focus_generation
184
+ )
185
+ if self._observe is not None and self._observe.done():
186
+ future, self._observe = self._observe, None
187
+ if self._online:
188
+ self._accept_layout(
189
+ future,
190
+ report=False,
191
+ focus_generation=self._observe_focus_generation,
192
+ )
193
+ if self._online and self._dirty and self._observe is None:
194
+ self._dirty = False
195
+ self._observe_focus_generation = self._focus_generation
196
+ self._observe = self._request("ui_manage", action="observe", args={})
197
+ for identity, (epoch, future) in tuple(self._sources.items()):
198
+ if not future.done():
199
+ continue
200
+ del self._sources[identity]
201
+ if epoch != self._epoch:
202
+ continue
203
+ try:
204
+ self.host.snapshot(future.result())
205
+ except (OSError, ValueError, KeyError, TypeError):
206
+ if identity in self.host.sources:
207
+ self.host.sources[identity].reset_live()
208
+ self.host.generation += 1
209
+ self._hydrated.add(identity)
210
+ if not self._online:
211
+ return
212
+ needed = dict.fromkeys(mount.source_id for mount in self.host.layout.mounts)
213
+ needed.update(dict.fromkeys(source for _, _, source, _ in self.host.pin_bindings()))
214
+ self._hydrated.intersection_update(needed)
215
+ for identity in needed:
216
+ if len(self._sources) >= _SOURCE_REQUESTS_MAX:
217
+ break
218
+ if identity not in self._hydrated and identity not in self._sources:
219
+ self._sources[identity] = (
220
+ self._epoch,
221
+ self._request("source.snapshot", source=identity),
222
+ )
223
+
224
+ def _accept_layout(
225
+ self, future: Future, *, report: bool, focus_generation: int
226
+ ) -> None:
227
+ try:
228
+ result = future.result()
229
+ if "preview" in result:
230
+ candidate = result["preview"]["layout"]
231
+ self.status = f"Preview · {candidate['tiling']} · {len(candidate['mounts'])} mounts"
232
+ return
233
+ previous_pending = self.host.approval_pending
234
+ self.host.set_layout(result)
235
+ if focus_generation != self._focus_generation and previous_pending:
236
+ self.host.approval_pending = True
237
+ if report:
238
+ self.status = f"Layout · {self.host.layout.tiling.value} · #{self.host.layout.revision}"
239
+ except (OSError, ValueError, KeyError, TypeError) as error:
240
+ if report:
241
+ self.status = f"Layout · {error}"
242
+
243
+ @property
244
+ def side(self) -> bool:
245
+ return any(
246
+ mount.slot
247
+ in (Slot.RIGHT_TOP, Slot.RIGHT_BOTTOM, Slot.REX_RIGHT, Slot.REX_BELOW)
248
+ for mount in self.host.layout.mounts
249
+ )
250
+
251
+ def compose(
252
+ self, width, panes, capacity, *, legacy: bool, protected: bool
253
+ ) -> tuple[list, list]:
254
+ regions = {}
255
+ wide = width >= WIDE_COLUMNS and panes.side_start is not None and not legacy
256
+ if wide:
257
+ midpoint = (capacity + 1) // 2
258
+ regions[Slot.RIGHT_TOP] = Extent(panes.side_width, midpoint)
259
+ regions[Slot.RIGHT_BOTTOM] = Extent(panes.side_width, capacity - midpoint)
260
+ compact_rows = min(3, capacity // 3)
261
+ if compact_rows and not protected:
262
+ regions[Slot.COMPOSER_TOP] = Extent(panes.core_width, compact_rows)
263
+ if not self.host.layout.mounts:
264
+ self.frame = None
265
+ return [], []
266
+ self.frame = self.host.render(width, regions)
267
+ side, compact = [], []
268
+ for slot in self.frame.slots:
269
+ placement = slot.placement
270
+ if placement.slot == Slot.COMPOSER_TOP:
271
+ target, start = compact, placement.row
272
+ elif placement.slot in {Slot.RIGHT_TOP, Slot.RIGHT_BOTTOM}:
273
+ target = side
274
+ start = placement.row + (
275
+ midpoint if placement.slot == Slot.RIGHT_BOTTOM else 0
276
+ )
277
+ else:
278
+ continue
279
+ if len(target) < start + len(slot.lines):
280
+ target.extend([("muted", "")] * (start + len(slot.lines) - len(target)))
281
+ for index, line in enumerate(slot.lines, start):
282
+ target[index] = (line.style.value, line.text)
283
+ return side, compact
284
+
285
+ def navigate(self, key: int | str) -> bool:
286
+ if self.frame is None or self.host.approval_pending:
287
+ return False
288
+ focused = self.host.focus
289
+ visible = {slot.mount: slot for slot in self.frame.slots}
290
+ selectable = [
291
+ mount_id
292
+ for mount_id, mount in self.host.mount_ids.items()
293
+ if mount in visible
294
+ and visible[mount].selectable_keys
295
+ and mount.emits is not None
296
+ ]
297
+ if key == 9 and selectable:
298
+ order = [None, *selectable]
299
+ next_focus = (
300
+ order[(order.index(focused) + 1) % len(order)]
301
+ if focused in order
302
+ else None
303
+ )
304
+ target = (
305
+ {"kind": "mount", "mount": next_focus}
306
+ if next_focus
307
+ else {"kind": "composer"}
308
+ )
309
+ self.change("apply", changes=[{"change": "focus", "target": target}])
310
+ return True
311
+ if focused not in selectable or key not in (curses.KEY_UP, curses.KEY_DOWN):
312
+ return False
313
+ slot = visible[self.host.mount_ids[focused]]
314
+ binding = slot.mount.emits
315
+ assert binding is not None
316
+ cursor = next(
317
+ (
318
+ cursor.key
319
+ for cursor in self.host.layout.cursors
320
+ if cursor.channel == binding.channel
321
+ ),
322
+ None,
323
+ )
324
+ keys = slot.selectable_keys
325
+ step = 1 if key == curses.KEY_DOWN else -1
326
+ index = (keys.index(cursor) + step) % len(keys) if cursor in keys else 0
327
+ choice = slot.select(keys[index])
328
+ assert choice is not None
329
+ self.change(
330
+ "apply",
331
+ changes=[
332
+ {
333
+ "change": "select_cursor",
334
+ "channel": choice.channel,
335
+ "key": choice.key,
336
+ },
337
+ ],
338
+ )
339
+ return True
340
+
341
+ def select_group(self, key: int | str, visible: dict[str, int]) -> bool:
342
+ if self.host.approval_pending or not visible:
343
+ self.group_focus = None
344
+ return False
345
+ ordered = sorted(visible, key=visible.__getitem__)
346
+ selected = self.group_focus in visible
347
+ if key == 7:
348
+ self.group_focus = None if selected else ordered[0]
349
+ return True
350
+ if not selected:
351
+ return False
352
+ if key in (curses.KEY_DOWN, curses.KEY_UP):
353
+ step = 1 if key == curses.KEY_DOWN else -1
354
+ self.group_focus = ordered[
355
+ (ordered.index(self.group_focus) + step) % len(ordered)
356
+ ]
357
+ return True
358
+ if key in (10, 13):
359
+ group = next(
360
+ (
361
+ group
362
+ for group in self.host.activity_groups
363
+ if group["group_id"] == self.group_focus
364
+ ),
365
+ None,
366
+ )
367
+ if group is not None:
368
+ self.change(
369
+ "apply",
370
+ changes=[
371
+ {
372
+ "change": "set_activity_expanded",
373
+ "group_id": self.group_focus,
374
+ "expanded": not group["expanded"],
375
+ }
376
+ ],
377
+ )
378
+ return True
379
+ if isinstance(key, str):
380
+ self.group_focus = None
381
+ return False
382
+
383
+ def change(self, action: str, **args) -> None:
384
+ if self._write is not None:
385
+ return
386
+ if action != "observe":
387
+ args["expected_revision"] = self.host.layout.revision
388
+ self._write_focus_generation = self._focus_generation
389
+ self._write = self._request("ui_manage", action=action, args=args)
390
+
391
+ def command(self, text: str) -> None:
392
+ words = text.split()
393
+ if not words or words == ["observe"]:
394
+ self.change("observe")
395
+ elif words == ["undo"]:
396
+ self.change("undo")
397
+ elif len(words) == 2 and words[0] in {"tiling", "preview"}:
398
+ self.change(
399
+ "apply" if words[0] == "tiling" else "preview",
400
+ changes=[
401
+ {"change": "set_tiling", "tiling": words[1]},
402
+ ],
403
+ )
404
+ elif words[0] == "group":
405
+ if not 5 <= len(words) <= 35 or len(words[3:]) != len(set(words[3:])):
406
+ raise ValueError("An activity group requires 2–32 distinct tool IDs")
407
+ self.change(
408
+ "apply",
409
+ changes=[
410
+ {
411
+ "change": "group_tools",
412
+ "group_id": words[1],
413
+ "turn": words[2],
414
+ "tool_ids": words[3:],
415
+ }
416
+ ],
417
+ )
418
+ elif len(words) == 2 and words[0] == "ungroup":
419
+ self.change(
420
+ "apply", changes=[{"change": "ungroup_activity", "group_id": words[1]}]
421
+ )
422
+ elif len(words) == 2 and words[0] in {"expand", "collapse"}:
423
+ self.change(
424
+ "apply",
425
+ changes=[
426
+ {
427
+ "change": "set_activity_expanded",
428
+ "group_id": words[1],
429
+ "expanded": words[0] == "expand",
430
+ }
431
+ ],
432
+ )
433
+ elif len(words) == 2 and words[0] == "unmount":
434
+ self.change("apply", changes=[{"change": "unmount", "id": words[1]}])
435
+ elif len(words) == 5 and words[0] == "mount":
436
+ _, identity, source, view, slot = words
437
+ self._mount(identity, source, view, slot)
438
+ else:
439
+ raise ValueError("Unknown layout action")
440
+
441
+ def _mount(self, identity: str, source: str, view: str, slot: str) -> None:
442
+ actual = self.host.sources.get(source)
443
+ if actual is None:
444
+ raise ValueError(f"Unknown source {source}")
445
+ declaration = next(
446
+ (item for item in actual.pack.manifest.views if item.id == view), None
447
+ )
448
+ if declaration is None:
449
+ raise ValueError(f"Unknown view {view} for source {source}")
450
+ self.change(
451
+ "apply",
452
+ changes=[
453
+ {
454
+ "change": "mount",
455
+ "mount": {
456
+ "id": identity,
457
+ "source_id": source,
458
+ "view_id": view,
459
+ "slot": slot,
460
+ "density": declaration.density.value,
461
+ "emits": {"channel": declaration.emits[0]}
462
+ if declaration.emits
463
+ else None,
464
+ "consumes": {"channel": declaration.consumes[0]}
465
+ if declaration.consumes
466
+ else None,
467
+ },
468
+ }
469
+ ],
470
+ )
@@ -0,0 +1,125 @@
1
+ """Maintain transcript and side-panel row projections across terminal frames."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import gc
6
+ from collections.abc import Sequence
7
+
8
+ from .plugin_host import PinPositions
9
+ from .terminal_layout import TranscriptProjector
10
+
11
+ __all__ = ["TerminalViewport", "retain_rows"]
12
+
13
+
14
+ def retain_rows() -> None:
15
+ """Exempt the rows a cold paint or catch-up frame just kept from full GC passes.
16
+
17
+ Rendered rows are tuples of rich `Segment`s, which stay GC-tracked (they hold
18
+ `Style`s), so a long history grows the tracked heap by ~100k objects as it catches
19
+ up, and each full (gen2) collection then stalls a frame for 100+ ms on C2. The rows
20
+ are immutable and acyclic, so refcounting still frees them; freezing only stops
21
+ cycle passes from rescanning them. Young cyclic garbage is collected first so the
22
+ freeze pins none of it. `gc.freeze()` splices generation lists: O(1).
23
+
24
+ `gc.freeze()` is process-wide, so only the full-screen terminal's frame loop calls
25
+ this (after a projection reports `retained`); library callers of `rows()` never do.
26
+ """
27
+ gc.collect(1)
28
+ gc.freeze()
29
+
30
+
31
+ class TerminalViewport:
32
+ def __init__(self, journal, commands, surfaces) -> None:
33
+ self.journal = journal
34
+ self.commands = commands
35
+ self.surfaces = surfaces
36
+ self.transcript = TranscriptProjector()
37
+ self.projected: Sequence = []
38
+ self.group_rows: dict[str, int] = {}
39
+ self.side_rows: list = []
40
+ self.summary = ""
41
+ self._pin_positions = PinPositions()
42
+ self._transcript_key = None
43
+ self._side_key = None
44
+
45
+ @property
46
+ def rewrapping(self) -> bool:
47
+ return self.transcript.rewrapping
48
+
49
+ def invalidate(self) -> None:
50
+ self.transcript.invalidate()
51
+ self._transcript_key = None
52
+
53
+ def update(self, panes, capacity, offset, *, follow, trace, side_binding) -> int:
54
+ journal, host = self.journal, self.surfaces.host
55
+ panels = journal.panels
56
+ transcript_key = (
57
+ journal.cursor,
58
+ journal.live_revision,
59
+ host.generation,
60
+ len(self.commands),
61
+ tuple(panels.seen.items()),
62
+ panes.core_width,
63
+ trace,
64
+ follow,
65
+ # Scrolling toward stand-in rows brings them into render reach.
66
+ None if follow else offset,
67
+ capacity,
68
+ )
69
+ if transcript_key != self._transcript_key or self.rewrapping:
70
+ offset = self._project(panes.core_width, offset, follow=follow, trace=trace, capacity=capacity)
71
+ self._transcript_key = transcript_key
72
+ side_key = (
73
+ journal.cursor,
74
+ journal.live_revision,
75
+ journal.history_before,
76
+ panels.group,
77
+ panels.selected,
78
+ panels.detail,
79
+ side_binding,
80
+ panes.side_width,
81
+ capacity,
82
+ )
83
+ if panels.group and side_key != self._side_key:
84
+ self.side_rows = panels.rows(journal.timeline, panes.side_width, capacity, side_binding)
85
+ self._side_key = side_key
86
+ return offset
87
+
88
+ def highlight_groups(self, body: list, offset: int) -> dict[str, int]:
89
+ visible = {
90
+ group: row - offset
91
+ for group, row in self.group_rows.items()
92
+ if offset <= row < offset + len(body)
93
+ }
94
+ selection = visible.get(self.surfaces.group_focus)
95
+ if selection is not None:
96
+ body[selection] = ("selection", body[selection][1])
97
+ return visible
98
+
99
+ def _project(self, width: int, offset: int, *, follow: bool, trace: bool, capacity: int) -> int:
100
+ journal, host = self.journal, self.surfaces.host
101
+ base_row, pill = self._pin_positions.base_row(offset)
102
+ anchor = self.transcript.viewport_anchor(base_row) if not follow else None
103
+ rows, self.summary = self.transcript.project(
104
+ journal.timeline,
105
+ self.commands,
106
+ journal.panels,
107
+ width,
108
+ trace,
109
+ follow,
110
+ live_transcript=journal.live.transcript,
111
+ activity_groups=host.activity_groups,
112
+ viewport_anchor=anchor,
113
+ viewport_rows=capacity,
114
+ )
115
+ if self.transcript.retained:
116
+ retain_rows()
117
+ self.projected, self.group_rows, self._pin_positions = host.pin_rows(
118
+ rows,
119
+ self.transcript.tool_rows,
120
+ width,
121
+ self.transcript.activity_group_rows,
122
+ )
123
+ if anchor is not None and (restored := self.transcript.viewport_offset(anchor)) is not None:
124
+ return self._pin_positions.visible_row(restored, pill)
125
+ return offset
@@ -0,0 +1,86 @@
1
+ """Terminal rows for typed tool receipts and bounded previews."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from rich.segment import Segment
6
+ from rich.style import Style
7
+
8
+ from .view import fit_cells, render_char, sanitize_text
9
+
10
+ __all__ = ["tool_rows", "width_cells"]
11
+
12
+ TOOL_PREVIEW_ROWS = 4
13
+
14
+
15
+ def tool_rows(tool, width, sequence, files=()):
16
+ state = tool["state"]
17
+ verb = {
18
+ "running": "Running",
19
+ "incomplete": "Incomplete",
20
+ "completed": "Ran" if tool["exit_code"] is not None else "Completed",
21
+ "failed": "Failed",
22
+ "declined": "Declined",
23
+ "cancelled": "Cancelled",
24
+ }[state]
25
+ details = []
26
+ if tool["exit_code"] not in (None, 0):
27
+ details.append(f"exit {tool['exit_code']}")
28
+ if tool["duration_ms"] is not None:
29
+ duration = tool["duration_ms"]
30
+ details.append(f"{duration} ms" if duration < 1000 else f"{duration / 1000:.1f}s")
31
+ target = tool["target"]
32
+ if target == "synth_agents/delegate_subagents":
33
+ target = "subagents"
34
+ if state == "running":
35
+ verb = "Launching"
36
+ elif state == "completed":
37
+ verb = "Queued"
38
+ prefix = f"• {verb} "
39
+ suffix = " · " + " · ".join(details) if details else ""
40
+ prefix = _fit_ellipsis(prefix, width)
41
+ available = width - width_cells(prefix)
42
+ # Keep the details when they fit, while leaving a cell for the target.
43
+ target = _fit_ellipsis(target, min(available, max(1, available - width_cells(suffix))))
44
+ suffix = _fit_ellipsis(suffix, width - width_cells(prefix) - width_cells(target))
45
+ rows = [
46
+ (
47
+ "error" if state == "failed" else "tool",
48
+ (
49
+ Segment(prefix, Style(bold=True)),
50
+ Segment(target, Style(meta={"code": True})),
51
+ Segment(suffix),
52
+ ),
53
+ )
54
+ ]
55
+ preview = tool["preview"]
56
+ preview_prefix = fit_cells(" │ ", width)
57
+ preview_room = width - width_cells(preview_prefix)
58
+ for line in preview[:TOOL_PREVIEW_ROWS]:
59
+ fitted = _fit_ellipsis(line, preview_room)
60
+ rows.append(("muted", preview_prefix + fitted))
61
+ remaining = len(preview) - TOOL_PREVIEW_ROWS
62
+ if remaining > 0:
63
+ rows.append(
64
+ ("muted", _fit_ellipsis(f" · {remaining} more lines · /event {sequence}", width))
65
+ )
66
+ if omitted := tool["omitted_lines"]:
67
+ rows.append(("muted", _fit_ellipsis(f" · {omitted} output lines trimmed", width)))
68
+ for path in files:
69
+ rows.append(("muted", _fit_ellipsis(f" └ {path}", width)))
70
+ return rows
71
+
72
+
73
+ def width_cells(text: str) -> int:
74
+ if text.isascii() and text.isprintable():
75
+ return len(text)
76
+ return sum(render_char(char)[1] for char in text)
77
+
78
+
79
+ def _fit_ellipsis(text: str, width: int) -> str:
80
+ """Fit text to `width` cells, marking a cut with an ellipsis."""
81
+ if width <= 0:
82
+ return ""
83
+ cleaned = sanitize_text(text)
84
+ if width_cells(cleaned) <= width:
85
+ return cleaned
86
+ return fit_cells(cleaned, width - 1) + "…"