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,643 @@
1
+ """Geometry and semantic color for the terminal conversation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import curses
6
+ import os
7
+ import sys
8
+ from collections.abc import Mapping
9
+ from dataclasses import dataclass
10
+ from datetime import datetime
11
+ from importlib.metadata import PackageNotFoundError, version
12
+
13
+ from .edition import Edition, side_agents_available
14
+ from .image_preview import IMAGE_LABEL, preview_draft
15
+ from .view import (
16
+ ComposerView,
17
+ composer_view,
18
+ fit_cells,
19
+ render_char,
20
+ sanitize_text,
21
+ wrap_cells,
22
+ )
23
+
24
+
25
+ def header_version(*, development):
26
+ try:
27
+ release = version("synth-code")
28
+ except PackageNotFoundError:
29
+ return "dev" if development else ""
30
+ return f"dev{release}" if development else release
31
+
32
+
33
+ def palette():
34
+ theme = os.environ.get("SYNTH_CODE_THEME", "auto").casefold()
35
+ background = os.environ.get("COLORFGBG", "").split(";")[-1]
36
+ known_background = theme in {"light", "dark"} or background in {"0", "7", "8", "15"}
37
+ if theme == "auto":
38
+ theme = "light" if background in {"7", "15"} else "dark"
39
+ styles = dict.fromkeys(("user", "approval", "error", "brand"), curses.A_BOLD)
40
+ styles["code"] = curses.A_BOLD
41
+ styles["selection"] = curses.A_REVERSE | curses.A_BOLD
42
+ if theme == "high-contrast":
43
+ styles["muted"] = curses.A_NORMAL
44
+ styles["side"] = curses.A_BOLD
45
+ return styles
46
+ styles["muted"] = curses.A_DIM
47
+ if os.environ.get("NO_COLOR") or not curses.has_colors() or curses.COLORS < 8:
48
+ return styles
49
+ curses.use_default_colors()
50
+ colors = (
51
+ {"brand": 124, "user": 25, "side": 28, "approval": 94, "error": 124}
52
+ if theme == "light"
53
+ else {"brand": 209, "user": 111, "side": 151, "approval": 222, "error": 203}
54
+ )
55
+ if curses.COLORS < 256:
56
+ colors = {"brand": 3, "user": 4, "side": 2, "approval": 3, "error": 1}
57
+ colors["code"] = (24 if theme == "light" else 117) if curses.COLORS >= 256 else 6
58
+ for pair, (key, color) in enumerate(colors.items(), 1):
59
+ curses.init_pair(pair, color, -1)
60
+ styles[key] = styles.get(key, 0) | curses.color_pair(pair)
61
+ user_turn_pair = len(colors) + 1
62
+ if curses.COLORS >= 256 and user_turn_pair < curses.COLOR_PAIRS:
63
+ foreground = -1 if known_background else 234
64
+ tint = 236 if known_background and theme == "dark" else 254
65
+ curses.init_pair(user_turn_pair, foreground, tint)
66
+ styles["user-turn"] = curses.color_pair(user_turn_pair)
67
+ if curses.COLORS < 256 or not known_background:
68
+ task_colors = (curses.COLOR_GREEN, curses.COLOR_BLUE, curses.COLOR_RED)
69
+ elif theme == "light":
70
+ task_colors = (29, 25, 124)
71
+ else:
72
+ task_colors = (114, 111, 203)
73
+ for pair, (key, color) in enumerate(
74
+ zip(("task-running", "task-done", "task-failed"), task_colors, strict=True),
75
+ user_turn_pair + 1,
76
+ ):
77
+ if pair < curses.COLOR_PAIRS:
78
+ curses.init_pair(pair, color, -1)
79
+ styles[key] = curses.color_pair(pair)
80
+ if curses.COLORS >= 256 and curses.COLOR_PAIRS >= 64:
81
+ for shade in range(24):
82
+ curses.init_pair(40 + shade, -1, 232 + shade)
83
+ styles[f"image-{shade}"] = curses.color_pair(40 + shade)
84
+ if "user-turn" in styles:
85
+ curses.init_pair(39, 24 if tint == 254 else 117, tint)
86
+ styles["image-label"] = curses.color_pair(39)
87
+ return styles
88
+
89
+
90
+ SPLIT_WIDTH = 88
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class Panes:
95
+ core_end: int
96
+ side_start: int | None
97
+ side_width: int
98
+ capacity: int
99
+ side_only: bool
100
+ composer_padding: int
101
+ composer: ComposerView
102
+ thumbnail: tuple[tuple[int, ...], ...]
103
+
104
+ @property
105
+ def core_width(self):
106
+ return max(1, self.core_end - 4)
107
+
108
+
109
+ def geometry(height, width, inspector=False, *, mounted=False, draft="", caret=0, state=None):
110
+ wide = width >= SPLIT_WIDTH
111
+ visible = inspector or (mounted and width >= 120)
112
+ split = max(width * 62 // 100, width - 66) if wide and visible else width
113
+ start = split + 1 if wide and visible else 0 if visible else None
114
+ padding = int(height >= 14)
115
+ capacity = max(1, height - 7 - 2 * padding)
116
+ thumbnail = ()
117
+ if state is not None:
118
+ draft, caret, thumbnail = preview_draft(
119
+ draft, caret, state, min(8, capacity // 3)
120
+ )
121
+ capacity -= len(thumbnail)
122
+ composer = composer_view(
123
+ draft, caret, max(1, split - 4), max(1, min(6, height // 3, capacity))
124
+ )
125
+ return Panes(
126
+ split,
127
+ start,
128
+ max(1, width - (start or 0) - 4),
129
+ capacity - len(composer.lines) + 1,
130
+ visible and not wide,
131
+ padding,
132
+ composer,
133
+ thumbnail,
134
+ )
135
+
136
+
137
+ def monitor_status(monitor):
138
+ state = monitor["state"]
139
+ progress = ""
140
+ agents = monitor["agents"]
141
+ if agents:
142
+ states = list(agents.values())
143
+ stopped = states.count("stopped")
144
+ blocked = states.count("blocked")
145
+ settled = states.count("done") + stopped
146
+ progress = f" · {settled}/{len(states)} settled"
147
+ if blocked:
148
+ progress += f" · {blocked} blocked"
149
+ if stopped:
150
+ progress += f" · {stopped} stopped"
151
+ if blocked:
152
+ state = "blocked"
153
+ elif settled < len(states):
154
+ state = "running"
155
+ else:
156
+ state = "stopped" if stopped else "done"
157
+ style = {
158
+ "running": "task-running",
159
+ "waiting": "muted",
160
+ "done": "task-done",
161
+ "blocked": "task-failed",
162
+ "stopped": "task-failed",
163
+ }[state]
164
+ return state.capitalize() + progress, style
165
+
166
+
167
+ def draw_workflow(put, row, col, width, workflow):
168
+ status, style = monitor_status(workflow)
169
+ label = f"Monitor · {status}"
170
+ message = " · " + workflow["text"]
171
+ remaining = width - len(label)
172
+ if updated_at := workflow.get("updated_at"):
173
+ clock = datetime.fromisoformat(updated_at).astimezone().strftime("%H:%M:%S")
174
+ stamp = f"Updated {clock}"
175
+ if remaining > len(stamp):
176
+ remaining -= len(stamp) + 1
177
+ put(row, col + width - len(stamp), stamp, len(stamp), "muted")
178
+ fitted = fit_cells(message, remaining)
179
+ if fitted != message and remaining > 3:
180
+ fitted = fit_cells(message, remaining - 1).rstrip() + "…"
181
+ put(row, col, label, width, style, curses.A_BOLD)
182
+ if remaining > 3:
183
+ put(row, col + len(label), fitted, remaining)
184
+
185
+
186
+ def side_footer_summary(summary: str, edition: Edition) -> str:
187
+ """The footer's side-agent summary and F2 hint; empty where side agents do not exist.
188
+
189
+ The single-agent public edition has no side agents or F2 panel, so its footer never
190
+ names either.
191
+ """
192
+ return summary if side_agents_available(edition) else ""
193
+
194
+
195
+ def draw(
196
+ screen,
197
+ styles,
198
+ *,
199
+ agent_binding,
200
+ active_core_model="",
201
+ side_binding,
202
+ status,
203
+ draft,
204
+ body,
205
+ mode,
206
+ version_label="",
207
+ panes,
208
+ side,
209
+ side_offset,
210
+ summary,
211
+ subagents="",
212
+ recipient="",
213
+ panel_title="Side agents",
214
+ panel_group=None,
215
+ picker=(),
216
+ workflow=None,
217
+ choices=(),
218
+ completion_index=0,
219
+ cache=None,
220
+ force=False,
221
+ mounted_inline=(),
222
+ ):
223
+ height, width = screen.getmaxyx()
224
+ ops: list[tuple[int, int, str, int]] = []
225
+
226
+ def put(y, x, value, span, style="", attributes=0):
227
+ if 0 <= y < height and 0 <= x < width - 1:
228
+ row_margin = 2 if (y == height - 1 and width > 3) else 1
229
+ max_span = max(0, min(span, width - x - row_margin))
230
+ fitted = fit_cells(value, max_span)
231
+ if fitted:
232
+ ops.append((y, x, fitted, styles.get(style, 0) | attributes))
233
+
234
+ def put_transcript(y, x, width, style, line):
235
+ if isinstance(line, str):
236
+ put(y, x, line, width, style)
237
+ return
238
+ end = x + width
239
+ for text, markup, _ in line:
240
+ fitted = fit_cells(text, end - x)
241
+ attributes = 0
242
+ segment_style = style
243
+ if markup:
244
+ if markup.bold:
245
+ attributes |= curses.A_BOLD
246
+ if markup.italic:
247
+ attributes |= getattr(curses, "A_ITALIC", curses.A_UNDERLINE)
248
+ if markup.underline:
249
+ attributes |= curses.A_UNDERLINE
250
+ if markup.meta.get("code"):
251
+ segment_style = "code"
252
+ elif task_state := markup.meta.get("task_state"):
253
+ segment_style = task_state
254
+ put(y, x, fitted, end - x, segment_style, attributes)
255
+ x += sum(render_char(char)[1] for char in fitted)
256
+ if x >= end:
257
+ break
258
+
259
+ padding = panes.composer_padding
260
+ footer_row = height - 2
261
+ prompt = max(0, footer_row - len(panes.composer.lines) - padding)
262
+ composer_top = prompt - padding - len(panes.thumbnail)
263
+ status_row = composer_top - 1 - bool(workflow)
264
+ left = 2 if panes.core_end >= 20 else 0
265
+ inset = max(0, left - 1)
266
+ band_width = panes.core_end - inset - 1
267
+ shaded = "user-turn" in styles
268
+ room = max(0, composer_top - 2)
269
+ room = max(0, room - bool(workflow))
270
+ menu = list(picker)
271
+ if choices and room >= 2:
272
+ count = min(6, len(choices), room - 1)
273
+ start = max(0, completion_index - count + 1)
274
+ menu.append(("brand", f"Commands {completion_index + 1}/{len(choices)}"))
275
+ for index in range(start, start + count):
276
+ name, spec = choices[index]
277
+ active = index == completion_index
278
+ menu.append(
279
+ (
280
+ "selection" if active else "",
281
+ f"{'›' if active else ' '} {name:<16} {spec.description}",
282
+ )
283
+ )
284
+ if len(menu) > room:
285
+ selected = next(
286
+ (index for index, (style, _) in enumerate(menu) if style == "selection"), 0
287
+ )
288
+ start = min(selected, len(menu) - room)
289
+ menu = menu[start : start + room]
290
+ menu_top = composer_top - len(menu) - bool(workflow)
291
+ if mounted_inline and not (menu or panes.side_only):
292
+ exclusive_bottom = status_row
293
+ first_row = exclusive_bottom - len(mounted_inline)
294
+ if first_row >= 2:
295
+ for row, (style, line) in enumerate(mounted_inline, first_row):
296
+ put_transcript(row, left, panes.core_width, style, line)
297
+ if menu or workflow:
298
+ body_room = max(0, menu_top - 2)
299
+ body = body[-body_room:] if body_room else []
300
+ if not panes.side_only:
301
+ put(0, left, "◆ synth code", panes.core_width, "brand")
302
+ put(0, left + 15, version_label, panes.core_width - 15, "muted")
303
+ mode_start = 15 + (len(version_label) + 3 if version_label else 0)
304
+ put(0, left + mode_start, mode, panes.core_width - mode_start, "muted")
305
+ for i, (style, line) in enumerate(body[: panes.capacity]):
306
+ row = 2 + i
307
+ if style == "user" and mode in {"", "Conversation"} and shaded:
308
+ style = "user-turn"
309
+ put(row, inset, " " * band_width, band_width, style)
310
+ put_transcript(row, left, panes.core_width, style, line)
311
+ if panes.side_start is not None:
312
+ x = panes.side_start + 2
313
+ put(0, x, panel_title, panes.side_width, "side")
314
+ for i, (style, line) in enumerate(
315
+ side[side_offset : side_offset + panes.capacity]
316
+ ):
317
+ put_transcript(2 + i, x, panes.side_width, style, line)
318
+ if not panes.side_only:
319
+ for y in range(height - 1):
320
+ put(y, panes.core_end, "│", 1, "muted")
321
+
322
+ # The core composer keeps its position through scrolling, resizing and inspector toggles.
323
+ if recipient and not menu:
324
+ put(status_row, left, recipient, panes.core_width, "muted")
325
+ elif not shaded and not menu and not workflow:
326
+ put(status_row, 0, "─" * panes.core_end, panes.core_end, "muted")
327
+ for row, (style, text) in enumerate(menu, menu_top):
328
+ put(row, left, text.ljust(panes.core_width), panes.core_width, style)
329
+ if workflow and composer_top >= 2:
330
+ draw_workflow(put, composer_top - 1, left, panes.core_width, workflow)
331
+ prompt_style = "" if draft else "muted"
332
+ if shaded:
333
+ prompt_style = "user-turn"
334
+ for row in range(composer_top, footer_row):
335
+ put(row, inset, " " * band_width, band_width, prompt_style)
336
+ for row, pixels in enumerate(panes.thumbnail, composer_top + padding):
337
+ for col, shade in enumerate(pixels[: panes.core_width]):
338
+ style = f"image-{shade}"
339
+ glyph = " " if style in styles else "█▓▒░ "[shade * 5 // 24]
340
+ put(row, left + col, glyph, 1, style if style in styles else prompt_style)
341
+ for row, line in enumerate(panes.composer.lines, prompt):
342
+ put(row, left, line, panes.core_width, prompt_style)
343
+ before, label, _ = line.partition(IMAGE_LABEL)
344
+ if label and "image-label" in styles:
345
+ indent = sum(render_char(char)[1] for char in before)
346
+ put(
347
+ row,
348
+ left + indent,
349
+ label,
350
+ panes.core_width - indent,
351
+ "image-label",
352
+ curses.A_BOLD,
353
+ )
354
+ action = (
355
+ "close"
356
+ if panes.side_start is not None and panel_group != "subagents"
357
+ else "view"
358
+ )
359
+ if panes.side_start and len(summary) + 15 > panes.side_width and " · " in summary:
360
+ summary = summary.split(" · ", 1)[0] + " · new finding"
361
+ footer_status = status if status not in recipient.split(" · ") else ""
362
+ footer = footer_status or agent_binding
363
+ if active_core_model:
364
+ footer = active_core_model + (f" · {footer_status}" if footer_status else "")
365
+
366
+ right_edge = width - 2
367
+ footer_min = min(14, right_edge // 2)
368
+ footer_min = sum(render_char(char)[1] for char in fit_cells(footer, footer_min))
369
+ summary_room = right_edge - left - footer_min - 1
370
+ label = fit_cells(summary, summary_room).rstrip(" ·") if summary_room >= 6 else ""
371
+ label_cells = sum(render_char(char)[1] for char in label)
372
+ shortcut = f" · F2 to {action}" if width >= 68 else " · F2"
373
+ if width < 22 or not label or label_cells + len(shortcut) > summary_room:
374
+ shortcut = ""
375
+ summary_start = right_edge - label_cells - len(shortcut)
376
+ footer_end = summary_start - 1 if label else width - 1
377
+ footer_room = min(panes.core_end, footer_end) - left
378
+ if active_core_model and footer_status:
379
+ full_footer_cells = sum(render_char(char)[1] for char in sanitize_text(footer))
380
+ if full_footer_cells > footer_room:
381
+ footer = footer_status
382
+ put(
383
+ footer_row,
384
+ left,
385
+ footer,
386
+ footer_room,
387
+ "status" if status or active_core_model else "muted",
388
+ )
389
+ if label:
390
+ put(footer_row, summary_start, label, label_cells, "side")
391
+ put(footer_row, summary_start + label_cells, shortcut, len(shortcut), "muted")
392
+
393
+ if width >= 22:
394
+ right_room = width // 2 - 2
395
+ side_detail = fit_cells(side_binding, right_room)
396
+ if subagents:
397
+ label = fit_cells(subagents, right_room - 5).rstrip()
398
+ side_detail = label + " · F3" if label else "F3"
399
+ side_cells = sum(render_char(char)[1] for char in side_detail)
400
+ put(
401
+ height - 1,
402
+ right_edge - side_cells,
403
+ side_detail,
404
+ right_room,
405
+ "side" if subagents else "muted",
406
+ )
407
+ row, column = panes.composer.cursor
408
+ cursor_pos = (prompt + row, min(width - 2, left + column)) if width > 1 else None
409
+ if cache is not None:
410
+ sig = (height, width, tuple(ops), cursor_pos)
411
+ if not force and cache.get("sig") == sig:
412
+ return
413
+ screen.erase()
414
+ if force or cache.get("size") != (height, width):
415
+ screen.clearok(True)
416
+ for y, x, text, attr in ops:
417
+ screen.addstr(y, x, text, attr)
418
+ if cursor_pos is not None:
419
+ screen.move(cursor_pos[0], cursor_pos[1])
420
+ screen.noutrefresh()
421
+ _synchronized_update()
422
+ cache["size"] = (height, width)
423
+ cache["sig"] = sig
424
+ return
425
+ screen.erase()
426
+ for y, x, text, attr in ops:
427
+ screen.addstr(y, x, text, attr)
428
+ if cursor_pos is not None:
429
+ screen.move(cursor_pos[0], cursor_pos[1])
430
+ screen.noutrefresh()
431
+ _synchronized_update()
432
+
433
+
434
+ # DEC private mode 2026: the terminal shows the frame only once it is complete,
435
+ # so a repaint (including a resize's full clear) never appears half drawn.
436
+ # Terminals without support ignore the mode.
437
+ SYNC_BEGIN = b"\x1b[?2026h"
438
+ SYNC_END = b"\x1b[?2026l"
439
+
440
+
441
+ def _synchronized_update():
442
+ """Flush the pending curses frame inside one synchronized-output bracket."""
443
+ output = sys.stdout.fileno()
444
+ os.write(output, SYNC_BEGIN)
445
+ try:
446
+ curses.doupdate()
447
+ finally:
448
+ os.write(output, SYNC_END)
449
+
450
+
451
+ def scroll(offset, rows, capacity, step):
452
+ return max(0, min(len(rows) - capacity, offset + step))
453
+
454
+
455
+ def move_panel(panels, rows, capacity, step):
456
+ if panels.detail:
457
+ panels.offset = scroll(panels.offset, rows, capacity, step)
458
+ else:
459
+ panels.move(step)
460
+
461
+
462
+ def overlay_rows(text, width):
463
+ return [
464
+ ("detail", piece)
465
+ for line in text.splitlines()
466
+ for piece in (wrap_cells(line, width) or [""])
467
+ ]
468
+
469
+
470
+ TRANSCRIPT_WIDTH = 108
471
+ # Blocks re-wrapped per frame after a width change while the view follows the bottom.
472
+ # Newest first, so the visible tail is exact on the first frame; the rest catch up.
473
+ REWRAP_BLOCKS_PER_FRAME = 24
474
+
475
+
476
+ class TranscriptProjector:
477
+ """Owns the transcript projection across frames and folds only new journal events.
478
+
479
+ The journal is append-only, so new events extend the fold. Local terminal
480
+ commands are rare and mutable (a picker records its outcome later), so a
481
+ change to them, or `invalidate()`, rebuilds the projection from the start.
482
+ """
483
+
484
+ def __init__(self, rewrap_blocks: int | None = REWRAP_BLOCKS_PER_FRAME) -> None:
485
+ self._rewrap_blocks = rewrap_blocks
486
+ self._timeline: list | None = None
487
+ self._fed = 0
488
+ self._commands_fed = -1
489
+ self._conversation = None
490
+ self._summary = None
491
+ self._summary_fed = 0
492
+ self._trace_rows: list = []
493
+ self._trace_anchors: dict[int, tuple[int, int]] = {}
494
+ self._trace = False
495
+ self.tool_rows: Mapping[tuple[str, str], int] = {}
496
+ self.activity_group_rows: dict[str, int] = {}
497
+ self._block_rows: Mapping[int, tuple[int, int]] = {}
498
+
499
+ def viewport_anchor(self, offset: int) -> tuple[int, int] | None:
500
+ if self._conversation is not None and not self._trace:
501
+ return self._conversation.viewport_anchor(offset)
502
+ if self._trace and self._trace_rows and offset >= 0:
503
+ index = min(offset, len(self._trace_rows) - 1)
504
+ return self._timeline[index]["seq"], 0
505
+ return None
506
+
507
+ def viewport_offset(self, anchor: tuple[int, int]) -> int | None:
508
+ sequence, relative = anchor
509
+ span = self._block_rows.get(sequence)
510
+ if span is None:
511
+ return None
512
+ start, stop = span
513
+ return min(start + relative, stop - 1)
514
+
515
+ def invalidate(self) -> None:
516
+ self._timeline = None
517
+
518
+ @property
519
+ def rewrapping(self) -> bool:
520
+ """True while a width change is still being applied to older blocks."""
521
+ return self._conversation is not None and self._conversation.rewrapping
522
+
523
+ @property
524
+ def retained(self) -> bool:
525
+ """True when the last projection rendered old rows that later frames keep."""
526
+ return not self._trace and self._conversation is not None and self._conversation.retained
527
+
528
+ def project(
529
+ self, timeline, commands, panels, content_width, trace, follow=True,
530
+ *, live_transcript=None, activity_groups=(), viewport_anchor=None, viewport_rows=None,
531
+ ):
532
+ from heapq import merge
533
+
534
+ from .activity_grouping import ActivityGroup
535
+ from .conversation import ConversationProjection
536
+ from .side_panel import SideSummary
537
+ from .transcript_rows import RowPrefix
538
+ from .view import label
539
+
540
+ rebuild = (
541
+ self._timeline is not timeline
542
+ or self._commands_fed != len(commands)
543
+ or len(timeline) < self._fed
544
+ )
545
+ if rebuild:
546
+ self._timeline = timeline
547
+ self._commands_fed = len(commands)
548
+ self._conversation = ConversationProjection(
549
+ core_only=True,
550
+ stream_anchors=live_transcript.stream_anchors if live_transcript is not None else None,
551
+ )
552
+ for event in merge(timeline, commands, key=lambda event: event["seq"]):
553
+ self._conversation.observe(event)
554
+ self._fed = len(timeline)
555
+ self._summary = SideSummary()
556
+ self._summary_fed = 0
557
+ self._trace_rows = []
558
+ self._trace_anchors = {}
559
+ else:
560
+ for event in timeline[self._fed :]:
561
+ self._conversation.observe(event)
562
+ self._fed = len(timeline)
563
+ for event in timeline[self._summary_fed :]:
564
+ self._summary.observe(event)
565
+ self._summary_fed = len(timeline)
566
+ self._trace = trace
567
+ if trace:
568
+ start = len(self._trace_rows)
569
+ for index, event in enumerate(timeline[start:], start):
570
+ sequence, kind = event["seq"], event["kind"]
571
+ self._trace_rows.append(("detail", f"{sequence:>4} {kind} {label(event)}"))
572
+ self._trace_anchors[sequence] = (index, index + 1)
573
+ projected = RowPrefix(self._trace_rows)
574
+ self.tool_rows = {}
575
+ self.activity_group_rows = {}
576
+ self._block_rows = self._trace_anchors
577
+ else:
578
+ projected = self._conversation.rows(
579
+ min(content_width, TRANSCRIPT_WIDTH), self._rewrap_blocks, live_transcript=live_transcript,
580
+ activity_groups=tuple(ActivityGroup.decode(group) for group in activity_groups),
581
+ rewrap_from=viewport_anchor[0] if viewport_anchor is not None and not follow else None,
582
+ viewport_rows=viewport_rows,
583
+ )
584
+ self.tool_rows = self._conversation.tool_rows
585
+ self.activity_group_rows = self._conversation.activity_group_rows
586
+ self._block_rows = self._conversation.block_rows
587
+ summary = self._summary.text
588
+ unread = [agent.name for key, agent in panels.agents.items() if panels.unread(key)]
589
+ if unread:
590
+ summary += " · " + (
591
+ unread[0] + " · new finding"
592
+ if len(unread) == 1
593
+ else f"{len(unread)} with findings"
594
+ )
595
+ return projected, summary
596
+
597
+
598
+ def project_transcript(timeline, commands, panels, content_width, trace):
599
+ """Project once without keeping state; the terminal uses TranscriptProjector."""
600
+ return TranscriptProjector().project(timeline, commands, panels, content_width, trace)
601
+
602
+
603
+ def detail_rows(overlay, shown, overlay_command, content_width):
604
+ from .view import detail
605
+
606
+ visible = (
607
+ overlay_rows(overlay, content_width)
608
+ if overlay
609
+ else [("detail", line) for line in detail(shown, content_width)]
610
+ if shown
611
+ else []
612
+ )
613
+ if (overlay or shown) and overlay_command:
614
+ visible[:0] = [
615
+ ("user", row)
616
+ for _, row in overlay_rows("You › " + overlay_command, content_width)
617
+ ] + [("blank", "")]
618
+ return visible
619
+
620
+
621
+ def account_rows(lines, width):
622
+ return [
623
+ ("selection" if line.startswith("› ") else "detail", row)
624
+ for line in lines
625
+ for _, row in overlay_rows(line, width)
626
+ ]
627
+
628
+
629
+ def permission_rows(profile, selected, modes):
630
+ current = profile.get("permissions", "manual")
631
+ return [("brand", "Workspace permissions")] + [
632
+ (
633
+ "selection" if index == selected else "detail",
634
+ label + (" (current)" if mode == current else ""),
635
+ )
636
+ for index, (mode, label) in enumerate(modes)
637
+ ]
638
+
639
+
640
+ def approval_rows(queue, width: int, capacity: int) -> list[tuple[str, str]]:
641
+ """The focused approval card in the protected composer area: header + key hint stay."""
642
+ rows = queue.render(width, min(capacity, max(4, capacity * 2 // 3)))
643
+ return [("approval" if index == 0 else "normal", row) for index, row in enumerate(rows)]