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
agent_chat/openapi.py ADDED
@@ -0,0 +1,322 @@
1
+ """Stable OpenAPI contract for the client and agent HTTP surface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .api import create_app
6
+
7
+ CONTRACT_VERSION = "1.0.0"
8
+
9
+ INCLUDED_PREFIXES = (
10
+ "/v1/sessions",
11
+ "/v1/instance",
12
+ "/v1/rooms",
13
+ "/v1/messages",
14
+ "/v1/threads",
15
+ "/v1/events",
16
+ )
17
+ EXCLUDED_PREFIXES = ("/v1/login", "/v1/logout", "/v1/browser")
18
+ EXCLUDED_OPERATIONS = {
19
+ ("post", "/v1/rooms"),
20
+ ("post", "/v1/rooms/{room}/memberships"),
21
+ ("post", "/v1/rooms/{room}/pm"),
22
+ ("post", "/v1/rooms/{room}/roles"),
23
+ ("post", "/v1/rooms/{room}/state"),
24
+ }
25
+ SUCCESS_SCHEMAS = {
26
+ ("post", "/v1/sessions"): "SessionBinding",
27
+ ("get", "/v1/rooms"): "RoomList",
28
+ ("get", "/v1/rooms/{room}/participants"): "ParticipantPage",
29
+ ("get", "/v1/rooms/{room}/history"): "HistoryPage",
30
+ ("post", "/v1/rooms/{room}/messages"): "PublicationMessage",
31
+ ("post", "/v1/messages/{message}/replies"): "PublicationMessage",
32
+ ("get", "/v1/rooms/{room}/state"): "StatePage",
33
+ ("get", "/v1/instance/status"): "InstanceStatus",
34
+ ("post", "/v1/messages/{message}/ack"): "Receipt",
35
+ }
36
+
37
+
38
+ def _included(path: str) -> bool:
39
+ return path.startswith(INCLUDED_PREFIXES) and not path.startswith(EXCLUDED_PREFIXES)
40
+
41
+
42
+ def build_openapi() -> dict:
43
+ """Return the filtered contract; live FastAPI docs remain disabled."""
44
+ spec = create_app("postgresql://unused", enabled=True).openapi()
45
+ paths = {}
46
+ for path, item in spec["paths"].items():
47
+ if not _included(path):
48
+ continue
49
+ kept = {method: operation for method, operation in item.items() if (method, path) not in EXCLUDED_OPERATIONS}
50
+ if kept:
51
+ paths[path] = kept
52
+ error_response = {
53
+ "description": "Stable Agent Chat refusal envelope",
54
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}},
55
+ }
56
+ object_schema = {"type": "object", "additionalProperties": True}
57
+ components = spec.setdefault("components", {})
58
+ schemas = components.setdefault("schemas", {})
59
+ schemas.update(
60
+ {
61
+ "JsonObject": object_schema,
62
+ "SessionBinding": {
63
+ "type": "object",
64
+ "required": ["session_id", "instance_id", "room_id", "host", "harness"],
65
+ "properties": {
66
+ name: {"type": "string"} for name in ("session_id", "instance_id", "room_id", "host", "harness")
67
+ },
68
+ },
69
+ "Room": {
70
+ "type": "object",
71
+ "required": ["id", "slug", "label"],
72
+ "properties": {"id": {"type": "string"}, "slug": {"type": "string"}, "label": {"type": "string"}},
73
+ },
74
+ "RoomList": {
75
+ "type": "object",
76
+ "required": ["rooms"],
77
+ "properties": {"rooms": {"type": "array", "items": {"$ref": "#/components/schemas/Room"}}},
78
+ },
79
+ "ParticipantPage": {
80
+ "type": "object",
81
+ "required": ["participants"],
82
+ "properties": {
83
+ "participants": {"type": "array", "items": {"$ref": "#/components/schemas/JsonObject"}},
84
+ "next_session_id": {"type": ["string", "null"]},
85
+ },
86
+ },
87
+ "HistoryPage": {
88
+ "type": "object",
89
+ "required": ["messages", "next_cursor", "retained_floor", "position", "has_more"],
90
+ "properties": {
91
+ "messages": {"type": "array", "items": {"$ref": "#/components/schemas/Message"}},
92
+ "next_cursor": {"type": "string"},
93
+ "retained_floor": {"type": "string"},
94
+ "position": {"type": "string"},
95
+ "has_more": {"type": "boolean"},
96
+ },
97
+ },
98
+ "Message": {
99
+ "type": "object",
100
+ "required": [
101
+ "id",
102
+ "room_id",
103
+ "body",
104
+ "kind",
105
+ "created_at",
106
+ "cursor",
107
+ "receipts",
108
+ "sender",
109
+ "recipients",
110
+ ],
111
+ "properties": {
112
+ "id": {"type": "string"},
113
+ "room_id": {"type": "string"},
114
+ "body": {"type": ["string", "null"]},
115
+ "kind": {"type": "string"},
116
+ "created_at": {"type": "string"},
117
+ "cursor": {"type": "string"},
118
+ "receipts": {"type": "array", "items": {"$ref": "#/components/schemas/JsonObject"}},
119
+ "sender": {"$ref": "#/components/schemas/JsonObject"},
120
+ "recipients": {"type": "array", "items": {"type": "string"}},
121
+ "thread_id": {"type": ["string", "null"]},
122
+ "reply_to": {"type": ["string", "null"]},
123
+ "thread_ref_key": {"type": ["string", "null"]},
124
+ "thread_resolved_at": {"type": ["string", "null"]},
125
+ },
126
+ },
127
+ "PublicationMessage": {
128
+ "type": "object",
129
+ "required": ["id", "room_id", "body", "kind", "created_at", "sender", "recipients"],
130
+ "properties": {
131
+ "id": {"type": "string"},
132
+ "room_id": {"type": "string"},
133
+ "body": {"type": "string"},
134
+ "kind": {"type": "string"},
135
+ "created_at": {"type": "string"},
136
+ "thread_id": {"type": ["string", "null"]},
137
+ "reply_to": {"type": ["string", "null"]},
138
+ "thread_ref_key": {"type": ["string", "null"]},
139
+ "thread_resolved_at": {"type": ["string", "null"]},
140
+ "sender": {"$ref": "#/components/schemas/JsonObject"},
141
+ "recipients": {"type": "array", "items": {"type": "string"}},
142
+ },
143
+ },
144
+ "StatePage": {
145
+ "type": "object",
146
+ "required": ["server_time", "entries", "next_key"],
147
+ "properties": {
148
+ "server_time": {"type": "string"},
149
+ "entries": {"type": "array", "items": {"$ref": "#/components/schemas/JsonObject"}},
150
+ "next_key": {"type": ["string", "null"]},
151
+ },
152
+ },
153
+ "InstanceStatus": {"type": "object", "additionalProperties": True},
154
+ "Receipt": {"type": "object", "additionalProperties": True},
155
+ }
156
+ )
157
+ for path, item in paths.items():
158
+ for method, operation in item.items():
159
+ if not isinstance(operation, dict):
160
+ continue
161
+ operation["security"] = [{"bearerAuth": []}]
162
+ responses = operation.setdefault("responses", {})
163
+ responses["422"] = error_response
164
+ for status in ("401", "403", "409", "410", "429", "503"):
165
+ responses.setdefault(status, error_response)
166
+ responses.setdefault("default", error_response)
167
+ success = SUCCESS_SCHEMAS.get((method, path), "JsonObject")
168
+ if path != "/v1/events":
169
+ responses["200"] = {
170
+ "description": "Successful response",
171
+ "content": {"application/json": {"schema": {"$ref": f"#/components/schemas/{success}"}}},
172
+ }
173
+ if path == "/v1/instance/deliveries/{attempt}/result" and method == "post":
174
+ operation["requestBody"]["content"]["application/json"]["schema"] = {
175
+ "oneOf": [
176
+ {
177
+ "type": "object",
178
+ "required": ["outcome"],
179
+ "additionalProperties": False,
180
+ "properties": {"outcome": {"const": "handed"}, "reason": {"type": "null"}},
181
+ },
182
+ {
183
+ "type": "object",
184
+ "required": ["outcome", "reason"],
185
+ "additionalProperties": False,
186
+ "properties": {"outcome": {"const": "failed"}, "reason": {"const": "native_unavailable"}},
187
+ },
188
+ {
189
+ "type": "object",
190
+ "required": ["outcome", "reason"],
191
+ "additionalProperties": False,
192
+ "properties": {
193
+ "outcome": {"const": "deferred"},
194
+ "reason": {
195
+ "enum": ["busy", "muted", "stopped", "plan", "unknown", "offline", "stale_binding"]
196
+ },
197
+ },
198
+ },
199
+ {
200
+ "type": "object",
201
+ "required": ["outcome", "reason"],
202
+ "additionalProperties": False,
203
+ "properties": {
204
+ "outcome": {"const": "uncertain"},
205
+ "reason": {"const": "transport_ambiguous"},
206
+ },
207
+ },
208
+ ]
209
+ }
210
+ if path == "/v1/rooms/{room}/messages" and method == "post":
211
+ base = {"$ref": "#/components/schemas/Publication"}
212
+ operation["requestBody"]["content"]["application/json"]["schema"] = {
213
+ "oneOf": [
214
+ {
215
+ "allOf": [
216
+ base,
217
+ {
218
+ "type": "object",
219
+ "required": ["reply_to"],
220
+ "properties": {
221
+ "kind": {"const": "reply"},
222
+ "reply_to": {"type": "string", "format": "uuid"},
223
+ "ref_key": {"type": "null"},
224
+ },
225
+ },
226
+ ]
227
+ },
228
+ {
229
+ "allOf": [
230
+ base,
231
+ {
232
+ "type": "object",
233
+ "required": ["ref_key"],
234
+ "properties": {
235
+ "kind": {
236
+ "enum": [
237
+ "message",
238
+ "status",
239
+ "heads_up",
240
+ "blocked_on",
241
+ "decision_needed",
242
+ "intent",
243
+ ]
244
+ },
245
+ "ref_key": {"type": "string"},
246
+ "thread_id": {"type": "null"},
247
+ "reply_to": {"type": "null"},
248
+ },
249
+ },
250
+ ]
251
+ },
252
+ {
253
+ "allOf": [
254
+ base,
255
+ {
256
+ "type": "object",
257
+ "properties": {
258
+ "kind": {
259
+ "enum": [
260
+ "message",
261
+ "status",
262
+ "question",
263
+ "consultation",
264
+ "heads_up",
265
+ "blocked_on",
266
+ "decision_needed",
267
+ "intent",
268
+ ]
269
+ },
270
+ "reply_to": {"type": "null"},
271
+ "ref_key": {"type": "null"},
272
+ },
273
+ },
274
+ ]
275
+ },
276
+ ]
277
+ }
278
+ if path == "/v1/events" and method == "get":
279
+ responses["200"] = {
280
+ "description": (
281
+ "Server-Sent Events stream. A normal lifetime close may reconnect "
282
+ "with the last event id; Last-Event-ID takes precedence over after. "
283
+ "If a control event reports ROOM_SCOPE_CHANGED, do not resume at the "
284
+ "old cursor: resynchronize room access and replay from the retained "
285
+ 'floor. The id-less control frame is {"error":{"code":"CODE"}} '
286
+ "and has no message field."
287
+ ),
288
+ "content": {"text/event-stream": {"schema": {"type": "string"}}},
289
+ }
290
+ parameters = operation.setdefault("parameters", [])
291
+ parameters.append(
292
+ {
293
+ "name": "Last-Event-ID",
294
+ "in": "header",
295
+ "required": False,
296
+ "schema": {"type": "string"},
297
+ "description": "Last durable event id; takes precedence over after.",
298
+ }
299
+ )
300
+ components.setdefault("securitySchemes", {})["bearerAuth"] = {
301
+ "type": "http",
302
+ "scheme": "bearer",
303
+ "bearerFormat": "Agent Chat instance or credential token",
304
+ }
305
+ schemas["Error"] = {
306
+ "type": "object",
307
+ "required": ["error"],
308
+ "properties": {
309
+ "error": {
310
+ "type": "object",
311
+ "required": ["code", "message"],
312
+ "properties": {
313
+ "code": {"type": "string", "description": "Stable refusal code"},
314
+ "message": {"type": "string", "description": "Same stable code"},
315
+ },
316
+ }
317
+ },
318
+ }
319
+ spec["paths"] = paths
320
+ spec["info"]["title"] = "Agent Chat client and agent API"
321
+ spec["info"]["version"] = CONTRACT_VERSION
322
+ return spec
agent_chat/producer.py ADDED
@@ -0,0 +1,208 @@
1
+ """One bounded validation-lease observation; no lease acquisition or native delivery."""
2
+
3
+ import json
4
+ import os
5
+ import re
6
+ import stat
7
+ import subprocess
8
+ from collections.abc import Mapping
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ from typing import Any
12
+ from uuid import UUID
13
+
14
+ from pydantic import ValidationError
15
+
16
+ from .client import Client
17
+ from .models import ChatError, StateEntry, StateUpsert
18
+ from .protocol import token_digest, validate_origin
19
+
20
+ STATUS_SCHEMA = "validation-lease-status.v1"
21
+ VALUE_SCHEMA = "agent-chat.validation-lease.v1"
22
+ CLASSES = ("leaf", "c1", "shared")
23
+ FIELDS = ("lane", "branch", "head", "profile", "effective", "owner", "step")
24
+ LEASE_ENV = (
25
+ "CI_PROFILE_SLOTS", "CI_PROFILE_LEAF_SLOTS", "CI_PROFILE_C1_SLOTS", "CI_PROFILE_RUN_USER_DIR", "TMPDIR"
26
+ )
27
+ HOST = re.compile(r"[a-z0-9][a-z0-9-]{0,62}")
28
+ MAX_CREDENTIAL_BYTES = 16 * 1024
29
+ MAX_STATUS_BYTES = 1024 * 1024
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class ProducerCredential:
34
+ server_origin: str
35
+ token: str = field(repr=False)
36
+ host: str
37
+ room_id: UUID
38
+
39
+
40
+ def read_credential(path: Path) -> ProducerCredential:
41
+ """Read the named, private producer file; never discover a credential or accept a symlink."""
42
+ try:
43
+ if not path.is_absolute():
44
+ raise ChatError("PRODUCER_CREDENTIAL_UNSAFE")
45
+ descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
46
+ with os.fdopen(descriptor, "rb") as handle:
47
+ info = os.fstat(handle.fileno())
48
+ if (
49
+ not stat.S_ISREG(info.st_mode)
50
+ or info.st_uid != os.geteuid()
51
+ or stat.S_IMODE(info.st_mode) != 0o600
52
+ or info.st_nlink != 1
53
+ ):
54
+ raise ChatError("PRODUCER_CREDENTIAL_UNSAFE")
55
+ raw = handle.read(MAX_CREDENTIAL_BYTES + 1)
56
+ except OSError:
57
+ raise ChatError("PRODUCER_CREDENTIAL_UNSAFE") from None
58
+ try:
59
+ data = json.loads(raw.decode("utf-8"))
60
+ if (
61
+ len(raw) > MAX_CREDENTIAL_BYTES
62
+ or not isinstance(data, dict)
63
+ or set(data) != {"server_origin", "token", "host", "room_id"}
64
+ or not all(isinstance(value, str) for value in data.values())
65
+ or HOST.fullmatch(data["host"]) is None
66
+ ):
67
+ raise ValueError("invalid producer credential")
68
+ validate_origin(data["server_origin"])
69
+ token_digest(data["token"])
70
+ room = UUID(data["room_id"])
71
+ if str(room) != data["room_id"]:
72
+ raise ValueError("noncanonical room")
73
+ return ProducerCredential(data["server_origin"], data["token"], data["host"], room)
74
+ except (ValueError, UnicodeError, ChatError, RecursionError):
75
+ raise ChatError("PRODUCER_CREDENTIAL_INVALID") from None
76
+
77
+
78
+ class _Unknown(Exception):
79
+ """A fixed, secret-free reason for replacing every class observation with unknown."""
80
+
81
+
82
+ def _safe_script(script: Path) -> bool:
83
+ try:
84
+ if not script.is_absolute():
85
+ return False
86
+ descriptor = os.open(script, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
87
+ with os.fdopen(descriptor, "rb") as handle:
88
+ info = os.fstat(handle.fileno())
89
+ return (
90
+ stat.S_ISREG(info.st_mode)
91
+ and info.st_uid in (0, os.geteuid())
92
+ and not info.st_mode & 0o022
93
+ )
94
+ except OSError:
95
+ return False
96
+
97
+
98
+ def _text(value: Any) -> str | None:
99
+ if value is None or value == "-":
100
+ return None
101
+ if not isinstance(value, str) or len(value.encode("utf-8")) > 512 or "\x00" in value:
102
+ raise _Unknown("invalid_status")
103
+ return value
104
+
105
+
106
+ def _fields(row: dict[str, Any]) -> dict[str, Any]:
107
+ fields = row.get("fields")
108
+ if not isinstance(fields, dict):
109
+ raise _Unknown("invalid_status")
110
+ return {name: _text(fields.get(name)) for name in FIELDS}
111
+
112
+
113
+ def _values(report: Any) -> dict[str, dict[str, Any]]:
114
+ if not isinstance(report, dict) or report.get("schema") != STATUS_SCHEMA:
115
+ raise _Unknown("schema_mismatch")
116
+ classes = {"classed": ("leaf", "c1"), "legacy": ("shared",)}.get(report.get("mode"))
117
+ if classes is None or not isinstance(report.get("slots"), list) or not isinstance(report.get("waiters"), list):
118
+ raise _Unknown("invalid_status")
119
+ values: dict[str, dict[str, Any]] = {
120
+ name: {"schema": VALUE_SCHEMA, "scan": "known", "slots": [], "waiters": []} for name in classes
121
+ }
122
+ seen = set()
123
+ for row in report["slots"]:
124
+ if not isinstance(row, dict):
125
+ raise _Unknown("invalid_status")
126
+ name, number, state = row.get("class"), row.get("slot"), row.get("state")
127
+ if (
128
+ name not in classes
129
+ or type(number) is not int
130
+ or not 1 <= number <= 16
131
+ or state not in ("free", "held", "stuck", "unknown")
132
+ or (name, number) in seen
133
+ ):
134
+ raise _Unknown("invalid_status")
135
+ seen.add((name, number))
136
+ values[name]["slots"].append({"class": name, "slot": number, "state": state, **_fields(row)})
137
+ if any(not value["slots"] for value in values.values()):
138
+ raise _Unknown("invalid_status")
139
+ for row in report["waiters"]:
140
+ if not isinstance(row, dict) or row.get("class") not in classes:
141
+ raise _Unknown("invalid_status")
142
+ name = row["class"]
143
+ values[name]["waiters"].append(
144
+ {"class": name, **_fields(row), "waiting_since": _text(row.get("waiting_since"))}
145
+ )
146
+ for value in values.values():
147
+ value["slots"].sort(key=lambda slot: slot["slot"])
148
+ return values
149
+
150
+
151
+ def _collect(script: Path, lock_file: Path | None, environ: Mapping[str, str]) -> dict[str, dict[str, Any]]:
152
+ if not _safe_script(script):
153
+ raise _Unknown("script_unsafe")
154
+ child_env = {"PATH": "/usr/bin:/bin", "LANG": "C.UTF-8"}
155
+ child_env.update({name: environ[name] for name in LEASE_ENV if name in environ})
156
+ if lock_file is not None:
157
+ if not lock_file.is_absolute():
158
+ raise ChatError("INVALID_ARGUMENTS")
159
+ child_env["CI_PROFILE_LOCK_FILE"] = str(lock_file)
160
+ try:
161
+ result = subprocess.run(
162
+ ["python3", "-I", str(script), "status", "--json", "--fast"],
163
+ env=child_env,
164
+ stdin=subprocess.DEVNULL,
165
+ stdout=subprocess.PIPE,
166
+ stderr=subprocess.DEVNULL,
167
+ timeout=5,
168
+ check=True,
169
+ )
170
+ except subprocess.TimeoutExpired:
171
+ raise _Unknown("command_timeout") from None
172
+ except (OSError, subprocess.CalledProcessError):
173
+ raise _Unknown("command_failed") from None
174
+ if len(result.stdout) > MAX_STATUS_BYTES:
175
+ raise _Unknown("invalid_status")
176
+ try:
177
+ return _values(json.loads(result.stdout.decode("utf-8")))
178
+ except (ValueError, UnicodeError, TypeError, RecursionError):
179
+ raise _Unknown("invalid_status") from None
180
+
181
+
182
+ def _entries(host: str, values: dict[str, dict[str, Any]]) -> StateUpsert:
183
+ return StateUpsert(
184
+ entries=tuple(
185
+ StateEntry(
186
+ state_key=f"validation-lease:{host}:{name}",
187
+ ref_key=f"resource:{host}:ci-validation",
188
+ value=values.get(name, {"schema": VALUE_SCHEMA, "scan": "unknown", "reason": "inactive"}),
189
+ ttl_seconds=90,
190
+ )
191
+ for name in CLASSES
192
+ )
193
+ )
194
+
195
+
196
+ def produce(credential: ProducerCredential, script: Path, lock_file: Path | None = None) -> dict[str, Any]:
197
+ """Publish once. Failed scans overwrite every possible class as unknown, never as free."""
198
+ try:
199
+ values = _collect(script, lock_file, os.environ)
200
+ request = _entries(credential.host, values)
201
+ except (_Unknown, ValidationError) as error:
202
+ reason = str(error) if isinstance(error, _Unknown) else "state_too_large"
203
+ values = {name: {"schema": VALUE_SCHEMA, "scan": "unknown", "reason": reason} for name in CLASSES}
204
+ request = _entries(credential.host, values)
205
+ Client(credential.server_origin, credential.token).request(
206
+ "POST", f"/v1/rooms/{credential.room_id}/state", request.model_dump(mode="json")
207
+ )
208
+ return {"entries": [{"state_key": entry.state_key, "scan": entry.value["scan"]} for entry in request.entries]}
agent_chat/protocol.py ADDED
@@ -0,0 +1,71 @@
1
+ """Wire-format helpers shared by the server and the CLI client.
2
+
3
+ This module must never import `psycopg`: the `agent-chat` CLI runs without the
4
+ optional `server` extra; a test pins that client-only import boundary.
5
+ """
6
+
7
+ import re
8
+ from hashlib import sha256
9
+ from urllib.parse import urlsplit
10
+
11
+ from .models import ChatError
12
+
13
+
14
+ def token_digest(token: str) -> str:
15
+ # v1 credentials are 32 random bytes encoded as lowercase hexadecimal.
16
+ if re.fullmatch(r"[0-9a-f]{64}", token) is None:
17
+ raise ChatError("UNAUTHENTICATED")
18
+ return sha256(token.encode("ascii")).hexdigest()
19
+
20
+
21
+ def cursor(value: str) -> int:
22
+ if re.fullmatch(r"[0-9]{1,19}", value) is None or int(value) > 9223372036854775807:
23
+ raise ChatError("INVALID_CURSOR")
24
+ return int(value)
25
+
26
+
27
+ def session_label(harness: str, host: str, native_session_id: str) -> str:
28
+ """The stored label of a session, which is also a selector alias."""
29
+ return f"{harness}@{host}/{native_session_id}"
30
+
31
+
32
+ def _internal_service_host(host: str) -> bool:
33
+ """A single-label DNS service name, never an IP literal or numeric shorthand."""
34
+ return (
35
+ re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", host) is not None
36
+ and any(char.isalpha() for char in host)
37
+ and not host.startswith(("0x", "0X"))
38
+ )
39
+
40
+
41
+ def validate_origin(origin: str, *, https_only: bool = False, allow_service_http: bool = False) -> None:
42
+ """Accept a canonical origin; loopback HTTP is allowed unless `https_only`.
43
+
44
+ Browsers omit a default port from `Origin`, so an explicit `:443` or `:80` is not canonical.
45
+ `allow_service_http` additionally accepts HTTP for a single-label DNS name, for an
46
+ internal container service. It never permits a dotted HTTP hostname.
47
+ """
48
+ try:
49
+ parsed = urlsplit(origin)
50
+ if (
51
+ not origin.isascii()
52
+ or any(ord(char) <= 32 or ord(char) == 127 for char in origin)
53
+ or not parsed.hostname
54
+ or parsed.username is not None
55
+ or parsed.password is not None
56
+ or parsed.path
57
+ or parsed.query
58
+ or parsed.fragment
59
+ or origin != parsed.scheme + "://" + parsed.netloc.lower()
60
+ or parsed.scheme not in (("https",) if https_only else ("https", "http"))
61
+ or (
62
+ parsed.scheme == "http"
63
+ and parsed.hostname not in ("127.0.0.1", "::1")
64
+ and not (allow_service_http and _internal_service_host(parsed.hostname))
65
+ )
66
+ or parsed.port == 0
67
+ or (parsed.scheme, parsed.port) in (("https", 443), ("http", 80))
68
+ ):
69
+ raise ValueError("invalid origin")
70
+ except ValueError:
71
+ raise ChatError("INVALID_ORIGIN") from None