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,449 @@
1
+ """Resolve a policy turn and its paired grades from committed events."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import math
8
+ from collections import defaultdict
9
+ from collections.abc import Callable, Iterable
10
+ from dataclasses import dataclass
11
+ from difflib import unified_diff
12
+ from typing import Any
13
+
14
+ from .file_edit_facts import is_file_edit
15
+ from .history_wire import input_text
16
+ from .protocol import Event
17
+ from .research_events import research_event
18
+
19
+ __all__ = ["PolicyTrace", "seed_lines"]
20
+
21
+
22
+ @dataclass(frozen=True, slots=True)
23
+ class PolicyTrace:
24
+ input: Event | None
25
+ observation: Event | None
26
+ interpretation_turn: Event | None
27
+ interpretation: Event | None
28
+ recommendation: Event | None
29
+ edit_request: Event | None
30
+ edit_turn: Event | None
31
+ edit_completion: Event | None
32
+ proposal: Event | None
33
+ approval: Event | None
34
+ claim: Event | None
35
+ applied: Event | None
36
+ baseline_hash: str | None
37
+ candidate_hash: str | None
38
+ grades: list[Event]
39
+ panels: dict[int, list[Event]]
40
+ gaps: list[str]
41
+ edit_diff: list[str] | None
42
+ diff_truncated: bool
43
+
44
+ @classmethod
45
+ def from_events(
46
+ cls,
47
+ rows: Iterable[Event],
48
+ run: str,
49
+ turn_id: str,
50
+ *,
51
+ edit_content: Callable[[dict], str],
52
+ ) -> PolicyTrace:
53
+ journal = _Journal(rows, edit_content)
54
+ turn = journal.reservations.get(turn_id)
55
+ if turn is None:
56
+ raise ValueError(f"Unknown turn {turn_id!r} in run {run!r}")
57
+ input_event = journal.source(turn)
58
+ if input_event and input_event["kind"] == "effect.proposed" and is_file_edit(input_event):
59
+ edit_request = input_event
60
+ edit_turn = turn
61
+ recommendation = journal.source(edit_request, "side.recommendation")
62
+ interpretation = journal.source(recommendation, "turn.finished")
63
+ reservation = journal.source(interpretation, "turn.reserved")
64
+ input_event = journal.source(reservation)
65
+ else:
66
+ reservation = turn
67
+ interpretation = journal.child(turn, "turn.finished", turn=turn_id)
68
+ recommendation = journal.child(interpretation, "side.recommendation")
69
+ edit_request = journal.child(recommendation, "effect.proposed", kind="file_edit")
70
+ edit_turn = journal.child(edit_request, "turn.reserved", role="core")
71
+ observation = journal.source(input_event, "experiment.observation")
72
+ effect = edit_request["payload"].get("id") if edit_request else None
73
+ edit_turn_id = edit_turn["turn"] if edit_turn else None
74
+ completed = journal.child(edit_turn, "turn.finished", turn=edit_turn_id)
75
+ proposal = journal.child(completed, "effect.proposed", effect=effect)
76
+ approval = journal.child(proposal, "effect.approved", effect=effect)
77
+ claim = journal.child(approval, "effect.claimed", effect=effect)
78
+ dispatch = None
79
+ while claim is not None:
80
+ dispatch = journal.child(claim, "effect.dispatching", effect=effect)
81
+ if dispatch is not None:
82
+ break
83
+ claim = journal.child(claim, "effect.claimed", effect=effect)
84
+ in_doubt = journal.child(dispatch, "effect.in_doubt", effect=effect)
85
+ applied = journal.child(dispatch, "effect.succeeded", effect=effect)
86
+ if applied is None:
87
+ applied = journal.child(
88
+ in_doubt or dispatch,
89
+ "effect.reconciled",
90
+ effect=effect,
91
+ result="succeeded",
92
+ )
93
+ baseline = edit_request["payload"].get("before") if edit_request else None
94
+ content = journal.verified_content(completed, proposal)
95
+ if proposal and edit_request:
96
+ proposed = proposal["payload"]
97
+ if proposed.get("before") != baseline or proposed.get("target") != edit_request[
98
+ "payload"
99
+ ].get("target"):
100
+ content = None
101
+ candidate = _content_hash(content) if content is not None else None
102
+
103
+ gaps = []
104
+ if not observation:
105
+ gaps.append("No grade observation is linked to the interpretation input.")
106
+ if not _advice_in_request(recommendation, edit_request) or not edit_turn:
107
+ gaps.append(
108
+ "No matching recommendation text was verified in the editor's reserved input."
109
+ )
110
+ if not (approval and applied):
111
+ gaps.append("No complete approval and application chain was found for this edit.")
112
+ if not candidate:
113
+ gaps.append("The editor output could not be verified against the proposal digest.")
114
+
115
+ edit_diff = None
116
+ diff_truncated = False
117
+ if edit_request and proposal and content is not None and baseline:
118
+ target = proposal["payload"]["target"]
119
+ if target == edit_request["payload"].get("target"):
120
+ prior = journal.prior_content(edit_request, target, baseline)
121
+ if prior is not None:
122
+ edit_diff, diff_truncated = _bounded_diff(target, prior, content)
123
+ if edit_diff is None:
124
+ gaps.append("Verified before and after source was unavailable for a code diff.")
125
+
126
+ grades = journal.grades(applied, observation, baseline, candidate)
127
+ return cls(
128
+ input=input_event,
129
+ observation=observation,
130
+ interpretation_turn=reservation,
131
+ interpretation=interpretation,
132
+ recommendation=recommendation,
133
+ edit_request=edit_request,
134
+ edit_turn=edit_turn,
135
+ edit_completion=completed,
136
+ proposal=proposal,
137
+ approval=approval,
138
+ claim=claim,
139
+ applied=applied,
140
+ baseline_hash=baseline,
141
+ candidate_hash=candidate,
142
+ grades=grades,
143
+ panels=journal.panels,
144
+ gaps=gaps,
145
+ edit_diff=edit_diff,
146
+ diff_truncated=diff_truncated,
147
+ )
148
+
149
+ def for_seed(self, run: str, turn_id: str, seed: int) -> dict[str, Any]:
150
+ matches = [event for event in self.grades if event["payload"]["pair"]["seed"] == seed]
151
+ gaps = list(self.gaps)
152
+ comparison = None
153
+ if len(matches) == 1:
154
+ comparison = matches[0]
155
+ elif matches:
156
+ gaps.append("Multiple paired grades match this seed and policy revision.")
157
+ else:
158
+ gaps.append("No paired grade matches this seed and the applied policy revision.")
159
+
160
+ pair = comparison["payload"]["pair"] if comparison else None
161
+ panel = None
162
+ delta = None
163
+ if comparison:
164
+ panel_rows = self.panels.get(comparison["seq"], [])
165
+ if panel_rows:
166
+ panel = panel_rows[-1]
167
+ delta = _score_delta(pair)
168
+ if delta is None:
169
+ gaps.append("A numeric score delta is unavailable for this disposition.")
170
+ if self.applied and comparison["cause"] != self.applied["seq"]:
171
+ gaps.append(
172
+ "The grade is matched by policy hashes. This grade has no direct "
173
+ "causal link to the applied edit in the journal."
174
+ )
175
+ gaps.append("The paired grade provides no action-level explanation for this seed.")
176
+ input_case = _input_case(self.input, seed)
177
+ if input_case is None:
178
+ gaps.append("The interpretation input has no structured case for this seed.")
179
+
180
+ return {
181
+ "run": run,
182
+ "turn": turn_id,
183
+ "seed": seed,
184
+ "input": self.input,
185
+ "observation": self.observation,
186
+ "interpretation_turn": self.interpretation_turn,
187
+ "interpretation": self.interpretation,
188
+ "input_case": input_case,
189
+ "recommendation": self.recommendation,
190
+ "advice_received": bool(
191
+ self.edit_turn and _advice_in_request(self.recommendation, self.edit_request)
192
+ ),
193
+ "edit_request": self.edit_request,
194
+ "edit_turn": self.edit_turn,
195
+ "edit_completion": self.edit_completion,
196
+ "proposal": self.proposal,
197
+ "approval": self.approval,
198
+ "claim": self.claim,
199
+ "applied": self.applied,
200
+ "baseline_hash": self.baseline_hash,
201
+ "candidate_hash": self.candidate_hash,
202
+ "comparison": comparison,
203
+ "pair": pair,
204
+ "delta": delta,
205
+ "panel": panel,
206
+ "gaps": gaps,
207
+ "edit_target": self.proposal["payload"]["target"] if self.proposal else None,
208
+ "edit_diff": self.edit_diff,
209
+ "diff_truncated": self.diff_truncated,
210
+ }
211
+
212
+
213
+ def seed_lines(report: dict[str, Any]) -> list[str]:
214
+ """Render the observed score and the journal links used to trace it."""
215
+ lines = [f"{report['run']} / {report['turn']} / Seed {report['seed']}"]
216
+ pair = report["pair"]
217
+ if pair:
218
+ lines.append(f"Paired {pair['metric']} · {pair['split']} · {pair['disposition']}")
219
+ baseline = pair.get("baseline")
220
+ candidate = pair.get("candidate")
221
+ delta = report["delta"]
222
+ baseline_text = str(baseline) if baseline is not None else "unavailable"
223
+ candidate_text = str(candidate) if candidate is not None else "unavailable"
224
+ delta_text = f"{delta:+g}" if delta is not None else "unavailable"
225
+ lines.append(f"Baseline {baseline_text} → candidate {candidate_text} · Δ {delta_text}")
226
+ else:
227
+ lines.append("Paired score unavailable")
228
+ lines.extend(report["gaps"])
229
+ case = report["input_case"]
230
+ if case is not None:
231
+ lines.append("Seed case supplied to the side agent")
232
+ lines.append(json.dumps(case, ensure_ascii=False, sort_keys=True))
233
+ if report["advice_received"]:
234
+ lines.append("The editor's reserved input included the recommendation.")
235
+ if report["edit_target"] and report["applied"]:
236
+ lines.append(f"Approved edit applied to {report['edit_target']}")
237
+ panel = report["panel"]
238
+ if panel:
239
+ lines.append(f"Decision · {panel['payload']['choice']}")
240
+ for field, label in (
241
+ ("observation", "Grade observation"),
242
+ ("input", "Interpretation input"),
243
+ ("interpretation_turn", "Interpretation reservation"),
244
+ ("interpretation", "Interpretation completed"),
245
+ ("recommendation", "Recommendation"),
246
+ ("edit_request", "Editor input"),
247
+ ("edit_turn", "Editor reservation"),
248
+ ("edit_completion", "Editor completed"),
249
+ ("proposal", "Edit proposal"),
250
+ ("approval", "Edit approval"),
251
+ ("claim", "Edit claimed"),
252
+ ("applied", "Edit applied"),
253
+ ("comparison", "Paired grade"),
254
+ ("panel", "Decision panel"),
255
+ ):
256
+ event = report[field]
257
+ if event:
258
+ citation = f"{label} · #{event['seq']} ← #{event['cause']}"
259
+ if field == "edit_request" and report["advice_received"]:
260
+ citation += " · recommendation received"
261
+ lines.append(citation)
262
+ summary = event["payload"].get("summary")
263
+ if field in {"input", "recommendation", "panel"} and isinstance(summary, str):
264
+ lines.extend(summary.splitlines())
265
+ if report["baseline_hash"]:
266
+ lines.append(f"Baseline SHA-256 {report['baseline_hash']}")
267
+ if report["candidate_hash"]:
268
+ lines.append(f"Candidate SHA-256 {report['candidate_hash']}")
269
+ if report["edit_diff"] is not None:
270
+ lines.append(f"Verified code diff · {report['edit_target']}")
271
+ lines.extend(report["edit_diff"])
272
+ if report["diff_truncated"]:
273
+ lines.append("Diff truncated")
274
+ return lines
275
+
276
+
277
+ class _Journal:
278
+ def __init__(self, rows: Iterable[Event], edit_content: Callable[[dict], str]) -> None:
279
+ self.by_seq = {}
280
+ self.children = defaultdict(list)
281
+ self.reservations = {}
282
+ self.panels = defaultdict(list)
283
+ self.edit_content = edit_content
284
+ for raw in rows:
285
+ event = research_event(raw)
286
+ self.by_seq[event["seq"]] = event
287
+ self.children[(event["cause"], event["kind"])].append(event)
288
+ if event["kind"] == "turn.reserved":
289
+ self.reservations[event["turn"]] = event
290
+ elif event["kind"] == "research.panel.revised":
291
+ self._index_panel(event)
292
+
293
+ def verified_content(self, completion: Event | None, proposal: Event | None) -> str | None:
294
+ if completion is None or proposal is None:
295
+ return None
296
+ payload = completion["payload"]
297
+ if payload["outcome"]["kind"] != "completed" or "edit_ref" not in payload:
298
+ return None
299
+ content = self.edit_content(payload["edit_ref"])
300
+ return _verified_content(content, proposal)
301
+
302
+ def source(self, event: Event | None, kind: str | None = None) -> Event | None:
303
+ source = self.by_seq.get(event["cause"]) if event else None
304
+ if source and (kind is None or source["kind"] == kind):
305
+ return source
306
+ return None
307
+
308
+ def child(
309
+ self, event: Event | None, event_kind: str, *, turn: str | None = None, **fields: Any
310
+ ) -> Event | None:
311
+ if event is None:
312
+ return None
313
+ matches = [
314
+ child
315
+ for child in self.children[(event["seq"], event_kind)]
316
+ if (turn is None or child["turn"] == turn)
317
+ and all(child["payload"].get(key) == value for key, value in fields.items())
318
+ ]
319
+ return matches[0] if len(matches) == 1 else None
320
+
321
+ def prior_content(self, request: Event, target: str, digest: str) -> str | None:
322
+ for event in reversed(self.by_seq.values()):
323
+ if event["seq"] >= request["seq"] or event["kind"] != "effect.proposed" or is_file_edit(event):
324
+ continue
325
+ if event["payload"].get("target") != target:
326
+ continue
327
+ content = self.verified_content(self.source(event, "turn.finished"), event)
328
+ if content is not None and _content_hash(content) == digest:
329
+ return content
330
+ return None
331
+
332
+ def grades(
333
+ self,
334
+ applied: Event | None,
335
+ observation: Event | None,
336
+ baseline: str | None,
337
+ candidate: str | None,
338
+ ) -> list[Event]:
339
+ if not applied or not baseline or not candidate:
340
+ return []
341
+ return [
342
+ event
343
+ for event in self.by_seq.values()
344
+ if event["kind"] == "experiment.paired_grade"
345
+ and event["seq"] > applied["seq"]
346
+ and (
347
+ event["cause"] == applied["seq"]
348
+ or observation is None
349
+ or event["cause"] == observation["cause"]
350
+ )
351
+ and event["payload"]["pair"]["baseline_hash"] == baseline
352
+ and event["payload"]["pair"]["candidate_hash"] == candidate
353
+ ]
354
+
355
+ def _index_panel(self, event: Event) -> None:
356
+ grade = self.by_seq.get(event["payload"].get("grade"))
357
+ if not grade or grade["kind"] != "experiment.paired_grade":
358
+ return
359
+ parent = self.source(event)
360
+ if parent and parent["kind"] in {"side.recommendation", "research.policy.selected"}:
361
+ wake = self.source(parent)
362
+ if wake and wake["kind"] == "turn.finished":
363
+ reservation = self.source(wake, "turn.reserved")
364
+ wake = self.source(reservation, "wake.scheduled")
365
+ if wake and (
366
+ wake["kind"] == "core.agent.woken"
367
+ or (wake["kind"] == "wake.scheduled" and wake["payload"].get("origin") == "advice")
368
+ ):
369
+ parent = self.source(wake)
370
+ elif parent and parent["kind"] == "advice.paused":
371
+ parent = self.source(parent)
372
+ if parent == grade and event["payload"].get("seed") == grade["payload"]["pair"]["seed"]:
373
+ self.panels[grade["seq"]].append(event)
374
+
375
+
376
+ def _advice_in_request(recommendation: Event | None, edit_request: Event | None) -> bool:
377
+ if not recommendation or not edit_request:
378
+ return False
379
+ advice = recommendation["payload"].get("summary")
380
+ instruction = edit_request["payload"].get("summary")
381
+ return isinstance(advice, str) and bool(advice) and advice == instruction
382
+
383
+
384
+ def _verified_content(content: str, proposal: Event) -> str | None:
385
+ proposed = proposal["payload"]
386
+ action = proposed.get("action")
387
+ if action == "replace":
388
+ fields = (action, proposed["target"], content, proposed["before"])
389
+ elif action == "create":
390
+ fields = (proposed["target"], content)
391
+ else:
392
+ return None
393
+ # These are the canonical proposal tuples used by src/journal.rs.
394
+ canonical = json.dumps(fields, ensure_ascii=False, separators=(",", ":")).encode()
395
+ if hashlib.sha256(canonical).hexdigest() != proposed["digest"]:
396
+ return None
397
+ return content
398
+
399
+
400
+ def _content_hash(content: str) -> str:
401
+ return hashlib.sha256(content.encode()).hexdigest()
402
+
403
+
404
+ def _bounded_diff(target: str, before: str, after: str) -> tuple[list[str], bool]:
405
+ lines = []
406
+ bytes_used = 0
407
+ for line in unified_diff(
408
+ before.splitlines(),
409
+ after.splitlines(),
410
+ f"a/{target}",
411
+ f"b/{target}",
412
+ n=2,
413
+ lineterm="",
414
+ ):
415
+ bytes_used += len(line.encode()) + 1
416
+ if len(lines) == 40 or bytes_used > 4096:
417
+ return lines, True
418
+ lines.append(line)
419
+ return lines, False
420
+
421
+
422
+ def _input_case(event: Event | None, seed: int) -> dict[str, Any] | None:
423
+ if not event:
424
+ return None
425
+ if event["kind"] != "input.received":
426
+ return None
427
+ summary = input_text(event["payload"]["parts"])
428
+ _, marker, text = summary.partition("Public case evidence: ")
429
+ if not marker:
430
+ return None
431
+ try:
432
+ cases = json.loads(text)
433
+ except json.JSONDecodeError:
434
+ return None
435
+ if not isinstance(cases, list):
436
+ return None
437
+ return next(
438
+ (case for case in cases if isinstance(case, dict) and case.get("seed") == seed),
439
+ None,
440
+ )
441
+
442
+
443
+ def _score_delta(pair: dict[str, Any]) -> float | None:
444
+ if pair.get("disposition") != "scored":
445
+ return None
446
+ baseline, candidate = pair.get("baseline"), pair.get("candidate")
447
+ if all(type(value) in (int, float) and math.isfinite(value) for value in (baseline, candidate)):
448
+ return candidate - baseline
449
+ return None
synth_code/rex_view.py ADDED
@@ -0,0 +1,58 @@
1
+ """Open a specific saved event in an explicitly selected Rex pane, without shell injection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import subprocess
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from .history import events
11
+
12
+
13
+ def show(client, seq, session, block):
14
+ if not session.startswith("session:") or not block.startswith("block:"):
15
+ raise ValueError("Explicit Rex session and pane IDs are required")
16
+ event = next(events(client, after=seq - 1, until=seq), None)
17
+ if event is None:
18
+ raise ValueError("Unknown source cursor")
19
+ cli = Path(sys.executable).parent / "synth-code"
20
+ result = subprocess.check_output(
21
+ [
22
+ "rex",
23
+ "split",
24
+ "-s",
25
+ session,
26
+ "-b",
27
+ block,
28
+ "--json",
29
+ "--focus=false",
30
+ "--shell",
31
+ "none",
32
+ "--",
33
+ str(cli),
34
+ "--state",
35
+ str(client.state.resolve()),
36
+ "--run",
37
+ client.run,
38
+ "attach",
39
+ "--event",
40
+ str(seq),
41
+ ],
42
+ text=True,
43
+ timeout=10,
44
+ )
45
+ return {
46
+ "run": client.run,
47
+ "seq": seq,
48
+ "session": session,
49
+ "anchor": block,
50
+ "viewer": json.loads(result),
51
+ }
52
+
53
+
54
+ def custody(client, action, effect_id, **binding):
55
+ """Route every managed source-view split through native effect custody."""
56
+ if action not in {"open", "lookup", "close"}:
57
+ raise ValueError("Unknown Rex view action")
58
+ return client.send(f"rex_{action}_view", effect_id=effect_id, **binding)
@@ -0,0 +1,108 @@
1
+ """Typed refusals for a client that cannot reach the local runtime socket.
2
+
3
+ Each refusal keeps its builtin ``OSError`` subclass (``FileNotFoundError``,
4
+ ``ConnectionRefusedError``, ``PermissionError``) so the daemon auto-start probe in
5
+ ``session.connect`` still recognises a missing or stale socket, while the CLI renders
6
+ one typed ``{"error": {...}}`` object instead of a traceback.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import errno
12
+ import os
13
+ from enum import StrEnum
14
+ from typing import TypedDict
15
+
16
+ __all__ = [
17
+ "RuntimeAccessDenied",
18
+ "RuntimeConnectRefused",
19
+ "RuntimeNotRunning",
20
+ "RuntimeUnreachable",
21
+ "RuntimeUnreachableCode",
22
+ "runtime_unreachable",
23
+ ]
24
+
25
+ START_HINT = "start it by running `synth-code` (or `synth-code start`) in this workspace"
26
+
27
+
28
+ class RuntimeUnreachableCode(StrEnum):
29
+ """Why the runtime socket could not be connected; stable codes surfaced verbatim."""
30
+
31
+ # No socket file: no runtime has started for this state directory.
32
+ NOT_RUNNING = "runtime_not_running"
33
+ # The socket file exists but nothing accepts on it: the runtime exited uncleanly.
34
+ CONNECT_REFUSED = "runtime_connect_refused"
35
+ # The socket or its directory is not accessible to this user.
36
+ ACCESS_DENIED = "runtime_access_denied"
37
+
38
+
39
+ class RuntimeRefusalPayload(TypedDict):
40
+ code: str
41
+ service: str
42
+ stage: str
43
+ socket: str
44
+ errno: int
45
+ detail: str
46
+ hint: str
47
+
48
+
49
+ class RuntimeUnreachable(OSError):
50
+ """The local runtime socket could not be connected."""
51
+
52
+ code: RuntimeUnreachableCode
53
+ service = "synth-code-runtime"
54
+ stage = "socket_connect"
55
+ hint: str
56
+
57
+ def __init__(self, socket_path: str, cause: OSError) -> None:
58
+ self.socket_path = socket_path
59
+ self.cause_errno = cause.errno or 0
60
+ super().__init__(
61
+ self.cause_errno,
62
+ f"{self.code.value}: {socket_path}: {cause.strerror or cause}",
63
+ socket_path,
64
+ )
65
+
66
+ def payload(self) -> RuntimeRefusalPayload:
67
+ return {
68
+ "code": self.code.value,
69
+ "service": self.service,
70
+ "stage": self.stage,
71
+ "socket": self.socket_path,
72
+ "errno": self.cause_errno,
73
+ "detail": str(self.strerror),
74
+ "hint": self.hint,
75
+ }
76
+
77
+
78
+ class RuntimeNotRunning(RuntimeUnreachable, FileNotFoundError):
79
+ code = RuntimeUnreachableCode.NOT_RUNNING
80
+ hint = f"No Synth Code runtime is running; {START_HINT}"
81
+
82
+
83
+ class RuntimeConnectRefused(RuntimeUnreachable, ConnectionRefusedError):
84
+ code = RuntimeUnreachableCode.CONNECT_REFUSED
85
+ hint = f"The runtime socket is stale (the runtime exited); {START_HINT} to restart it"
86
+
87
+
88
+ class RuntimeAccessDenied(RuntimeUnreachable, PermissionError):
89
+ code = RuntimeUnreachableCode.ACCESS_DENIED
90
+ hint = "The runtime socket is not accessible to this user; check the state directory owner and permissions"
91
+
92
+
93
+ _BY_ERRNO: dict[int, type[RuntimeUnreachable]] = {
94
+ errno.ENOENT: RuntimeNotRunning,
95
+ errno.ECONNREFUSED: RuntimeConnectRefused,
96
+ errno.EACCES: RuntimeAccessDenied,
97
+ errno.EPERM: RuntimeAccessDenied,
98
+ }
99
+
100
+
101
+ def runtime_unreachable(socket_path: os.PathLike[str] | str, cause: OSError) -> OSError:
102
+ """The typed refusal for a socket connect failure, or ``cause`` when no code fits."""
103
+ if isinstance(cause, RuntimeUnreachable):
104
+ return cause
105
+ refusal = _BY_ERRNO.get(cause.errno or 0)
106
+ if refusal is None:
107
+ return cause
108
+ return refusal(os.fspath(socket_path), cause)
@@ -0,0 +1,17 @@
1
+ {
2
+ "version": 2,
3
+ "adapter_line_bytes": 2097152,
4
+ "adapter_receipt_bytes": 2097152,
5
+ "adapter_stdout_bytes": 33554432,
6
+ "provider_line_bytes": 2097152,
7
+ "text_bytes": 1048576,
8
+ "output_bytes": 1048576,
9
+ "activity_bytes": 262144,
10
+ "steer_bytes": 2048,
11
+ "live_frames": 1024,
12
+ "live_retained_bytes": 2097152,
13
+ "live_delta_bytes": 16384,
14
+ "inline_text_bytes": 98304,
15
+ "adapter_timeout_seconds": 250,
16
+ "core_turn_timeout_seconds": 900
17
+ }