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
synth_code/view.py ADDED
@@ -0,0 +1,854 @@
1
+ """Private per-view drafts, raw-fd UTF-8/SIGWINCH input, Unicode cell fitting and event detail rendering."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import codecs
6
+ import ctypes
7
+ import curses
8
+ import errno
9
+ import fcntl
10
+ import hashlib
11
+ import json
12
+ import logging
13
+ import os
14
+ import re
15
+ import select
16
+ import signal
17
+ import socket
18
+ import struct
19
+ import sys
20
+ import tempfile
21
+ import termios
22
+ import time
23
+ import warnings
24
+ from collections import deque
25
+ from contextlib import contextmanager
26
+ from dataclasses import dataclass
27
+ from enum import Enum, auto
28
+ from pathlib import Path
29
+ from uuid import uuid4
30
+
31
+ from .history_wire import input_text
32
+ from .image_preview import draft_image_span
33
+
34
+ __all__ = [
35
+ "ComposerView",
36
+ "InputDecoder",
37
+ "InputHistory",
38
+ "InputSignal",
39
+ "TerminalInput",
40
+ "WorkspaceViewBusy",
41
+ "apply_composer_edit",
42
+ "composer_view",
43
+ "decode_batch",
44
+ "detail",
45
+ "fit_cells",
46
+ "is_composer_text",
47
+ "label",
48
+ "render_char",
49
+ "run_curses",
50
+ "terminal_log_path",
51
+ "tty_diagnostics",
52
+ "sanitize_text",
53
+ "workspace_view",
54
+ "wrap_cells",
55
+ ]
56
+
57
+ _PASTE_START = "\x1b[200~"
58
+ _PASTE_END = "\x1b[201~"
59
+ _PASTE_IDLE_SECONDS = 5.0
60
+ _COMPOSER_FORMAT_CHARS = frozenset(("\u00a0", "\u200c", "\u200d"))
61
+ _WHEEL_REPORT = re.compile(r"\x1b\[<(64|65);([1-9][0-9]*);[1-9][0-9]*M")
62
+ _MOUSE_ENABLE = b"\x1b[?1000h\x1b[?1006h"
63
+ _MOUSE_DISABLE = b"\x1b[?1000l\x1b[?1006l"
64
+ _ANSI_STRIP_RE = re.compile(
65
+ r"\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]"
66
+ )
67
+ _SPLIT_KEYS: dict[str, int | str] = {
68
+ "\x1b[A": curses.KEY_UP,
69
+ "\x1b[B": curses.KEY_DOWN,
70
+ "\x1b[C": curses.KEY_RIGHT,
71
+ "\x1b[D": curses.KEY_LEFT,
72
+ "\x1b[H": curses.KEY_HOME,
73
+ "\x1b[F": curses.KEY_END,
74
+ "\x1b[1~": curses.KEY_HOME,
75
+ "\x1b[3~": curses.KEY_DC,
76
+ "\x1b[4~": curses.KEY_END,
77
+ "\x1b[5~": curses.KEY_PPAGE,
78
+ "\x1b[6~": curses.KEY_NPAGE,
79
+ "\x1b[7~": curses.KEY_HOME,
80
+ "\x1b[8~": curses.KEY_END,
81
+ "\x1b[12~": curses.KEY_F2,
82
+ "\x1b[13~": curses.KEY_F3,
83
+ "\x1b[[B": curses.KEY_F2,
84
+ "\x1b[[C": curses.KEY_F3,
85
+ "\x1b[Z": curses.KEY_BTAB,
86
+ "\x1bOA": curses.KEY_UP,
87
+ "\x1bOB": curses.KEY_DOWN,
88
+ "\x1bOC": curses.KEY_RIGHT,
89
+ "\x1bOD": curses.KEY_LEFT,
90
+ "\x1bOH": curses.KEY_HOME,
91
+ "\x1bOF": curses.KEY_END,
92
+ "\x1bOQ": curses.KEY_F2,
93
+ "\x1bOR": curses.KEY_F3,
94
+ "\x1b[1;3D": "word_left",
95
+ "\x1b[1;5D": "word_left",
96
+ "\x1b[5D": "word_left",
97
+ "\x1b[1;3C": "word_right",
98
+ "\x1b[1;5C": "word_right",
99
+ "\x1b[5C": "word_right",
100
+ "\x1b[3;3~": "kill_word_right",
101
+ "\x1b[3;5~": "kill_word_right",
102
+ }
103
+
104
+
105
+ class InputSignal(Enum):
106
+ EOF = auto()
107
+
108
+
109
+ class TerminalInput:
110
+ def __init__(self, fd: int) -> None:
111
+ self.fd = fd
112
+ self.utf8 = codecs.getincrementaldecoder("utf-8")("ignore")
113
+ self.buf: deque[str | int | InputSignal] = deque()
114
+ self.wake_r, self.wake_w = socket.socketpair()
115
+ self.wake_r.setblocking(False)
116
+ self.wake_w.setblocking(False)
117
+ self.resized = False
118
+ self.external_wake: tuple[int, ...] = ()
119
+ self._prev_winch = signal.getsignal(signal.SIGWINCH)
120
+ signal.signal(signal.SIGWINCH, self._on_winch)
121
+
122
+ def _on_winch(self, _signum: int, _frame: object) -> None:
123
+ self.resized = True
124
+ self.wake()
125
+
126
+ def wake(self) -> None:
127
+ try:
128
+ self.wake_w.send(b"w")
129
+ except OSError:
130
+ pass
131
+
132
+ def close(self) -> None:
133
+ signal.signal(signal.SIGWINCH, self._prev_winch)
134
+ self.wake_r.close()
135
+ self.wake_w.close()
136
+
137
+ def window_size(self) -> tuple[int, int] | None:
138
+ try:
139
+ rows, cols, _, _ = struct.unpack(
140
+ "HHHH", fcntl.ioctl(self.fd, termios.TIOCGWINSZ, bytes(8))
141
+ )
142
+ if rows > 0 and cols > 0:
143
+ return rows, cols
144
+ except OSError:
145
+ pass
146
+ return None
147
+
148
+ def poll(self, timeout_ms: int | None) -> bool:
149
+ wait_s = None if timeout_ms is None else max(0.0, timeout_ms / 1000.0)
150
+ ready, _, _ = select.select(
151
+ [self.fd, self.wake_r, *self.external_wake], [], [],
152
+ 0.0 if self.buf else wait_s,
153
+ )
154
+ if self.wake_r in ready:
155
+ try:
156
+ while self.wake_r.recv(256):
157
+ pass
158
+ except BlockingIOError:
159
+ pass
160
+ did_resize = self.resized
161
+ self.resized = False
162
+ if self.fd in ready:
163
+ try:
164
+ chunk = os.read(self.fd, 4096)
165
+ except OSError as error:
166
+ if error.errno in (errno.EAGAIN, errno.EINTR):
167
+ return did_resize
168
+ if error.errno != errno.EIO:
169
+ raise
170
+ chunk = b""
171
+ if not chunk:
172
+ self.buf.append(InputSignal.EOF)
173
+ else:
174
+ self.buf.extend(self.utf8.decode(chunk, False))
175
+ return did_resize
176
+
177
+
178
+ def is_composer_text(stroke: str) -> bool:
179
+ return stroke.isprintable() or stroke in _COMPOSER_FORMAT_CHARS
180
+
181
+
182
+ @dataclass(slots=True)
183
+ class InputDecoder:
184
+ in_paste: bool = False
185
+ esc_buf: str = ""
186
+ esc_deadline: float = 0.0
187
+ paste_cr: bool = False
188
+ paste_deadline: float = 0.0
189
+
190
+ def timeout_ms(self, now: float) -> int | None:
191
+ if self.in_paste:
192
+ deadline = self.paste_deadline
193
+ elif self.esc_buf:
194
+ deadline = self.esc_deadline
195
+ else:
196
+ return None
197
+ return max(1, int((deadline - now) * 1000))
198
+
199
+ def on_timeout(self, now: float) -> str | None:
200
+ if self.in_paste:
201
+ if now >= self.paste_deadline:
202
+ self._end_paste()
203
+ return "paste_cancel"
204
+ return None
205
+ if self.esc_buf and now >= self.esc_deadline:
206
+ bare_esc = self.esc_buf == "\x1b"
207
+ self.esc_buf = ""
208
+ if bare_esc:
209
+ return "detach"
210
+ return None
211
+
212
+ def _end_paste(self) -> None:
213
+ self.in_paste = False
214
+ self.esc_buf = ""
215
+ self.paste_cr = False
216
+
217
+ def _paste_char(self, ch: str) -> list[tuple[str, str | int]]:
218
+ if ch == "\r":
219
+ self.paste_cr = True
220
+ return [("paste_text", "\n")]
221
+ if ch == "\n":
222
+ was_cr = self.paste_cr
223
+ self.paste_cr = False
224
+ return [] if was_cr else [("paste_text", "\n")]
225
+ self.paste_cr = False
226
+ if ch == "\t":
227
+ return [("paste_text", " ")]
228
+ if is_composer_text(ch):
229
+ return [("paste_text", ch)]
230
+ return []
231
+
232
+ def feed(
233
+ self, stroke: str | int | InputSignal, now: float
234
+ ) -> list[tuple[str, str | int]]:
235
+ if stroke is InputSignal.EOF:
236
+ return [("eof", 0)]
237
+ if stroke == curses.KEY_RESIZE:
238
+ return [("resize", 0)]
239
+ if self.in_paste:
240
+ if stroke in ("\x03", 3):
241
+ self._end_paste()
242
+ return [("paste_cancel", 0)]
243
+ if not isinstance(stroke, str):
244
+ return []
245
+ self.paste_deadline = now + _PASTE_IDLE_SECONDS
246
+ if self.esc_buf:
247
+ cand = self.esc_buf + stroke
248
+ if cand == _PASTE_END:
249
+ self._end_paste()
250
+ return [("paste_mode", 0)]
251
+ if _PASTE_END.startswith(cand):
252
+ self.esc_buf = cand
253
+ return []
254
+ flushed = self.esc_buf[1:]
255
+ if stroke == "\x1b":
256
+ self.esc_buf = "\x1b"
257
+ else:
258
+ self.esc_buf = ""
259
+ flushed += stroke
260
+ events: list[tuple[str, str | int]] = []
261
+ for ch in flushed:
262
+ events.extend(self._paste_char(ch))
263
+ return events
264
+ if stroke == "\x1b":
265
+ self.esc_buf = "\x1b"
266
+ self.paste_cr = False
267
+ return []
268
+ return self._paste_char(stroke)
269
+
270
+ if stroke in ("\x04", 4):
271
+ self.esc_buf = ""
272
+ return [("detach", 4)]
273
+ if stroke in ("\x03", 3):
274
+ self.esc_buf = ""
275
+ return [("interrupt", 0)]
276
+ if self.on_timeout(now) == "detach":
277
+ return [("detach", 0), *self.feed(stroke, now)]
278
+ if self.esc_buf:
279
+ if not isinstance(stroke, str):
280
+ self.esc_buf = ""
281
+ return self.feed(stroke, now)
282
+ if self.esc_buf == "\x1b":
283
+ if stroke == "[":
284
+ self.esc_buf = "\x1b["
285
+ self.esc_deadline = now + 1.0
286
+ return []
287
+ if stroke == "O":
288
+ self.esc_buf = "\x1bO"
289
+ self.esc_deadline = now + 1.0
290
+ return []
291
+ if stroke == "\x1b":
292
+ # The second Escape may start a bracketed paste or another key.
293
+ self.esc_deadline = now + 0.14
294
+ return [("detach", 0)]
295
+ self.esc_buf = ""
296
+ if stroke in ("b", "B"):
297
+ return [("edit", "word_left")]
298
+ if stroke in ("f", "F"):
299
+ return [("edit", "word_right")]
300
+ if stroke in ("d", "D"):
301
+ return [("edit", "kill_word_right")]
302
+ if stroke in ("\x7f", "\x08"):
303
+ return [("edit", "kill_word_left")]
304
+ return [("detach", 0), *self.feed(stroke, now)]
305
+ if self.esc_buf.startswith("\x1b["):
306
+ code = ord(stroke)
307
+ if stroke == "\x1b":
308
+ self.esc_buf = "\x1b"
309
+ self.esc_deadline = now + 0.14
310
+ return []
311
+ seq = self.esc_buf + stroke
312
+ if 0x40 <= code <= 0x7E:
313
+ self.esc_buf = ""
314
+ if seq == _PASTE_START:
315
+ self.in_paste = True
316
+ self.paste_deadline = now + _PASTE_IDLE_SECONDS
317
+ self.paste_cr = False
318
+ return [("paste_mode", 1)]
319
+ if seq == _PASTE_END:
320
+ return []
321
+ if wheel := _WHEEL_REPORT.fullmatch(seq):
322
+ direction = "wheel_up" if wheel[1] == "64" else "wheel_down"
323
+ return [(direction, int(wheel[2]) - 1)]
324
+ mapped = _SPLIT_KEYS.get(seq)
325
+ if isinstance(mapped, str):
326
+ return [("edit", mapped)]
327
+ if isinstance(mapped, int):
328
+ return [("key", mapped)]
329
+ return []
330
+ if (0x20 <= code <= 0x3F or seq == "\x1b[[") and len(seq) <= 32:
331
+ self.esc_buf = seq
332
+ self.esc_deadline = now + 1.0
333
+ return []
334
+ self.esc_buf = ""
335
+ return []
336
+ if self.esc_buf == "\x1bO":
337
+ seq = self.esc_buf + stroke
338
+ self.esc_buf = ""
339
+ mapped = _SPLIT_KEYS.get(seq)
340
+ if isinstance(mapped, int):
341
+ return [("key", mapped)]
342
+ return []
343
+
344
+ if stroke == "\x1b":
345
+ self.esc_buf = "\x1b"
346
+ self.esc_deadline = now + 0.14
347
+ return []
348
+ return [("key", stroke)]
349
+
350
+
351
+ def decode_batch(
352
+ inp: TerminalInput, decoder: InputDecoder, now_fn
353
+ ) -> list[tuple[str, str | int]]:
354
+ decoded: list[tuple[str, str | int]] = []
355
+ for _ in range(512):
356
+ if not inp.buf:
357
+ if inp.poll(0):
358
+ decoded.append(("resize", 0))
359
+ if not inp.buf:
360
+ break
361
+ events = decoder.feed(inp.buf.popleft(), now_fn())
362
+ decoded.extend(events)
363
+ if ("paste_cancel", 0) in events:
364
+ # Discard the remainder of this read, which may contain pasted controls.
365
+ inp.buf.clear()
366
+ break
367
+ if any(
368
+ kind in ("detach", "interrupt", "eof")
369
+ or (kind == "key" and stroke in (10, 13, "\n", "\r"))
370
+ for kind, stroke in events
371
+ ):
372
+ break
373
+ return decoded
374
+
375
+
376
+ def _is_word_char(ch: str) -> bool:
377
+ return ch.isalnum() or ch == "_"
378
+
379
+
380
+ def _prev_word_pos(draft: str, caret: int) -> int:
381
+ pos = max(0, min(len(draft), caret))
382
+ while pos > 0 and draft[pos - 1].isspace():
383
+ pos -= 1
384
+ if pos > 0 and _is_word_char(draft[pos - 1]):
385
+ while pos > 0 and _is_word_char(draft[pos - 1]):
386
+ pos -= 1
387
+ else:
388
+ while (
389
+ pos > 0
390
+ and not draft[pos - 1].isspace()
391
+ and not _is_word_char(draft[pos - 1])
392
+ ):
393
+ pos -= 1
394
+ return pos
395
+
396
+
397
+ def _next_word_pos(draft: str, caret: int) -> int:
398
+ n = len(draft)
399
+ pos = max(0, min(n, caret))
400
+ while pos < n and draft[pos].isspace():
401
+ pos += 1
402
+ if pos < n and _is_word_char(draft[pos]):
403
+ while pos < n and _is_word_char(draft[pos]):
404
+ pos += 1
405
+ else:
406
+ while pos < n and not draft[pos].isspace() and not _is_word_char(draft[pos]):
407
+ pos += 1
408
+ return pos
409
+
410
+
411
+ def apply_composer_edit(
412
+ draft: str, caret: int, action: str | int
413
+ ) -> tuple[str, int, bool]:
414
+ image_keys = (curses.KEY_LEFT, curses.KEY_RIGHT, 6, 8, 127, curses.KEY_BACKSPACE, curses.KEY_DC)
415
+ if action in image_keys and (image := draft_image_span(draft)):
416
+ start, end = image
417
+ if start < caret <= end and action in (curses.KEY_LEFT, 8, 127, curses.KEY_BACKSPACE):
418
+ if action == curses.KEY_LEFT:
419
+ return draft, start, True
420
+ return draft[:start] + draft[end:], start, True
421
+ if start <= caret < end:
422
+ if action in (curses.KEY_RIGHT, 6):
423
+ return draft, end, True
424
+ if action == curses.KEY_DC:
425
+ return draft[:start] + draft[end:], start, True
426
+ if action == curses.KEY_LEFT:
427
+ return draft, max(0, caret - 1), True
428
+ if action in (curses.KEY_RIGHT, 6):
429
+ return draft, min(len(draft), caret + 1), True
430
+ if action in (curses.KEY_HOME, 1):
431
+ return draft, 0, True
432
+ if action in (curses.KEY_END, 5):
433
+ return draft, len(draft), True
434
+ if action == "word_left":
435
+ return draft, _prev_word_pos(draft, caret), True
436
+ if action == "word_right":
437
+ return draft, _next_word_pos(draft, caret), True
438
+ if action in (8, 127, curses.KEY_BACKSPACE):
439
+ if caret > 0:
440
+ return draft[: caret - 1] + draft[caret:], caret - 1, True
441
+ return draft, caret, True
442
+ if action == curses.KEY_DC:
443
+ if caret < len(draft):
444
+ return draft[:caret] + draft[caret + 1 :], caret, True
445
+ return draft, caret, True
446
+ if action == 21:
447
+ return draft[caret:], 0, True
448
+ if action == 11:
449
+ return draft[:caret], caret, True
450
+ if action in (23, "kill_word_left"):
451
+ target = _prev_word_pos(draft, caret)
452
+ return draft[:target] + draft[caret:], target, True
453
+ if action == "kill_word_right":
454
+ target = _next_word_pos(draft, caret)
455
+ return draft[:caret] + draft[target:], caret, True
456
+ return draft, caret, False
457
+
458
+
459
+ def terminal_log_path(state_dir: Path | None) -> Path:
460
+ """A fresh per-run diagnostics log for one full-screen terminal session."""
461
+ root = (state_dir if state_dir is not None else Path(tempfile.gettempdir()) / "synth-code") / "logs"
462
+ root.mkdir(parents=True, exist_ok=True)
463
+ return root / f"terminal-{time.strftime('%Y%m%dT%H%M%S')}-{os.getpid()}.log"
464
+
465
+
466
+ @contextmanager
467
+ def tty_diagnostics(log_path: Path):
468
+ """Route every stray diagnostic to ``log_path`` while the full-screen terminal owns the TTY.
469
+
470
+ Python logging (including ``logging.lastResort``, which asyncio's default loop exception
471
+ handler and child-watcher warnings fall back to), ``warnings``, and fd 2 itself (so child
472
+ helpers and C extensions inherit the log, not the TTY) all land in the log. Nothing is
473
+ dropped: on exit everything is restored and, when the log holds anything, one line naming
474
+ it is written to the restored stderr. Exceptions still propagate and print normally after.
475
+ """
476
+ err_fd = sys.stderr.fileno()
477
+ log_path.parent.mkdir(parents=True, exist_ok=True)
478
+ log_fd = os.open(log_path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
479
+ log_stream = os.fdopen(os.dup(log_fd), "a", buffering=1, encoding="utf-8", errors="replace")
480
+ handler = logging.StreamHandler(log_stream)
481
+ handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))
482
+ root = logging.getLogger()
483
+ saved_last_resort = logging.lastResort
484
+ capturing_before = getattr(logging, "_warnings_showwarning", None) is not None
485
+ saved_err: int | None = None
486
+ try:
487
+ if os.isatty(err_fd):
488
+ sys.stderr.flush()
489
+ saved_err = os.dup(err_fd)
490
+ os.dup2(log_fd, err_fd)
491
+ root.addHandler(handler)
492
+ logging.lastResort = handler
493
+ if not capturing_before:
494
+ logging.captureWarnings(True)
495
+ yield log_path
496
+ finally:
497
+ if not capturing_before:
498
+ logging.captureWarnings(False)
499
+ logging.lastResort = saved_last_resort
500
+ root.removeHandler(handler)
501
+ handler.close()
502
+ log_stream.close()
503
+ sys.stderr.flush()
504
+ if saved_err is not None:
505
+ os.dup2(saved_err, err_fd)
506
+ os.close(saved_err)
507
+ os.close(log_fd)
508
+ if log_path.stat().st_size:
509
+ sys.stderr.write(f"synth-code: terminal diagnostics were written to {log_path}\n")
510
+ sys.stderr.flush()
511
+ else:
512
+ log_path.unlink(missing_ok=True)
513
+
514
+
515
+ def run_curses(fn, *args, mouse=False, state_dir: Path | None = None):
516
+ with tty_diagnostics(terminal_log_path(state_dir)):
517
+ return _run_curses(fn, *args, mouse=mouse)
518
+
519
+
520
+ def _run_curses(fn, *args, mouse=False):
521
+ tty_fd, in_fd = sys.stdout.fileno(), sys.stdin.fileno()
522
+ saved_out = termios.tcgetattr(tty_fd) if os.isatty(tty_fd) else None
523
+ saved_in = termios.tcgetattr(in_fd) if os.isatty(in_fd) and in_fd != tty_fd else None
524
+ screen = curses.initscr()
525
+ custom_colors: list[int] = []
526
+ try:
527
+ curses.noecho()
528
+ curses.cbreak()
529
+ curses.nonl()
530
+ vdisable = getattr(os, "_POSIX_VDISABLE", 0)
531
+ for fd in {tty_fd, in_fd}:
532
+ if os.isatty(fd):
533
+ raw_cc = termios.tcgetattr(fd)
534
+ raw_cc[0] &= ~(termios.ICRNL | termios.IXON)
535
+ raw_cc[3] &= ~(termios.ECHO | termios.ICANON)
536
+ raw_cc[6][termios.VINTR] = vdisable
537
+ raw_cc[6][termios.VMIN] = 1
538
+ raw_cc[6][termios.VTIME] = 0
539
+ termios.tcsetattr(fd, termios.TCSANOW, raw_cc)
540
+ screen.keypad(True)
541
+ if not os.environ.get("NO_COLOR") and curses.has_colors():
542
+ curses.start_color()
543
+ if os.environ.get("TERM_PROGRAM") == "rex" and curses.COLORS >= 256 and curses.can_change_color():
544
+ # Rex's theme can remap indexed grays. These slots are used by user turns.
545
+ for index, gray in ((234, 141), (236, 188), (254, 954)):
546
+ curses.init_color(index, gray, gray, gray)
547
+ custom_colors.append(index)
548
+ os.write(tty_fd, b"\x1b[?2004h")
549
+ if mouse:
550
+ os.write(tty_fd, _MOUSE_ENABLE)
551
+ return fn(screen, *args)
552
+ finally:
553
+ if mouse:
554
+ os.write(tty_fd, _MOUSE_DISABLE)
555
+ screen.keypad(False)
556
+ curses.echo()
557
+ curses.nl()
558
+ curses.nocbreak()
559
+ curses.endwin()
560
+ if custom_colors:
561
+ slots = ";".join(map(str, custom_colors))
562
+ os.write(tty_fd, f"\x1b]104;{slots}\x1b\\".encode("ascii"))
563
+ if saved_in is not None:
564
+ termios.tcsetattr(in_fd, termios.TCSANOW, saved_in)
565
+ if saved_out is not None:
566
+ termios.tcsetattr(tty_fd, termios.TCSANOW, saved_out)
567
+ os.write(tty_fd, b"\x1b[?2004l")
568
+
569
+
570
+ _LIBC = ctypes.CDLL(None)
571
+ _LIBC.wcwidth.argtypes = [ctypes.c_wchar]
572
+ _LIBC.wcwidth.restype = ctypes.c_int
573
+
574
+
575
+ def sanitize_text(text: str, *, expand_tabs: bool = True) -> str:
576
+ cleaned = _ANSI_STRIP_RE.sub("", text).replace("\r\n", "\n").replace("\r", "\n")
577
+ return cleaned.replace("\t", " ") if expand_tabs else cleaned
578
+
579
+
580
+ def render_char(ch: str) -> tuple[str, int]:
581
+ if (
582
+ not ch.isprintable()
583
+ or (0x202A <= ord(ch) <= 0x202E)
584
+ or (0x2066 <= ord(ch) <= 0x2069)
585
+ ):
586
+ return " ", 1
587
+ width = _LIBC.wcwidth(ch)
588
+ if width < 0:
589
+ return " ", 1
590
+ return ch, width
591
+
592
+
593
+ def fit_cells(text: str, limit: int) -> str:
594
+ if limit <= 0:
595
+ return ""
596
+ out: list[str] = []
597
+ used = 0
598
+ for ch in sanitize_text(text):
599
+ rendered, width = render_char(ch)
600
+ if width == 0:
601
+ if not out or used >= limit:
602
+ continue
603
+ out.append(rendered)
604
+ continue
605
+ if used + width > limit:
606
+ break
607
+ out.append(rendered)
608
+ used += width
609
+ return "".join(out)
610
+
611
+
612
+ def wrap_cells(line: str, limit: int) -> list[str]:
613
+ cap = max(8, limit)
614
+ cleaned = sanitize_text(line)
615
+ if not cleaned:
616
+ return []
617
+ pieces: list[str] = []
618
+ current: list[str] = []
619
+ used = 0
620
+ for ch in cleaned:
621
+ rendered, width = render_char(ch)
622
+ if width == 0:
623
+ if current:
624
+ current.append(rendered)
625
+ continue
626
+ if used + width > cap and current:
627
+ pieces.append("".join(current))
628
+ current = [rendered]
629
+ used = width
630
+ else:
631
+ current.append(rendered)
632
+ used += width
633
+ if current:
634
+ pieces.append("".join(current))
635
+ return pieces
636
+
637
+
638
+ class InputHistory:
639
+ """Recall recorded chat messages while keeping the current draft and caret."""
640
+
641
+ def __init__(self):
642
+ self.entries: list[str] = []
643
+ self.index: int | None = None
644
+ self.end = 0
645
+ self.draft = "", 0
646
+
647
+ def observe(self, event):
648
+ kind, payload = event["kind"], event["payload"]
649
+ if kind == "input.received":
650
+ text = input_text(payload["parts"])
651
+ elif kind in {"user.message", "user.steer"} and "input_id" not in payload:
652
+ text = payload["summary"]
653
+ else:
654
+ return
655
+ if text:
656
+ self.entries.append(text)
657
+
658
+ def prepend(self, events):
659
+ older = InputHistory()
660
+ for event in events:
661
+ older.observe(event)
662
+ if older.entries:
663
+ self.entries[:0] = older.entries
664
+ if self.index is not None:
665
+ self.index += len(older.entries)
666
+ self.end += len(older.entries)
667
+
668
+ def reset(self):
669
+ self.index = None
670
+ self.draft = "", 0
671
+
672
+ def move(self, direction, draft, caret):
673
+ if self.index is None:
674
+ if direction > 0 or not self.entries:
675
+ return None
676
+ self.draft = draft, caret
677
+ self.end = len(self.entries)
678
+ self.index = self.end
679
+ index = max(0, self.index + direction)
680
+ if index == self.index:
681
+ return None
682
+ if index == self.end:
683
+ original = self.draft
684
+ self.reset()
685
+ return original
686
+ self.index = index
687
+ text = self.entries[index]
688
+ return text, len(text)
689
+
690
+
691
+ @dataclass(frozen=True)
692
+ class ComposerView:
693
+ lines: tuple[str, ...]
694
+ cursor: tuple[int, int]
695
+
696
+
697
+ def composer_view(draft: str, caret: int, width: int, max_rows: int) -> ComposerView:
698
+ """Soft-wrap the draft in terminal cells without changing the text or caret."""
699
+ indent = 2 if width >= 3 else 0
700
+ budget = max(1, width - indent)
701
+ pos = max(0, min(len(draft), caret))
702
+ rows = [""]
703
+ used = 0
704
+ cursor = None
705
+ for match in re.finditer(r"\n|[^\S\n]+|\S+", draft):
706
+ word = match.group()
707
+ if word == "\n":
708
+ if match.start() == pos:
709
+ cursor = len(rows) - 1, used
710
+ rows.append("")
711
+ used = 0
712
+ continue
713
+ cells = [render_char(char) for char in word]
714
+ span = sum(size for _, size in cells)
715
+ if not word.isspace() and used and budget - used < span <= budget:
716
+ rows.append("")
717
+ used = 0
718
+ for index, (char, size) in enumerate(cells, match.start()):
719
+ if size > budget:
720
+ char, size = "�", 1
721
+ if used + size > budget:
722
+ rows.append("")
723
+ used = 0
724
+ if index == pos:
725
+ cursor = len(rows) - 1, used
726
+ rows[-1] += char
727
+ used += size
728
+
729
+ row, column = cursor if cursor is not None else (len(rows) - 1, used)
730
+ start = max(0, row - max_rows + 1)
731
+ visible = tuple(
732
+ ("› " if index == 0 else " ")[:indent] + line
733
+ for index, line in enumerate(rows[start : start + max_rows], start)
734
+ )
735
+ return ComposerView(visible, (row - start, column + indent))
736
+
737
+
738
+ class WorkspaceViewBusy(RuntimeError):
739
+ """A live terminal owns the named view's saved state."""
740
+
741
+
742
+ _VIEW_FIELDS = {
743
+ "draft": str,
744
+ "caret": int,
745
+ "offset": int,
746
+ "follow": bool,
747
+ "trace": bool,
748
+ "event": int,
749
+ "detail_offset": int,
750
+ "commands": list,
751
+ "pending_inputs": list,
752
+ "seen_findings": dict,
753
+ "operation": (str, type(None)),
754
+ }
755
+
756
+
757
+ def _read_saved_view(path: Path) -> dict:
758
+ saved = json.loads(path.read_text())
759
+ if not isinstance(saved, dict):
760
+ raise TypeError("expected a view object")
761
+ for name, field_type in _VIEW_FIELDS.items():
762
+ if name in saved and not isinstance(saved[name], field_type):
763
+ raise TypeError(f"invalid saved view field {name}")
764
+ for command in saved.get("commands", ()):
765
+ if (
766
+ not isinstance(command, dict)
767
+ or type(command.get("seq")) is not int
768
+ or command.get("kind") != "terminal.command"
769
+ or not isinstance(command.get("payload"), dict)
770
+ or not isinstance(command["payload"].get("summary"), str)
771
+ ):
772
+ raise TypeError("invalid saved command")
773
+ if pending := saved.get("pending_inputs"):
774
+ from .composer_delivery import ComposerDelivery
775
+
776
+ ComposerDelivery(pending, None)
777
+ return saved
778
+
779
+
780
+ @contextmanager
781
+ def workspace_view(state: Path, run: str, name: str | None):
782
+ if name is None:
783
+ yield {}, lambda _: None
784
+ return
785
+ folder = state / "views"
786
+ folder.mkdir(mode=0o700, exist_ok=True)
787
+ basename = hashlib.sha256(json.dumps([run, name]).encode()).hexdigest()
788
+ path = folder / (basename + ".json")
789
+ with (folder / (basename + ".lock")).open("a") as lock:
790
+ try:
791
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
792
+ except OSError as exc:
793
+ if exc.errno not in (errno.EACCES, errno.EAGAIN, errno.EWOULDBLOCK):
794
+ raise
795
+ raise WorkspaceViewBusy(
796
+ f"View {name!r} for run {run!r} is already open."
797
+ ) from exc
798
+ previous = {}
799
+ if path.exists():
800
+ try:
801
+ previous = _read_saved_view(path)
802
+ except (TypeError, ValueError) as error:
803
+ backup = path.with_suffix(f".corrupt-{uuid4().hex}.json")
804
+ path.replace(backup)
805
+ previous = {
806
+ "view_warning": f"Invalid saved view moved to {backup.name} · {error}"
807
+ }
808
+
809
+ def save(fields):
810
+ temp = path.with_suffix(".tmp")
811
+ with temp.open("w") as output:
812
+ json.dump(fields, output)
813
+ output.flush()
814
+ os.fsync(output.fileno())
815
+ temp.replace(path)
816
+
817
+ yield previous, save
818
+
819
+
820
+ def label(event):
821
+ from .file_edit_facts import is_file_edit
822
+ from .slash import public_role
823
+
824
+ payload = event["payload"]
825
+ if event["kind"] == "message.completed":
826
+ text = payload.get("text")
827
+ if text is None:
828
+ text = f"Stored reply · {payload['text_ref']['bytes']} bytes"
829
+ return f"{public_role(payload['role'])} {text}"
830
+ if is_file_edit(event):
831
+ return payload["summary"] if event["kind"] == "effect.proposed" else payload["fault"]
832
+ if event["kind"] == "effect.proposed":
833
+ return f"{payload['effect']} {payload['target']} {payload['digest']}"
834
+ if event["kind"] == "config.changed" and payload["field"] == "profile":
835
+ config = payload["to"]["config"]
836
+ return f"Core {config['core']} · Side {config['side']}"
837
+ if "pair" in payload:
838
+ pair = payload["pair"]
839
+ a = pair["baseline"] if pair["baseline"] is not None else "not scored"
840
+ b = pair["candidate"] if pair["candidate"] is not None else "not scored"
841
+ return f"{pair['seed']} {pair['metric']} {a} → {b} {pair['disposition']}"
842
+ if event["kind"] == "turn.finished":
843
+ return f"{public_role(payload['role'])} {payload['outcome']['kind']}"
844
+ return str(payload.get("summary", payload.get("target", payload.get("effect", ""))))
845
+
846
+
847
+ def detail(event, width):
848
+ body = json.dumps(event["payload"], ensure_ascii=False, indent=2)
849
+ title = f"{event['seq']} {event['kind']} ← {event['cause']}"
850
+ return [title] + [
851
+ piece
852
+ for line in body.splitlines()
853
+ for piece in (wrap_cells(line, max(8, width - 2)) or [""])
854
+ ]