sessionyard 0.7.0__py3-none-any.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 (62) hide show
  1. agent_chat/001_core.sql +172 -0
  2. agent_chat/002_coordination.sql +63 -0
  3. agent_chat/003_harness_admission.sql +10 -0
  4. agent_chat/004_session_titles.sql +3 -0
  5. agent_chat/005_viewer.sql +9 -0
  6. agent_chat/006_quotas.sql +6 -0
  7. agent_chat/007_sender_receipts.sql +20 -0
  8. agent_chat/008_direct_threads.sql +49 -0
  9. agent_chat/009_pm_mark.sql +23 -0
  10. agent_chat/010_quota_backfill.sql +12 -0
  11. agent_chat/011_roles_and_work.sql +31 -0
  12. agent_chat/__init__.py +1 -0
  13. agent_chat/adapter.py +414 -0
  14. agent_chat/admin.py +524 -0
  15. agent_chat/api.py +641 -0
  16. agent_chat/auth.py +226 -0
  17. agent_chat/browser.py +118 -0
  18. agent_chat/browser_verify.py +487 -0
  19. agent_chat/browser_verify_artifacts.py +280 -0
  20. agent_chat/browser_verify_checks.py +236 -0
  21. agent_chat/browser_verify_run.py +523 -0
  22. agent_chat/cli.py +532 -0
  23. agent_chat/client.py +272 -0
  24. agent_chat/deliveries.py +555 -0
  25. agent_chat/events.py +48 -0
  26. agent_chat/feed.py +193 -0
  27. agent_chat/http_boundary.py +154 -0
  28. agent_chat/instance_client.py +349 -0
  29. agent_chat/instance_file.py +207 -0
  30. agent_chat/instance_worker.py +326 -0
  31. agent_chat/mcp/__init__.py +5 -0
  32. agent_chat/mcp/__main__.py +39 -0
  33. agent_chat/mcp/app.py +183 -0
  34. agent_chat/mcp/auth.py +67 -0
  35. agent_chat/mcp/config.py +55 -0
  36. agent_chat/mcp/tools.py +295 -0
  37. agent_chat/metrics.py +60 -0
  38. agent_chat/models.py +430 -0
  39. agent_chat/openapi.py +322 -0
  40. agent_chat/producer.py +208 -0
  41. agent_chat/protocol.py +71 -0
  42. agent_chat/publication.py +252 -0
  43. agent_chat/receipts.py +225 -0
  44. agent_chat/retention.py +154 -0
  45. agent_chat/roles.py +153 -0
  46. agent_chat/rooms.py +179 -0
  47. agent_chat/sessions.py +340 -0
  48. agent_chat/skills/agent-chat/SKILL.md +64 -0
  49. agent_chat/state.py +144 -0
  50. agent_chat/storage.py +110 -0
  51. agent_chat/threads.py +50 -0
  52. agent_chat/web/Manrope-OFL.txt +93 -0
  53. agent_chat/web/Manrope-Variable.ttf +0 -0
  54. agent_chat/web/chat.css +936 -0
  55. agent_chat/web/chat.js +1922 -0
  56. agent_chat/web/i18n.js +340 -0
  57. agent_chat/web/index.html +264 -0
  58. sessionyard-0.7.0.dist-info/METADATA +314 -0
  59. sessionyard-0.7.0.dist-info/RECORD +62 -0
  60. sessionyard-0.7.0.dist-info/WHEEL +4 -0
  61. sessionyard-0.7.0.dist-info/entry_points.txt +3 -0
  62. sessionyard-0.7.0.dist-info/licenses/LICENSE +661 -0
@@ -0,0 +1,349 @@
1
+ """Explicit adapter lifecycle calls, not a scheduler, launcher or native sender.
2
+
3
+ The native adapter owns eligibility, a fresh boot UUID, context fencing and the
4
+ outer process/request deadline. These synchronous calls perform no retry,
5
+ credential discovery, automatic join or model work.
6
+ """
7
+
8
+ import json
9
+ import re
10
+ from dataclasses import dataclass, field
11
+ from datetime import UTC, datetime
12
+ from pathlib import Path
13
+ from typing import Any, Literal
14
+ from uuid import UUID
15
+
16
+ from .client import Client
17
+ from .instance_file import InstanceSecret, prepare_instance
18
+ from .models import RECEIPT_FEED_LIMIT, ChatError, DeliveryClaim, DeliveryResult, Heartbeat, ReceiptDelivery
19
+ from .protocol import cursor, token_digest
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class JoinedInstance:
24
+ binding: InstanceSecret = field(repr=False)
25
+ session_id: UUID
26
+ instance_id: UUID
27
+ room_id: UUID
28
+ host: str
29
+ harness: str
30
+
31
+
32
+ def _uuid(value: Any) -> UUID:
33
+ if not isinstance(value, str):
34
+ raise ValueError("invalid binding ID")
35
+ result = UUID(value)
36
+ if str(result) != value:
37
+ raise ValueError("noncanonical binding ID")
38
+ return result
39
+
40
+
41
+ def join_instance(
42
+ directory: Path,
43
+ native_session_id: str,
44
+ boot_id: UUID,
45
+ *,
46
+ server_origin: str,
47
+ host_token: str,
48
+ harness: Literal["pi", "codex", "claude", "deepseek", "opencode"],
49
+ enabled: bool = False,
50
+ deadline: float | None = None,
51
+ ) -> JoinedInstance:
52
+ """Persist the instance secret before sending its digest with host authority.
53
+
54
+ On uncertainty the owner may explicitly repeat this exact boot/origin/ID.
55
+ It must not rotate the secret or turn a retry into a replacement process.
56
+ A malformed response remains uncertain even if registration committed.
57
+ """
58
+ if enabled is not True:
59
+ raise ChatError("INTEGRATION_DISABLED")
60
+ if harness not in ("pi", "codex", "claude", "deepseek", "opencode"):
61
+ raise ChatError("INVALID_REQUEST")
62
+ registration_client = Client(server_origin, host_token, deadline=deadline)
63
+ secret = prepare_instance(directory, native_session_id, boot_id, server_origin=server_origin)
64
+ result = registration_client.request(
65
+ "POST",
66
+ "/v1/sessions",
67
+ {
68
+ "native_session_id": secret.native_session_id,
69
+ "boot_id": str(secret.boot_id),
70
+ "instance_token_hash": token_digest(secret.token),
71
+ },
72
+ )
73
+ try:
74
+ if (
75
+ not isinstance(result, dict)
76
+ or set(result) != {"session_id", "instance_id", "room_id", "host", "harness"}
77
+ or result["harness"] != harness
78
+ or not isinstance(result["host"], str)
79
+ or not result["host"]
80
+ ):
81
+ raise ValueError("invalid registration response")
82
+ return JoinedInstance(
83
+ secret,
84
+ _uuid(result["session_id"]),
85
+ _uuid(result["instance_id"]),
86
+ _uuid(result["room_id"]),
87
+ result["host"],
88
+ result["harness"],
89
+ )
90
+ except (ValueError, TypeError, KeyError):
91
+ raise ChatError("REQUEST_UNCERTAIN") from None
92
+
93
+
94
+ def _request(
95
+ instance: JoinedInstance, method: str, path: str, payload=None, *,
96
+ invalid: str | None = None, deadline: float | None = None,
97
+ ) -> dict[str, Any]:
98
+ # Each lifecycle operation has its own bounded response budget. Never retain
99
+ # the host credential here or reopen/discover a different binding file.
100
+ client = Client(instance.binding.server_origin, instance.binding.token, deadline=deadline)
101
+ result = client.request(method, path, payload, invalid=invalid)
102
+ try:
103
+ if not isinstance(result, dict) or _uuid(result.get("instance_id")) != instance.instance_id:
104
+ raise ValueError("different binding in response")
105
+ if method == "GET":
106
+ if _uuid(result.get("session_id")) != instance.session_id:
107
+ raise ValueError("different logical session in response")
108
+ except (ValueError, TypeError):
109
+ # The worker tolerates a short outage on heartbeat and pending, so those two name a
110
+ # foreign or malformed binding `invalid`: a protocol violation is never an outage.
111
+ raise ChatError(invalid or ("REQUEST_UNCERTAIN" if method == "POST" else "TRANSPORT_UNAVAILABLE")) from None
112
+ return result
113
+
114
+
115
+ def heartbeat(instance: JoinedInstance, state: Heartbeat, *, deadline: float | None = None) -> dict[str, Any]:
116
+ """Only publish the owner's explicit observation; never clear stop implicitly."""
117
+ if not isinstance(state, Heartbeat):
118
+ raise ChatError("INVALID_REQUEST")
119
+ return _request(
120
+ instance,
121
+ "POST",
122
+ "/v1/instance/heartbeat",
123
+ state.model_dump(mode="json", exclude_unset=True),
124
+ invalid="INVALID_RESPONSE",
125
+ deadline=deadline,
126
+ )
127
+
128
+
129
+ def status(instance: JoinedInstance, *, deadline: float | None = None) -> dict[str, Any]:
130
+ """Observe this binding without renewing its lease or acknowledging messages."""
131
+ return _request(instance, "GET", "/v1/instance/status", deadline=deadline)
132
+
133
+
134
+ def end(instance: JoinedInstance, *, deadline: float | None = None) -> dict[str, Any]:
135
+ """Explicitly end this exact binding, including a safe same-binding retry."""
136
+ return _request(instance, "POST", "/v1/instance/end", {}, deadline=deadline)
137
+
138
+
139
+ def pending(instance: JoinedInstance, sizing: bool = False, *, deadline: float | None = None) -> dict[str, Any]:
140
+ """Candidate IDs; `sizing` adds the server's body sizes and retry marker, but only when it sent them."""
141
+ result = _request(
142
+ instance, "GET", "/v1/instance/deliveries/pending", invalid="INVALID_RESPONSE", deadline=deadline
143
+ )
144
+ try:
145
+ ids = result["messages"]
146
+ if not isinstance(ids, list) or len(ids) > 16 or len({_uuid(value) for value in ids}) != len(ids):
147
+ raise ValueError("invalid candidates")
148
+ if not sizing or not ids or ("sizes" not in result and "retry" not in result):
149
+ return {"messages": ids}
150
+ sizes, retry = result["sizes"], result["retry"]
151
+ if (
152
+ type(retry) is not bool
153
+ or not isinstance(sizes, dict)
154
+ or set(sizes) != set(ids)
155
+ or any(type(size) is not int or size < 0 for size in sizes.values())
156
+ ):
157
+ raise ValueError("invalid sizing")
158
+ except (ValueError, TypeError, KeyError):
159
+ raise ChatError("INVALID_RESPONSE") from None
160
+ return {"messages": ids, "sizes": sizes, "retry": retry}
161
+
162
+
163
+ #: The most UTF-8 bytes of one body that may cross IPC: the notice's own per-body bound.
164
+ NOTICE_BODY_BYTES = 4096
165
+ #: The worker frame is at most 128 KiB of ASCII-escaped JSON (instance_worker.MAX_FRAME). A character escapes to
166
+ #: up to six bytes, so a claimed batch of bodies could overflow it; the bodies share this part of the frame.
167
+ IPC_BODY_WIRE_BYTES = 96 * 1024
168
+
169
+
170
+ def _bounded_body(body: str, wire_bytes: int) -> tuple[str, bool]:
171
+ """Cut at a code point so the body fits both bounds: `(text, whether it was cut)`."""
172
+ used = wire = 0
173
+ for index, char in enumerate(body):
174
+ used += len(char.encode("utf-8"))
175
+ wire += len(json.dumps(char, ensure_ascii=True)) - 2
176
+ if used > NOTICE_BODY_BYTES or wire > wire_bytes:
177
+ return body[:index], True
178
+ return body, False
179
+
180
+
181
+ def _utc(moment: datetime) -> str:
182
+ """A server time as UTC text with a plain `+00:00` offset: the Node renderer reads no offset with seconds."""
183
+ return moment.astimezone(UTC).isoformat()
184
+
185
+
186
+ def _body_fields(row: dict[str, Any], wire_bytes: int) -> dict[str, Any]:
187
+ """The named extra fields of one claimed message that bodies mode passes on."""
188
+ body, sender = row["body"], row["sender"]
189
+ if not isinstance(body, str) or not body or not isinstance(sender, dict):
190
+ raise ValueError("invalid content")
191
+ session = sender["session_id"] # an operator or browser publication has no sending session
192
+ created = datetime.fromisoformat(row["created_at"])
193
+ if created.utcoffset() is None:
194
+ raise ValueError("invalid creation time")
195
+ text, cut = _bounded_body(body, wire_bytes)
196
+ return {
197
+ "body": text,
198
+ "body_truncated": cut,
199
+ "sender_session_id": None if session is None else str(_uuid(session)),
200
+ "sender_principal_id": str(_uuid(sender["principal_id"])),
201
+ "created_at": _utc(created),
202
+ "thread_id": str(_uuid(row["thread_id"])),
203
+ }
204
+
205
+
206
+ def claim(
207
+ instance: JoinedInstance, key: UUID, request: DeliveryClaim, bodies: bool = False, *,
208
+ deadline: float | None = None,
209
+ ) -> dict[str, Any]:
210
+ """Validate a grant and return metadata only; bodies stay in explicit history unless `bodies` asks."""
211
+ result = Client(instance.binding.server_origin, instance.binding.token, deadline=deadline).request(
212
+ "POST",
213
+ "/v1/instance/deliveries/claim",
214
+ request.model_dump(mode="json"),
215
+ str(key),
216
+ )
217
+ try:
218
+ attempt = result["attempt"]
219
+ if _uuid(attempt["instance_id"]) != instance.instance_id or type(result["dispatch"]) is not bool:
220
+ raise ValueError("invalid grant identity")
221
+ attempt_id = _uuid(attempt["id"])
222
+ admitted, expires = (datetime.fromisoformat(attempt[field]) for field in ("admitted_at", "expires_at"))
223
+ if admitted.utcoffset() is None or expires.utcoffset() is None:
224
+ raise ValueError("invalid grant clock")
225
+ reservation_ms = (expires - admitted).total_seconds() * 1000
226
+ if not 0 < reservation_ms <= 30_000:
227
+ raise ValueError("invalid grant lifetime")
228
+ messages = result["messages"]
229
+ if not isinstance(messages, list) or len(messages) > 16:
230
+ raise ValueError("invalid batch")
231
+ if result["dispatch"]:
232
+ if (
233
+ attempt["outcome"] is not None
234
+ or {_uuid(row["id"]) for row in messages} != set(request.messages)
235
+ or len(messages) != len(request.messages)
236
+ ):
237
+ raise ValueError("invalid dispatch")
238
+ elif messages:
239
+ raise ValueError("replayed content")
240
+ metadata = []
241
+ for row in messages:
242
+ if row["kind"] not in ("question", "consultation", "reply"):
243
+ raise ValueError("ineligible kind")
244
+ # Whitelist, not a shallow copy: no body or upstream extras cross IPC unless a field is named.
245
+ item = {
246
+ "id": str(_uuid(row["id"])),
247
+ "room_id": str(_uuid(row["room_id"])),
248
+ "history_after": str(cursor(row["history_after"])),
249
+ "kind": row["kind"],
250
+ }
251
+ if bodies:
252
+ item.update(_body_fields(row, IPC_BODY_WIRE_BYTES // len(messages)))
253
+ metadata.append(item)
254
+ grant = {
255
+ "dispatch": result["dispatch"],
256
+ "attempt_id": str(attempt_id),
257
+ "reservation_ms": reservation_ms,
258
+ "messages": metadata,
259
+ }
260
+ if bodies:
261
+ grant["admitted_at"] = _utc(admitted)
262
+ return grant
263
+ except (ValueError, TypeError, KeyError, AttributeError, OverflowError, ChatError):
264
+ raise ChatError("REQUEST_UNCERTAIN") from None
265
+
266
+
267
+ #: A server-controlled principal field (harness or host): the administration owner's host grammar.
268
+ _PRINCIPAL_FIELD = re.compile(r"[a-z0-9][a-z0-9-]{0,62}")
269
+
270
+
271
+ def _receipt(row: dict[str, Any]) -> dict[str, str]:
272
+ """Whitelist one sender receipt: IDs, state, the recipient's harness and host, creation time. No free text."""
273
+ created = datetime.fromisoformat(row["created_at"])
274
+ if (
275
+ row["state"] not in ("handed", "acked")
276
+ or created.utcoffset() is None
277
+ or not all(
278
+ isinstance(row[key], str) and _PRINCIPAL_FIELD.fullmatch(row[key])
279
+ for key in ("recipient_harness", "recipient_host")
280
+ )
281
+ ):
282
+ raise ValueError("invalid receipt")
283
+ return {
284
+ "id": str(_uuid(row["id"])),
285
+ "message_id": str(_uuid(row["message_id"])),
286
+ "state": row["state"],
287
+ "recipient_session_id": str(_uuid(row["recipient_session_id"])),
288
+ "recipient_harness": row["recipient_harness"],
289
+ "recipient_host": row["recipient_host"],
290
+ "created_at": created.isoformat(),
291
+ }
292
+
293
+
294
+ def receipts(instance: JoinedInstance, *, deadline: float | None = None) -> dict[str, Any]:
295
+ """The session's own undelivered sender receipts, oldest first. Reading marks nothing delivered."""
296
+ result = _request(
297
+ instance, "GET", "/v1/instance/receipts", invalid="INVALID_RESPONSE", deadline=deadline
298
+ )
299
+ try:
300
+ rows = result["receipts"]
301
+ if not isinstance(rows, list) or len(rows) > RECEIPT_FEED_LIMIT:
302
+ raise ValueError("invalid receipts")
303
+ items = [_receipt(row) for row in rows]
304
+ if len({item["id"] for item in items}) != len(items):
305
+ raise ValueError("duplicate receipt")
306
+ except (ValueError, TypeError, KeyError, AttributeError):
307
+ raise ChatError("INVALID_RESPONSE") from None
308
+ return {"receipts": items}
309
+
310
+
311
+ def receipts_delivered(
312
+ instance: JoinedInstance, request: ReceiptDelivery, *, deadline: float | None = None
313
+ ) -> dict[str, Any]:
314
+ """Mark receipts the adapter output as delivered; only the session's own are marked, and a repeat is safe."""
315
+ if not isinstance(request, ReceiptDelivery):
316
+ raise ChatError("INVALID_REQUEST")
317
+ result = _request(
318
+ instance, "POST", "/v1/instance/receipts/delivered", request.model_dump(mode="json"), deadline=deadline
319
+ )
320
+ try:
321
+ delivered = result["delivered"]
322
+ if not isinstance(delivered, list):
323
+ raise ValueError("invalid delivered list")
324
+ ids = [str(_uuid(value)) for value in delivered]
325
+ if len(set(ids)) != len(ids) or not set(ids) <= {str(value) for value in request.receipts}:
326
+ raise ValueError("delivered receipts were not requested")
327
+ except (ValueError, TypeError, KeyError):
328
+ raise ChatError("REQUEST_UNCERTAIN") from None
329
+ return {"delivered": ids}
330
+
331
+
332
+ def settle(
333
+ instance: JoinedInstance, attempt: UUID, request: DeliveryResult, *, deadline: float | None = None
334
+ ) -> dict[str, Any]:
335
+ result = Client(instance.binding.server_origin, instance.binding.token, deadline=deadline).request(
336
+ "POST",
337
+ f"/v1/instance/deliveries/{attempt}/result",
338
+ request.model_dump(mode="json"),
339
+ )
340
+ try:
341
+ if (
342
+ _uuid(result["instance_id"]) != instance.instance_id
343
+ or _uuid(result["id"]) != attempt
344
+ or (result["outcome"], result["reason"]) != (request.outcome, request.reason)
345
+ ):
346
+ raise ValueError("invalid settlement")
347
+ except (ValueError, TypeError, KeyError):
348
+ raise ChatError("REQUEST_UNCERTAIN") from None
349
+ return {"attempt_id": str(attempt), "outcome": request.outcome, "reason": request.reason}
@@ -0,0 +1,207 @@
1
+ """Persist one process's secret and destination; readers never rotate or discover it."""
2
+
3
+ import json
4
+ import os
5
+ import secrets
6
+ import stat
7
+ import time
8
+ from dataclasses import dataclass, field
9
+ from pathlib import Path
10
+ from uuid import UUID
11
+
12
+ from .models import ChatError, Registration
13
+ from .protocol import token_digest, validate_origin
14
+
15
+ # Housekeeping bounds: a record untouched this long (far beyond the 90 s lease; a live worker touches it at
16
+ # every heartbeat) is an orphan, and a sweep looks at no more than this many directory names.
17
+ SWEEP_STALE_SECONDS = 3600
18
+ SWEEP_NAMES = 200
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class InstanceSecret:
23
+ native_session_id: str
24
+ boot_id: UUID
25
+ token: str = field(repr=False)
26
+ server_origin: str
27
+
28
+
29
+ def _directory(directory: Path) -> int:
30
+ fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
31
+ info = os.fstat(fd)
32
+ if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) != 0o700:
33
+ os.close(fd)
34
+ raise ChatError("BINDING_FILE_UNSAFE")
35
+ return fd
36
+
37
+
38
+ def _read(directory_fd: int, name: str, *, sync: bool = False) -> InstanceSecret:
39
+ fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory_fd)
40
+ with os.fdopen(fd, "rb") as stream:
41
+ info = os.fstat(stream.fileno())
42
+ if (
43
+ not stat.S_ISREG(info.st_mode)
44
+ or info.st_uid != os.geteuid()
45
+ or stat.S_IMODE(info.st_mode) != 0o600
46
+ or info.st_nlink != 1
47
+ ):
48
+ raise ChatError("BINDING_FILE_UNSAFE")
49
+ content = stream.read(4097)
50
+ if sync:
51
+ os.fsync(stream.fileno())
52
+ try:
53
+ data = json.loads(content)
54
+ if (
55
+ len(content) > 4096
56
+ or not isinstance(data, dict)
57
+ or set(data) != {"native_session_id", "boot_id", "token", "server_origin"}
58
+ or not all(isinstance(value, str) for value in data.values())
59
+ ):
60
+ raise ValueError("invalid binding record")
61
+ registration = Registration(
62
+ native_session_id=data["native_session_id"],
63
+ boot_id=data["boot_id"],
64
+ instance_token_hash=token_digest(data["token"]),
65
+ )
66
+ if name != f"{registration.boot_id}.json":
67
+ raise ChatError("BINDING_FILE_CONFLICT")
68
+ validate_origin(data["server_origin"])
69
+ return InstanceSecret(
70
+ registration.native_session_id, registration.boot_id, data["token"], data["server_origin"]
71
+ )
72
+ except (ValueError, UnicodeError):
73
+ raise ChatError("BINDING_FILE_INVALID") from None
74
+
75
+
76
+ def read_instance(path: Path) -> InstanceSecret:
77
+ """An explicit adapter-selected file, never a scan for the newest process.
78
+
79
+ A missing record is ``BINDING_FILE_MISSING``. A record that exists but is
80
+ unreadable, is not a regular single-link file, or fails its owner or mode
81
+ check is ``BINDING_FILE_UNSAFE``. The two conditions have different
82
+ recoveries, so every reader keeps them distinct.
83
+ """
84
+ try:
85
+ if path.name != f"{UUID(path.stem)}.json":
86
+ raise ValueError("invalid filename")
87
+ except ValueError:
88
+ raise ChatError("BINDING_FILE_INVALID") from None
89
+ try:
90
+ fd = _directory(path.parent)
91
+ except FileNotFoundError:
92
+ raise ChatError("BINDING_FILE_MISSING") from None
93
+ except OSError:
94
+ raise ChatError("BINDING_FILE_UNSAFE") from None
95
+ try:
96
+ try:
97
+ return _read(fd, path.name)
98
+ except FileNotFoundError:
99
+ raise ChatError("BINDING_FILE_MISSING") from None
100
+ except OSError:
101
+ raise ChatError("BINDING_FILE_UNSAFE") from None
102
+ finally:
103
+ os.close(fd)
104
+
105
+
106
+ def prepare_instance(directory: Path, native_session_id: str, boot_id: UUID, *, server_origin: str) -> InstanceSecret:
107
+ """Adapter supplies a fresh boot UUID and destination before registration.
108
+
109
+ A retry must match native identity, boot and destination. Partial/older-format
110
+ files fail closed and are not overwritten. The CLI is only a reader.
111
+ """
112
+ validate_origin(server_origin)
113
+ token = secrets.token_hex(32)
114
+ registration = Registration(
115
+ native_session_id=native_session_id, boot_id=boot_id, instance_token_hash=token_digest(token)
116
+ )
117
+ name = f"{registration.boot_id}.json"
118
+ directory_fd = _directory(directory)
119
+ try:
120
+ try:
121
+ fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=directory_fd)
122
+ except FileExistsError as exc:
123
+ record = _read(directory_fd, name, sync=True)
124
+ if record.native_session_id != native_session_id or record.server_origin != server_origin:
125
+ raise ChatError("BINDING_FILE_CONFLICT") from exc
126
+ os.fsync(directory_fd)
127
+ return record
128
+ with os.fdopen(fd, "w", encoding="utf-8") as stream:
129
+ os.fchmod(stream.fileno(), 0o600)
130
+ json.dump(
131
+ {
132
+ "native_session_id": native_session_id,
133
+ "boot_id": str(registration.boot_id),
134
+ "token": token,
135
+ "server_origin": server_origin,
136
+ },
137
+ stream,
138
+ )
139
+ stream.flush()
140
+ os.fsync(stream.fileno())
141
+ os.fsync(directory_fd)
142
+ return InstanceSecret(native_session_id, registration.boot_id, token, server_origin)
143
+ finally:
144
+ os.close(directory_fd)
145
+
146
+
147
+ def discard_instance(directory: Path, boot_id: UUID) -> None:
148
+ """Best effort: drop one record whose instance is over. A failure leaves the file; never raises."""
149
+ try:
150
+ directory_fd = _directory(directory)
151
+ except (OSError, ChatError):
152
+ return
153
+ try:
154
+ os.unlink(f"{boot_id}.json", dir_fd=directory_fd)
155
+ except OSError:
156
+ pass
157
+ finally:
158
+ os.close(directory_fd)
159
+
160
+
161
+ def touch_instance(directory: Path, boot_id: UUID) -> None:
162
+ """Best effort: mark this process's record as live. Its mtime is the only liveness a sweep reads."""
163
+ try:
164
+ directory_fd = _directory(directory)
165
+ except (OSError, ChatError):
166
+ return
167
+ try:
168
+ os.utime(f"{boot_id}.json", dir_fd=directory_fd, follow_symlinks=False)
169
+ except OSError:
170
+ pass
171
+ finally:
172
+ os.close(directory_fd)
173
+
174
+
175
+ def sweep_stale(directory: Path, own: UUID) -> int:
176
+ """Unlink sibling `<uuid>.json` regular files not touched for SWEEP_STALE_SECONDS; return the count.
177
+
178
+ Local only: it reads names and mtimes, never a record's content or token. A live session touches its
179
+ file at every heartbeat, and one silent for an hour has a lapsed lease and rejoins with a new file.
180
+ At most SWEEP_NAMES names are examined; every OSError leaves the file, and a failed listing or close
181
+ ends the sweep with the count so far.
182
+ """
183
+ try:
184
+ directory_fd = _directory(directory)
185
+ except (OSError, ChatError):
186
+ return 0
187
+ removed = 0
188
+ try:
189
+ cutoff = time.time() - SWEEP_STALE_SECONDS
190
+ for name in os.listdir(directory_fd)[:SWEEP_NAMES]:
191
+ try:
192
+ if name == f"{own}.json" or name != f"{UUID(name.removesuffix('.json'))}.json":
193
+ continue
194
+ info = os.stat(name, dir_fd=directory_fd, follow_symlinks=False)
195
+ if stat.S_ISREG(info.st_mode) and info.st_mtime < cutoff:
196
+ os.unlink(name, dir_fd=directory_fd)
197
+ removed += 1
198
+ except (ValueError, OSError):
199
+ continue
200
+ except OSError:
201
+ pass # the listing failed: housekeeping stays best effort and returns the count so far
202
+ finally:
203
+ try:
204
+ os.close(directory_fd)
205
+ except OSError:
206
+ pass
207
+ return removed