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,171 @@
1
+ """Track reserved turns and their provider-reported actions across TUI attaches."""
2
+
3
+ from concurrent.futures import Future
4
+ from datetime import datetime
5
+ from threading import Thread
6
+ from time import time
7
+
8
+ from .image_input import image_draft
9
+ from .session import validate_message
10
+ from .subscriptions import preview_tier
11
+ from .transcript_frames import LiveTranscript
12
+
13
+
14
+ def submit(fn, *args, **kwargs):
15
+ future = Future()
16
+
17
+ def execute():
18
+ try:
19
+ future.set_result(fn(*args, **kwargs))
20
+ except Exception as error: # noqa: BLE001 -- propagate the worker failure to its Future.
21
+ future.set_exception(error)
22
+
23
+ Thread(target=execute, name="synth-client-request", daemon=True).start()
24
+ return future
25
+
26
+
27
+ def wake_after(future, wake):
28
+ future.add_done_callback(lambda _: wake())
29
+ return future
30
+
31
+
32
+ def submit_core_turn(client, text, identity, expected_turn_id=None):
33
+ if image_draft(text):
34
+ raise ValueError("Image attachments are not supported by the Core model")
35
+ validate_message(text)
36
+ return client.send(
37
+ "submit_input",
38
+ id=identity,
39
+ target="core",
40
+ parts=[{"type": "text", "text": text}],
41
+ expected_turn_id=expected_turn_id,
42
+ )
43
+
44
+
45
+ class LiveTurns:
46
+ def __init__(self):
47
+ self.active = {}
48
+ self.known = set()
49
+ self.queued_inputs = set()
50
+ self.retrying = set()
51
+ self.transcript = LiveTranscript()
52
+
53
+ def observe_live(self, frame, after=0):
54
+ self.transcript.observe(frame, after)
55
+ kind = frame["kind"]
56
+ if kind == "turn.progress":
57
+ if (turn := self.active.get(frame["turn"])) is not None:
58
+ turn["live_action"] = frame["label"]
59
+ elif kind == "message.delta":
60
+ if (turn := self.active.get(frame["turn"])) is not None:
61
+ turn["live_action"] = "Writing a reply…"
62
+ elif kind == "turn.retrying":
63
+ fault = frame.get("fault")
64
+ ids = fault.get("ids") if isinstance(fault, dict) else None
65
+ identity = ids.get("turn") if isinstance(ids, dict) else None
66
+ if identity in self.active:
67
+ self.retrying.add(identity)
68
+
69
+ def reset_live(self):
70
+ self.retrying.clear()
71
+ self.transcript.reset()
72
+ for turn in self.active.values():
73
+ turn.pop("live_action", None)
74
+
75
+ def observe(self, event):
76
+ kind, data = event["kind"], event["payload"]
77
+ identity = data.get("id")
78
+ if kind == "input.queued":
79
+ self.queued_inputs.add(identity)
80
+ elif kind in (
81
+ "input.admitted",
82
+ "input.steered",
83
+ "input.withdrawn",
84
+ "input.not_delivered",
85
+ "input.quarantined",
86
+ ):
87
+ self.queued_inputs.discard(identity)
88
+ self.transcript.commit(event)
89
+ identity = event.get("turn") or data.get("id")
90
+ if kind in {
91
+ "turn.cancel_requested", "turn.finished", "message.completed",
92
+ "tool.started", "tool.finished", "reasoning.summary",
93
+ }:
94
+ self.retrying.discard(identity)
95
+ if kind == "turn.reserved":
96
+ self.known.add(identity)
97
+ self.active[identity] = {
98
+ "role": data["role"],
99
+ "provider": data["provider"],
100
+ "model": data.get("model"),
101
+ "effort": data.get("effort"),
102
+ "service_tier": data.get("service_tier"),
103
+ "action": "Working…",
104
+ "started_at": (
105
+ datetime.fromisoformat(started).timestamp()
106
+ if (started := event.get("at"))
107
+ else None
108
+ ),
109
+ }
110
+ elif kind == "turn.finished":
111
+ self.active.pop(identity, None)
112
+ elif identity in self.active:
113
+ turn = self.active[identity]
114
+ if kind == "turn.cancel_requested":
115
+ turn["action"] = "Stopping…"
116
+ turn.pop("live_action", None)
117
+ elif kind == "core.turn.service_tier":
118
+ turn["service_tier"] = data["service_tier"]
119
+
120
+ def current(self, preferred=None):
121
+ if preferred in self.active:
122
+ return preferred
123
+ core = [key for key, value in self.active.items() if value["role"] == "core"]
124
+ return core[0] if len(core) == 1 else None
125
+
126
+ def status_line(self, identity):
127
+ turn = self.active[identity]
128
+ action = "Retrying…" if identity in self.retrying else turn.get("live_action", turn["action"])
129
+ if turn["started_at"] is not None:
130
+ elapsed = max(0, int(time() - turn["started_at"]))
131
+ minutes, seconds = divmod(elapsed, 60)
132
+ duration = f"{minutes}m {seconds:02d}s" if minutes else f"{seconds}s"
133
+ action += f" · {duration}"
134
+ if turn["action"] != "Stopping…":
135
+ action += " · Ctrl+C"
136
+ return action
137
+
138
+ def core_model_label(self):
139
+ turn = self.active.get(self.current())
140
+ if turn is None or turn["role"] != "core" or not turn["model"]:
141
+ return ""
142
+ tier = preview_tier(turn["service_tier"], {})
143
+ return " ".join(filter(None, (turn["model"], turn["effort"], tier)))
144
+
145
+ def control(self, client, command, rest, operation, current):
146
+ if command == "cancel":
147
+ target = rest or current
148
+ if not target:
149
+ raise ValueError(
150
+ "Choose a turn to cancel" if self.active else "No active turn"
151
+ )
152
+ result = client.send("cancel", id=target)
153
+ return "Stopping…" if result["outcome"] == "stopping" else result["outcome"]
154
+ first, _, remaining = rest.partition(" ")
155
+ target, message = (
156
+ (first, remaining)
157
+ if command == "steer" and first in self.known
158
+ else (current, rest)
159
+ )
160
+ if not target:
161
+ raise ValueError(
162
+ "Choose a turn to steer" if self.active else "No active turn"
163
+ )
164
+ if not message.strip():
165
+ raise ValueError("Enter a steering message")
166
+ result = client.send("steer", id=target, operation=operation, message=message)
167
+ return (
168
+ "Steering queued"
169
+ if result.get("outcome") == "pending"
170
+ else result.get("outcome", "Steering requested")
171
+ )
@@ -0,0 +1,311 @@
1
+ """Per-agent model selection for the attached run."""
2
+
3
+ import enum
4
+ import json
5
+
6
+ from . import slash, subscriptions
7
+
8
+ _AGENT_NAMES = {
9
+ "core": "Core",
10
+ "side": "Advisor",
11
+ "manager": "Manager",
12
+ "visualizor": "Visualizor",
13
+ }
14
+
15
+
16
+ QUEUED_NOTE = "queued — applies at next compaction"
17
+
18
+
19
+ class SettingsOutcome(enum.Enum):
20
+ """What Core did with a model or effort change (`ModelReceipt.settings`)."""
21
+
22
+ QUEUED = "queued"
23
+ APPLIED = "applied"
24
+ NO_THREAD = "no_thread"
25
+
26
+
27
+ def agent_name(role):
28
+ return _AGENT_NAMES.get(role, role)
29
+
30
+
31
+ def model_binding(role, provider, models, service_tiers, capabilities):
32
+ selection = models.get((role, provider), {})
33
+ model = selection.get("model")
34
+ details = {}
35
+ if provider == "inkling-2-mini":
36
+ details = subscriptions.available_models(provider)[model or provider]
37
+ effort = selection.get("effort") or details.get("default")
38
+ tier = service_tiers.get((role, provider, model or provider))
39
+ return slash.binding_detail(
40
+ provider,
41
+ model,
42
+ effort,
43
+ subscriptions.preview_tier(tier, details),
44
+ show_provider=False,
45
+ )
46
+
47
+
48
+ class ModelPicker:
49
+ def __init__(self, client, submit, arguments, workspace=None):
50
+ if client.viewer is not None:
51
+ raise ValueError("Changing models requires the owner terminal")
52
+ snapshot = client.send("snapshot")
53
+ if "model_targets" not in snapshot:
54
+ raise ValueError("Restart the run daemon to enable model selection")
55
+ self.targets = [row for row in snapshot["model_targets"] if row["model"]]
56
+ self.names = {row["role"]: agent_name(row["role"]) for row in self.targets}
57
+ kinds = {"side_agent": "Side agent", "subagent": "Subagent", "worker": "Worker"}
58
+ for node in snapshot.get("nodes", []):
59
+ if node["id"] in self.names and node["id"] not in _AGENT_NAMES:
60
+ kind = json.loads(node["assignment"])[1]
61
+ self.names[node["id"]] = f"{kinds[kind]} · {node['id']}"
62
+ if not self.targets:
63
+ raise ValueError("No live agents with selectable models")
64
+ self.workspace = workspace
65
+ self.client = client
66
+ self.submit = submit
67
+ self.target_index = self.index = 0
68
+ self.catalog = None
69
+ self.models = []
70
+ self.requested = self.requested_effort = None
71
+ self.selected_model = None
72
+ self.details = {}
73
+ parts = arguments.split()
74
+ if len(parts) > 3:
75
+ raise ValueError("Usage: /model [AGENT [MODEL [EFFORT]]]")
76
+ if parts:
77
+ names = {row["role"]: i for i, row in enumerate(self.targets)}
78
+ role = names.get(parts[0])
79
+ if role is None:
80
+ aliases = {label.casefold(): key for key, label in _AGENT_NAMES.items()}
81
+ aliases.update({"side": "side", "side-agent": "side"})
82
+ role = names.get(aliases.get(parts[0].casefold()))
83
+ if role is None:
84
+ raise ValueError(f"Unknown live agent {parts[0]}")
85
+ self.target_index = role
86
+ self.open_models()
87
+ self.requested = parts[1] if len(parts) >= 2 else None
88
+ self.requested_effort = parts[2] if len(parts) == 3 else None
89
+
90
+ @property
91
+ def target(self):
92
+ return self.targets[self.target_index]
93
+
94
+ def open_models(self):
95
+ self.catalog = self.submit(
96
+ subscriptions.available_models, self.target["provider"], self.workspace
97
+ )
98
+ self.models = []
99
+ self.index = 0
100
+
101
+ def refresh(self):
102
+ if self.catalog is None or not self.catalog.done() or self.models:
103
+ return
104
+ self.details = self.catalog.result()
105
+ self.models = list(self.details)
106
+ if not self.models:
107
+ raise ValueError("Provider returned no selectable models")
108
+ current = self.target["model"]
109
+ if current in self.models:
110
+ self.index = self.models.index(current)
111
+
112
+ def rows(self):
113
+ if self.catalog is None:
114
+ title = "Choose an agent"
115
+ names = [
116
+ f"{self.names[row['role']]} · {row['model']}" for row in self.targets
117
+ ]
118
+ selected = self.target_index
119
+ elif self.selected_model:
120
+ options = self.details[self.selected_model]
121
+ title = f"{self.selected_model} · Reasoning effort · {options['tier']}"
122
+ names = options["efforts"]
123
+ selected = self.index
124
+ else:
125
+ title = f"{self.names[self.target['role']]} · Choose a model"
126
+ if not self.models:
127
+ return [("brand", title), ("muted", "Loading models…")]
128
+ names = [
129
+ m + (" (current)" if m == self.target["model"] else "")
130
+ for m in self.models
131
+ ]
132
+ selected = self.index
133
+ start = max(0, selected - 5)
134
+ rows = [("brand", f"{title} {selected + 1}/{len(names)}")]
135
+ for i in range(start, min(len(names), start + 6)):
136
+ rows.append(
137
+ ("selection", "› " + names[i])
138
+ if i == selected
139
+ else ("detail", " " + names[i])
140
+ )
141
+ return rows
142
+
143
+ def move(self, step):
144
+ if self.catalog is None:
145
+ self.target_index = (self.target_index + step) % len(self.targets)
146
+ elif self.selected_model:
147
+ self.index = (self.index + step) % len(
148
+ self.details[self.selected_model]["efforts"]
149
+ )
150
+ elif self.models:
151
+ self.index = (self.index + step) % len(self.models)
152
+
153
+ def back(self):
154
+ if self.catalog is None:
155
+ return False
156
+ if self.selected_model:
157
+ self.index = self.models.index(self.selected_model)
158
+ self.selected_model = None
159
+ else:
160
+ self.catalog = None
161
+ self.requested = self.requested_effort = None
162
+ return True
163
+
164
+ def select(self):
165
+ if self.catalog is None:
166
+ self.open_models()
167
+ elif self.models:
168
+ model = self.selected_model or self.requested or self.models[self.index]
169
+ if model not in self.models:
170
+ raise ValueError(f"Unknown model {model}")
171
+ options = self.details[model]
172
+ efforts = options.get("efforts", [])
173
+ if self.requested_effort and self.requested_effort not in efforts:
174
+ raise ValueError(
175
+ f"Unsupported effort for {model}: {self.requested_effort}"
176
+ )
177
+ if efforts and not self.selected_model and not self.requested_effort:
178
+ self.selected_model = model
179
+ self.requested = None
180
+ current = (
181
+ self.target.get("effort") if model == self.target["model"] else None
182
+ )
183
+ default = current or options["default"]
184
+ self.index = efforts.index(default) if default in efforts else 0
185
+ return None
186
+ effort = self.requested_effort or (efforts[self.index] if efforts else None)
187
+ if effort and "effort" not in self.target:
188
+ raise ValueError("Restart the run daemon to enable effort selection")
189
+ receipt = self.client.send(
190
+ "set_model",
191
+ role=self.target["role"],
192
+ provider=self.target["provider"],
193
+ model=model,
194
+ effort=effort,
195
+ )
196
+ outcome = " · ".join(
197
+ filter(
198
+ None,
199
+ (
200
+ self.names[self.target["role"]],
201
+ model,
202
+ effort,
203
+ options.get("tier"),
204
+ ),
205
+ )
206
+ )
207
+ settings = SettingsOutcome(receipt["settings"])
208
+ if settings is SettingsOutcome.QUEUED:
209
+ outcome = f"{outcome} · {QUEUED_NOTE}"
210
+ return {"outcome": outcome, "result_seq": receipt.get("seq"), "settings": settings.value}
211
+
212
+ return None
213
+
214
+
215
+ class ServiceTierPicker:
216
+ def __init__(self, client, submit, arguments, workspace=None, *, role="core"):
217
+ if client.viewer is not None:
218
+ raise ValueError("Changing service tiers requires the owner terminal")
219
+ self.requested = arguments.casefold()
220
+ if self.requested and self.requested not in subscriptions.SERVICE_TIERS:
221
+ raise ValueError("Usage: /service-tier [standard|fast|ultrafast]")
222
+ snapshot = client.send("snapshot")
223
+ self.target = next(
224
+ (row for row in snapshot.get("model_targets", []) if row["role"] == role),
225
+ None,
226
+ )
227
+ if not self.target or not self.target["model"]:
228
+ raise ValueError("The active model has no selectable service tiers")
229
+ if "service_tier" not in self.target:
230
+ raise ValueError("Restart the run daemon to enable service tier selection")
231
+ self.model = self.target["model"]
232
+ self.client = client
233
+ self.catalog = submit(
234
+ subscriptions.available_models, self.target["provider"], workspace
235
+ )
236
+ self.tiers = {}
237
+ self.current = None
238
+ self.index = 0
239
+
240
+ def refresh(self):
241
+ if self.tiers or not self.catalog.done():
242
+ return
243
+ details = self.catalog.result().get(self.model, {})
244
+ self.tiers = details.get("service_tiers", {})
245
+ if not self.tiers:
246
+ raise ValueError(f"Service tiers unavailable for {self.model}")
247
+ self.current = subscriptions.tier_label(self.target["service_tier"], details)
248
+ if self.current in self.tiers:
249
+ self.index = list(self.tiers).index(self.current)
250
+
251
+ def rows(self):
252
+ title = ("brand", f"{self.model} · Service tier")
253
+ if not self.tiers:
254
+ return [title, ("muted", "Loading service tiers…")]
255
+ rows = [title]
256
+ for index, name in enumerate(self.tiers):
257
+ active = index == self.index
258
+ label = name.capitalize() + (" (current)" if name == self.current else "")
259
+ rows.append(
260
+ (
261
+ "selection" if active else "detail",
262
+ ("› " if active else " ") + label,
263
+ )
264
+ )
265
+ return rows
266
+
267
+ def move(self, step):
268
+ if self.tiers:
269
+ self.index = (self.index + step) % len(self.tiers)
270
+
271
+ def back(self):
272
+ return False
273
+
274
+ def select(self):
275
+ if not self.tiers:
276
+ return None
277
+ name = self.requested or list(self.tiers)[self.index]
278
+ if name not in self.tiers:
279
+ raise ValueError(f"{name.capitalize()} is unavailable for {self.model}")
280
+ receipt = self.client.send(
281
+ "set_service_tier",
282
+ role=self.target["role"],
283
+ provider=self.target["provider"],
284
+ model=self.model,
285
+ tier=self.tiers[name],
286
+ )
287
+ return {
288
+ "outcome": f"{self.model} · {name.capitalize()}",
289
+ "result_seq": receipt.get("seq"),
290
+ }
291
+
292
+
293
+ def refresh_picker(picker, finish, status):
294
+ """Update an open picker and record a selection when it settles."""
295
+ if picker is None:
296
+ return [], None, status
297
+ try:
298
+ picker.refresh()
299
+ if picker.requested and (result := picker.select()):
300
+ finish(result)
301
+ # A queued change leaves the footer on the live model, so the status
302
+ # line carries the pending change until something else replaces it.
303
+ # The typed daemon outcome decides, never the display text. The value is a
304
+ # string so the result stays JSON-safe in the stored command payload.
305
+ queued = result.get("settings") == SettingsOutcome.QUEUED.value
306
+ return [], None, result["outcome"] if queued else ""
307
+ return picker.rows(), picker, status
308
+ except (ValueError, KeyError, OSError) as error:
309
+ status = str(error) or "Provider model list unavailable"
310
+ finish({"outcome": status})
311
+ return [], None, status
@@ -0,0 +1 @@
1
+ {"platform": "macosx_15_0_arm64", "sha256": "f9bd6d312b8031d5f54784c86066f158f1e017cd0f014d5cb2f24070018f9ec4", "version": "0.0.1"}
Binary file
synth_code/native.py ADDED
@@ -0,0 +1,95 @@
1
+ """Locate and verify the native runtime a wheel ships under ``synth_code/native``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from dataclasses import dataclass
8
+ from importlib import metadata
9
+ from pathlib import Path
10
+
11
+ from . import edition
12
+
13
+ DISTRIBUTION = "synth-code"
14
+ NATIVE_ROOT = Path(__file__).with_name("native")
15
+ RUNTIME_NAME = "synth-code-runtime"
16
+ MANIFEST_NAME = "manifest.json"
17
+
18
+
19
+ class NativeRuntimeRefused(RuntimeError):
20
+ """The runtime bytes cannot be trusted as the ones this package shipped."""
21
+
22
+ def __init__(self, code: str, path: Path, *, expected: str | None = None, actual: str | None = None):
23
+ self.code = code
24
+ self.path = path
25
+ self.expected = expected
26
+ self.actual = actual
27
+ detail = f" (expected {expected}, found {actual})" if expected or actual else ""
28
+ super().__init__(f"{code}: {path}{detail}")
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class NativeRuntime:
33
+ path: Path
34
+ sha256: str
35
+ version: str | None
36
+ """The manifest version; ``None`` for an explicitly selected source-tree runtime."""
37
+
38
+
39
+ def product_version() -> str:
40
+ try:
41
+ return metadata.version(DISTRIBUTION)
42
+ except metadata.PackageNotFoundError as exc:
43
+ raise NativeRuntimeRefused("package_metadata_missing", Path(__file__).parent) from exc
44
+
45
+
46
+ def channel(version: str) -> str:
47
+ """Beta builds report the beta channel; public builds stable or nightly from the version."""
48
+ if edition.BUILD_EDITION is edition.Edition.BETA:
49
+ return "beta"
50
+ return "nightly" if ".dev" in version else "stable"
51
+
52
+
53
+ def version_line() -> str:
54
+ version = product_version()
55
+ return f"Synth Code {version} · {channel(version)}"
56
+
57
+
58
+ def file_sha256(path: Path) -> str:
59
+ try:
60
+ return hashlib.sha256(path.read_bytes()).hexdigest()
61
+ except FileNotFoundError as exc:
62
+ raise NativeRuntimeRefused("native_runtime_missing", path) from exc
63
+
64
+
65
+ def installed_runtime(root: Path = NATIVE_ROOT, *, version: str | None = None) -> NativeRuntime:
66
+ """Return the packaged runtime only when its bytes and version match the manifest."""
67
+ manifest_path = root / MANIFEST_NAME
68
+ try:
69
+ manifest = json.loads(manifest_path.read_text())
70
+ except FileNotFoundError as exc:
71
+ raise NativeRuntimeRefused("native_manifest_missing", manifest_path) from exc
72
+ except json.JSONDecodeError as exc:
73
+ raise NativeRuntimeRefused("native_manifest_invalid", manifest_path) from exc
74
+ if not isinstance(manifest, dict) or not all(
75
+ isinstance(manifest.get(key), str) for key in ("version", "sha256")
76
+ ):
77
+ raise NativeRuntimeRefused("native_manifest_invalid", manifest_path)
78
+ expected_version = version if version is not None else product_version()
79
+ if manifest["version"] != expected_version:
80
+ raise NativeRuntimeRefused(
81
+ "native_version_mismatch", manifest_path, expected=expected_version, actual=manifest["version"]
82
+ )
83
+ binary = root / RUNTIME_NAME
84
+ digest = file_sha256(binary)
85
+ if digest != manifest["sha256"]:
86
+ raise NativeRuntimeRefused("native_runtime_tampered", binary, expected=manifest["sha256"], actual=digest)
87
+ return NativeRuntime(binary, digest, manifest["version"])
88
+
89
+
90
+ def source_runtime(path: Path) -> NativeRuntime:
91
+ """Accept an explicitly named runtime from a checkout; its identity is its own bytes."""
92
+ binary = Path(path).resolve()
93
+ if not binary.is_file():
94
+ raise NativeRuntimeRefused("native_runtime_missing", binary)
95
+ return NativeRuntime(binary, file_sha256(binary), None)