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.
- agent_chat/001_core.sql +172 -0
- agent_chat/002_coordination.sql +63 -0
- agent_chat/003_harness_admission.sql +10 -0
- agent_chat/004_session_titles.sql +3 -0
- agent_chat/005_viewer.sql +9 -0
- agent_chat/006_quotas.sql +6 -0
- agent_chat/007_sender_receipts.sql +20 -0
- agent_chat/008_direct_threads.sql +49 -0
- agent_chat/009_pm_mark.sql +23 -0
- agent_chat/010_quota_backfill.sql +12 -0
- agent_chat/011_roles_and_work.sql +31 -0
- agent_chat/__init__.py +1 -0
- agent_chat/adapter.py +414 -0
- agent_chat/admin.py +524 -0
- agent_chat/api.py +641 -0
- agent_chat/auth.py +226 -0
- agent_chat/browser.py +118 -0
- agent_chat/browser_verify.py +487 -0
- agent_chat/browser_verify_artifacts.py +280 -0
- agent_chat/browser_verify_checks.py +236 -0
- agent_chat/browser_verify_run.py +523 -0
- agent_chat/cli.py +532 -0
- agent_chat/client.py +272 -0
- agent_chat/deliveries.py +555 -0
- agent_chat/events.py +48 -0
- agent_chat/feed.py +193 -0
- agent_chat/http_boundary.py +154 -0
- agent_chat/instance_client.py +349 -0
- agent_chat/instance_file.py +207 -0
- agent_chat/instance_worker.py +326 -0
- agent_chat/mcp/__init__.py +5 -0
- agent_chat/mcp/__main__.py +39 -0
- agent_chat/mcp/app.py +183 -0
- agent_chat/mcp/auth.py +67 -0
- agent_chat/mcp/config.py +55 -0
- agent_chat/mcp/tools.py +295 -0
- agent_chat/metrics.py +60 -0
- agent_chat/models.py +430 -0
- agent_chat/openapi.py +322 -0
- agent_chat/producer.py +208 -0
- agent_chat/protocol.py +71 -0
- agent_chat/publication.py +252 -0
- agent_chat/receipts.py +225 -0
- agent_chat/retention.py +154 -0
- agent_chat/roles.py +153 -0
- agent_chat/rooms.py +179 -0
- agent_chat/sessions.py +340 -0
- agent_chat/skills/agent-chat/SKILL.md +64 -0
- agent_chat/state.py +144 -0
- agent_chat/storage.py +110 -0
- agent_chat/threads.py +50 -0
- agent_chat/web/Manrope-OFL.txt +93 -0
- agent_chat/web/Manrope-Variable.ttf +0 -0
- agent_chat/web/chat.css +936 -0
- agent_chat/web/chat.js +1922 -0
- agent_chat/web/i18n.js +340 -0
- agent_chat/web/index.html +264 -0
- sessionyard-0.7.0.dist-info/METADATA +314 -0
- sessionyard-0.7.0.dist-info/RECORD +62 -0
- sessionyard-0.7.0.dist-info/WHEEL +4 -0
- sessionyard-0.7.0.dist-info/entry_points.txt +3 -0
- sessionyard-0.7.0.dist-info/licenses/LICENSE +661 -0
agent_chat/admin.py
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
"""Server launcher and administration: `python -m agent_chat.admin <subcommand> --config PATH`.
|
|
2
|
+
|
|
3
|
+
Every expected failure prints one `agent-chat-admin: <CODE>` line to stderr and exits nonzero
|
|
4
|
+
(2 for configuration or usage, 1 for operational). Nothing here prints a DSN, token, digest,
|
|
5
|
+
message body or raw database exception text. The DSN comes only from the systemd credential
|
|
6
|
+
named by the configuration; there is no argv or environment fallback.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import sys
|
|
17
|
+
from collections.abc import Mapping, Sequence
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any, TextIO
|
|
20
|
+
from uuid import UUID, uuid5
|
|
21
|
+
|
|
22
|
+
import psycopg
|
|
23
|
+
import psycopg.errors
|
|
24
|
+
import uvicorn
|
|
25
|
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
|
|
26
|
+
|
|
27
|
+
from . import retention
|
|
28
|
+
from .api import create_app
|
|
29
|
+
from .models import ChatError
|
|
30
|
+
from .protocol import token_digest, validate_origin
|
|
31
|
+
from .storage import connect, migrate, review_digest, review_lines
|
|
32
|
+
|
|
33
|
+
PROGRAM = "agent-chat-admin"
|
|
34
|
+
USAGE_EXIT = 2
|
|
35
|
+
OPERATIONAL_EXIT = 1
|
|
36
|
+
MAX_CONFIG_BYTES = 65536
|
|
37
|
+
MAX_CREDENTIAL_BYTES = 4096
|
|
38
|
+
# Seconds uvicorn waits for open connections after SIGTERM before it cancels them. Its listener is already closed
|
|
39
|
+
# for that whole wait, so the wait is the restart outage. Without a limit one open `/v1/events` stream, which
|
|
40
|
+
# ignores shutdown for the rest of its 60 s lifetime, kept the listener closed for up to a minute. A client
|
|
41
|
+
# heartbeats every 30 s against a 90 s lease and lapses only when two consecutive beats fail, so an outage under
|
|
42
|
+
# 30 s lapses no lease: this limit plus about 2 s of start-up stays well below it. It is twice the 5 s statement
|
|
43
|
+
# limit of `storage.connect`, so a request cut at the deadline is the rare case. A cut stream reconnects with its
|
|
44
|
+
# last event id.
|
|
45
|
+
GRACEFUL_SHUTDOWN_SECONDS = 10
|
|
46
|
+
|
|
47
|
+
# The schema stores no principal name, so a name maps to the deterministic id uuid5(PRINCIPAL_NAMESPACE, name).
|
|
48
|
+
# The primary key then backs the name's uniqueness. NEVER change this constant: every provisioned id would move
|
|
49
|
+
# and `revoke --name` would stop finding the principals this tool created.
|
|
50
|
+
PRINCIPAL_NAMESPACE = UUID("6b5a50e4-028b-4409-874a-46b9e4a3b372")
|
|
51
|
+
# Serializes principal provisioning across processes. Distinct from storage.migrate's key (617204831095).
|
|
52
|
+
PRINCIPAL_LOCK = 617204831096
|
|
53
|
+
NAME_PATTERN = re.compile(r"[a-z0-9][a-z0-9._-]{0,63}")
|
|
54
|
+
HOST_PATTERN = re.compile(r"[a-z0-9][a-z0-9-]{0,62}")
|
|
55
|
+
HOMELAB_ROOM = "homelab"
|
|
56
|
+
REVIEWED_PATTERN = re.compile(r"[0-9a-f]{64}")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class _ListenerErrorFilter(logging.Filter):
|
|
60
|
+
def filter(self, record: logging.LogRecord) -> bool:
|
|
61
|
+
# Uvicorn logs the bind OSError before exiting; _serve emits the fixed code.
|
|
62
|
+
return not isinstance(record.msg, OSError)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# systemd (SyslogLevelPrefix=yes) turns a leading `<N>` on a stderr line into the journal PRIORITY. Python's
|
|
66
|
+
# levels map onto syslog's; every line of a multi-line record carries the prefix, so a traceback keeps its level.
|
|
67
|
+
_SYSLOG_PRIORITY = (
|
|
68
|
+
(logging.CRITICAL, 2),
|
|
69
|
+
(logging.ERROR, 3),
|
|
70
|
+
(logging.WARNING, 4),
|
|
71
|
+
(logging.INFO, 6),
|
|
72
|
+
(logging.NOTSET, 7),
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class _JournalFormatter(logging.Formatter):
|
|
77
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
78
|
+
priority = next(value for level, value in _SYSLOG_PRIORITY if record.levelno >= level)
|
|
79
|
+
return "\n".join(f"<{priority}>{line}" for line in super().format(record).splitlines())
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# Stderr only, no uvicorn.access handler: access lines would carry raw request URLs.
|
|
83
|
+
LOG_CONFIG: dict[str, Any] = {
|
|
84
|
+
"version": 1,
|
|
85
|
+
"disable_existing_loggers": False,
|
|
86
|
+
"formatters": {
|
|
87
|
+
"plain": {"()": _JournalFormatter, "format": "%(asctime)s %(levelname)s %(name)s %(message)s"},
|
|
88
|
+
},
|
|
89
|
+
"filters": {"listener_errors": {"()": _ListenerErrorFilter}},
|
|
90
|
+
"handlers": {"stderr": {"class": "logging.StreamHandler", "stream": "ext://sys.stderr", "formatter": "plain"}},
|
|
91
|
+
"loggers": {
|
|
92
|
+
"uvicorn": {"handlers": ["stderr"], "level": "INFO", "propagate": False},
|
|
93
|
+
"uvicorn.error": {"level": "INFO", "filters": ["listener_errors"]},
|
|
94
|
+
"uvicorn.access": {"handlers": [], "level": "CRITICAL", "propagate": False},
|
|
95
|
+
"agent_chat.api": {"handlers": ["stderr"], "level": "INFO", "propagate": False},
|
|
96
|
+
},
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _diagnose(stderr: TextIO, environ: Mapping[str, str], text: str, priority: int = 3) -> None:
|
|
101
|
+
# Uvicorn's formatter is installed only once it runs, so a failure before that (and every prune or migrate
|
|
102
|
+
# failure) prefixes its own line. systemd names the journal stream it connected in JOURNAL_STREAM; matching it
|
|
103
|
+
# to stderr keeps the prefix out of a terminal, a pipe and a captured stream, where it would be noise.
|
|
104
|
+
try:
|
|
105
|
+
status = os.fstat(stderr.fileno())
|
|
106
|
+
journal = environ.get("JOURNAL_STREAM") == f"{status.st_dev}:{status.st_ino}"
|
|
107
|
+
except (OSError, ValueError):
|
|
108
|
+
journal = False
|
|
109
|
+
print(f"<{priority}>{text}" if journal else text, file=stderr)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class AdminError(Exception):
|
|
113
|
+
"""An expected failure: a fixed code, never a message that could carry a secret."""
|
|
114
|
+
|
|
115
|
+
def __init__(self, code: str, status: int = USAGE_EXIT, hint: str | None = None):
|
|
116
|
+
super().__init__(code)
|
|
117
|
+
self.code = code
|
|
118
|
+
self.status = status
|
|
119
|
+
self.hint = hint
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class Config(BaseModel):
|
|
123
|
+
model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
|
|
124
|
+
|
|
125
|
+
bind_host: str = Field(min_length=1, max_length=255)
|
|
126
|
+
port: int = Field(ge=1024, le=65535)
|
|
127
|
+
public_origin: str | None = None
|
|
128
|
+
enabled: bool = False
|
|
129
|
+
delivery_enabled: bool = False
|
|
130
|
+
dsn_credential: str = Field(default="agent-chat-dsn", max_length=255, pattern=r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
|
|
131
|
+
|
|
132
|
+
@field_validator("public_origin")
|
|
133
|
+
@classmethod
|
|
134
|
+
def canonical_https_origin(cls, value: str | None) -> str | None:
|
|
135
|
+
if value is not None:
|
|
136
|
+
try:
|
|
137
|
+
validate_origin(value, https_only=True)
|
|
138
|
+
except ChatError:
|
|
139
|
+
raise ValueError("public_origin must be a canonical HTTPS origin") from None
|
|
140
|
+
return value
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class _Parser(argparse.ArgumentParser):
|
|
144
|
+
def error(self, message: str):
|
|
145
|
+
# argparse messages quote the offending argument; none is echoed.
|
|
146
|
+
raise AdminError("USAGE", USAGE_EXIT, "see --help")
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _reviewed_digest(value: str) -> str:
|
|
150
|
+
if REVIEWED_PATTERN.fullmatch(value) is None:
|
|
151
|
+
raise argparse.ArgumentTypeError("not a sha256 digest")
|
|
152
|
+
return value
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _parser() -> argparse.ArgumentParser:
|
|
156
|
+
parser = _Parser(prog="python -m agent_chat.admin", description="Agent Chat server launcher and administration.")
|
|
157
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
158
|
+
for name, text in (
|
|
159
|
+
("serve", "Run the HTTP server. Inert unless the configuration sets enabled=true."),
|
|
160
|
+
(
|
|
161
|
+
"migrate",
|
|
162
|
+
"Apply the schema migrations; idempotent. --check applies nothing and lists the pending ones; "
|
|
163
|
+
"--reviewed refuses to apply any other pending set.",
|
|
164
|
+
),
|
|
165
|
+
("prune", "Run bounded retention batches."),
|
|
166
|
+
):
|
|
167
|
+
command = commands.add_parser(name, help=text, description=text)
|
|
168
|
+
command.add_argument("--config", required=True, metavar="PATH", help="JSON configuration file")
|
|
169
|
+
if name == "migrate":
|
|
170
|
+
command.add_argument(
|
|
171
|
+
"--check",
|
|
172
|
+
action="store_true",
|
|
173
|
+
help="run no DDL: print pending=<n>, one line per pending file and reviewed=<sha256>",
|
|
174
|
+
)
|
|
175
|
+
command.add_argument(
|
|
176
|
+
"--reviewed",
|
|
177
|
+
type=_reviewed_digest,
|
|
178
|
+
metavar="SHA256",
|
|
179
|
+
help="the reviewed=<sha256> of --check; under the migration lock, run nothing (REVIEW_MISMATCH) "
|
|
180
|
+
"unless the pending set has this digest",
|
|
181
|
+
)
|
|
182
|
+
if name == "prune":
|
|
183
|
+
command.add_argument("--limit", type=int, default=100, help="rows per batch, 1-1000 (default 100)")
|
|
184
|
+
command.add_argument("--max-batches", type=int, default=50, help="batch bound, at least 1 (default 50)")
|
|
185
|
+
principal = commands.add_parser("principal", help="Provision or revoke a principal.")
|
|
186
|
+
actions = principal.add_subparsers(dest="action", required=True)
|
|
187
|
+
ensure = actions.add_parser(
|
|
188
|
+
"ensure",
|
|
189
|
+
help="Create or update a principal; the raw token is read from stdin.",
|
|
190
|
+
description="Create, rotate or restore a principal. The raw token (64 lowercase hex characters) is read "
|
|
191
|
+
"from stdin only.",
|
|
192
|
+
)
|
|
193
|
+
ensure.add_argument("--config", required=True, metavar="PATH", help="JSON configuration file")
|
|
194
|
+
ensure.add_argument("--name", required=True, help="principal name; maps to a deterministic id")
|
|
195
|
+
ensure.add_argument("--kind", required=True, choices=("operator", "agent", "producer", "viewer"))
|
|
196
|
+
ensure.add_argument("--host", help="agent or producer host")
|
|
197
|
+
ensure.add_argument(
|
|
198
|
+
"--harness",
|
|
199
|
+
choices=("pi", "claude", "codex", "deepseek", "opencode"),
|
|
200
|
+
help="agent harness (agent only)",
|
|
201
|
+
)
|
|
202
|
+
ensure.add_argument("--producer", help="producer namespace (producer only)")
|
|
203
|
+
ensure.add_argument(
|
|
204
|
+
"--room", action="append", type=UUID, default=[], help="existing room UUID; repeat for viewer grants"
|
|
205
|
+
)
|
|
206
|
+
ensure.add_argument("--json", action="store_true", help="Return principal_id, room_id(s) and outcome as JSON")
|
|
207
|
+
revoke = actions.add_parser("revoke", help="Revoke a principal created by `principal ensure`.")
|
|
208
|
+
revoke.add_argument("--config", required=True, metavar="PATH", help="JSON configuration file")
|
|
209
|
+
revoke.add_argument("--name", required=True)
|
|
210
|
+
return parser
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def load_config(path: str) -> Config:
|
|
214
|
+
try:
|
|
215
|
+
with open(path, "rb") as handle:
|
|
216
|
+
raw = handle.read(MAX_CONFIG_BYTES + 1)
|
|
217
|
+
except OSError:
|
|
218
|
+
raise AdminError("CONFIG_UNREADABLE") from None
|
|
219
|
+
if len(raw) > MAX_CONFIG_BYTES:
|
|
220
|
+
raise AdminError("CONFIG_INVALID")
|
|
221
|
+
try:
|
|
222
|
+
document = json.loads(raw.decode("utf-8"))
|
|
223
|
+
return Config.model_validate(document)
|
|
224
|
+
except (ValueError, ValidationError):
|
|
225
|
+
# ValidationError text includes the submitted input; report the code only.
|
|
226
|
+
raise AdminError("CONFIG_INVALID") from None
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def read_dsn(config: Config, environ: Mapping[str, str]) -> str:
|
|
230
|
+
directory = environ.get("CREDENTIALS_DIRECTORY")
|
|
231
|
+
if not directory:
|
|
232
|
+
raise AdminError("CREDENTIALS_DIRECTORY_MISSING")
|
|
233
|
+
try:
|
|
234
|
+
with open(Path(directory) / config.dsn_credential, "rb") as handle:
|
|
235
|
+
raw = handle.read(MAX_CREDENTIAL_BYTES + 1)
|
|
236
|
+
value = raw.decode("utf-8")
|
|
237
|
+
except (OSError, ValueError):
|
|
238
|
+
raise AdminError("DSN_CREDENTIAL_UNREADABLE") from None
|
|
239
|
+
if len(raw) > MAX_CREDENTIAL_BYTES:
|
|
240
|
+
raise AdminError("DSN_CREDENTIAL_UNREADABLE")
|
|
241
|
+
value = value.removesuffix("\n")
|
|
242
|
+
if not value:
|
|
243
|
+
raise AdminError("DSN_CREDENTIAL_UNREADABLE")
|
|
244
|
+
return value
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _serve(config: Config, environ: Mapping[str, str], stderr: TextIO) -> int:
|
|
248
|
+
if not config.enabled:
|
|
249
|
+
# A deployed unit stays inert until inventory enables it: no DSN read, no listener.
|
|
250
|
+
_diagnose(stderr, environ, f"{PROGRAM}: DISABLED", 6)
|
|
251
|
+
return 0
|
|
252
|
+
dsn = read_dsn(config, environ)
|
|
253
|
+
# No database connection here: create_app connects per request, so liveness survives a database outage.
|
|
254
|
+
app = create_app(dsn, enabled=True, public_origin=config.public_origin, delivery_enabled=config.delivery_enabled)
|
|
255
|
+
# proxy_headers=False is deliberate. Origin and CSRF checks compare against the configured public_origin
|
|
256
|
+
# (RequestBoundary) and the login limit is global (browser.login, table agent_chat.login_guard), so no client
|
|
257
|
+
# IP or forwarded header is trusted.
|
|
258
|
+
try:
|
|
259
|
+
uvicorn.run(
|
|
260
|
+
app,
|
|
261
|
+
host=config.bind_host,
|
|
262
|
+
port=config.port,
|
|
263
|
+
access_log=False,
|
|
264
|
+
proxy_headers=False,
|
|
265
|
+
server_header=False,
|
|
266
|
+
log_config=LOG_CONFIG,
|
|
267
|
+
timeout_graceful_shutdown=GRACEFUL_SHUTDOWN_SECONDS,
|
|
268
|
+
)
|
|
269
|
+
except (OSError, SystemExit) as error:
|
|
270
|
+
if isinstance(error, SystemExit) and error.code in (None, 0):
|
|
271
|
+
return 0
|
|
272
|
+
raise AdminError("LISTENER_UNAVAILABLE", OPERATIONAL_EXIT) from None
|
|
273
|
+
return 0
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _migrate(
|
|
277
|
+
config: Config, environ: Mapping[str, str], stdout: TextIO, *, check: bool = False, reviewed: str | None = None
|
|
278
|
+
) -> int:
|
|
279
|
+
with connect(read_dsn(config, environ)) as db:
|
|
280
|
+
before = _applied_versions(db)
|
|
281
|
+
pending = migrate(db, check=check, reviewed=reviewed)
|
|
282
|
+
if check:
|
|
283
|
+
# The printed lines and the reviewed digest come from the same list, in the printed order. With
|
|
284
|
+
# nothing pending there is nothing to review, so no `reviewed=` line is printed.
|
|
285
|
+
print(f"pending={len(pending)}", file=stdout)
|
|
286
|
+
for line in review_lines(pending):
|
|
287
|
+
print(line, file=stdout)
|
|
288
|
+
if pending:
|
|
289
|
+
print(f"reviewed={review_digest(pending)}", file=stdout)
|
|
290
|
+
return 0
|
|
291
|
+
after = _applied_versions(db)
|
|
292
|
+
applied = [version for version in after if version not in before]
|
|
293
|
+
current = after[-1] if after else "none"
|
|
294
|
+
print(f"applied={','.join(map(str, applied)) or 'none'} current={current}", file=stdout)
|
|
295
|
+
return 0
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _applied_versions(db: psycopg.Connection[dict[str, Any]]) -> list[int]:
|
|
299
|
+
try:
|
|
300
|
+
rows = db.execute("SELECT version FROM agent_chat.schema_migrations ORDER BY version").fetchall()
|
|
301
|
+
except (psycopg.errors.UndefinedTable, psycopg.errors.InvalidSchemaName):
|
|
302
|
+
return []
|
|
303
|
+
return [row["version"] for row in rows]
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _prune(config: Config, environ: Mapping[str, str], limit: int, max_batches: int, stdout: TextIO) -> int:
|
|
307
|
+
if not 1 <= limit <= 1000 or max_batches < 1:
|
|
308
|
+
raise _usage()
|
|
309
|
+
totals = dict.fromkeys(
|
|
310
|
+
(
|
|
311
|
+
"events",
|
|
312
|
+
"redacted",
|
|
313
|
+
"deleted",
|
|
314
|
+
"ended_instances",
|
|
315
|
+
"memberships",
|
|
316
|
+
"expired_undelivered",
|
|
317
|
+
"reservations",
|
|
318
|
+
"delivery_batches",
|
|
319
|
+
"browser_sessions",
|
|
320
|
+
"room_state",
|
|
321
|
+
),
|
|
322
|
+
0,
|
|
323
|
+
)
|
|
324
|
+
batches = 0
|
|
325
|
+
with connect(read_dsn(config, environ)) as db:
|
|
326
|
+
while batches < max_batches:
|
|
327
|
+
removed = retention.prune(db, limit=limit)
|
|
328
|
+
batches += 1
|
|
329
|
+
for key, count in removed.items():
|
|
330
|
+
totals[key] += count
|
|
331
|
+
if not any(removed.values()):
|
|
332
|
+
break
|
|
333
|
+
# One line, the original keys first in their original order: a LogQL parser reads it by key.
|
|
334
|
+
print(f"batches={batches} " + " ".join(f"{key}={count}" for key, count in totals.items()), file=stdout)
|
|
335
|
+
return 0
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _usage() -> AdminError:
|
|
339
|
+
return AdminError("USAGE", USAGE_EXIT, "see --help")
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _principal_id(name: str) -> UUID:
|
|
343
|
+
if NAME_PATTERN.fullmatch(name) is None:
|
|
344
|
+
raise _usage()
|
|
345
|
+
return uuid5(PRINCIPAL_NAMESPACE, name)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _read_token(stdin: TextIO) -> str:
|
|
349
|
+
"""The raw token: 64 lowercase hex characters and at most one trailing newline, from stdin only."""
|
|
350
|
+
raw = stdin.read(67)
|
|
351
|
+
digest_source = raw.removesuffix("\n")
|
|
352
|
+
try:
|
|
353
|
+
token_digest(digest_source)
|
|
354
|
+
except ChatError:
|
|
355
|
+
raise AdminError("TOKEN_INVALID") from None
|
|
356
|
+
return digest_source
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _ensure_principal(
|
|
360
|
+
config: Config, environ: Mapping[str, str], args: argparse.Namespace, stdin: TextIO, stdout: TextIO
|
|
361
|
+
) -> int:
|
|
362
|
+
principal_id = _principal_id(args.name)
|
|
363
|
+
if args.kind == "agent":
|
|
364
|
+
if (
|
|
365
|
+
args.host is None
|
|
366
|
+
or args.harness is None
|
|
367
|
+
or args.producer is not None
|
|
368
|
+
or HOST_PATTERN.fullmatch(args.host) is None
|
|
369
|
+
):
|
|
370
|
+
raise _usage()
|
|
371
|
+
elif args.kind == "producer":
|
|
372
|
+
if (
|
|
373
|
+
args.host is None
|
|
374
|
+
or args.producer is None
|
|
375
|
+
or args.harness is not None
|
|
376
|
+
or HOST_PATTERN.fullmatch(args.host) is None
|
|
377
|
+
or HOST_PATTERN.fullmatch(args.producer) is None
|
|
378
|
+
):
|
|
379
|
+
raise _usage()
|
|
380
|
+
elif args.host is not None or args.harness is not None or args.producer is not None:
|
|
381
|
+
raise _usage()
|
|
382
|
+
room_ids = sorted(set(args.room))
|
|
383
|
+
if (args.kind == "viewer") != bool(room_ids):
|
|
384
|
+
raise _usage()
|
|
385
|
+
digest = token_digest(_read_token(stdin))
|
|
386
|
+
with connect(read_dsn(config, environ)) as db, db.transaction():
|
|
387
|
+
db.execute("SELECT pg_advisory_xact_lock(%s)", (PRINCIPAL_LOCK,))
|
|
388
|
+
row = db.execute(
|
|
389
|
+
"""SELECT kind, host, harness, producer, credential_hash, revoked
|
|
390
|
+
FROM agent_chat.principals WHERE id = %s FOR UPDATE""",
|
|
391
|
+
(principal_id,),
|
|
392
|
+
).fetchone()
|
|
393
|
+
if args.kind == "viewer" and db.execute(
|
|
394
|
+
"SELECT 1 FROM agent_chat.instances WHERE token_hash = %s", (digest,)
|
|
395
|
+
).fetchone() is not None:
|
|
396
|
+
raise AdminError("TOKEN_IN_USE", OPERATIONAL_EXIT)
|
|
397
|
+
try:
|
|
398
|
+
if row is None:
|
|
399
|
+
db.execute(
|
|
400
|
+
"""INSERT INTO agent_chat.principals(id, kind, credential_hash, host, harness, producer)
|
|
401
|
+
VALUES (%s, %s, %s, %s, %s, %s)""",
|
|
402
|
+
(principal_id, args.kind, digest, args.host, args.harness, args.producer),
|
|
403
|
+
)
|
|
404
|
+
outcome = "created"
|
|
405
|
+
elif (row["kind"], row["host"], row["harness"], row["producer"]) != (
|
|
406
|
+
args.kind,
|
|
407
|
+
args.host,
|
|
408
|
+
args.harness,
|
|
409
|
+
args.producer,
|
|
410
|
+
):
|
|
411
|
+
raise AdminError("PRINCIPAL_CONFLICT", OPERATIONAL_EXIT)
|
|
412
|
+
elif row["credential_hash"] != digest:
|
|
413
|
+
db.execute(
|
|
414
|
+
"UPDATE agent_chat.principals SET credential_hash = %s, revoked = false WHERE id = %s",
|
|
415
|
+
(digest, principal_id),
|
|
416
|
+
)
|
|
417
|
+
outcome = "rotated"
|
|
418
|
+
elif row["revoked"]:
|
|
419
|
+
db.execute("UPDATE agent_chat.principals SET revoked = false WHERE id = %s", (principal_id,))
|
|
420
|
+
outcome = "restored"
|
|
421
|
+
else:
|
|
422
|
+
outcome = "unchanged"
|
|
423
|
+
except psycopg.errors.UniqueViolation as error:
|
|
424
|
+
if error.diag.constraint_name != "principals_credential_hash_key":
|
|
425
|
+
raise
|
|
426
|
+
raise AdminError("TOKEN_IN_USE", OPERATIONAL_EXIT) from None
|
|
427
|
+
if args.kind == "viewer":
|
|
428
|
+
existing = db.execute(
|
|
429
|
+
"SELECT id FROM agent_chat.rooms WHERE id = ANY(%s::uuid[]) ORDER BY id FOR SHARE", (room_ids,)
|
|
430
|
+
).fetchall()
|
|
431
|
+
if [room["id"] for room in existing] != room_ids:
|
|
432
|
+
raise AdminError("ROOM_NOT_FOUND", OPERATIONAL_EXIT)
|
|
433
|
+
removed = db.execute(
|
|
434
|
+
"DELETE FROM agent_chat.principal_rooms WHERE principal_id = %s AND NOT (room_id = ANY(%s::uuid[]))",
|
|
435
|
+
(principal_id, room_ids),
|
|
436
|
+
).rowcount
|
|
437
|
+
added = 0
|
|
438
|
+
for room_id in room_ids:
|
|
439
|
+
added += db.execute(
|
|
440
|
+
"INSERT INTO agent_chat.principal_rooms VALUES (%s, %s) ON CONFLICT DO NOTHING",
|
|
441
|
+
(principal_id, room_id),
|
|
442
|
+
).rowcount
|
|
443
|
+
if outcome in ("rotated", "restored"):
|
|
444
|
+
db.execute("DELETE FROM agent_chat.browser_sessions WHERE principal_id = %s", (principal_id,))
|
|
445
|
+
elif outcome == "unchanged" and (removed or added):
|
|
446
|
+
outcome = "updated"
|
|
447
|
+
scope = {"room_ids": [str(room_id) for room_id in room_ids]}
|
|
448
|
+
else:
|
|
449
|
+
room = db.execute("SELECT id FROM agent_chat.rooms WHERE slug = %s", (HOMELAB_ROOM,)).fetchone()
|
|
450
|
+
if room is None:
|
|
451
|
+
raise ChatError("SCHEMA_MISMATCH")
|
|
452
|
+
db.execute(
|
|
453
|
+
"INSERT INTO agent_chat.principal_rooms VALUES (%s, %s) ON CONFLICT DO NOTHING",
|
|
454
|
+
(principal_id, room["id"]),
|
|
455
|
+
)
|
|
456
|
+
scope = {"room_id": str(room["id"])}
|
|
457
|
+
if args.json:
|
|
458
|
+
print(json.dumps({"principal_id": str(principal_id), **scope, "outcome": outcome}), file=stdout)
|
|
459
|
+
else:
|
|
460
|
+
print(f"{args.name} {principal_id} {outcome}", file=stdout)
|
|
461
|
+
return 0
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _revoke_principal(config: Config, environ: Mapping[str, str], name: str, stdout: TextIO) -> int:
|
|
465
|
+
principal_id = _principal_id(name)
|
|
466
|
+
with connect(read_dsn(config, environ)) as db, db.transaction():
|
|
467
|
+
db.execute("SELECT pg_advisory_xact_lock(%s)", (PRINCIPAL_LOCK,))
|
|
468
|
+
row = db.execute(
|
|
469
|
+
"SELECT kind, revoked FROM agent_chat.principals WHERE id = %s FOR UPDATE", (principal_id,)
|
|
470
|
+
).fetchone()
|
|
471
|
+
if row is None:
|
|
472
|
+
raise AdminError("PRINCIPAL_NOT_FOUND", OPERATIONAL_EXIT)
|
|
473
|
+
# History stays. Authentication already requires NOT revoked, so every token of the principal fails.
|
|
474
|
+
db.execute("UPDATE agent_chat.principals SET revoked = true WHERE id = %s", (principal_id,))
|
|
475
|
+
if row["kind"] == "viewer":
|
|
476
|
+
db.execute("DELETE FROM agent_chat.browser_sessions WHERE principal_id = %s", (principal_id,))
|
|
477
|
+
print(f"{name} {principal_id} {'already_revoked' if row['revoked'] else 'revoked'}", file=stdout)
|
|
478
|
+
return 0
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def main(
|
|
482
|
+
argv: Sequence[str] | None = None,
|
|
483
|
+
*,
|
|
484
|
+
stdin: TextIO | None = None,
|
|
485
|
+
stdout: TextIO | None = None,
|
|
486
|
+
stderr: TextIO | None = None,
|
|
487
|
+
environ: Mapping[str, str] | None = None,
|
|
488
|
+
) -> int:
|
|
489
|
+
stdin = stdin if stdin is not None else sys.stdin
|
|
490
|
+
stdout = stdout if stdout is not None else sys.stdout
|
|
491
|
+
stderr = stderr if stderr is not None else sys.stderr
|
|
492
|
+
environ = environ if environ is not None else os.environ
|
|
493
|
+
try:
|
|
494
|
+
try:
|
|
495
|
+
args = _parser().parse_args(argv)
|
|
496
|
+
except SystemExit as stop: # --help
|
|
497
|
+
return stop.code if isinstance(stop.code, int) else 0
|
|
498
|
+
config = load_config(args.config)
|
|
499
|
+
if args.command == "serve":
|
|
500
|
+
return _serve(config, environ, stderr)
|
|
501
|
+
if args.command == "migrate":
|
|
502
|
+
return _migrate(config, environ, stdout, check=args.check, reviewed=args.reviewed)
|
|
503
|
+
if args.command == "prune":
|
|
504
|
+
return _prune(config, environ, args.limit, args.max_batches, stdout)
|
|
505
|
+
if args.action == "ensure":
|
|
506
|
+
return _ensure_principal(config, environ, args, stdin, stdout)
|
|
507
|
+
return _revoke_principal(config, environ, args.name, stdout)
|
|
508
|
+
except AdminError as error:
|
|
509
|
+
_diagnose(stderr, environ, f"{PROGRAM}: {error.code}" + (f" ({error.hint})" if error.hint else ""))
|
|
510
|
+
return error.status
|
|
511
|
+
except ChatError as error:
|
|
512
|
+
_diagnose(stderr, environ, f"{PROGRAM}: {re.sub(r'[^A-Z_]', '', error.code) or 'INTERNAL_ERROR'}")
|
|
513
|
+
return OPERATIONAL_EXIT
|
|
514
|
+
except (psycopg.errors.UndefinedTable, psycopg.errors.InvalidSchemaName):
|
|
515
|
+
_diagnose(stderr, environ, f"{PROGRAM}: SCHEMA_MISSING (run migrate)")
|
|
516
|
+
return OPERATIONAL_EXIT
|
|
517
|
+
except psycopg.Error:
|
|
518
|
+
# Connection errors can carry host and user details; print nothing from the exception.
|
|
519
|
+
_diagnose(stderr, environ, f"{PROGRAM}: DATABASE_UNAVAILABLE")
|
|
520
|
+
return OPERATIONAL_EXIT
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
if __name__ == "__main__":
|
|
524
|
+
sys.exit(main())
|