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.
- synth_code/__init__.py +0 -0
- synth_code/account.py +551 -0
- synth_code/account_http.py +86 -0
- synth_code/account_refusal.py +80 -0
- synth_code/accounting.py +148 -0
- synth_code/activity_grouping.py +149 -0
- synth_code/agent_panels.py +127 -0
- synth_code/approvals.py +397 -0
- synth_code/blobs.py +31 -0
- synth_code/cli.py +734 -0
- synth_code/client.py +413 -0
- synth_code/composer_delivery.py +139 -0
- synth_code/conversation.py +949 -0
- synth_code/daemon.py +34 -0
- synth_code/edition.py +306 -0
- synth_code/enrollment.py +304 -0
- synth_code/file_edit_facts.py +10 -0
- synth_code/freeze.py +234 -0
- synth_code/grant.py +59 -0
- synth_code/history.py +140 -0
- synth_code/history_generated.py +219 -0
- synth_code/history_wire.py +166 -0
- synth_code/image_input.py +109 -0
- synth_code/image_preview.py +105 -0
- synth_code/legacy_history.py +161 -0
- synth_code/live_turns.py +171 -0
- synth_code/model_picker.py +311 -0
- synth_code/native/manifest.json +1 -0
- synth_code/native/synth-code-runtime +0 -0
- synth_code/native.py +95 -0
- synth_code/oauth.py +284 -0
- synth_code/operator.py +116 -0
- synth_code/pack_source.py +65 -0
- synth_code/panel_request.py +291 -0
- synth_code/panels.py +40 -0
- synth_code/plugin_host.py +459 -0
- synth_code/protocol.py +35 -0
- synth_code/provider.py +313 -0
- synth_code/provider_fault.py +173 -0
- synth_code/provider_frames.py +571 -0
- synth_code/recommendation.py +324 -0
- synth_code/report.py +72 -0
- synth_code/research_events.py +44 -0
- synth_code/research_trace.py +449 -0
- synth_code/rex_view.py +58 -0
- synth_code/runtime_refusal.py +108 -0
- synth_code/schema/budgets.json +17 -0
- synth_code/schema/history-v2.json +1002 -0
- synth_code/session.py +291 -0
- synth_code/shoal.py +564 -0
- synth_code/side_panel.py +309 -0
- synth_code/skills.py +269 -0
- synth_code/slash.py +425 -0
- synth_code/source_view.py +135 -0
- synth_code/starter.json +13 -0
- synth_code/stdio.py +75 -0
- synth_code/stream.py +142 -0
- synth_code/subscriptions.py +267 -0
- synth_code/synth_authority.py +362 -0
- synth_code/synth_extra.py +32 -0
- synth_code/terminal.py +817 -0
- synth_code/terminal_journal.py +284 -0
- synth_code/terminal_layout.py +643 -0
- synth_code/terminal_surfaces.py +470 -0
- synth_code/terminal_viewport.py +125 -0
- synth_code/tool_render.py +86 -0
- synth_code/transcript_frames.py +212 -0
- synth_code/transcript_placement.py +63 -0
- synth_code/transcript_rows.py +456 -0
- synth_code/transport.py +243 -0
- synth_code/v001_history.py +468 -0
- synth_code/view.py +854 -0
- synth_code/views/__init__.py +93 -0
- synth_code/views/charts.py +196 -0
- synth_code/views/curses_adapter.py +116 -0
- synth_code/views/engine.py +170 -0
- synth_code/views/model.py +226 -0
- synth_code/views/primitives.py +270 -0
- synth_code/views/tiling.py +124 -0
- synth_code-0.0.1.dist-info/METADATA +50 -0
- synth_code-0.0.1.dist-info/RECORD +110 -0
- synth_code-0.0.1.dist-info/WHEEL +5 -0
- synth_code-0.0.1.dist-info/entry_points.txt +6 -0
- synth_code-0.0.1.dist-info/licenses/temper/LICENSE-APACHE +190 -0
- synth_code-0.0.1.dist-info/licenses/temper/LICENSE-MIT +21 -0
- synth_code-0.0.1.dist-info/licenses/temper/SOURCE.json +433 -0
- synth_code-0.0.1.dist-info/top_level.txt +2 -0
- synth_code_plugins/_sdk/__init__.py +19 -0
- synth_code_plugins/_sdk/callback_wire.py +240 -0
- synth_code_plugins/_sdk/callbacks.py +317 -0
- synth_code_plugins/_sdk/compliance.py +51 -0
- synth_code_plugins/_sdk/contracts.py +236 -0
- synth_code_plugins/_sdk/discovery.py +75 -0
- synth_code_plugins/_sdk/job_binding.py +71 -0
- synth_code_plugins/_sdk/lifecycle.py +50 -0
- synth_code_plugins/_sdk/lifecycle_generated.py +15 -0
- synth_code_plugins/_sdk/manifest.py +269 -0
- synth_code_plugins/_sdk/pack.py +332 -0
- synth_code_plugins/_sdk/push.py +98 -0
- synth_code_plugins/_sdk/records.py +26 -0
- synth_code_plugins/_sdk/registry.py +491 -0
- synth_code_plugins/_sdk/schemas.py +210 -0
- synth_code_plugins/_sdk/sources.py +230 -0
- synth_code_plugins/_sdk/surfaces.py +54 -0
- synth_code_plugins/_sdk/tools.py +172 -0
- synth_code_plugins/_sdk/worker_memory.py +49 -0
- synth_code_plugins/core/SKILL.md +6 -0
- synth_code_plugins/core/__init__.py +21 -0
- synth_code_plugins/core/plugin.toml +44 -0
- synth_code_plugins/core/source.py +18 -0
synth_code/client.py
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
"""Local protocol transport and read-only inspection for SYN-6245."""
|
|
2
|
+
|
|
3
|
+
from collections import deque
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from threading import Condition, Lock, Thread
|
|
6
|
+
from threading import Event as StopSignal
|
|
7
|
+
|
|
8
|
+
from .edition import Edition, edition_from_initialize
|
|
9
|
+
from .history_generated import DurableEvent, HistorySnapshot
|
|
10
|
+
from .history_wire import message_text, read_event, read_history
|
|
11
|
+
from .protocol import Event
|
|
12
|
+
from .transport import CommandCapacity, Connection
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Rejected(ValueError):
|
|
16
|
+
def __init__(self, message, *, refusal=None, fault=None):
|
|
17
|
+
super().__init__(message)
|
|
18
|
+
self.refusal = refusal
|
|
19
|
+
self.fault = fault
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Client:
|
|
23
|
+
_transport: Connection | None = None
|
|
24
|
+
|
|
25
|
+
def __init__(self, state: Path, run: str, version: int = 2, viewer=None):
|
|
26
|
+
self.viewer = viewer
|
|
27
|
+
self.state = state.absolute()
|
|
28
|
+
self.run = run
|
|
29
|
+
self.version = version
|
|
30
|
+
self._lock = Lock()
|
|
31
|
+
self._transport = None
|
|
32
|
+
self._closed = False
|
|
33
|
+
self._subscription = None
|
|
34
|
+
self.edition = Edition.BETA
|
|
35
|
+
|
|
36
|
+
def __enter__(self):
|
|
37
|
+
return self
|
|
38
|
+
|
|
39
|
+
def __exit__(self, *_):
|
|
40
|
+
self.close()
|
|
41
|
+
|
|
42
|
+
def __del__(self):
|
|
43
|
+
if self._transport is not None:
|
|
44
|
+
self._transport.close()
|
|
45
|
+
|
|
46
|
+
def close(self):
|
|
47
|
+
with self._lock:
|
|
48
|
+
self._closed = True
|
|
49
|
+
subscription, transport = self._subscription, self._transport
|
|
50
|
+
self._transport = None
|
|
51
|
+
if transport is not None:
|
|
52
|
+
transport.close()
|
|
53
|
+
if subscription is not None:
|
|
54
|
+
subscription.close()
|
|
55
|
+
|
|
56
|
+
def page(self, after: int) -> list[Event]:
|
|
57
|
+
events = self.send("events", after=after, limit=50)["events"]
|
|
58
|
+
if self.viewer is None:
|
|
59
|
+
for event in events:
|
|
60
|
+
read_event(event, self.run)
|
|
61
|
+
return events
|
|
62
|
+
|
|
63
|
+
def event(self, sequence: int) -> DurableEvent:
|
|
64
|
+
if type(sequence) is not int or sequence < 1:
|
|
65
|
+
raise ValueError("Invalid event sequence")
|
|
66
|
+
records = self.send("events", after=sequence - 1, limit=1)["events"]
|
|
67
|
+
if not records or records[0]["seq"] != sequence:
|
|
68
|
+
raise ValueError(f"Unknown event #{sequence}")
|
|
69
|
+
return read_event(records[0], self.run)
|
|
70
|
+
|
|
71
|
+
def snapshot(self, *, at: int | None = None, before: int | None = None) -> HistorySnapshot:
|
|
72
|
+
_, history = self._snapshot(at=at, before=before)
|
|
73
|
+
return history
|
|
74
|
+
|
|
75
|
+
def _connection(self):
|
|
76
|
+
with self._lock:
|
|
77
|
+
if self._closed:
|
|
78
|
+
raise ConnectionError("Local engine client closed")
|
|
79
|
+
if self._transport is None or self._transport.closed:
|
|
80
|
+
name = "view.sock" if self.viewer is not None else "agent.sock"
|
|
81
|
+
transport = Connection(self.state / name, self.run, self.viewer, self.version)
|
|
82
|
+
try:
|
|
83
|
+
metadata = _result(
|
|
84
|
+
transport.request(
|
|
85
|
+
"initialize",
|
|
86
|
+
{
|
|
87
|
+
"client_version": "0.0.1",
|
|
88
|
+
"capabilities": [
|
|
89
|
+
"subscribe",
|
|
90
|
+
"live_frames",
|
|
91
|
+
"multiplexed_commands",
|
|
92
|
+
],
|
|
93
|
+
},
|
|
94
|
+
timeout=5,
|
|
95
|
+
)
|
|
96
|
+
)
|
|
97
|
+
if (
|
|
98
|
+
not isinstance(metadata, dict)
|
|
99
|
+
or metadata.get("schema") != 2
|
|
100
|
+
or not isinstance(metadata.get("capabilities"), list)
|
|
101
|
+
or "subscribe" not in metadata["capabilities"]
|
|
102
|
+
):
|
|
103
|
+
raise ConnectionError("Local engine does not support v2 subscriptions")
|
|
104
|
+
self.edition = edition_from_initialize(metadata)
|
|
105
|
+
limits = metadata.get("limits")
|
|
106
|
+
limit = limits.get("in_flight") if isinstance(limits, dict) else None
|
|
107
|
+
if type(limit) is int and limit > 0:
|
|
108
|
+
transport.pending_limit = min(transport.pending_limit, limit)
|
|
109
|
+
except (OSError, ValueError):
|
|
110
|
+
transport.close()
|
|
111
|
+
raise
|
|
112
|
+
self._transport = transport
|
|
113
|
+
return self._transport
|
|
114
|
+
|
|
115
|
+
def send(self, op, **fields):
|
|
116
|
+
timeout = 910 if op == "turn" else 12
|
|
117
|
+
connection = self._connection()
|
|
118
|
+
try:
|
|
119
|
+
return _result(connection.request(op, fields, timeout))
|
|
120
|
+
except CommandCapacity as error:
|
|
121
|
+
limit = connection.pending_limit
|
|
122
|
+
raise Rejected(
|
|
123
|
+
str(error),
|
|
124
|
+
refusal={
|
|
125
|
+
"code": "invalid_request",
|
|
126
|
+
"stage": "request",
|
|
127
|
+
"retryable": True,
|
|
128
|
+
"failed_check": "in_flight_commands_lt",
|
|
129
|
+
"expected": limit,
|
|
130
|
+
"actual": limit,
|
|
131
|
+
"ids": {"run": self.run},
|
|
132
|
+
},
|
|
133
|
+
) from error
|
|
134
|
+
|
|
135
|
+
def subscribe(self, after=0, *, wake=lambda: None, with_history=False, source=None):
|
|
136
|
+
if source is not None and (
|
|
137
|
+
with_history
|
|
138
|
+
or not isinstance(source, tuple)
|
|
139
|
+
or len(source) != 2
|
|
140
|
+
or any(not isinstance(identity, str) or not identity for identity in source)
|
|
141
|
+
):
|
|
142
|
+
raise ValueError("Scoped subscription requires a source and view identity")
|
|
143
|
+
with self._lock:
|
|
144
|
+
if self._closed:
|
|
145
|
+
raise ConnectionError("Local engine client closed")
|
|
146
|
+
if self._subscription is not None:
|
|
147
|
+
raise ValueError("This client already has an active subscription")
|
|
148
|
+
self._subscription = Subscription(
|
|
149
|
+
self, after, wake, with_history=with_history, source=source
|
|
150
|
+
)
|
|
151
|
+
return self._subscription
|
|
152
|
+
|
|
153
|
+
def _snapshot(self, *, at, before):
|
|
154
|
+
fields = {}
|
|
155
|
+
if at is not None:
|
|
156
|
+
fields["at"] = at
|
|
157
|
+
if before is not None:
|
|
158
|
+
fields["before"] = before
|
|
159
|
+
snapshot = self.send("snapshot", **fields)
|
|
160
|
+
if not isinstance(snapshot, dict):
|
|
161
|
+
raise ConnectionError("Invalid snapshot from the local engine")
|
|
162
|
+
return snapshot, read_history(snapshot.get("history"), self.run, at=at, before=before)
|
|
163
|
+
|
|
164
|
+
def history_page(self, *, at=None, before=None):
|
|
165
|
+
snapshot, history = self._snapshot(at=at, before=before)
|
|
166
|
+
resolved: dict[tuple[str, int], str] = {}
|
|
167
|
+
rows = [self._hydrate_event(event, resolved) for event in history["rows"]]
|
|
168
|
+
transcript = [self._hydrate_block(block, resolved) for block in history["transcript"]]
|
|
169
|
+
state = {
|
|
170
|
+
"profile": snapshot.get("profile"),
|
|
171
|
+
"model_targets": snapshot.get("model_targets", ()),
|
|
172
|
+
"workflow_event": snapshot.get("workflow_event"),
|
|
173
|
+
"view_state": snapshot.get("view_state"),
|
|
174
|
+
"sources": snapshot.get("sources", ()),
|
|
175
|
+
"tool_pins": snapshot.get("tool_pins", ()),
|
|
176
|
+
}
|
|
177
|
+
return {**history, "rows": rows, "transcript": transcript}, state
|
|
178
|
+
|
|
179
|
+
def _hydrate_event(self, event, resolved=None):
|
|
180
|
+
if resolved is None:
|
|
181
|
+
resolved = {}
|
|
182
|
+
change = event.get("history_change")
|
|
183
|
+
block = change["upsert"] if change else None
|
|
184
|
+
if block is not None:
|
|
185
|
+
# The upsert carries the canonical display row, including its original anchor.
|
|
186
|
+
block = self._hydrate_block(block, resolved)
|
|
187
|
+
event = {**event, "history_change": {**change, "upsert": block}}
|
|
188
|
+
if event["kind"] not in {"message.completed", "reasoning.summary"}:
|
|
189
|
+
return event
|
|
190
|
+
payload = event["payload"]
|
|
191
|
+
if payload.get("text_ref") is None or isinstance(payload.get("text"), str):
|
|
192
|
+
return event
|
|
193
|
+
if block is not None and "text" in block:
|
|
194
|
+
text = block["text"]
|
|
195
|
+
else:
|
|
196
|
+
text = self._history_text(payload, resolved)
|
|
197
|
+
return {**event, "payload": {**payload, "text": text}}
|
|
198
|
+
|
|
199
|
+
def _hydrate_block(self, block, resolved):
|
|
200
|
+
if block["kind"] in {"message", "reasoning"} and block.get("text_ref") is not None:
|
|
201
|
+
return {**block, "text": self._history_text(block, resolved)}
|
|
202
|
+
return block
|
|
203
|
+
|
|
204
|
+
def _history_text(self, body, resolved):
|
|
205
|
+
reference = body["text_ref"]
|
|
206
|
+
key = reference["sha256"], reference["bytes"]
|
|
207
|
+
if key not in resolved:
|
|
208
|
+
resolved[key] = message_text(self, body)
|
|
209
|
+
return resolved[key]
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _result(reply):
|
|
213
|
+
if reply.get("ok") is False:
|
|
214
|
+
raise _rejection(reply)
|
|
215
|
+
if reply.get("ok") is not True:
|
|
216
|
+
raise ConnectionError("Invalid reply from the local engine")
|
|
217
|
+
if "result" not in reply:
|
|
218
|
+
raise ConnectionError("Incomplete reply from the local engine")
|
|
219
|
+
return reply["result"]
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _rejection(frame):
|
|
223
|
+
refusal, fault = frame.get("refusal"), frame.get("fault")
|
|
224
|
+
error = frame.get("error")
|
|
225
|
+
if not isinstance(error, str):
|
|
226
|
+
detail = refusal or fault or error
|
|
227
|
+
error = detail.get("code") if isinstance(detail, dict) else frame.get("code")
|
|
228
|
+
if not isinstance(error, str):
|
|
229
|
+
error = "Local engine refused request"
|
|
230
|
+
return Rejected(error, refusal=refusal, fault=fault)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
SUBSCRIPTION_BATCH = 32
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
class Subscription:
|
|
237
|
+
"""Queue ordered push frames and resume from the last queued durable row."""
|
|
238
|
+
|
|
239
|
+
def __init__(self, client, after, wake, *, with_history=False, source=None):
|
|
240
|
+
if type(after) is not int or after < 0:
|
|
241
|
+
raise ValueError("Invalid subscription cursor")
|
|
242
|
+
self._client = client
|
|
243
|
+
self._cursor = after
|
|
244
|
+
self._source = source
|
|
245
|
+
self._with_history = with_history
|
|
246
|
+
self._seed_history = with_history
|
|
247
|
+
self._wake = wake
|
|
248
|
+
self._condition = Condition()
|
|
249
|
+
self._queue = deque()
|
|
250
|
+
self._stopped = StopSignal()
|
|
251
|
+
self._worker = Thread(target=self._follow, daemon=True, name="synth-subscription")
|
|
252
|
+
self._worker.start()
|
|
253
|
+
|
|
254
|
+
def __enter__(self):
|
|
255
|
+
return self
|
|
256
|
+
|
|
257
|
+
def __exit__(self, *_):
|
|
258
|
+
self.close()
|
|
259
|
+
|
|
260
|
+
def close(self):
|
|
261
|
+
with self._condition:
|
|
262
|
+
self._stopped.set()
|
|
263
|
+
self._queue.clear()
|
|
264
|
+
self._condition.notify_all()
|
|
265
|
+
# Closing this socket also releases a server-side replay that is blocked
|
|
266
|
+
# on our consumer. A subsequent command opens a fresh connection.
|
|
267
|
+
with self._client._lock:
|
|
268
|
+
if self._client._subscription is self:
|
|
269
|
+
self._client._subscription = None
|
|
270
|
+
if self._client._transport is not None:
|
|
271
|
+
self._client._transport.close()
|
|
272
|
+
|
|
273
|
+
def drain(self):
|
|
274
|
+
with self._condition:
|
|
275
|
+
batch = list(self._queue)
|
|
276
|
+
self._queue.clear()
|
|
277
|
+
self._condition.notify_all()
|
|
278
|
+
return batch
|
|
279
|
+
|
|
280
|
+
def __iter__(self):
|
|
281
|
+
while True:
|
|
282
|
+
with self._condition:
|
|
283
|
+
self._condition.wait_for(lambda: self._queue or self._stopped.is_set())
|
|
284
|
+
if not self._queue:
|
|
285
|
+
return
|
|
286
|
+
frame = self._queue.popleft()
|
|
287
|
+
self._condition.notify_all()
|
|
288
|
+
yield frame
|
|
289
|
+
if frame["type"] == "refused":
|
|
290
|
+
return
|
|
291
|
+
|
|
292
|
+
def _publish(self, frame):
|
|
293
|
+
with self._condition:
|
|
294
|
+
self._condition.wait_for(
|
|
295
|
+
lambda: self._stopped.is_set() or len(self._queue) < SUBSCRIPTION_BATCH
|
|
296
|
+
)
|
|
297
|
+
if self._stopped.is_set():
|
|
298
|
+
return False
|
|
299
|
+
self._queue.append(frame)
|
|
300
|
+
self._condition.notify_all()
|
|
301
|
+
self._wake()
|
|
302
|
+
return True
|
|
303
|
+
|
|
304
|
+
def _follow(self):
|
|
305
|
+
delay = 0.1
|
|
306
|
+
while not self._stopped.is_set():
|
|
307
|
+
transport = None
|
|
308
|
+
try:
|
|
309
|
+
transport = self._client._connection()
|
|
310
|
+
if self._stopped.is_set():
|
|
311
|
+
transport.close()
|
|
312
|
+
return
|
|
313
|
+
if self._seed_history:
|
|
314
|
+
history, state = self._client.history_page()
|
|
315
|
+
if history["cursor"] < self._cursor:
|
|
316
|
+
raise ConnectionError(f"Transcript snapshot precedes #{self._cursor}")
|
|
317
|
+
if not self._publish({"type": "history", "history": history, "state": state}):
|
|
318
|
+
return
|
|
319
|
+
self._cursor = history["cursor"]
|
|
320
|
+
self._seed_history = False
|
|
321
|
+
if self._source is None:
|
|
322
|
+
_result(transport.request("subscribe", {"after": self._cursor}, timeout=12))
|
|
323
|
+
else:
|
|
324
|
+
source, view = self._source
|
|
325
|
+
_result(
|
|
326
|
+
transport.request(
|
|
327
|
+
"source.subscribe",
|
|
328
|
+
{"after": self._cursor, "source": source, "view_id": view},
|
|
329
|
+
timeout=12,
|
|
330
|
+
)
|
|
331
|
+
)
|
|
332
|
+
while frame := transport.next_push(self._stopped):
|
|
333
|
+
kind = frame["type"]
|
|
334
|
+
if kind == "refused":
|
|
335
|
+
raise _rejection(frame)
|
|
336
|
+
if kind == "lagged":
|
|
337
|
+
if not self._publish({"type": "resyncing"}):
|
|
338
|
+
return
|
|
339
|
+
break
|
|
340
|
+
if kind == "event":
|
|
341
|
+
event = self._event(frame)
|
|
342
|
+
if self._with_history:
|
|
343
|
+
frame = {**frame, "event": self._client._hydrate_event(event)}
|
|
344
|
+
if kind == "caught_up" and frame.get("seq") != self._cursor:
|
|
345
|
+
raise ConnectionError(f"Inconsistent catch-up cursor after #{self._cursor}")
|
|
346
|
+
if kind == "live":
|
|
347
|
+
body = frame.get("frame")
|
|
348
|
+
if not isinstance(body, dict):
|
|
349
|
+
raise ConnectionError("Invalid live frame from the local engine")
|
|
350
|
+
if self._source is not None and (
|
|
351
|
+
body.get("kind") != "view.changed"
|
|
352
|
+
and (
|
|
353
|
+
body.get("kind") not in {"source.frame", "source.health"}
|
|
354
|
+
or body.get("source") != self._source[0]
|
|
355
|
+
)
|
|
356
|
+
):
|
|
357
|
+
raise ConnectionError(
|
|
358
|
+
"Live frame exceeded its authenticated source scope"
|
|
359
|
+
)
|
|
360
|
+
if not self._publish(frame):
|
|
361
|
+
return
|
|
362
|
+
if kind == "event":
|
|
363
|
+
self._cursor = event["seq"]
|
|
364
|
+
if kind in {"event", "caught_up"}:
|
|
365
|
+
delay = 0.1
|
|
366
|
+
except Rejected as error:
|
|
367
|
+
if transport is not None:
|
|
368
|
+
transport.close()
|
|
369
|
+
detail = error.refusal or error.fault or {}
|
|
370
|
+
if detail.get("retryable") is not True:
|
|
371
|
+
self._publish({"type": "refused", "error": error})
|
|
372
|
+
return
|
|
373
|
+
delay = self._backoff(error, delay)
|
|
374
|
+
except CommandCapacity as error:
|
|
375
|
+
delay = self._backoff(error, delay)
|
|
376
|
+
except (OSError, ValueError) as error:
|
|
377
|
+
if transport is not None:
|
|
378
|
+
transport.close()
|
|
379
|
+
delay = self._backoff(error, delay)
|
|
380
|
+
|
|
381
|
+
def _backoff(self, error, delay):
|
|
382
|
+
if self._publish({"type": "disconnected", "error": error}):
|
|
383
|
+
with self._condition:
|
|
384
|
+
self._condition.wait_for(self._stopped.is_set, timeout=delay)
|
|
385
|
+
return min(delay * 2, 3)
|
|
386
|
+
|
|
387
|
+
def _valid_cursor(self, sequence: int) -> bool:
|
|
388
|
+
if self._source is not None:
|
|
389
|
+
return sequence > self._cursor
|
|
390
|
+
return sequence == self._cursor + 1
|
|
391
|
+
|
|
392
|
+
def _event(self, frame) -> Event:
|
|
393
|
+
event = frame.get("event")
|
|
394
|
+
if (
|
|
395
|
+
not isinstance(event, dict)
|
|
396
|
+
or event.get("run") != self._client.run
|
|
397
|
+
or type(event.get("seq")) is not int
|
|
398
|
+
or not self._valid_cursor(event["seq"])
|
|
399
|
+
or not isinstance(event.get("kind"), str)
|
|
400
|
+
or not isinstance(event.get("payload"), dict)
|
|
401
|
+
):
|
|
402
|
+
raise ConnectionError(f"Discontinuous or invalid journal after #{self._cursor}")
|
|
403
|
+
if self._source is not None and (
|
|
404
|
+
event["kind"] not in {"source.registered", "source.fact"}
|
|
405
|
+
or event["payload"].get("source") != self._source[0]
|
|
406
|
+
):
|
|
407
|
+
raise ConnectionError("Source subscription exceeded its authenticated scope")
|
|
408
|
+
return event
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def bound_workspace(client: Client) -> Path:
|
|
412
|
+
"""Resolve the journal's workspace through the owning daemon."""
|
|
413
|
+
return Path(client.send("describe")["target"])
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Keep authored inputs in submission order until the daemon acknowledges them."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import deque
|
|
6
|
+
from concurrent.futures import Future
|
|
7
|
+
from dataclasses import asdict, dataclass, replace
|
|
8
|
+
from enum import StrEnum
|
|
9
|
+
from math import ceil
|
|
10
|
+
from time import monotonic
|
|
11
|
+
|
|
12
|
+
from .client import Rejected
|
|
13
|
+
from .live_turns import submit_core_turn
|
|
14
|
+
from .session import validate_message
|
|
15
|
+
|
|
16
|
+
MAX_PENDING = 16
|
|
17
|
+
RETRY_DELAYS_MS = (80, 240, 600, 1400)
|
|
18
|
+
FAILURE_TEXT_MAX = 256
|
|
19
|
+
RETRY_STATUS = "Retrying input"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class DraftRevision(StrEnum):
|
|
23
|
+
"""How a draft relates to the restored input it came from."""
|
|
24
|
+
|
|
25
|
+
# The text is unchanged: sending it again is the same input, so it keeps its id and
|
|
26
|
+
# the daemon's `submit_input` dedupe returns the prior receipt if it was accepted.
|
|
27
|
+
RESEND = "resend"
|
|
28
|
+
# The owner edited the text: it is a new input and must be sent under a new id.
|
|
29
|
+
EDITED = "edited"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True, slots=True)
|
|
33
|
+
class AuthoredInput:
|
|
34
|
+
text: str
|
|
35
|
+
identity: str
|
|
36
|
+
expected_turn: str | None
|
|
37
|
+
retry_count: int = 0
|
|
38
|
+
failure: str | None = None
|
|
39
|
+
|
|
40
|
+
def __post_init__(self):
|
|
41
|
+
if not isinstance(self.text, str) or not isinstance(self.identity, str) or not self.identity:
|
|
42
|
+
raise ValueError("Invalid saved input")
|
|
43
|
+
if self.expected_turn is not None and not isinstance(self.expected_turn, str):
|
|
44
|
+
raise ValueError("Invalid saved steering target")
|
|
45
|
+
if type(self.retry_count) is not int or not 0 <= self.retry_count <= len(RETRY_DELAYS_MS):
|
|
46
|
+
raise ValueError("Invalid saved input retry count")
|
|
47
|
+
if self.failure is not None and (
|
|
48
|
+
not isinstance(self.failure, str) or not 1 <= len(self.failure) <= FAILURE_TEXT_MAX
|
|
49
|
+
):
|
|
50
|
+
raise ValueError("Invalid saved input failure")
|
|
51
|
+
validate_message(self.text)
|
|
52
|
+
|
|
53
|
+
def revision(self, draft: str) -> DraftRevision:
|
|
54
|
+
return DraftRevision.RESEND if draft == self.text else DraftRevision.EDITED
|
|
55
|
+
|
|
56
|
+
def snapshot(self):
|
|
57
|
+
saved = asdict(self)
|
|
58
|
+
if not self.retry_count:
|
|
59
|
+
del saved["retry_count"]
|
|
60
|
+
if self.failure is None:
|
|
61
|
+
del saved["failure"]
|
|
62
|
+
return saved
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class ComposerDelivery:
|
|
66
|
+
def __init__(self, saved, submit):
|
|
67
|
+
if len(saved) > MAX_PENDING:
|
|
68
|
+
raise ValueError(f"Pending input count {len(saved)} exceeds {MAX_PENDING}")
|
|
69
|
+
self.waiting = deque(AuthoredInput(**entry) for entry in saved)
|
|
70
|
+
self.submit = submit
|
|
71
|
+
self.active: Future | None = None
|
|
72
|
+
self.retry_at: float | None = None
|
|
73
|
+
|
|
74
|
+
def enqueue(self, text, identity, expected_turn=None):
|
|
75
|
+
if len(self.waiting) == MAX_PENDING:
|
|
76
|
+
raise ValueError(f"Pending input limit {MAX_PENDING} reached")
|
|
77
|
+
self.waiting.append(AuthoredInput(text, identity, expected_turn))
|
|
78
|
+
|
|
79
|
+
def snapshot(self):
|
|
80
|
+
return [entry.snapshot() for entry in self.waiting]
|
|
81
|
+
|
|
82
|
+
def timeout_ms(self, now: float) -> int | None:
|
|
83
|
+
if self.retry_at is None:
|
|
84
|
+
return None
|
|
85
|
+
return max(0, ceil((self.retry_at - now) * 1000))
|
|
86
|
+
|
|
87
|
+
def advance(self, client, draft):
|
|
88
|
+
"""Advance the oldest pending input without taking over the current draft."""
|
|
89
|
+
changed = False
|
|
90
|
+
restored = None
|
|
91
|
+
if self.active is not None and self.active.done():
|
|
92
|
+
try:
|
|
93
|
+
self.active.result()
|
|
94
|
+
except Rejected as error:
|
|
95
|
+
detail = error.refusal or error.fault or {}
|
|
96
|
+
self._record_failure(error, retryable=detail.get("retryable") is True)
|
|
97
|
+
except OSError as error:
|
|
98
|
+
# A dropped or refused connection (including the typed
|
|
99
|
+
# `runtime_connect_refused`/`runtime_not_running` refusals) leaves the
|
|
100
|
+
# daemon's acceptance unknown; the retry keeps the same id, so an input
|
|
101
|
+
# the daemon already accepted is deduped rather than queued twice.
|
|
102
|
+
self._record_failure(error, retryable=True)
|
|
103
|
+
except ValueError as error:
|
|
104
|
+
self._record_failure(error, retryable=False)
|
|
105
|
+
else:
|
|
106
|
+
self.waiting.popleft()
|
|
107
|
+
changed = True
|
|
108
|
+
self.active = None
|
|
109
|
+
|
|
110
|
+
status = ""
|
|
111
|
+
if self.waiting:
|
|
112
|
+
entry = self.waiting[0]
|
|
113
|
+
if entry.failure is not None:
|
|
114
|
+
status = entry.failure
|
|
115
|
+
if not draft:
|
|
116
|
+
restored = self.waiting.popleft()
|
|
117
|
+
changed = True
|
|
118
|
+
elif entry.retry_count:
|
|
119
|
+
status = RETRY_STATUS
|
|
120
|
+
|
|
121
|
+
if self.waiting and self.active is None:
|
|
122
|
+
entry = self.waiting[0]
|
|
123
|
+
if entry.failure is None and self.timeout_ms(monotonic()) in (None, 0):
|
|
124
|
+
self.retry_at = None
|
|
125
|
+
self.active = self.submit(
|
|
126
|
+
submit_core_turn, client, entry.text, entry.identity, entry.expected_turn
|
|
127
|
+
)
|
|
128
|
+
return changed, restored, status
|
|
129
|
+
|
|
130
|
+
def _record_failure(self, error: ValueError | OSError, *, retryable: bool) -> None:
|
|
131
|
+
entry = self.waiting[0]
|
|
132
|
+
if retryable and entry.retry_count < len(RETRY_DELAYS_MS):
|
|
133
|
+
self.retry_at = monotonic() + RETRY_DELAYS_MS[entry.retry_count] / 1000
|
|
134
|
+
self.waiting[0] = replace(entry, retry_count=entry.retry_count + 1)
|
|
135
|
+
return
|
|
136
|
+
|
|
137
|
+
reason = "Delivery retries exhausted · " if retryable else ""
|
|
138
|
+
failure = f"Pending draft · {reason}{error}"[:FAILURE_TEXT_MAX]
|
|
139
|
+
self.waiting[0] = replace(entry, failure=failure)
|