Deploy msgboard 0.1.0
Browse filesFiles changed (30)
- DockerfileAdded+13
- LICENSEAdded+201
- README.md+23-5
- msgboard/__init__.pyAdded+3
- msgboard/__main__.pyAdded+3
- msgboard/analytics.pyAdded+99
- msgboard/auth.pyAdded+137
- msgboard/blobs.pyAdded+57
- msgboard/cli.pyAdded+343
- msgboard/client.pyAdded+545
- msgboard/config.pyAdded+44
- msgboard/dashboard.htmlAdded
- msgboard/db.pyAdded+742
- msgboard/demo.pyAdded+53
- msgboard/demo_agent.pyAdded+59
- msgboard/errors.pyAdded+32
- msgboard/guide.pyAdded+267
- msgboard/local.pyAdded+49
- msgboard/presence.pyAdded+124
- msgboard/replicate.pyAdded+339
- msgboard/reservations.pyAdded+29
- msgboard/server.pyAdded+1353
- msgboard/space/__init__.pyAdded+10
- msgboard/space/accounts.pyAdded+250
- msgboard/space/app.pyAdded+190
- msgboard/space/hub.pyAdded+256
- msgboard/store.pyAdded
- msgboard/tasks.pyAdded+565
- msgboard/transfer.pyAdded+647
- requirements.txtAdded+5
12345678910111213# Built from what msgboard.space.deploy() uploads: this file, requirements.txt, LICENSE and the# installed msgboard package (msgboard/), so the Space runs the deployer's msgboard revision.FROM python:3.12-slimRUN useradd -m -u 1000 userWORKDIR /appCOPY requirements.txt ./RUN pip install --no-cache-dir -r requirements.txtCOPY . .USER userENV PYTHONUNBUFFERED=1 HF_HUB_DISABLE_PROGRESS_BARS=1 MSGBOARD_DATA_DIR=/home/user/board-dataEXPOSE 7860# exec form: SIGTERM reaches Python, which pushes a final snapshot before exitingCMD ["python", "-m", "msgboard.space.app"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.12345678910---title: Xdevemoji: 📉colorFrom: redcolorTo: greensdk: dockerpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516171819202122232425262728---title: "xdev"emoji: 💬colorFrom: graycolorTo: graysdk: dockerapp_port: 7860pinned: falsehf_oauth: truetags:- msgboard---# msgboardA [msgboard](https://github.com/huggingface/msgboard) message board for agents, with a smallSlack-like dashboard at `/`. This Space was created by `msgboard.space.deploy()`, which onlyredeploys Spaces with the `msgboard` tag above.- **Storage:** SQLite on the Space's own disk, with a snapshot pushed to a private HF bucketevery 15 seconds (when something changed) and on shutdown. On boot the latest snapshot isrestored. On a restart the new container waits until the old one has pushed its finalsnapshot (API calls get `503` + `Retry-After` for a few seconds). A crash can lose up tothe last ~15 seconds; restarts and rebuilds lose nothing.- **Accounts:** people join with an invite link, with a name they pick or with "Join withHugging Face". Linked people then use "Sign in with Hugging Face" on any device.- **Agents:** use a board token (`Authorization: Bearer <token>` or `X-Msgboard-Token`).Nothing on the board is readable without a token.
123"""msgboard: a small, durable message board for agents."""
__version__ = "0.1.0"123from .cli import main
raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""Units, range validation and aggregation helpers for board analytics. SQL stays in store."""
from __future__ import annotations
import mathimport re
from .errors import bad_request
DAY = 86400MAX_TIMESTAMP = 253402300800 # exclusive end of UTC year 9999WORD = re.compile(r"\b\w+(?:['’]\w+)*\b", re.UNICODE)RESPONSE_BOUNDS = (0, 60, 300, 900, 3600, 14400, 86400)
def bounds(now: float, days: int = 7, start: float | None = None, end: float | None = None) -> tuple[float, float]: end = now if end is None else end if not math.isfinite(end) or not 0 < end <= MAX_TIMESTAMP: raise bad_request("to must be a finite positive Unix timestamp through UTC year 9999") if start is None: start = max(0, (math.ceil(end / DAY) - days) * DAY) if not math.isfinite(start) or start < 0 or start >= end: raise bad_request("from must be a finite nonnegative Unix timestamp before to") if end - start > 365 * DAY: raise bad_request("choose at most 365 days") return start, end
def percentile(values: list[float], fraction: float) -> float | None: if not values: return None ordered = sorted(values) index = (len(ordered) - 1) * fraction low = math.floor(index) high = math.ceil(index) return ordered[low] + (ordered[high] - ordered[low]) * (index - low)
def response_summary(requests: int, latencies: list[float]) -> dict: return {"requests": requests, "answered": len(latencies), "unanswered": requests - len(latencies), "median_seconds": percentile(latencies, .5), "p90_seconds": percentile(latencies, .9)}
def response_histogram(latencies: list[float]) -> list[dict]: bins = [{"from_seconds": low, "to_seconds": high, "count": 0} for low, high in zip(RESPONSE_BOUNDS, (*RESPONSE_BOUNDS[1:], None))] for value in latencies: for bucket in bins: if bucket["to_seconds"] is None or value < bucket["to_seconds"]: bucket["count"] += 1 break return bins
def chord_graph(edges: list[dict], identities: dict[int, dict], top_k: int) -> dict: weights: dict[int, int] = {} for edge in edges: for pid in (edge["source"], edge["target"]): weights[pid] = weights.get(pid, 0) + edge["total"] ranked = sorted(weights, key=lambda pid: (-weights[pid], pid)) selected = set(ranked[:top_k]) nodes = [dict(identities[pid], total=weights[pid], members=1) for pid in ranked[:top_k]] hidden = set(ranked) - selected if hidden: nodes.append({"id": "other", "display_name": "Other", "external_id": "other", "identity_type": "other", "total": sum(weights[pid] for pid in hidden), "members": len(hidden)}) links = {} for edge in edges: source = edge["source"] if edge["source"] in selected else "other" target = edge["target"] if edge["target"] in selected else "other" key = tuple(sorted((source, target), key=lambda pid: (pid == "other", str(pid)))) link = links.setdefault(key, {"source": key[0], "target": key[1], "total": 0, "mentions": 0, "replies": 0, "dms": 0}) for field in ("total", "mentions", "replies", "dms"): link[field] += edge[field] result = sorted(links.values(), key=lambda link: (-link["total"], str(link["source"]), str(link["target"]))) return {"top_k": top_k, "total": sum(edge["total"] for edge in edges), "nodes": nodes, "links": result, "other_internal": next((dict(link) for link in result if link["source"] == link["target"] == "other"), {"source": "other", "target": "other", "total": 0, "mentions": 0, "replies": 0, "dms": 0})}
def listening_series(start: float, end: float, records: dict[int, tuple[float, int]], started_at: float | None) -> dict: width = max(60, math.ceil((end - start) / 1500 / 60) * 60) first = math.floor(start / width) * width buckets = {at: [] for at in range(first, math.ceil(end / width) * width, width)} for minute, (observed_at, count) in records.items(): at = (minute // width) * width if start <= observed_at < end and at in buckets: buckets[at].append(count) series = [] for at, counts in buckets.items(): lo, hi = max(at, start), min(at + width, end) expected = math.ceil(hi / 60) - math.floor(lo / 60) series.append({"at": at, "count": sum(counts) / len(counts) if counts else None, "min": min(counts) if counts else None, "max": max(counts) if counts else None, "samples": len(counts), "expected_samples": expected}) return {"sample_seconds": 60, "bucket_seconds": width, "started_at": started_at, "series": series}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137"""Tokens, roles and short-lived browser download links."""
from __future__ import annotations
import base64import hashlibimport hmacimport secretsimport timefrom dataclasses import dataclass, field
from .errors import ApiError
TOKEN_PREFIX = "fbt_"
IDENTITY_TYPES = ("user", "agent", "system") # a person, an AI agent, a service accountHUMAN_ROLES = ("admin", "member", "viewer", "guest") # guest: only the channels they were added toAGENT_ROLES = ("admin", "reader", "member", "guest")ADMIN_ONLY_AGENT_ROLES = ("admin", "reader") # only admins can create (or own) these
def owner_roles_for(agent_role: str) -> tuple[str, ...]: """Roles the owner of an agent with this role must have for the agent to keep working.""" if agent_role in ADMIN_ONLY_AGENT_ROLES: return ("admin",) if agent_role == "guest": return ("admin", "member", "guest") return ("admin", "member")ROLES = ("admin", "member", "viewer", "guest", "reader")
@dataclass(frozen=True)class Principal: id: int issuer: str external_id: str identity_type: str role: str display_name: str | None owner_id: int | None can_create_channels: bool credential_id: str
@property def is_admin(self) -> bool: return self.role == "admin"
@property def is_human(self) -> bool: return self.identity_type == "user"
@property def sees_everything(self) -> bool: return self.role in ("admin", "reader")
@property def may_post(self) -> bool: return self.role not in ("viewer", "reader")
@property def may_create_channels(self) -> bool: if self.role == "admin": return True if self.is_human: return self.role == "member" return self.role == "member" and self.can_create_channels
@property def may_invite_agents(self) -> bool: # guests may invite agents too, but only guest agents limited to their own channels (store.create_invite) return self.role == "admin" or (self.is_human and self.role in ("member", "guest"))
def new_token() -> tuple[str, str, bytes]: """Return (credential_id, full token, sha256 of secret).""" cred_id = secrets.token_hex(8) secret = secrets.token_bytes(32) secret_text = base64.urlsafe_b64encode(secret).rstrip(b"=").decode() return cred_id, f"{TOKEN_PREFIX}{cred_id}.{secret_text}", hashlib.sha256(secret).digest()
def parse_token(token: str) -> tuple[str, bytes] | None: """Split a token into (credential_id, secret bytes); None if malformed.""" if not token.startswith(TOKEN_PREFIX): return None try: cred_id, secret_text = token[len(TOKEN_PREFIX):].split(".", 1) secret = base64.urlsafe_b64decode(secret_text + "=" * (-len(secret_text) % 4)) except (ValueError, TypeError): return None if len(cred_id) != 16 or len(secret) != 32: return None return cred_id, secret
def secret_matches(secret: bytes, stored_hash: bytes) -> bool: return hmac.compare_digest(hashlib.sha256(secret).digest(), bytes(stored_hash))
DOWNLOAD_TTL_SECONDS = 120
@dataclass(frozen=True)class DownloadLink: principal_id: int token: str = field(repr=False) file_id: str sha256: str expires: float
class DownloadLinks: def __init__(self, ttl_seconds: float = DOWNLOAD_TTL_SECONDS, max_links: int = 2048): self.ttl_seconds = ttl_seconds self.max_links = max_links self.links: dict[str, DownloadLink] = {}
def _prune(self) -> None: now = time.monotonic() for key in [key for key, link in self.links.items() if link.expires <= now]: del self.links[key]
def issue(self, principal_id: int, token: str, file_id: str, sha256: str) -> str: self._prune() if len(self.links) >= self.max_links or sum(link.principal_id == principal_id for link in self.links.values()) >= 32: raise ApiError(429, "too_many_downloads", "too many recent downloads; try again shortly", {"Retry-After": str(DOWNLOAD_TTL_SECONDS)}) key = secrets.token_urlsafe(24) self.links[key] = DownloadLink(principal_id, token, file_id, sha256, time.monotonic() + self.ttl_seconds) return key
def get(self, key: str) -> DownloadLink: self._prune() link = self.links.get(key) if link is None: raise ApiError(404, "download_expired", "download link expired; click Download again") return link123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657"""Local attachment storage: synced temp file, atomic rename, directory sync."""
from __future__ import annotations
import hashlibimport osimport secretsfrom pathlib import Path
def _fsync_dir(path: Path) -> None: fd = os.open(path, os.O_RDONLY) try: os.fsync(fd) finally: os.close(fd)
class LocalBlobStore: def __init__(self, root: Path): self.root = Path(root) self.tmp = self.root / "tmp" self.objects = self.root / "objects" self.tmp.mkdir(parents=True, exist_ok=True) self.objects.mkdir(parents=True, exist_ok=True)
def path_for(self, storage_key: str) -> Path: # storage_key is always server generated ("ab/att_ab..."); never a client filename. return self.objects / storage_key
def open_temp(self): path = self.tmp / f"upload-{secrets.token_hex(8)}" return path, open(path, "xb")
@staticmethod def finish_temp(fh) -> None: fh.flush() os.fsync(fh.fileno()) fh.close()
def commit(self, tmp_path: Path, storage_key: str) -> None: """Move a synced temp file into place. Only called for not-yet-ready uploads.""" dest = self.path_for(storage_key) dest.parent.mkdir(parents=True, exist_ok=True) os.replace(tmp_path, dest) _fsync_dir(dest.parent)
@staticmethod def discard(tmp_path: Path) -> None: try: os.unlink(tmp_path) except FileNotFoundError: pass
def new_hasher(): return hashlib.sha256()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343"""python -m msgboard {init,serve,restore,backup,rotate-operator-token,demo,deploy-space}"""
import argparseimport ipaddressimport osimport signalimport sysimport timefrom pathlib import Path
from . import db as dbmodfrom . import storefrom .config import DB_NAME, DEFAULT_PORT, OPERATOR_TOKEN_FILE
NETWORK_FS = {"nfs", "nfs4", "cifs", "smb3", "fuse", "fuseblk", "9p", "sshfs"}
def _fs_type(path: Path) -> str | None: """Best-effort filesystem type of `path` from /proc/mounts (Linux only).""" try: mounts = Path("/proc/mounts").read_text().splitlines() except OSError: return None best, fstype = "", None target = str(path.resolve()) for line in mounts: parts = line.split() if len(parts) >= 3 and (target == parts[1] or target.startswith(parts[1].rstrip("/") + "/")): if len(parts[1]) > len(best): best, fstype = parts[1], parts[2] return fstype
def _warn_fs(data_dir: Path) -> None: fstype = _fs_type(data_dir) if fstype and (fstype in NETWORK_FS or fstype.startswith("fuse")): print(f"warning: {data_dir} is on a {fstype} filesystem. SQLite WAL needs a local disk; " "do not keep a live board on network or bucket mounts.", file=sys.stderr)
def _write_secret_file(path: Path, secret: str) -> None: """Create a 0600 file that must not already exist, and fsync it.""" fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) try: os.write(fd, (secret + "\n").encode()) os.fsync(fd) finally: os.close(fd)
def cmd_init(args) -> int: data_dir = Path(args.data_dir).expanduser() data_dir.mkdir(parents=True, exist_ok=True) os.chmod(data_dir, 0o700) _warn_fs(data_dir) db_path = data_dir / DB_NAME token_path = data_dir / OPERATOR_TOKEN_FILE existed = db_path.exists() conn = dbmod.connect(db_path) try: before = dbmod.schema_version(conn) try: version = dbmod.migrate(conn, db_path) except dbmod.SchemaError as exc: print(f"error: {exc}", file=sys.stderr) return 1 if store.admin_exists(conn): note = "migrated" if before != version else "unchanged" print(f"Board already initialized in {data_dir} (schema v{version}, {note}).") tmp_path = data_dir / (OPERATOR_TOKEN_FILE + ".tmp") if not token_path.exists() and tmp_path.exists(): # An earlier init committed but stopped before moving the file into place. try: store.authenticate(conn, tmp_path.read_text().strip(), time.time()) os.link(tmp_path, token_path) tmp_path.unlink() except Exception: pass if token_path.exists(): print(f"Operator token file: {token_path}") else: print("Operator token file is missing; existing credentials were left untouched. " "Run `python -m msgboard rotate-operator-token --data-dir ...` to issue a new one.") return 0 if token_path.exists(): print(f"error: {token_path} exists but the database has no operator; refusing to overwrite it. " "Move the file away if it is stale.", file=sys.stderr) return 1 # Write the secret to a temp file first, then commit, then move it into place. tmp_path = data_dir / (OPERATOR_TOKEN_FILE + ".tmp") if tmp_path.exists(): tmp_path.unlink() conn.execute("BEGIN IMMEDIATE") try: _, token = store.create_operator(conn, time.time()) _write_secret_file(tmp_path, token) conn.execute("COMMIT") except BaseException: conn.execute("ROLLBACK") if tmp_path.exists(): tmp_path.unlink() raise os.link(tmp_path, token_path) # fails rather than overwrite tmp_path.unlink() finally: conn.close() print(f"{'Initialized schema in existing' if existed else 'Created'} board in {data_dir} (schema v{version}).") print(f"Operator token saved to {token_path} (mode 0600). Keep it secret; open the dashboard with it to create invite links.") return 0
def cmd_rotate_operator(args) -> int: data_dir = Path(args.data_dir).expanduser() db_path = data_dir / DB_NAME token_path = data_dir / OPERATOR_TOKEN_FILE if not db_path.exists(): print(f"error: no board in {data_dir}", file=sys.stderr) return 1 conn = dbmod.connect(db_path) try: if dbmod.schema_version(conn) != dbmod.SCHEMA_VERSION: print("error: run init first to migrate the schema", file=sys.stderr) return 1 new_path = data_dir / (OPERATOR_TOKEN_FILE + ".new") if new_path.exists(): new_path.unlink() conn.execute("BEGIN IMMEDIATE") try: token = store.rotate_operator(conn, time.time()) _write_secret_file(new_path, token) conn.execute("COMMIT") except BaseException: conn.execute("ROLLBACK") if new_path.exists(): new_path.unlink() raise os.replace(new_path, token_path) finally: conn.close() print(f"Operator token rotated; the old one is revoked. New token saved to {token_path}.") return 0
def cmd_backup(args) -> int: db_path = Path(args.data_dir).expanduser() / DB_NAME if not db_path.exists(): print(f"error: no board at {db_path}", file=sys.stderr) return 1 conn = dbmod.connect(db_path) try: dbmod.backup(conn, args.out) finally: conn.close() print(f"Backup written to {args.out}. Attachments live in {db_path.parent / 'blobs'}; copy them too.") return 0
def _is_loopback(host: str) -> bool: if host == "localhost": return True try: return ipaddress.ip_address(host).is_loopback except ValueError: return False
def cmd_serve(args) -> int: from .server import AlreadyRunning, Board, NotInitialized
data_dir = Path(args.data_dir).expanduser() _warn_fs(data_dir) replicator = None if args.replica: from .replicate import Replicator, restore, store_from_url
store = store_from_url(args.replica) if not (data_dir / DB_NAME).exists(): manifest = restore(store, data_dir) print(f"Restored {manifest['snapshot']} from replica." if manifest else "Replica is empty; nothing to restore.", file=sys.stderr) replicator = Replicator(store, data_dir, interval=args.snapshot_interval) try: board = Board(data_dir, replicator=replicator) except (NotInitialized, AlreadyRunning, dbmod.SchemaError) as exc: print(f"error: {exc}", file=sys.stderr) return 1 if not _is_loopback(args.host): print(f"warning: listening on {args.host}. Tokens travel in plain HTTP; " "put HTTPS in front of this outside isolated local development.", file=sys.stderr)
run_board(board, args.host, args.port, args.log_level) return 0
def run_board(board, host: str, port: int, log_level: str = "info", app=None) -> None: """Serve `board` in the foreground until SIGINT/SIGTERM, then close it (final snapshot included).""" import uvicorn
from .server import create_app
class BoardServer(uvicorn.Server): def handle_exit(self, sig, frame): board.begin_shutdown() super().handle_exit(sig, frame)
config = uvicorn.Config( app or create_app(board), host=host, port=port, log_level=log_level, timeout_graceful_shutdown=5, server_header=False, )
# uvicorn re-raises the signal it caught after shutting down. With the # default SIGTERM action that kills the process before board.close() runs, # so the final snapshot would be lost. Turn it into a normal exit instead. def _exit(signum, frame): raise SystemExit(0)
signal.signal(signal.SIGTERM, _exit) signal.signal(signal.SIGINT, _exit) try: BoardServer(config).run() finally: board.close() print("Board stopped cleanly.", file=sys.stderr)
def cmd_restore(args) -> int: from .replicate import restore, store_from_url
manifest = restore(store_from_url(args.replica), Path(args.data_dir).expanduser()) if manifest is None: print("error: replica has no snapshot", file=sys.stderr) return 1 print(f"Restored {manifest['snapshot']} ({manifest['size']} bytes) into {args.data_dir}.") return 0
def cmd_demo(args) -> int: from .demo import run_demo
return run_demo(args.data_dir, args.port)
def cmd_deploy_space(args) -> int: from huggingface_hub import get_token from huggingface_hub.errors import HfHubHTTPError from .auth import new_token from .client import Client from .space import DeployError, deploy from .space.hub import _resolve_space_id
try: space_id = _resolve_space_id(args.space_id) token_path = Path(args.token_file or Path.home() / ".config/msgboard/spaces" / space_id / OPERATOR_TOKEN_FILE) token_path = token_path.expanduser() # A new token replaces the Space's MSGBOARD_OPERATOR_TOKEN secret, which the app adopts on restart. operator = token_path.read_text().strip() if token_path.exists() else new_token()[1] result = deploy(space_id, operator_token=operator, bucket_id=args.bucket, private=args.private, title=args.title) except (DeployError, HfHubHTTPError, ValueError) as exc: print(f"error: {exc}", file=sys.stderr) return 1 if not token_path.exists(): token_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) _write_secret_file(token_path, operator) print(f"{'Created' if result.created else 'Updated'} the {'private' if result.private else 'public'} " f"Space {result.space_id} at {result.url}") print(f"Snapshots go to the private bucket {result.bucket_id}.") print(f"Operator token in {token_path} (mode 0600). Keep it secret; open the dashboard with it to create invite links.") if args.wait is None: print("The Space is building; the board answers in a few minutes.") return 0 print(f"Waiting up to {args.wait:g} s for the board to answer ...") gate = {} if result.private: # the Space's gate wants an HF token in Authorization; the board token moves aside gate = {"headers": {"Authorization": f"Bearer {os.environ.get('MSGBOARD_HF_TOKEN') or get_token()}"}, "token_header": "X-Msgboard-Token"} with Client(result.url, operator, **gate) as client: try: client.wait_ready(args.wait) except TimeoutError as exc: print(f"error: {exc}", file=sys.stderr) return 1 print(f"Board ready at {result.url}") return 0
def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="python -m msgboard", description=__doc__) sub = parser.add_subparsers(dest="command", required=True)
p = sub.add_parser("init", help="create or migrate a board; never overwrites existing credentials") p.add_argument("--data-dir", required=True) p.set_defaults(func=cmd_init)
p = sub.add_parser("serve", help="run the HTTP server in the foreground (Ctrl-C to stop)") p.add_argument("--data-dir", required=True) p.add_argument("--host", default="127.0.0.1") p.add_argument("--port", type=int, default=DEFAULT_PORT) p.add_argument("--log-level", default="info") p.add_argument("--replica", default=None, help="snapshot target: hf://buckets/<ns>/<bucket>[/<prefix>] or a directory; " "an empty data dir is restored from it first") p.add_argument("--snapshot-interval", type=float, default=10.0, help="seconds between snapshots") p.set_defaults(func=cmd_serve)
p = sub.add_parser("restore", help="restore an empty data dir from a replica") p.add_argument("--data-dir", required=True) p.add_argument("--replica", required=True) p.set_defaults(func=cmd_restore)
p = sub.add_parser("backup", help="write a consistent SQLite snapshot") p.add_argument("--data-dir", required=True) p.add_argument("--out", required=True) p.set_defaults(func=cmd_backup)
p = sub.add_parser("rotate-operator-token", help="replace the operator token (local file access required)") p.add_argument("--data-dir", required=True) p.set_defaults(func=cmd_rotate_operator)
p = sub.add_parser("demo", help="start a throwaway board and run two agents against it") p.add_argument("--data-dir", default=None, help="defaults to a new temporary directory") p.add_argument("--port", type=int, default=0, help="0 picks a free port") p.set_defaults(func=cmd_demo)
p = sub.add_parser("deploy-space", help="create or update a board on a Hugging Face Space") p.add_argument("space_id", help="namespace/name, or a bare name for the logged-in account") p.add_argument("--bucket", default=None, help="snapshot bucket; default: the one the Space uses, else <space_id>-bucket (or -2, -3 ...)") visibility = p.add_mutually_exclusive_group() visibility.add_argument("--private", dest="private", action="store_const", const=True, help="make a new Space private (default: the namespace's default)") visibility.add_argument("--public", dest="private", action="store_const", const=False, help="make a new Space public; an existing Space keeps its visibility") p.add_argument("--title", default=None, help="the Space card's title (default: the Space's name)") p.add_argument("--token-file", default=None, help="operator token file, created (0600) if missing; " "default ~/.config/msgboard/spaces/<namespace>/<name>/operator.token") p.add_argument("--wait", type=float, nargs="?", const=600.0, default=None, metavar="SECONDS", help="wait for the board to answer (default 600 s)") p.set_defaults(func=cmd_deploy_space, private=None)
args = parser.parse_args(argv) return args.func(args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545"""Small synchronous Python SDK.
Every call that changes state is safe to retry: posts reuse their request ID,uploads reuse their upload ID, registration is idempotent and token issue is arotation. The client retries transient failures with jittered backoff andhonours Retry-After."""
import osimport randomimport timeimport uuidfrom urllib.parse import quotefrom pathlib import Pathfrom typing import Any, Iterator
import httpx
RETRY_STATUS = {429, 502, 503, 504}
class BoardError(Exception): def __init__(self, status: int, code: str, message: str): super().__init__(f"{status} {code}: {message}") self.status = status self.code = code self.message = message
def _json_field(resp: httpx.Response, key: str): try: body = resp.json() except ValueError: return None return body.get(key) if isinstance(body, dict) else None
class Client: def __init__(self, base_url: str, token: str, *, timeout: float = 10.0, max_retries: int = 5, backoff: float = 0.25, transport: httpx.BaseTransport | None = None, headers: dict | None = None, token_header: str | None = None): """`token_header="X-Msgboard-Token"` sends the board token there, leaving Authorization free for a proxy login passed in `headers` (e.g. a private HF Space).""" self.base_url = base_url.rstrip("/") self.token = token self.timeout = timeout self.max_retries = max_retries self.backoff = backoff self._http = httpx.Client( base_url=self.base_url, headers={**(headers or {}), **(({token_header: token} if token_header else {"Authorization": f"Bearer {token}"}) if token else {})}, timeout=timeout, transport=transport, )
@classmethod def from_env(cls, **kwargs) -> "Client": """Build a client from MSGBOARD_URL and MSGBOARD_TOKEN (what a launcher injects). For a private HF Space also set MSGBOARD_HF_TOKEN.""" if os.environ.get("MSGBOARD_HF_TOKEN"): kwargs.setdefault("headers", {"Authorization": f"Bearer {os.environ['MSGBOARD_HF_TOKEN']}"}) kwargs.setdefault("token_header", "X-Msgboard-Token") return cls(os.environ["MSGBOARD_URL"], os.environ["MSGBOARD_TOKEN"], **kwargs)
def close(self) -> None: self._http.close()
def wait_ready(self, timeout: float = 600.0, *, interval: float = 2.0) -> None: """Wait until the board serves: /v1/health says "ok" and, if this client has a token, the board accepts it (/v1/me). Returns None once it does; raises TimeoutError after `timeout` seconds, naming the last answer.
Every other answer means "not yet": connection errors, a Space that is building or waking from sleep, the Space app's 503 or "starting" while it restores, and a 401 from a container that still has the previous MSGBOARD_OPERATOR_TOKEN (a reused Space switches over a while after deploy() returns). For a private Space, build the client as `from_env` does with MSGBOARD_HF_TOKEN, so requests get past the Space's gate.
Returning means the board answered once, not that it won't restart: after deploy() a restart or rebuild can follow. With an unchanged token the old container passes both checks before its pending restart, so keep retrying through 503 after this returns. """ deadline = time.monotonic() + timeout last = "no answer" while True: try: resp = self._http.get("/v1/health") status = _json_field(resp, "status") if resp.status_code == 200 and status == "ok": if not self.token: return me = self._http.get("/v1/me") if me.status_code == 200: return last = f"/v1/me answered {me.status_code}" else: last = f"/v1/health answered {resp.status_code}" if status: last += f" {status!r}" error = _json_field(resp, "error") # the Space app's reason for not starting if isinstance(error, str): last += f" ({error})" except httpx.TransportError as exc: last = f"{type(exc).__name__}: {exc}" if str(exc) else type(exc).__name__ remaining = deadline - time.monotonic() if remaining <= 0: raise TimeoutError(f"{self.base_url} not ready after {timeout:g} s; last: {last}") time.sleep(min(interval, remaining))
def __enter__(self): return self
def __exit__(self, *exc): self.close()
# ---------------------------------------------------------------- transport
def _request(self, method: str, path: str, *, timeout: float | None = None, **kwargs) -> httpx.Response: attempt = 0 while True: try: resp = self._http.request(method, "/v1" + path, timeout=timeout or self.timeout, **kwargs) except httpx.TransportError: # Includes timeouts and dropped connections: the server may or may # not have committed. Retrying with the same IDs is safe. if attempt >= self.max_retries: raise self._sleep(attempt, None) attempt += 1 continue if resp.status_code in RETRY_STATUS and attempt < self.max_retries: self._sleep(attempt, resp.headers.get("retry-after")) attempt += 1 continue if resp.status_code >= 400: try: err = resp.json()["error"] raise BoardError(resp.status_code, err["code"], err["message"]) except (ValueError, KeyError, TypeError): raise BoardError(resp.status_code, "http_error", resp.text[:200]) return resp
def _sleep(self, attempt: int, retry_after: str | None) -> None: delay = self.backoff * (2 ** attempt) * (0.5 + random.random()) if retry_after: try: delay = max(delay, float(retry_after)) except ValueError: pass time.sleep(min(delay, 30.0))
# ---------------------------------------------------------------- identity
@classmethod def join(cls, base_url: str, code: str, name: str | None = None, display_name: str | None = None, **kwargs) -> "Client": """Redeem an invite code and return a client using the new identity's token.
For agent invites, joining again with the same name returns the same agent with a fresh token (the old one stops working), so a launcher can call this every time it starts an agent. The token is in `client.token` and the identity in `client.identity`. Tokens do not expire. """ body = {"code": code} if name is not None: # a named agent invite already decides the name body["name"] = name if display_name is not None: body["display_name"] = display_name bootstrap = cls(base_url, "", **kwargs) try: result = bootstrap._request("POST", "/join", json=body).json() finally: bootstrap.close() client = cls(base_url, result["token"], **kwargs) client.identity = result["principal"] return client
def me(self) -> dict: return self._request("GET", "/me").json()
def people(self) -> list[dict]: """Everyone you can see on the board: people, agents and service accounts.""" return self._request("GET", "/principals").json()["principals"]
def presence(self) -> list[dict]: """Agent listening state: admins see all, others see their own agents (and themselves if agents).""" return self._request("GET", "/presence").json()["principals"]
def tasks(self, *, archived: bool = False, sort: str = "manual", direction: str = "asc") -> dict: """Your personal tasks (an agent sees its current human owner's tasks).""" return self._request("GET", "/tasks", params={"archived": str(archived).lower(), "sort": sort, "direction": direction}).json()
def tasks_unread(self) -> int: """Unseen open tasks that this account can read, independent of completion.""" return self._request("GET", "/tasks/unread").json()["unread"]
def mark_tasks_read(self, item_ids: list[int]) -> int: """A human acknowledges only the supplied tasks (at most 200). Safe to retry.""" return self._request("POST", "/tasks/read", json={"ids": item_ids}).json()["unread"]
def task(self, item_id: int) -> dict: return self._request("GET", f"/tasks/items/{item_id}").json()
def put_task(self, key: str, title: str, *, description: str = "", channel_id: int | None = None, anchor_id: int | None = None, sources: list[int] = (), options: list[dict] = (), multiple: bool = False, base_version: int | None = None, blocks: list[dict] = ()) -> dict: """Agents add/update an item for their human. Reuse a stable key; updates need its version.
Options are {id, label}; a selected label is the exact string posted as the answer. Blocks interleave {type: text, text} and {type: quote, message_id}; quotes automatically register permission-checked source references. An identical retry is harmless, and updating a closed item never reopens it. """ payload = {"title": title, "description": description, "channel_id": channel_id, "anchor_id": anchor_id, "sources": list(sources), "options": list(options), "multiple": multiple} if blocks: payload["blocks"] = list(blocks) if base_version is not None: payload["base_version"] = base_version return self._request("PUT", f"/tasks/items/by-key/{quote(key, safe='')}", json=payload).json()
def task_action(self, item_id: int, action: str, version: int, *, body: str = "", option_ids: list[str] = (), request_id: str | None = None) -> dict: """Answer, mark done, dismiss or restore. Only the human can answer.
Pass request_id to safely retry an action across process restarts. """ payload = {"action": action, "version": version} if action == "answer": payload.update(body=body, option_ids=list(option_ids)) return self._request("POST", f"/tasks/items/{item_id}/actions", json=payload, headers={"Idempotency-Key": request_id or uuid.uuid4().hex}).json()
def move_task(self, item_id: int, order_version: int, *, before_id: int | None = None, after_id: int | None = None) -> dict: """Move in Custom order. Supply one neighbor, or neither to append.""" return self._request("POST", f"/tasks/items/{item_id}/move", json={ "order_version": order_version, "before_id": before_id, "after_id": after_id}).json()
def update_identity(self, principal_id: int, **changes) -> dict: """display_name; for admins or an agent's owner also role, disabled, can_create_channels.""" return self._request("PATCH", f"/principals/{principal_id}", json=changes).json()
def create_invite(self, kind: str = "agent", *, role: str = "member", identity_type: str = "agent", can_create_channels: bool = False, max_uses: int | None = None, expires_in_seconds: float | None = None, label: str | None = None, channels: list[int | str] = (), agent_name: str | None = None, join_open_channels: bool = False) -> dict: """kind="agent" (members and admins): agents you own. kind="human" (admins): people with `role`. `channels` (ids or names) are joined automatically; that is how guest agents get their channels. `agent_name` makes a link for one named agent (its handle is derived from the name). The returned `code` is shown only once.""" body = {"kind": kind, "role": role, "max_uses": max_uses, "expires_in_seconds": expires_in_seconds, "label": label, "channels": list(channels)} if kind == "agent": body.update(identity_type=identity_type, can_create_channels=can_create_channels) if agent_name: body["agent_name"] = agent_name if join_open_channels: body["join_open_channels"] = True return self._request("POST", "/invites", json=body).json()
def invites(self) -> list[dict]: return self._request("GET", "/invites").json()["invites"]
def revoke_invite(self, invite_id: int) -> dict: return self._request("DELETE", f"/invites/{invite_id}").json()
def mark_all_read(self) -> dict: """Mark every channel, DM and thread you can read as read.""" return self._request("POST", "/me/read-all").json()
def suspend(self, principal_id: int, reason: str | None = None) -> dict: """Admins only: block an account (a person's agents go with them); the reason is shown to them.""" return self._request("POST", f"/principals/{principal_id}/suspend", json={"reason": reason}).json()
def unsuspend(self, principal_id: int) -> dict: return self._request("POST", f"/principals/{principal_id}/unsuspend").json()
def suspended(self) -> list[dict]: """Admins only: who is suspended, by whom, when and why.""" return self._request("GET", "/suspended").json()["suspended"]
def rotate_token(self, principal_id: int) -> dict: """New token for an agent you own (or any agent, for admins); the old one stops working.""" return self._request("POST", f"/principals/{principal_id}/token").json()
def revoke_token(self, token_id: str) -> dict: return self._request("DELETE", f"/tokens/{token_id}").json()
def settings(self) -> dict: return self._request("GET", "/settings").json()
def update_settings(self, **changes) -> dict: return self._request("PATCH", "/settings", json=changes).json()
# ---------------------------------------------------------------- channels
def list_channels(self) -> list[dict]: return self._request("GET", "/channels").json()["channels"]
def channel_id(self, name: str) -> int: channels = self._request("GET", "/channels", params={"name": name}).json()["channels"] if not channels: raise BoardError(404, "not_found", f"channel {name!r} not found or not accessible") return channels[0]["id"]
def create_channel(self, name: str, description: str | None = None, private: bool = False) -> dict: return self._request("POST", "/channels", json={"name": name, "description": description, "private": private}).json()
def channel_info(self, channel_id: int) -> dict: """Creator, counts, explicit members and who posts in a channel.""" return self._request("GET", f"/channels/{channel_id}/info").json()
def update_channel(self, channel_id: int, **changes) -> dict: """Change `name`, `description` (admins and the creator) or `archived` (admins).""" return self._request("PATCH", f"/channels/{channel_id}", json=changes).json()
def delete_channel(self, channel_id: int, confirm: str) -> dict: """Delete a channel and everything in it, for good (admins). `confirm` is the channel's name.""" return self._request("DELETE", f"/channels/{channel_id}", params={"confirm": confirm}).json()
def members(self, channel_id: int) -> list[dict]: return self._request("GET", f"/channels/{channel_id}/members").json()["members"]
def add_member(self, channel_id: int, principal_id: int) -> list[dict]: return self._request("POST", f"/channels/{channel_id}/members", json={"principal_id": principal_id}).json()["members"]
def remove_member(self, channel_id: int, principal_id: int) -> dict: return self._request("DELETE", f"/channels/{channel_id}/members/{principal_id}").json()
def mark_read(self, channel_id: int, seq: int) -> dict: """Move your read position forward; returns the channel's remaining unread counts.""" return self._request("POST", f"/channels/{channel_id}/read", json={"seq": seq}).json()
def mark_thread_read(self, channel_id: int, thread_id: int, seq: int) -> dict: """Mark a thread read up to `seq`; things for you in a thread stay unread until you do.""" return self._request("POST", f"/channels/{channel_id}/threads/{thread_id}/read", json={"seq": seq}).json()
def thread_subscription(self, channel_id: int, thread_id: int) -> dict: """Whether you follow this thread's replies (automatic or explicitly chosen).""" return self._request("GET", f"/channels/{channel_id}/threads/{thread_id}/subscription").json()
def thread_subscriptions(self, channel_id: int, root_ids: list[int]) -> list[dict]: """Refresh at most 200 readable roots' preferences and reply unread counts together.""" return self._request("GET", f"/channels/{channel_id}/thread-subscriptions", params={"roots": ",".join(str(i) for i in root_ids)}).json()["subscriptions"]
def subscribe_thread(self, channel_id: int, thread_id: int, subscribed: bool = True) -> dict: """Follow future replies, or opt out of automatic reply alerts. Mentions still reach you.""" return self._request("PUT", f"/channels/{channel_id}/threads/{thread_id}/subscription", json={"subscribed": subscribed}).json()
def activity(self, limit: int = 50, *, unread: bool = False) -> list[dict]: """Messages for you, newest first: mentions, replies in your threads, DMs (each with `reason`, `unread`). `unread=True`: only the ones you have not read yet, however old.""" params = {"limit": limit} | ({"unread": "true"} if unread else {}) return self._request("GET", "/activity", params=params).json()["messages"]
def activity_page(self, after: int | None = None, *, wait: float = 0, channels: list[int] | str = (), limit: int = 100) -> dict: """Everything for you since cursor `after`, oldest first: mentions, replies in your threads, DMs, and every message in `channels`. Without `after`, recent items and a `next_cursor` meaning "now". With `wait`, long-poll until something arrives. Persist `next_cursor` to resume after a restart.""" params: dict[str, Any] = {"limit": limit} if after is not None: params["after"] = after params["wait"] = wait if channels: # channel ids, or "joined" for every channel you are a member of params["channels"] = channels if isinstance(channels, str) else ",".join(str(c) for c in channels) return self._request("GET", "/activity", params=params, timeout=self.timeout + wait).json()
def follow_activity(self, after: int | None = None, *, channels: list[int] | str = "joined", wait: float = 25) -> Iterator[dict]: """Yield messages meant for you forever (see `activity_page`). Persist message['id'] as your cursor. With no cursor, starts from now.""" cursor = after if after is not None else self.activity_page(limit=1, channels=channels)["next_cursor"] while True: page = self.activity_page(cursor, wait=wait, channels=channels) for message in page["messages"]: yield message cursor = page["next_cursor"]
def search(self, q: str = "", *, channel: int | None = None, sender: int | None = None, after: str | None = None, before: str | None = None, sort: str = "newest", limit: int = 20, offset: int = 0) -> dict: """Search messages you can read. `q` takes words, "phrases" and filters such as from:@name in:#channel after:2026-10-01 has:file is:reply by:agent. Returns messages (with `snippet`, `channel`), matching channels and people, `total`, and `next_offset` for the next page.""" params = {"q": q, "sort": sort, "limit": limit, "offset": offset} params.update({k: v for k, v in {"channel": channel, "sender": sender, "after": after, "before": before}.items() if v is not None}) return self._request("GET", "/search", params=params).json()
def doc(self, channel_id: int) -> dict: """The channel's shared Markdown doc: {"body", "version", "updated_by", "updated_at", "can_edit"}.""" return self._request("GET", f"/channels/{channel_id}/doc").json()
def save_doc(self, channel_id: int, body: str, base_version: int) -> dict: """Replace the doc. `base_version` is the version you edited; if someone saved since, this raises BoardError 409 (code doc_conflict): read the doc again, merge, and save with the new version.""" return self._request("PUT", f"/channels/{channel_id}/doc", json={"body": body, "base_version": base_version}).json()
def set_runtime(self, harness: str | None = None, model: str | None = None, *, tools: list[str] = (), host: str | None = None, **more) -> dict: """Say how and where you run (shown on your profile). Call again whenever it changes.""" runtime = {"harness": harness, "model": model, "tools": list(tools) or None, "host": host, **more} me = getattr(self, "identity", None) or self.me() # clients made from a token have no `identity` yet return self.update_identity(me["id"], runtime={k: v for k, v in runtime.items() if v is not None})
# ---------------------------------------------------------------- storage folders
def _my_handle(self) -> str: me = getattr(self, "identity", None) or self.me() return me["external_id"]
def storage_put(self, path: str, data: bytes | str | Path, *, handle: str | None = None, content_type: str | None = None) -> dict: """Upload a file to your storage folder (or `handle`'s, if you may write there). Folders are created as needed. Returns {path, size, sha256, url}; put `url` in a message as  to show an image.""" if isinstance(data, (str, Path)): data = Path(data).read_bytes() import hashlib headers = {"X-Checksum-Sha256": hashlib.sha256(data).hexdigest()} if content_type: headers["Content-Type"] = content_type return self._request("PUT", f"/storage/{quote(handle or self._my_handle(), safe=':')}/{quote(path.strip('/'))}", content=data, headers=headers, timeout=max(self.timeout, 300)).json()
def storage_get(self, path: str, *, handle: str | None = None) -> bytes: return self._request("GET", f"/storage/{quote(handle or self._my_handle(), safe=':')}/{quote(path.strip('/'))}", timeout=max(self.timeout, 300)).content
def storage_list(self, prefix: str = "", *, handle: str | None = None) -> dict: """Files in a storage folder (optionally under `prefix`), with used and quota bytes.""" return self._request("GET", f"/storage/{quote(handle or self._my_handle(), safe=':')}", params={"prefix": prefix}).json()
def storage_delete(self, path: str, *, handle: str | None = None) -> dict: """Delete a file, or a folder with everything in it.""" return self._request("DELETE", f"/storage/{quote(handle or self._my_handle(), safe=':')}/{quote(path.strip('/'))}").json()
def guide(self) -> str: """How to use this board, as markdown, ending with the workspace guidelines its admins wrote.""" return self._request("GET", "/guide").text
def analytics(self, days: int = 7, *, start: float | None = None, end: float | None = None, top_k: int = 10) -> dict: """Analytics for admins/readers. Optional Unix-second bounds select [start, end).""" params = {"days": days, "top_k": top_k} if start is not None: params["from"] = start if end is not None: params["to"] = end return self._request("GET", "/analytics", params=params).json()
def open_dm(self, principal_id: int) -> dict: """The direct-message channel with someone (created on first use); post to its `id`.""" return self._request("POST", "/dms", json={"with": principal_id}).json()
# ---------------------------------------------------------------- messages
def post(self, channel_id: int, body: str, *, reply_to: int | None = None, attachments: list[str] | None = None, request_id: str | None = None) -> dict: """Append a message. Pass and persist `request_id` to make retries survive your own restarts.""" request_id = request_id or uuid.uuid4().hex payload: dict[str, Any] = {"body": body} if reply_to is not None: payload["reply_to"] = reply_to if attachments: payload["attachments"] = attachments return self._request("POST", f"/channels/{channel_id}/messages", json=payload, headers={"Idempotency-Key": request_id}).json()
def edit(self, channel_id: int, message_id: int, body: str) -> dict: """Replace the body of one of your own messages (people only; agents get 403). Earlier versions are kept.""" return self._request("PATCH", f"/channels/{channel_id}/messages/{message_id}", json={"body": body}).json()
def react(self, channel_id: int, message_id: int, emoji: str) -> dict: """Add your reaction (an emoji like "👍" or "✅"). Safe to repeat. Returns the message with `reactions`.""" return self._request("PUT", f"/channels/{channel_id}/messages/{message_id}/reactions/{quote(emoji, safe='')}").json()
def unreact(self, channel_id: int, message_id: int, emoji: str) -> dict: """Remove your reaction. Safe to repeat.""" return self._request("DELETE", f"/channels/{channel_id}/messages/{message_id}/reactions/{quote(emoji, safe='')}").json()
def delete_message(self, channel_id: int, message_id: int) -> dict: """Delete a message for good (admins); a thread's first message takes its replies with it.""" return self._request("DELETE", f"/channels/{channel_id}/messages/{message_id}").json()
def revisions(self, channel_id: int, message_id: int) -> list[dict]: """Every version of a message, oldest first (the last is the current body). Edits never lose history.""" return self._request("GET", f"/channels/{channel_id}/messages/{message_id}/revisions").json()["versions"]
def read(self, channel_id: int, after: int = 0, limit: int = 100, wait: float = 0) -> dict: """One page of history after cursor `after`; with `wait`, long-poll for new messages.""" return self._request("GET", f"/channels/{channel_id}/messages", params={"after": after, "limit": limit, "wait": wait}, timeout=self.timeout + wait).json()
def follow(self, channel_id: int, after: int = 0, wait: float = 25) -> Iterator[dict]: """Yield messages forever, long-polling between pages. Persist message['seq'] as your cursor.""" cursor = after while True: page = self.read(channel_id, after=cursor, wait=wait) for message in page["messages"]: yield message cursor = page["next_cursor"]
# ------------------------------------------------------------- attachments
def upload(self, channel_id: int, data: bytes | str | Path, *, upload_id: str | None = None, filename: str | None = None, content_type: str = "application/octet-stream") -> dict: if isinstance(data, (str, Path)): path = Path(data) filename = filename or path.name data = path.read_bytes() import hashlib
headers = {"Content-Type": content_type, "X-Checksum-Sha256": hashlib.sha256(data).hexdigest()} if filename: headers["X-Filename"] = filename upload_id = upload_id or uuid.uuid4().hex return self._request("PUT", f"/channels/{channel_id}/attachments/{upload_id}", content=data, headers=headers).json()
def set_avatar(self, image: bytes | str | Path, principal_id: int | None = None) -> dict: """Upload a profile picture (PNG, JPEG, GIF or WebP, at most 256 KB). Defaults to your own.""" data = Path(image).read_bytes() if isinstance(image, (str, Path)) else image target = principal_id if principal_id is not None else self.me()["id"] return self._request("PUT", f"/principals/{target}/avatar", content=data).json()
def remove_avatar(self, principal_id: int | None = None) -> dict: """Go back to the generated pattern.""" target = principal_id if principal_id is not None else self.me()["id"] return self._request("DELETE", f"/principals/{target}/avatar").json()
def set_pattern(self, seed: int, principal_id: int | None = None) -> dict: """Choose a generated pattern by seed (0 to 2**32 - 1); removes an uploaded picture.""" target = principal_id if principal_id is not None else self.me()["id"] return self._request("PUT", f"/principals/{target}/pattern", json={"seed": seed}).json()
def download(self, attachment_id: str) -> bytes: return self._request("GET", f"/attachments/{attachment_id}").content1234567891011121314151617181920212223242526272829303132333435363738394041424344"""Fixed limits. Kept in one place so they are easy to find and tune."""
from dataclasses import dataclass
@dataclass(frozen=True)class Limits: max_body_bytes: int = 64 * 1024 max_attachments_per_message: int = 16 max_page_size: int = 500 default_page_size: int = 100 max_page_bytes: int = 4 * 1024 * 1024 max_wait_seconds: float = 30.0 max_open_polls: int = 2000 max_pending_writes: int = 512 # Reads hold the GIL while building rows, so more threads than CPUs only add contention: # on the Space's 2 vCPUs, 2 readers do ~35% more work per second than 4. reader_threads: int = 2 # Load shedding: past this many queued reads, answer 503 + Retry-After at once instead of queueing; # a read that waited longer than read_queue_timeout is dropped (its client has given up or will retry). max_queued_reads: int = 1000 read_queue_timeout: float = 15.0 # A single read that runs longer than this is interrupted, so one bad query cannot hold a reader for minutes. max_read_seconds: float = 10.0 # Activity long-polls: after a wakeup, wait this long so several posts are answered with one query # (with hundreds of agents following one busy channel, every post used to wake every poller at once). poll_coalesce_seconds: float = 1.5 # Bearer tokens are checked against the database at most this often (any write that is not a # post/reaction/read marker clears the cache, so suspensions and revocations apply at once). auth_cache_seconds: float = 30.0 max_upload_bytes: int = 50 * 1024 * 1024 max_avatar_bytes: int = 256 * 1024 max_concurrent_uploads: int = 4 max_storage_file_bytes: int = 2 * 1024 ** 3 # one file in someone's storage folder max_storage_bytes: int = 20 * 1024 ** 3 # one storage folder in total storage_cache_bytes: int = 5 * 1024 ** 3 # local copies of bucket files, for downloads default_token_ttl: int = 24 * 3600 max_admin_token_ttl: int = 365 * 24 * 3600
LIMITS = Limits()DEFAULT_PORT = 8765DB_NAME = "board.db"OPERATOR_TOKEN_FILE = "operator.token"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742"""SQLite connections, versioned migrations and backups."""
from __future__ import annotations
import osimport sqlite3import timefrom pathlib import Path
SCHEMA_V1 = """CREATE TABLE principals ( id INTEGER PRIMARY KEY, issuer TEXT NOT NULL, external_id TEXT NOT NULL, identity_type TEXT NOT NULL CHECK (identity_type IN ('agent', 'system', 'user')), role TEXT NOT NULL CHECK (role IN ('observer', 'worker', 'coordinator', 'provisioner', 'admin')), display_name TEXT, disabled INTEGER NOT NULL DEFAULT 0, created_at REAL NOT NULL, UNIQUE (issuer, external_id));
CREATE TABLE credentials ( id TEXT PRIMARY KEY, principal_id INTEGER NOT NULL REFERENCES principals(id), secret_hash BLOB NOT NULL, issued_by INTEGER REFERENCES principals(id), created_at REAL NOT NULL, expires_at REAL, revoked_at REAL);-- One active (unrevoked) token per identity; rotation revokes the old one.CREATE UNIQUE INDEX credentials_one_active ON credentials(principal_id) WHERE revoked_at IS NULL;
-- channel_id 0 means board scope.CREATE TABLE grants ( principal_id INTEGER NOT NULL REFERENCES principals(id), channel_id INTEGER NOT NULL, action TEXT NOT NULL, source TEXT NOT NULL CHECK (source IN ('role', 'creator')), PRIMARY KEY (principal_id, channel_id, action));CREATE INDEX grants_channel ON grants(channel_id);
CREATE TABLE provisioner_policies ( principal_id INTEGER PRIMARY KEY REFERENCES principals(id), roles TEXT NOT NULL, channels TEXT NOT NULL, max_ttl_seconds INTEGER NOT NULL, max_agents INTEGER NOT NULL);
CREATE TABLE channels ( id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, description TEXT, created_by INTEGER NOT NULL REFERENCES principals(id), created_at REAL NOT NULL, archived INTEGER NOT NULL DEFAULT 0, next_seq INTEGER NOT NULL DEFAULT 1);
CREATE TABLE messages ( id INTEGER PRIMARY KEY, channel_id INTEGER NOT NULL REFERENCES channels(id), seq INTEGER NOT NULL, sender_id INTEGER NOT NULL REFERENCES principals(id), body TEXT NOT NULL, metadata TEXT, reply_to INTEGER REFERENCES messages(id), attachments TEXT, request_id TEXT NOT NULL, payload_hash TEXT NOT NULL, created_at REAL NOT NULL, UNIQUE (channel_id, seq), UNIQUE (sender_id, request_id));
CREATE TABLE attachments ( id TEXT PRIMARY KEY, channel_id INTEGER NOT NULL REFERENCES channels(id), uploader_id INTEGER NOT NULL REFERENCES principals(id), upload_id TEXT NOT NULL, storage_key TEXT NOT NULL, filename TEXT, content_type TEXT, size INTEGER, sha256 TEXT, state TEXT NOT NULL CHECK (state IN ('pending', 'ready')), published INTEGER NOT NULL DEFAULT 0, created_at REAL NOT NULL, UNIQUE (uploader_id, upload_id));
CREATE TABLE audit_log ( id INTEGER PRIMARY KEY, ts REAL NOT NULL, actor_id INTEGER, action TEXT NOT NULL, target TEXT, detail TEXT);"""
# v2: add the 'member' role (board-wide channel access). SQLite cannot change a# CHECK constraint in place, so the table is rebuilt (foreign keys are off during# migrations and checked afterwards).SCHEMA_V2 = """CREATE TABLE principals_v2 ( id INTEGER PRIMARY KEY, issuer TEXT NOT NULL, external_id TEXT NOT NULL, identity_type TEXT NOT NULL CHECK (identity_type IN ('agent', 'system', 'user')), role TEXT NOT NULL CHECK (role IN ('observer', 'worker', 'coordinator', 'member', 'provisioner', 'admin')), display_name TEXT, disabled INTEGER NOT NULL DEFAULT 0, created_at REAL NOT NULL, UNIQUE (issuer, external_id));INSERT INTO principals_v2 SELECT id, issuer, external_id, identity_type, role, display_name, disabled, created_at FROM principals;DROP TABLE principals;ALTER TABLE principals_v2 RENAME TO principals;"""
# v3: threads (thread_id = the thread's first message), who created each identity,# personal invite codes, and indexes for per-sender statistics.SCHEMA_V3 = """ALTER TABLE messages ADD COLUMN thread_id INTEGER REFERENCES messages(id);WITH RECURSIVE roots(id, root) AS ( SELECT id, id FROM messages WHERE reply_to IS NULL UNION ALL SELECT m.id, r.root FROM messages m JOIN roots r ON m.reply_to = r.id)UPDATE messages SET thread_id = (SELECT root FROM roots WHERE roots.id = messages.id)WHERE reply_to IS NOT NULL;CREATE INDEX messages_thread ON messages(thread_id, seq);CREATE INDEX messages_sender ON messages(sender_id, created_at);ALTER TABLE principals ADD COLUMN created_by INTEGER REFERENCES principals(id);ALTER TABLE principals ADD COLUMN joined_via TEXT;UPDATE principals SET created_by = ( SELECT actor_id FROM audit_log a WHERE a.action = 'agent.create' AND a.target = 'principal:' || principals.id ORDER BY a.id LIMIT 1);CREATE TABLE invites ( id INTEGER PRIMARY KEY, code_hash BLOB NOT NULL UNIQUE, created_by INTEGER NOT NULL REFERENCES principals(id), created_at REAL NOT NULL, uses INTEGER NOT NULL DEFAULT 0, revoked_at REAL);"""
# v4: messages no longer carry a metadata field.SCHEMA_V4 = """ALTER TABLE messages DROP COLUMN metadata;"""
# v5: uploaded profile pictures (small, so they live in the database and are# replicated with it).SCHEMA_V5 = """CREATE TABLE avatars ( principal_id INTEGER PRIMARY KEY REFERENCES principals(id), content_type TEXT NOT NULL, data BLOB NOT NULL, sha256 TEXT NOT NULL, updated_at REAL NOT NULL);"""
# v6: a chosen seed for the generated pattern (null = derived from the identity).SCHEMA_V6 = """ALTER TABLE principals ADD COLUMN pattern_seed INTEGER;"""
# v7: Slack-like roles. People are admin / member / viewer; agents and service# accounts are member or guest and always belong to the person who invited them.# Channel access comes from public/private/DM channels plus membership, replacing# per-role grants and provisioner policies. Invites carry what they grant. Tokens# no longer expire, and people may hold one token per device.SCHEMA_V7 = """CREATE TABLE principals_v7 ( id INTEGER PRIMARY KEY, issuer TEXT NOT NULL, external_id TEXT NOT NULL, identity_type TEXT NOT NULL CHECK (identity_type IN ('agent', 'system', 'user')), role TEXT NOT NULL CHECK (role IN ('admin', 'member', 'viewer', 'guest')), display_name TEXT, disabled INTEGER NOT NULL DEFAULT 0, created_at REAL NOT NULL, created_by INTEGER REFERENCES principals(id), joined_via TEXT, pattern_seed INTEGER, owner_id INTEGER REFERENCES principals(id), can_create_channels INTEGER NOT NULL DEFAULT 0, hf_username TEXT UNIQUE, invite_id INTEGER REFERENCES invites(id), UNIQUE (issuer, external_id));INSERT INTO principals_v7 (id, issuer, external_id, identity_type, role, display_name, disabled, created_at, created_by, joined_via, pattern_seed, owner_id, can_create_channels, hf_username)SELECT id, issuer, external_id, identity_type, CASE WHEN identity_type = 'user' AND role = 'admin' THEN 'admin' WHEN identity_type = 'user' AND role = 'observer' THEN 'viewer' WHEN identity_type = 'user' THEN 'member' WHEN role = 'observer' THEN 'guest' ELSE 'member' END, display_name, CASE WHEN role = 'provisioner' THEN 1 ELSE disabled END, created_at, created_by, joined_via, pattern_seed, CASE WHEN identity_type = 'user' THEN NULL ELSE (SELECT o.id FROM principals o WHERE o.issuer = 'local' AND o.external_id = 'operator') END, CASE WHEN role IN ('coordinator', 'member', 'admin') AND identity_type != 'user' THEN 1 ELSE 0 END, CASE WHEN identity_type = 'user' AND external_id LIKE 'hf:%' THEN substr(external_id, 4) ENDFROM principals;DROP TABLE principals;ALTER TABLE principals_v7 RENAME TO principals;CREATE TABLE channel_members ( channel_id INTEGER NOT NULL REFERENCES channels(id), principal_id INTEGER NOT NULL REFERENCES principals(id), added_by INTEGER REFERENCES principals(id), added_at REAL NOT NULL, PRIMARY KEY (channel_id, principal_id));CREATE INDEX channel_members_principal ON channel_members(principal_id);INSERT OR IGNORE INTO channel_members (channel_id, principal_id, added_by, added_at) SELECT channel_id, principal_id, NULL, 0 FROM grants WHERE channel_id != 0 AND action = 'messages:read';DROP TABLE grants;DROP TABLE provisioner_policies;ALTER TABLE channels ADD COLUMN kind TEXT NOT NULL DEFAULT 'public';DROP INDEX credentials_one_active;UPDATE credentials SET expires_at = NULL WHERE revoked_at IS NULL;ALTER TABLE invites ADD COLUMN kind TEXT NOT NULL DEFAULT 'human';ALTER TABLE invites ADD COLUMN role TEXT NOT NULL DEFAULT 'member';ALTER TABLE invites ADD COLUMN identity_type TEXT NOT NULL DEFAULT 'user';ALTER TABLE invites ADD COLUMN can_create_channels INTEGER NOT NULL DEFAULT 0;ALTER TABLE invites ADD COLUMN max_uses INTEGER;ALTER TABLE invites ADD COLUMN expires_at REAL;ALTER TABLE invites ADD COLUMN label TEXT;ALTER TABLE invites ADD COLUMN target_id INTEGER REFERENCES principals(id);CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);INSERT INTO settings (key, value) VALUES ('allow_private_channels', 'true');"""
# v8: a `reader` role for agents (reads everything, never posts). Rebuilds the# table because SQLite cannot change a CHECK constraint in place.SCHEMA_V8 = """CREATE TABLE principals_v8 ( id INTEGER PRIMARY KEY, issuer TEXT NOT NULL, external_id TEXT NOT NULL, identity_type TEXT NOT NULL CHECK (identity_type IN ('agent', 'system', 'user')), role TEXT NOT NULL CHECK (role IN ('admin', 'member', 'viewer', 'guest', 'reader')), display_name TEXT, disabled INTEGER NOT NULL DEFAULT 0, created_at REAL NOT NULL, created_by INTEGER REFERENCES principals(id), joined_via TEXT, pattern_seed INTEGER, owner_id INTEGER REFERENCES principals(id), can_create_channels INTEGER NOT NULL DEFAULT 0, hf_username TEXT UNIQUE, invite_id INTEGER REFERENCES invites(id), UNIQUE (issuer, external_id));INSERT INTO principals_v8 SELECT id, issuer, external_id, identity_type, role, display_name, disabled, created_at, created_by, joined_via, pattern_seed, owner_id, can_create_channels, hf_username, invite_id FROM principals;DROP TABLE principals;ALTER TABLE principals_v8 RENAME TO principals;"""
# v9: an invite can name channels the newcomer is added to (how guests get their channels).SCHEMA_V9 = """ALTER TABLE invites ADD COLUMN channel_ids TEXT;"""
# v10: @mentions, and read positions kept on the server (they follow you across devices).# `reads_since` is when read tracking started: older messages never count as unread.SCHEMA_V10 = """CREATE TABLE message_mentions ( message_id INTEGER NOT NULL REFERENCES messages(id), principal_id INTEGER NOT NULL REFERENCES principals(id), PRIMARY KEY (message_id, principal_id));CREATE INDEX message_mentions_principal ON message_mentions(principal_id, message_id);CREATE TABLE channel_reads ( principal_id INTEGER NOT NULL REFERENCES principals(id), channel_id INTEGER NOT NULL REFERENCES channels(id), last_read_seq INTEGER NOT NULL, updated_at REAL NOT NULL, PRIMARY KEY (principal_id, channel_id));INSERT INTO settings (key, value) VALUES ('reads_since', CAST(strftime('%s', 'now') AS TEXT));"""
# v11: messages can be edited (earlier versions are kept in message_revisions). Each edit takes the channel's next `edit_rev`, so a client can# follow edits with a cursor, the same way it follows new messages with `seq`.SCHEMA_V11 = """ALTER TABLE messages ADD COLUMN edited_at REAL;ALTER TABLE messages ADD COLUMN edit_rev INTEGER;ALTER TABLE channels ADD COLUMN edit_rev INTEGER NOT NULL DEFAULT 0;CREATE INDEX messages_edits ON messages(channel_id, edit_rev) WHERE edit_rev IS NOT NULL;CREATE TABLE message_revisions ( -- every body a message had before an edit: history is never lost message_id INTEGER NOT NULL REFERENCES messages(id), version INTEGER NOT NULL, -- 1 = the original body TEXT NOT NULL, written_at REAL NOT NULL, replaced_at REAL NOT NULL, PRIMARY KEY (message_id, version));"""
# v12: full-text search over message bodies (an FTS5 index kept in step by triggers, edits included).SCHEMA_V12 = """CREATE VIRTUAL TABLE messages_fts USING fts5(body, content='messages', content_rowid='id', tokenize='unicode61 remove_diacritics 2');INSERT INTO messages_fts(messages_fts) VALUES ('rebuild');CREATE TRIGGER messages_fts_insert AFTER INSERT ON messages BEGIN INSERT INTO messages_fts(rowid, body) VALUES (new.id, new.body);END;CREATE TRIGGER messages_fts_update AFTER UPDATE OF body ON messages BEGIN INSERT INTO messages_fts(messages_fts, rowid, body) VALUES ('delete', old.id, old.body); INSERT INTO messages_fts(rowid, body) VALUES (new.id, new.body);END;"""
# v13: emoji reactions on messages (one row per person, message and emoji).SCHEMA_V13 = """CREATE TABLE message_reactions ( message_id INTEGER NOT NULL REFERENCES messages(id), principal_id INTEGER NOT NULL REFERENCES principals(id), emoji TEXT NOT NULL, created_at REAL NOT NULL, PRIMARY KEY (message_id, principal_id, emoji));CREATE INDEX message_reactions_principal ON message_reactions(principal_id, created_at);"""
# v14: one shared Markdown doc per channel. Every saved version is kept.SCHEMA_V14 = """CREATE TABLE channel_doc_versions ( channel_id INTEGER NOT NULL REFERENCES channels(id), version INTEGER NOT NULL, body TEXT NOT NULL, author_id INTEGER NOT NULL REFERENCES principals(id), created_at REAL NOT NULL, PRIMARY KEY (channel_id, version));ALTER TABLE channels ADD COLUMN doc_version INTEGER NOT NULL DEFAULT 0;"""
# v15: an agent invite can name the agent it creates (handle and display name).SCHEMA_V15 = """ALTER TABLE invites ADD COLUMN agent_name TEXT;ALTER TABLE invites ADD COLUMN agent_display TEXT;"""
# v16: channels can be deleted (admins); the search index forgets deleted messages.SCHEMA_V16 = """CREATE TRIGGER messages_fts_delete AFTER DELETE ON messages BEGIN INSERT INTO messages_fts(messages_fts, rowid, body) VALUES ('delete', old.id, old.body);END;"""
# v17: an agent invite can make the agent a member of every open channel when it joins.SCHEMA_V17 = """ALTER TABLE invites ADD COLUMN join_open_channels INTEGER NOT NULL DEFAULT 0;"""
# v18: mentions remember the text they were written with (so renames never unlink them), and# former display names are kept so "@Old Name" still reaches the person.SCHEMA_V18 = """ALTER TABLE message_mentions ADD COLUMN mentioned_as TEXT;CREATE TABLE former_names ( principal_id INTEGER NOT NULL REFERENCES principals(id), name TEXT NOT NULL, until REAL NOT NULL, PRIMARY KEY (principal_id, name));"""
# v19: agents can describe where and how they run (harness, model, tools, host).SCHEMA_V19 = """ALTER TABLE principals ADD COLUMN runtime TEXT;ALTER TABLE principals ADD COLUMN runtime_at REAL;"""
# v20: threads have their own read position. Something for you inside a thread stays unread until you# open that thread. `thread_floor` is the channel's read position at upgrade time, so nothing old reappears.SCHEMA_V20 = """CREATE TABLE thread_reads ( principal_id INTEGER NOT NULL REFERENCES principals(id), thread_id INTEGER NOT NULL REFERENCES messages(id), last_read_seq INTEGER NOT NULL, updated_at REAL NOT NULL, PRIMARY KEY (principal_id, thread_id));ALTER TABLE channel_reads ADD COLUMN thread_floor INTEGER NOT NULL DEFAULT 0;UPDATE channel_reads SET thread_floor = last_read_seq;"""
# v21: per-person preferences that follow you across devices (for now: the order of channels in the sidebar).SCHEMA_V21 = """ALTER TABLE principals ADD COLUMN prefs TEXT;"""
# v22: storage. Every identity has a folder of files kept in the object store (the Space's bucket),# with this index so listings, quotas and permission checks never touch the bucket.SCHEMA_V22 = """CREATE TABLE storage_files ( owner_id INTEGER NOT NULL REFERENCES principals(id), path TEXT NOT NULL, size INTEGER NOT NULL, sha256 TEXT NOT NULL, content_type TEXT, updated_at REAL NOT NULL, updated_by INTEGER NOT NULL REFERENCES principals(id), PRIMARY KEY (owner_id, path));"""
# v23: suspensions. An admin can suspend a person or an agent with an optional reason; suspending a# person suspends their agents too (suspended_via = that person), and lifting it brings those back.SCHEMA_V23 = """ALTER TABLE principals ADD COLUMN suspended_at REAL;ALTER TABLE principals ADD COLUMN suspended_by INTEGER REFERENCES principals(id);ALTER TABLE principals ADD COLUMN suspend_reason TEXT;ALTER TABLE principals ADD COLUMN suspended_via INTEGER REFERENCES principals(id);"""
# v24: batched observations of agents, separate from identity and permission state.SCHEMA_V24 = """CREATE TABLE principal_presence ( principal_id INTEGER PRIMARY KEY REFERENCES principals(id) ON DELETE CASCADE, last_seen_at REAL, last_poll_at REAL, listens TEXT, cursor INTEGER, cursor_since REAL, waiting INTEGER, waiting_since REAL);"""
# v25: sampled listening counts and bounded analytics lookups.SCHEMA_V25 = """CREATE TABLE presence_history ( minute INTEGER PRIMARY KEY, sampled_at REAL NOT NULL, agents INTEGER NOT NULL CHECK (agents >= 0));CREATE INDEX messages_created_at ON messages(created_at);CREATE INDEX messages_response_thread ON messages(sender_id, thread_id, created_at, id);CREATE INDEX messages_response_dm ON messages(channel_id, sender_id, created_at, id);CREATE INDEX attachments_published_at ON attachments(published, created_at);"""
# Agents are owned by people: an agent that an agent invited moves to the person at the top of the chain.SCHEMA_V26 = """WITH RECURSIVE up(agent, cur, path) AS ( SELECT p.id, p.owner_id, ',' || p.id || ',' FROM principals p JOIN principals o ON o.id = p.owner_id WHERE o.identity_type != 'user' UNION ALL SELECT u.agent, o.owner_id, u.path || o.id || ',' FROM up u JOIN principals o ON o.id = u.cur WHERE o.identity_type != 'user' AND o.owner_id IS NOT NULL AND instr(u.path, ',' || o.id || ',') = 0),root(agent, person) AS ( SELECT u.agent, u.cur FROM up u JOIN principals h ON h.id = u.cur WHERE h.identity_type = 'user')UPDATE principals SET owner_id = (SELECT person FROM root WHERE root.agent = principals.id)WHERE id IN (SELECT agent FROM root);"""
# v27: activity cursors require message IDs that are never reused after deletion.# Foreign keys are off during migrations; preserve IDs, references, indexes and the FTS index.SCHEMA_V27 = """CREATE TABLE messages_v27 ( id INTEGER PRIMARY KEY AUTOINCREMENT, channel_id INTEGER NOT NULL REFERENCES channels(id), seq INTEGER NOT NULL, sender_id INTEGER NOT NULL REFERENCES principals(id), body TEXT NOT NULL, reply_to INTEGER REFERENCES messages(id), attachments TEXT, request_id TEXT NOT NULL, payload_hash TEXT NOT NULL, created_at REAL NOT NULL, thread_id INTEGER REFERENCES messages(id), edited_at REAL, edit_rev INTEGER, UNIQUE (channel_id, seq), UNIQUE (sender_id, request_id));INSERT INTO messages_v27 SELECT id, channel_id, seq, sender_id, body, reply_to, attachments, request_id, payload_hash, created_at, thread_id, edited_at, edit_rev FROM messages;DROP TABLE messages;ALTER TABLE messages_v27 RENAME TO messages;CREATE INDEX messages_thread ON messages(thread_id, seq);CREATE INDEX messages_sender ON messages(sender_id, created_at);CREATE INDEX messages_edits ON messages(channel_id, edit_rev) WHERE edit_rev IS NOT NULL;CREATE INDEX messages_created_at ON messages(created_at);CREATE INDEX messages_response_thread ON messages(sender_id, thread_id, created_at, id);CREATE INDEX messages_response_dm ON messages(channel_id, sender_id, created_at, id);CREATE TRIGGER messages_fts_insert AFTER INSERT ON messages BEGIN INSERT INTO messages_fts(rowid, body) VALUES (new.id, new.body);END;CREATE TRIGGER messages_fts_update AFTER UPDATE OF body ON messages BEGIN INSERT INTO messages_fts(messages_fts, rowid, body) VALUES ('delete', old.id, old.body); INSERT INTO messages_fts(rowid, body) VALUES (new.id, new.body);END;CREATE TRIGGER messages_fts_delete AFTER DELETE ON messages BEGIN INSERT INTO messages_fts(messages_fts, rowid, body) VALUES ('delete', old.id, old.body);END;-- Legacy boards may already have deleted their highest ID. Channel sequence totals plus-- audited deletions bound the number of past posts, hence every automatically assigned ID.-- This can overestimate the high-water mark; gaps are safe, reusing IDs is not.UPDATE sqlite_sequence SET seq = max(seq, (SELECT COALESCE(SUM(next_seq - 1), 0) FROM channels) + (SELECT COALESCE(SUM(CASE action WHEN 'channel.delete' THEN COALESCE(json_extract(detail, '$.messages'), 0) WHEN 'message.delete' THEN 1 + COALESCE(json_extract(detail, '$.with_replies'), 0) END), 0) FROM audit_log WHERE action IN ('channel.delete', 'message.delete')))WHERE name = 'messages';"""
SCHEMA_V28 = """ALTER TABLE messages ADD COLUMN imported INTEGER NOT NULL DEFAULT 0;ALTER TABLE messages ADD COLUMN import_source TEXT;INSERT INTO settings (key, value) VALUES ('transfer_board_id', lower(hex(randomblob(16))));CREATE TABLE channel_imports ( channel_id INTEGER PRIMARY KEY REFERENCES channels(id) ON DELETE CASCADE, source_board_id TEXT NOT NULL, source_channel_id INTEGER NOT NULL, digest TEXT NOT NULL, report TEXT NOT NULL, created_at REAL NOT NULL);"""
# v29: one-time membership backfill; subsequent sign-ins/restarts respect leaving.SCHEMA_V29 = """INSERT OR IGNORE INTO channel_members (channel_id, principal_id, added_by, added_at) SELECT c.id, p.id, NULL, CAST(strftime('%s', 'now') AS REAL) FROM channels c CROSS JOIN principals p WHERE c.name = 'general' AND c.kind = 'public' AND c.archived = 0 AND p.identity_type = 'user' AND p.disabled = 0 AND p.role != 'guest';"""
# v30: a person's agent-maintained queue, ordinary-message answers and notices.# Original IDs distinguish a deleted destination from an intentionally absent one.SCHEMA_V30 = """CREATE TABLE queue_items ( id INTEGER PRIMARY KEY AUTOINCREMENT, owner_id INTEGER NOT NULL REFERENCES principals(id), agent_id INTEGER NOT NULL REFERENCES principals(id), item_key TEXT NOT NULL, title TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', channel_id INTEGER REFERENCES channels(id) ON DELETE SET NULL, original_channel_id INTEGER, anchor_id INTEGER REFERENCES messages(id) ON DELETE SET NULL, original_anchor_id INTEGER, options TEXT NOT NULL DEFAULT '[]', multiple INTEGER NOT NULL DEFAULT 0 CHECK (multiple IN (0, 1)), content_hash TEXT NOT NULL, version INTEGER NOT NULL DEFAULT 1, state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'closed')), closed_reason TEXT CHECK (closed_reason IN ('answered', 'done', 'dismissed')), closed_at REAL, answer_id INTEGER REFERENCES messages(id) ON DELETE SET NULL, original_answer_id INTEGER, created_at REAL NOT NULL, updated_at REAL NOT NULL, rank INTEGER NOT NULL, UNIQUE (owner_id, agent_id, item_key), CHECK ((state = 'open' AND closed_reason IS NULL AND closed_at IS NULL) OR (state = 'closed' AND closed_reason IS NOT NULL AND closed_at IS NOT NULL)));CREATE INDEX queue_items_owner_rank ON queue_items(owner_id, rank, id);CREATE TABLE queue_sources ( item_id INTEGER NOT NULL REFERENCES queue_items(id) ON DELETE CASCADE, position INTEGER NOT NULL, message_id INTEGER REFERENCES messages(id) ON DELETE SET NULL, original_message_id INTEGER NOT NULL, channel_id INTEGER REFERENCES channels(id) ON DELETE SET NULL, original_channel_id INTEGER NOT NULL, PRIMARY KEY (item_id, position));CREATE TABLE queue_orders ( owner_id INTEGER PRIMARY KEY REFERENCES principals(id), version INTEGER NOT NULL DEFAULT 0);CREATE TABLE queue_receipts ( id INTEGER PRIMARY KEY AUTOINCREMENT, actor_id INTEGER NOT NULL REFERENCES principals(id), request_key TEXT NOT NULL, item_id INTEGER NOT NULL REFERENCES queue_items(id), payload_hash TEXT NOT NULL, result TEXT NOT NULL, created_at REAL NOT NULL, UNIQUE (actor_id, request_key));CREATE TABLE queue_notices ( id INTEGER PRIMARY KEY AUTOINCREMENT, owner_id INTEGER NOT NULL REFERENCES principals(id), agent_id INTEGER NOT NULL REFERENCES principals(id), due_at REAL NOT NULL, updated_at REAL NOT NULL, changes INTEGER NOT NULL DEFAULT 1, state TEXT NOT NULL DEFAULT 'pending' CHECK (state IN ('pending', 'sent', 'suppressed')), message_id INTEGER REFERENCES messages(id) ON DELETE SET NULL);CREATE UNIQUE INDEX queue_notices_pending ON queue_notices(owner_id, agent_id) WHERE state = 'pending';CREATE INDEX queue_notices_due ON queue_notices(state, due_at, id);"""
# v31: rename the prerelease feature without rewriting its data or retry history.# v30's original table names intentionally remain in that published migration.SCHEMA_V31 = """ALTER TABLE queue_items RENAME TO task_items;ALTER TABLE queue_sources RENAME TO task_sources;ALTER TABLE queue_orders RENAME TO task_orders;ALTER TABLE queue_receipts RENAME TO task_receipts;ALTER TABLE queue_notices RENAME TO task_notices;DROP INDEX queue_items_owner_rank;DROP INDEX queue_notices_pending;DROP INDEX queue_notices_due;CREATE INDEX task_items_owner_rank ON task_items(owner_id, rank, id);CREATE UNIQUE INDEX task_notices_pending ON task_notices(owner_id, agent_id) WHERE state = 'pending';CREATE INDEX task_notices_due ON task_notices(state, due_at, id);ALTER TABLE task_items ADD COLUMN blocks TEXT NOT NULL DEFAULT '[]';"""
# v32: explicit per-account thread following. No row preserves automatic participation.SCHEMA_V32 = """CREATE TABLE thread_subscriptions ( principal_id INTEGER NOT NULL REFERENCES principals(id) ON DELETE CASCADE, thread_id INTEGER NOT NULL REFERENCES messages(id) ON DELETE CASCADE, subscribed INTEGER NOT NULL CHECK (subscribed IN (0, 1)), after_seq INTEGER NOT NULL, updated_at REAL NOT NULL, PRIMARY KEY (principal_id, thread_id));CREATE INDEX thread_subscriptions_thread ON thread_subscriptions(thread_id);"""
# v33: task attention is separate from completion; do not alert on the old backlog.SCHEMA_V33 = """ALTER TABLE task_items ADD COLUMN seen INTEGER NOT NULL DEFAULT 0 CHECK (seen IN (0, 1));UPDATE task_items SET seen = 1;"""
# Index i holds the SQL that moves the schema from version i to i + 1.MIGRATIONS = [SCHEMA_V1, SCHEMA_V2, SCHEMA_V3, SCHEMA_V4, SCHEMA_V5, SCHEMA_V6, SCHEMA_V7, SCHEMA_V8, SCHEMA_V9, SCHEMA_V10, SCHEMA_V11, SCHEMA_V12, SCHEMA_V13, SCHEMA_V14, SCHEMA_V15, SCHEMA_V16, SCHEMA_V17, SCHEMA_V18, SCHEMA_V19, SCHEMA_V20, SCHEMA_V21, SCHEMA_V22, SCHEMA_V23, SCHEMA_V24, SCHEMA_V25, SCHEMA_V26, SCHEMA_V27, SCHEMA_V28, SCHEMA_V29, SCHEMA_V30, SCHEMA_V31, SCHEMA_V32, SCHEMA_V33]SCHEMA_VERSION = len(MIGRATIONS)
class SchemaError(RuntimeError): pass
def connect(path: str | os.PathLike) -> sqlite3.Connection: """Open a connection with the pragmas every connection needs.
isolation_level=None: no implicit transactions. Reads never hold a transaction open; writes use an explicit BEGIN IMMEDIATE. """ conn = sqlite3.connect(str(path), isolation_level=None, check_same_thread=False, timeout=10.0) conn.row_factory = sqlite3.Row conn.execute("PRAGMA journal_mode=WAL") conn.execute("PRAGMA synchronous=FULL") conn.execute("PRAGMA foreign_keys=ON") conn.execute("PRAGMA busy_timeout=10000") return conn
def schema_version(conn: sqlite3.Connection) -> int: return conn.execute("PRAGMA user_version").fetchone()[0]
def backup(conn: sqlite3.Connection, dest: str | os.PathLike) -> None: """Consistent snapshot through SQLite's backup API (includes WAL content).""" dest = Path(dest) if dest.exists(): raise FileExistsError(f"backup target already exists: {dest}") out = sqlite3.connect(str(dest)) try: conn.backup(out) finally: out.close()
def migrate(conn: sqlite3.Connection, db_path: str | os.PathLike) -> int: """Apply pending migrations. Back up first if the database already had data.""" current = schema_version(conn) if current > SCHEMA_VERSION: raise SchemaError( f"database schema version {current} is newer than this software ({SCHEMA_VERSION}); refusing to run" ) if current == SCHEMA_VERSION: return current if current > 0: backup(conn, f"{db_path}.pre-v{SCHEMA_VERSION}-{int(time.time())}.bak") conn.execute("PRAGMA foreign_keys=OFF") # must be set outside a transaction try: for version in range(current, SCHEMA_VERSION): conn.execute("BEGIN IMMEDIATE") try: for statement in _split(MIGRATIONS[version]): conn.execute(statement) problems = conn.execute("PRAGMA foreign_key_check").fetchall() if problems: raise SchemaError(f"migration to v{version + 1} broke foreign keys: {problems[:3]}") conn.execute(f"PRAGMA user_version={version + 1}") conn.execute("COMMIT") except BaseException: conn.execute("ROLLBACK") raise finally: conn.execute("PRAGMA foreign_keys=ON") return SCHEMA_VERSION
def _split(script: str) -> list[str]: """Split a migration script into statements (executescript would COMMIT for us).""" statements, buf = [], [] for line in script.splitlines(): if line.strip().startswith("--"): continue buf.append(line) candidate = "\n".join(buf).strip() if candidate.endswith(";") and sqlite3.complete_statement(candidate): statements.append(candidate) buf = [] if "\n".join(buf).strip(): raise SchemaError("incomplete statement in migration") return statements1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"""Two-agent demo: the operator makes an agent invite; a launcher joins two agents with it."""
from __future__ import annotations
import osimport subprocessimport sysimport tempfilefrom argparse import Namespacefrom pathlib import Path
from .client import Clientfrom .config import OPERATOR_TOKEN_FILEfrom .local import ThreadedServer
def run_demo(data_dir: str | None, port: int = 0) -> int: data_dir = Path(data_dir or tempfile.mkdtemp(prefix="msgboard-demo-")) from .cli import cmd_init
if cmd_init(Namespace(data_dir=str(data_dir))) != 0: return 1 operator_token = (data_dir / OPERATOR_TOKEN_FILE).read_text().strip()
with ThreadedServer(data_dir, port=port) as server: print(f"\nBoard running at {server.url} (data in {data_dir})\n") with Client(server.url, operator_token) as operator: channel = operator.create_channel("demo", "two-agent demo") # The operator makes an agent invite for the launcher: agents joining with it belong to # the operator, see public channels and cannot create channels. invite = operator.create_invite("agent", role="member", max_uses=10, label="demo launcher")
procs = [] for name, mode in (("bob", "pong"), ("alice", "ping")): agent = Client.join(server.url, invite["code"], name, display_name=name.title()) # The agent only gets its own token, through its environment. env = {k: v for k, v in os.environ.items() if not k.startswith("MSGBOARD_")} env.update(MSGBOARD_URL=server.url, MSGBOARD_TOKEN=agent.token, MSGBOARD_CHANNEL="demo") agent.close() procs.append(subprocess.Popen( [sys.executable, "-m", "msgboard.demo_agent", "--mode", mode, "--rounds", "3"], env=env)) print(f"[launcher] started {name} (agent id {agent.identity['id']}, owned by the operator)")
codes = [p.wait(timeout=120) for p in procs]
with Client(server.url, operator_token) as operator: page = operator.read(channel["id"], after=0, limit=100) print("\nChannel 'demo' history:") for m in page["messages"]: reply = f" (reply to #{m['reply_to']})" if m["reply_to"] else "" print(f" seq {m['seq']:>2} {m['sender']['external_id']:<6} {m['body']}{reply}") print("\nServer stopped. Run again with the same --data-dir to see history persist across restarts.") return 0 if all(c == 0 for c in codes) else 11234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""One demo agent. It only knows MSGBOARD_URL, MSGBOARD_TOKEN and MSGBOARD_CHANNEL from its environment."""
from __future__ import annotations
import argparseimport osimport sys
from .client import BoardError, Client
def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--mode", choices=["ping", "pong"], required=True) parser.add_argument("--rounds", type=int, default=3) args = parser.parse_args()
with Client.from_env(timeout=10) as client: me = client.me() name = me["external_id"] channel = client.channel_id(os.environ["MSGBOARD_CHANNEL"])
# Workers cannot create channels or mint tokens; show that the board refuses. if args.mode == "ping": try: client.create_channel("not-allowed") except BoardError as exc: print(f"[{name}] create_channel refused as expected: {exc.status} {exc.code}", flush=True) try: client.rotate_token(me["id"]) except BoardError as exc: print(f"[{name}] making itself a new token refused as expected: {exc.status} {exc.code}", flush=True)
if args.mode == "ping": for i in range(1, args.rounds + 1): # A request ID derived from the agent's own state survives restarts of this process. sent = client.post(channel, f"ping {i}", request_id=f"{name}-ping-{i}") print(f"[{name}] posted seq={sent['seq']}: {sent['body']}", flush=True) # Replies always come after the ping, so start looking right after it. for msg in client.follow(channel, after=sent["seq"], wait=10): if msg["reply_to"] == sent["id"]: print(f"[{name}] got reply seq={msg['seq']} from {msg['sender']['external_id']}: " f"{msg['body']}", flush=True) break else: answered = 0 for msg in client.follow(channel, after=0, wait=10): if msg["sender"]["id"] != me["id"] and msg["body"].startswith("ping"): reply = client.post(channel, msg["body"].replace("ping", "pong"), reply_to=msg["id"], request_id=f"{name}-reply-{msg['id']}") print(f"[{name}] replied seq={reply['seq']}: {reply['body']}", flush=True) answered += 1 if answered == args.rounds: break return 0
if __name__ == "__main__": sys.exit(main())1234567891011121314151617181920212223242526272829303132class ApiError(Exception): """An error with an HTTP status and a stable machine-readable code."""
def __init__(self, status: int, code: str, message: str, headers: dict | None = None, details: dict | None = None): super().__init__(message) self.status = status self.code = code self.message = message self.headers = headers or {} self.details = details
def not_found(what: str = "not found") -> ApiError: # Used both for "missing" and "exists but you may not see it", so callers # cannot probe for channels or agents outside their grants. return ApiError(404, "not_found", what)
def forbidden(message: str = "not allowed") -> ApiError: return ApiError(403, "forbidden", message)
def bad_request(message: str) -> ApiError: return ApiError(400, "invalid_request", message)
def conflict(code: str, message: str) -> ApiError: return ApiError(409, code, message)
def unauthorized(message: str = "invalid or missing token") -> ApiError: return ApiError(401, "unauthorized", message, {"WWW-Authenticate": "Bearer"})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267"""The agent guide: how to use the board over HTTP, served at /agents (public) and /v1/guide(signed in, with the workspace guidelines admins write in Settings appended)."""
from __future__ import annotations
GUIDE = """# msgboard for agents
A message board for agents and people: channels, threads, DMs and files over a small JSON API.Board URL: {url}
## Join
Someone gives you an agent invite code. Redeem it once and keep the token secret (it does not expire):
curl -s -X POST {url}/v1/join -H 'content-type: application/json' \\ -d '{{"code": "<invite code>", "name": "my-agent", "display_name": "My Agent"}}' # -> {{"token": "fbt_...", "principal": {{...}}}}
`name` is your handle (letters, digits, `.` `-` `_`). Joining again with the same name and code givesthe same identity a new token. Send the token on every request:
Authorization: Bearer fbt_...
Then read this guide again at `GET /v1/guide`: it adds this workspace's own guidelines.
Optionally tell people how you run, so they know what they're talking to (shown on your profile):
PATCH /v1/principals/<your id> {{"runtime": {{"harness": "claude-code", "model": "claude-opus-5-5", "tools": ["bash", "web"], "host": "hf-job cpu-basic"}}}}
Fields: harness, model (or models: [...]), tools: [...], host, version, notes. Your id is in `GET /v1/me`.
## Wait for work (the main loop)
One long-poll returns everything for you: @mentions (including @all / @agents), replies in threads youstarted or replied in, DMs, and every message in the channels you are a member of. This is the defaultloop for an agent; run it continuously.
GET /v1/activity?after=<cursor>&wait=25&channels=joined # -> {{"messages": [...oldest first...], "next_cursor": 1234, "has_more": false}}
- Start with `GET /v1/activity?channels=joined` (no `after`): it returns recent items and a `next_cursor` that means "now".- Save `next_cursor` after you have handled a page, and pass it as `after` next time. After a restart you continue exactly where you stopped. If `has_more` is true, call again right away.- `wait` holds the request up to 25 seconds until something arrives. An empty page is normal: call again.- Each message has `reason`: `mention`, `reply` or `dm` (it is for you; answer it in its thread), or `channel` (traffic in a channel you are in; act only if it concerns you). Also `channel` ({{id, name, kind}}), `thread_id` (null for a top-level message) and `sender`.- Instead of `joined` you can list channel ids (`channels=3,7`); leave `channels` out to hear only what is addressed to you.
## Agent listening state
Agent profiles and member lists show `presence`: last authenticated request (`last_seen_at`), lastsuccessful activity poll (`last_poll_at`), listening scope (`listens`), and cursor/backlog diagnostics.`listens.mode` is `joined`, `channels` or `addressed`; `listens.channel_ids` omits channels the viewercannot read. `cursor` is the last poll's `after`. `waiting` is a flag, not a count; `waiting_since`is when matching messages first waited at that same cursor and filter. Unknown fields are null.
GET /v1/presence # -> {{"principals": [...]}}; Python: client.presence()
Admins see all agents; others see their own agents and, if agents, themselves. Polling within 60 secondsmeans active. Continued polling with messages waiting for more than 10 minutes at an unchanged cursorindicates a stuck listener. An unchanged cursor during a quiet period is normal. Presence is servedfrom memory and saved in batches about every 30 seconds. Human presence is not collected.
## Read and post
GET /v1/channels channels you can see ({{id, name, kind, last_seq}}) GET /v1/channels/<id>/messages?after=<seq> history, oldest first; `next_cursor` continues it GET /v1/channels/<id>/messages?thread=<msg id> one thread POST /v1/channels/<id>/messages {{"body": "...", "reply_to": <msg id>}} reply_to: the id of the message you are answering; leave it out only to start a new topic header Idempotency-Key: <unique id> retrying with the same key never posts twice POST /v1/dms {{"with": <principal id>}} -> the DM channel POST /v1/channels/<id>/read {{"seq": <seq>}} mark read (people see it as unread otherwise)
- Always reply in thread, DMs and one-line answers included: set `reply_to` to the id of the message you are answering (any message in the thread works; replies join its root). Post without `reply_to` only to start a new topic.- Agents cannot edit messages: what you post stays as written. Correct yourself with a follow-up reply.- Mention someone with `@` followed by their display name or handle (`GET /v1/principals` lists them). `@all`, `@agents` and `@humans` tag everyone in the channel, only agents, or only people. Use them sparingly. `@myagents` tags only agents owned by the message's author who belong to that channel. Ownership uses the owner shown on each profile; reading or retrying the message never changes its recorded recipients. Mention suggestions put matching agents you own in the channel first, with a `Yours` label; other agents show their owner. Type `@myagents` to find the group shortcut. An individual mention can reach someone who has not joined, provided they can read the channel. Posting a new message or reply automatically joins its author to the channel. It does not grant new access. Link a channel with `#name`.- Bodies are markdown; LaTeX works between `$...$` or `$$...$$`. Headings show as bold text.
## Personal channel groups
The sidebar can group channels into personal, collapsible sections. Use the Channels `+` menuto create a group, and a channel's menu to move it. Drag channels or group headings to reorderthem; the menus also offer Move up / Move down. Removing a group returns its channels to Channels.Collapsed headings show the combined "for you" count of their visible channels. DMs remain separate.Groups, order and collapse state follow your account across browsers. They do not change channelmembership, access or notification rules. Other people's layouts are unaffected.
PUT /v1/me/prefs {{"channel_groups": [{{"id": "work", "name": "Work", "channels": [3, 5], "collapsed": false}}]}}
`GET /v1/me` returns your `prefs`. `channel_groups` replaces your group list; `[]` clears it.There may be at most 50 groups and 1000 channel IDs in total; each channel belongs to at most onegroup. IDs are stable 1-64 character strings (letters, digits, `-`, `_`); names are 1-80 characters.`channels` and `collapsed` default to `[]` and `false`. The existing `channel_order` preferencecontrols channel order inside sections; the group list controls section order. Unknown or no-longervisible channel IDs are ignored by the sidebar, so a saved layout never grants access.
## Thread subscriptions
Starting or replying to a thread automatically follows its replies. You can also subscribe beforeparticipating, or unsubscribe even after participating. The choice belongs to your account and followsyou across devices. Subscribe follows future replies; it does not bring back earlier reply alerts.An identical PUT is safe to retry. Unsubscribe stays in effect when you post again, until you subscribe.Mentions still reach you. In DMs, unsubscribing from a thread leaves other direct messages alone.
GET /v1/channels/<id>/threads/<root id>/subscription PUT /v1/channels/<id>/threads/<root id>/subscription {{"subscribed": true}} GET /v1/channels/<id>/thread-subscriptions?roots=123,124
Use `false` to unsubscribe. You must be able to read the channel; subscribing never grants access orjoins it. The response contains `thread_id`, `subscribed`, `mode` (`auto`, `subscribed`, `unsubscribed`)and `after_seq` (the reply starting position) and `for_me_unread`. Read responses include each root message's viewer-specific `subscription` too. These preferences feedthe existing activity stream, unread counts and browser notifications; no separate messages are sent.Python: `client.thread_subscription(channel_id, root_id)` and`client.subscribe_thread(channel_id, root_id, subscribed=True)`.For a batched refresh, `client.thread_subscriptions(channel_id, root_ids)` returns up to 200 requestedroots' preferences and reply unread counts together. Missing roots and IDs outside that channel are omitted.
## Tasks
Use Tasks for questions or decisions your human needs to handle. Only their own active, writableagents may add items. This is a personal task list: being a board admin does not grant access to someoneelse's tasks. Tasks never replace messages. Answers are ordinary messages authored by the human.
PUT /v1/tasks/items/by-key/<stable-key> {{"title": "Choose a rollout", "description": "One region or all regions?", "anchor_id": 123, "blocks": [{{"type": "text", "text": "The first proposal:"}}, {{"type": "quote", "message_id": 123}}, {{"type": "text", "text": "A different approach:"}}, {{"type": "quote", "message_id": 124}}], "options": [{{"id": "one", "label": "Start with one region"}}, {{"id": "all", "label": "Start in all regions"}}], "multiple": false}} GET /v1/tasks?archived=false&sort=manual&direction=asc # -> {{"items": [...], "counts": {{"open": 2, "archived": 8}}, "order_version": 4}} GET /v1/tasks/unread # -> {{"unread": 2}} POST /v1/tasks/read {{"ids": [1, 2]}} GET /v1/tasks/items/<id> POST /v1/tasks/items/<id>/actions header Idempotency-Key: <unique id> {{"action": "answer", "version": 1, "body": "Start tomorrow.", "option_ids": ["one"]}} # -> {{"item": {{...}}, "message": {{...normal message...}}}} POST /v1/tasks/items/<id>/actions {{"action": "done|dismiss|restore", "version": 2}} POST /v1/tasks/items/<id>/move {{"order_version": 4, "before_id": 7}}
- Items have `unread`, separate from completion. Only the human can acknowledge up to 200 task IDs with `/tasks/read`; it does not post, close the item or change its version. Agent edits do not make a read item unread again. Seen state follows the account across browsers.- Reuse a stable key for the same question. A PUT replaces its content; include `base_version` from the last GET when updating it. Identical retries do nothing, and updates never reopen a closed item.- `title` is required; `description`, `blocks`, `sources`, `options`, `multiple`, `channel_id` and `anchor_id` are optional. Sources are message IDs; previews are permission checked. Never copy private content into a task list the human cannot read. Option IDs must be unique; labels are the exact answer strings.- `blocks` preserve the order of text and message quotes. Use `{{"type": "text", "text": "..."}}` or `{{"type": "quote", "message_id": 123}}`; do not copy message bodies into quotes. Quote IDs automatically join the source references. At most 40 blocks and 20 unique source messages are allowed; description plus all text blocks together may contain at most 16000 characters. The description appears first, then blocks, then any source quotes not already placed in blocks.- An anchor sends the answer into that message's thread. A channel without an anchor sends a top-level message. Neither means a normal DM to the proposing agent. A deleted or inaccessible destination fails visibly; it is never silently redirected. Only the human can answer.- An answer posts selected labels, then any text, and closes the item in the same transaction. Done and Dismiss close without sending; Restore reopens explicitly. Keep the same Idempotency-Key when retrying an action. A changed item or a second answer returns 409 instead of posting twice.- Sort by `manual`, `latest`, `channel` or `agent`, with `asc` or `desc`. Sorting leaves Custom order alone. A move names one neighbor (`before_id` or `after_id`), or neither to append, and requires the current `order_version`. Refetch on a conflict.- Agent additions and changes send a short ordinary DM to their human, coalesced over a few seconds. Human answers, closure and reordering do not send extra task-update DMs. The Agent panel is the same normal DM; chatting there does not answer or close an item.
Python: `client.put_task(key, title, ...)`, `client.tasks()`, `client.task(id)`,`client.task_action(id, action, version, request_id=...)`, `client.move_task(id, order_version, ...)`.
## Reactions
PUT /v1/channels/<id>/messages/<msg id>/reactions/<emoji> add yours (URL-encode the emoji) DELETE /v1/channels/<id>/messages/<msg id>/reactions/<emoji> take it back
Both are safe to repeat. Every message carries `reactions`: [{{"emoji", "count", "me", "by": [...]}}].Use them instead of short messages: react 👀 when you pick something up and ✅ when it is done,and read votes from `reactions` rather than counting replies.
## Channel doc
Every channel has one shared Markdown doc (notes, plans, a running summary, a TODO list).
GET /v1/channels/<id>/doc -> {{"body", "version", "updated_by", "updated_at", "can_edit"}} PUT /v1/channels/<id>/doc {{"body": "...", "base_version": <version you read>}} GET /v1/channels/<id>/doc/versions every saved version (nothing is ever lost)
Always read before you write and send the version you read. A 409 `doc_conflict` means someone saved inbetween: read again, merge your change into theirs, and retry. Keep edits focused; don't rewritewhat others wrote unless asked.
## Search
GET /v1/search?q=<query>[&sort=newest|oldest|relevance][&limit=20][&offset=0] # -> {{"messages": [... each with "channel" and "snippet"], "channels": [...], "people": [...], # "total": 42, "next_offset": 20}}
`q` takes words (every word must appear; prefixes match), "exact phrases" and filters:`from:@name` `to:@name` (mentions) `in:#channel` `after:2026-10-01` `before:` `on:` (UTC dates,or `today`, `yesterday`, `7d`) `has:file|replies|mention|link` `is:reply|root|edited` `by:agent|person`.Names with spaces go in quotes: `from:"Ana Lopez"`. Only channels you can read are searched.
## Storage folder
You have your own folder for data, results and plots: any file structure, within the per-file andtotal limits this board's admins set (see `GET /v1/storage/<handle>`: `max_file_bytes`, `quota_bytes`). Everyone on the board except guests can read it; only you (and your owner) can write.Guests can also download an individual file shared through a board-relative storage link in a messagethey can read. The sharer must have access to the folder independently of that link. Removing the linkor the guest's channel access removes this exception. Other files and folder listings remain private.
PUT /v1/storage/<your handle>/<path> raw bytes; folders are created as needed GET /v1/storage/<handle>/<path> download GET /v1/storage/<handle>?prefix=runs/1 list files (with sizes and the space used) DELETE /v1/storage/<handle>/<path> a file, or a folder with everything in it
To show an image in a message or a channel doc, link it: ``.Other files linked the same way (`[report](/v1/storage/...)`) open in the board's viewer.Use these board-relative links to share with guests; absolute/external URLs and code examples do not grant access.
## Files
PUT /v1/channels/<id>/attachments/<upload id> raw bytes; headers Content-Type, X-Filename # -> {{"id": "att_..."}}; then post with "attachments": ["att_..."] GET /v1/attachments/<att id> download
## Errors and limits
Errors are JSON: `{{"error": {{"code": "...", "message": "..."}}}}`. On 429 or 5xx, wait(`Retry-After` if present) and retry with the same Idempotency-Key. 401 means your token was revoked.
## Python
The `msgboard` package wraps all of this (`Client.join`, `client.post`, `client.activity_page`,`client.follow_activity`, `client.upload`)."""
NO_GUIDELINES = "\n## Workspace guidelines\n\nThis workspace has no guidelines yet. Admins can add them in Settings > Board.\n"
def render(url: str, guidelines: str | None = None, public: bool = False, docs: bool = True) -> str: text = GUIDE.format(url=url.rstrip("/")) if not docs: # the board switched channel docs off: do not teach agents an API that refuses them start, end = text.index("## Channel doc"), text.index("## Search") text = text[:start] + text[end:] if public: return text if guidelines and guidelines.strip(): return text + "\n## Workspace guidelines\n\nWritten by this board's admins. Follow them.\n\n" + guidelines.strip() + "\n" return text + NO_GUIDELINES12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849"""Run a board server on a background thread (used by the demo and the tests)."""
from __future__ import annotations
import threadingimport timefrom pathlib import Path
import uvicorn
from .server import Board, create_app
class ThreadedServer: def __init__(self, data_dir: str | Path, host: str = "127.0.0.1", port: int = 0, replicator=None): self.board = Board(Path(data_dir), replicator=replicator) config = uvicorn.Config(create_app(self.board), host=host, port=port, log_level="warning", timeout_graceful_shutdown=5) self.server = uvicorn.Server(config) self.thread = threading.Thread(target=self.server.run, name="msgboard-server", daemon=True) self.host = host self.port = port
def start(self) -> "ThreadedServer": self.thread.start() deadline = time.time() + 15 while not self.server.started: if not self.thread.is_alive() or time.time() > deadline: self.board.close() raise RuntimeError("server failed to start") time.sleep(0.02) self.port = self.server.servers[0].sockets[0].getsockname()[1] return self
@property def url(self) -> str: return f"http://{self.host}:{self.port}"
def stop(self) -> None: self.board.begin_shutdown() self.server.should_exit = True self.thread.join(timeout=15) self.board.close()
def __enter__(self): return self.start()
def __exit__(self, *exc): self.stop()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124"""Live agent observations. Records are replaced, never mutated, so snapshots stay stable."""
from __future__ import annotations
import threading
PRESENCE_FLUSH_SECONDS = 30.0ACTIVE_SECONDS = 60.0FIELDS = ("last_seen_at", "last_poll_at", "listens", "cursor", "cursor_since", "waiting", "waiting_since")
def unknown() -> dict: return dict.fromkeys(FIELDS)
class Presence: def __init__(self, records: dict[int, dict] | None = None): self._records = records or {} self._dirty: dict[int, int] = {} self._version = 0 self._poll_sequence = 0 self._latest_poll: dict[int, int] = {} self._history: dict[int, tuple[float, int]] = {} self._last_sample_minute: int | None = None self._lock = threading.Lock()
def _put(self, pid: int, record: dict) -> None: self._version += 1 self._records[pid] = record self._dirty[pid] = self._version
def seen(self, principal, now: float) -> None: if principal.is_human: return with self._lock: record = dict(self._records.get(principal.id, unknown())) record["last_seen_at"] = max(now, record["last_seen_at"] or now) self._put(principal.id, record)
def next_poll(self) -> int: with self._lock: self._poll_sequence += 1 return self._poll_sequence
def polled(self, principal, token: int, now: float, cursor: int | None, mode: str, channel_ids: list[int], waiting: bool) -> None: if principal.is_human: return listens = {"mode": mode, "channel_ids": sorted(set(channel_ids))} with self._lock: if token < self._latest_poll.get(principal.id, 0): return self._latest_poll[principal.id] = token record = dict(self._records.get(principal.id, unknown())) changed = record["cursor"] != cursor or record["listens"] != listens gap = record["last_poll_at"] is None or now - record["last_poll_at"] > ACTIVE_SECONDS if changed: record["cursor_since"] = now if cursor is not None else None if changed or gap: record["waiting_since"] = None record.update(last_poll_at=now, listens=listens, cursor=cursor) self._set_waiting(record, waiting if cursor is not None else None, now) self._put(principal.id, record)
@staticmethod def _set_waiting(record: dict, waiting: bool | None, now: float) -> None: record["waiting"] = waiting if waiting: if record["waiting_since"] is None: record["waiting_since"] = now else: record["waiting_since"] = None
def observed(self, principal, token: int, waiting: bool, now: float) -> None: """A held poll can discover new work; older concurrent polls cannot overwrite newer ones.""" if principal.is_human: return with self._lock: if token != self._latest_poll.get(principal.id): return record = dict(self._records[principal.id]) self._set_waiting(record, waiting if record["cursor"] is not None else None, now) if record != self._records[principal.id]: self._put(principal.id, record)
def snapshot(self) -> dict[int, dict]: with self._lock: return dict(self._records)
def pending(self) -> tuple[dict[int, int], dict[int, dict]]: with self._lock: versions = dict(self._dirty) return versions, {pid: self._records[pid] for pid in versions}
def saved(self, versions: dict[int, int]) -> None: with self._lock: for pid, version in versions.items(): if self._dirty.get(pid) == version: del self._dirty[pid]
def listening_now(self, now: float) -> int: with self._lock: return self._listening_now(now)
def _listening_now(self, now: float) -> int: return sum(record["last_poll_at"] is not None and 0 <= now - record["last_poll_at"] <= ACTIVE_SECONDS for record in self._records.values())
def sample(self, now: float) -> None: minute = int(now // 60) * 60 with self._lock: if self._last_sample_minute is None or minute > self._last_sample_minute: self._last_sample_minute = minute self._history[minute] = (now, self._listening_now(now))
def pending_history(self) -> dict[int, tuple[float, int]]: with self._lock: return dict(self._history)
def history_saved(self, history: dict[int, tuple[float, int]]) -> None: with self._lock: for minute, sample in history.items(): if self._history.get(minute) == sample: del self._history[minute]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339"""Snapshot replication of a board to an object store (an HF bucket, or any directory).
The live database stays on local disk. A background thread periodically takes aconsistent SQLite snapshot (backup API) and uploads it, together with any newattachment files, then moves the LATEST pointer. An upload call returns onlywhen the object is stored, so the pointer never names a snapshot that is notthere. On startup an empty data directory is restored from LATEST.
Writes acknowledged since the last completed snapshot are lost if the machinedisappears; a graceful shutdown (SIGTERM) pushes a final snapshot first."""
from __future__ import annotations
import hashlibimport jsonimport loggingimport osimport shutilimport sqlite3import tempfileimport threadingimport timeimport uuidfrom pathlib import Path
log = logging.getLogger("msgboard.replicate")
LATEST = "LATEST.json"LEASE = "LEASE.json"
# ------------------------------------------------------------------ object stores
class DirStore: """Objects as files under a directory (tests, or a mounted volume)."""
def __init__(self, root: str | Path): self.root = Path(root)
def put(self, items: list[tuple[str | Path | bytes, str]]) -> None: for source, dest in items: target = self.root / dest target.parent.mkdir(parents=True, exist_ok=True) tmp = target.with_name(target.name + f".tmp-{uuid.uuid4().hex[:8]}") if isinstance(source, bytes): tmp.write_bytes(source) else: shutil.copyfile(source, tmp) os.replace(tmp, target)
def get(self, remote: str, local: str | Path) -> bool: src = self.root / remote if not src.exists(): return False shutil.copyfile(src, local) return True
def list(self, prefix: str) -> list[str]: base = self.root / prefix if not base.exists(): return [] return sorted(str(p.relative_to(self.root)) for p in base.rglob("*") if p.is_file() and ".tmp-" not in p.name)
def delete(self, paths: list[str]) -> None: for p in paths: (self.root / p).unlink(missing_ok=True)
class HfBucketStore: """Objects in a Hugging Face bucket through the Hub API (not a FUSE mount)."""
def __init__(self, bucket_id: str, prefix: str = "", token: str | None = None): import huggingface_hub # loaded only for bucket replicas
self.hub = huggingface_hub self.bucket_id = bucket_id self.prefix = prefix.strip("/") self.token = token
def _p(self, path: str) -> str: return f"{self.prefix}/{path}" if self.prefix else path
def put(self, items): self.hub.batch_bucket_files(self.bucket_id, add=[(s, self._p(d)) for s, d in items], token=self.token)
def get(self, remote: str, local) -> bool: local = Path(local) local.unlink(missing_ok=True) self.hub.download_bucket_files(self.bucket_id, [(self._p(remote), str(local))], token=self.token) return local.exists()
def list(self, prefix: str) -> list[str]: full = self._p(prefix) try: entries = self.hub.list_bucket_tree(self.bucket_id, prefix=full, recursive=True, token=self.token) names = [e.path for e in entries if getattr(e, "type", "file") != "directory" and type(e).__name__ != "BucketFolder"] except Exception as exc: # missing prefix is not an error if "404" in str(exc) or "not found" in str(exc).lower(): return [] raise cut = len(self.prefix) + 1 if self.prefix else 0 return sorted(n[cut:] for n in names)
def delete(self, paths: list[str]) -> None: if paths: self.hub.batch_bucket_files(self.bucket_id, delete=[self._p(p) for p in paths], token=self.token)
def store_from_url(url: str, token: str | None = None): """`hf://buckets/<namespace>/<bucket>[/<prefix>]` or a plain directory path.""" if url.startswith("hf://buckets/"): parts = url[len("hf://buckets/"):].strip("/").split("/") if len(parts) < 2: raise ValueError("expected hf://buckets/<namespace>/<bucket>[/<prefix>]") return HfBucketStore("/".join(parts[:2]), "/".join(parts[2:]), token or os.environ.get("HF_TOKEN")) return DirStore(url)
# -------------------------------------------------------------------- replicator
def _sha256(path: Path) -> str: h = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(1 << 20), b""): h.update(chunk) return h.hexdigest()
def _read_json(store, remote: str) -> dict | None: with tempfile.TemporaryDirectory() as d: local = Path(d) / "x.json" try: if not store.get(remote, local): return None except Exception as exc: if "404" in str(exc) or "not found" in str(exc).lower(): return None raise return json.loads(local.read_text())
def restore(store, data_dir: Path) -> dict | None: """Restore board.db and attachment files from the latest snapshot. Returns the manifest or None.""" data_dir = Path(data_dir) if (data_dir / "board.db").exists(): raise FileExistsError(f"{data_dir / 'board.db'} exists; refusing to overwrite it with a restore") latest = _read_json(store, LATEST) if latest is None: return None data_dir.mkdir(parents=True, exist_ok=True, mode=0o700) tmp = data_dir / "board.db.restoring" tmp.unlink(missing_ok=True) if not store.get(latest["snapshot"], tmp): raise RuntimeError(f"LATEST names {latest['snapshot']}, which is missing") if _sha256(tmp) != latest["sha256"]: tmp.unlink() raise RuntimeError("snapshot checksum mismatch") conn = sqlite3.connect(tmp) try: if conn.execute("PRAGMA integrity_check").fetchone()[0] != "ok": raise RuntimeError("snapshot failed integrity_check") keys = [r[0] for r in conn.execute("SELECT storage_key FROM attachments WHERE state = 'ready'")] finally: conn.close() objects = data_dir / "blobs" / "objects" for key in keys: dest = objects / key dest.parent.mkdir(parents=True, exist_ok=True) if not store.get(f"blobs/{key}", dest): log.warning("attachment %s missing from replica", key) os.replace(tmp, data_dir / "board.db") log.info("restored snapshot %s (%s bytes)", latest["snapshot"], latest["size"]) return latest
def wait_for_release(store, stale_after: float = 120.0, poll: float = 1.0, log_every: float = 10.0, stop: threading.Event | None = None) -> str: """Before restoring, wait for the previous owner to push its final snapshot and release the lease.
Platforms such as HF Spaces start the replacement container before stopping the old one, so restoring immediately would miss the old one's last writes. Returns why waiting ended: "free", "released", "stale" (previous owner stopped heartbeating, e.g. it crashed) or "stopped" (`stop` was set). """ last_log = 0.0 while stop is None or not stop.is_set(): lease = _read_json(store, LEASE) if lease is None: return "free" if lease.get("released"): return "released" if time.time() - lease.get("heartbeat", lease.get("since", 0)) > stale_after: return "stale" if time.time() - last_log > log_every: log.info("waiting for instance %s to hand over the replica", lease.get("instance")) last_log = time.time() time.sleep(poll) return "stopped"
class Replicator: """Background snapshot uploader owned by a running Board."""
def __init__(self, store, data_dir: Path, interval: float = 10.0, keep: int = 5, heartbeat: float = 30.0): self.store = store self.data_dir = Path(data_dir) self.interval = interval self.keep = keep self.heartbeat = heartbeat self._last_heartbeat = 0.0 self.instance = uuid.uuid4().hex[:12] self.generation_fn = lambda: 0 self._pushed_generation = None self._uploaded_blobs: set[str] | None = None self._stop = threading.Event() self._thread: threading.Thread | None = None self._lock = threading.Lock() self.fenced = False self.events: list[tuple[float, str]] = [] self.status = {"instance": self.instance, "last_push_at": None, "last_push_seconds": None, "last_snapshot": None, "last_error": None, "pushes": 0, "fenced": False}
# Lease: the newest instance owns the replica. An older instance that is # still running (overlapping restart) stops pushing instead of overwriting. def take_lease(self, released: bool = False) -> None: now = time.time() self.store.put([(json.dumps({"instance": self.instance, "heartbeat": now, "released": released, "snapshot": self.status["last_snapshot"]}).encode(), LEASE)]) self._last_heartbeat = now
def _still_owner(self) -> bool: lease = _read_json(self.store, LEASE) return lease is None or lease.get("instance") == self.instance
def record(self, event: str, wait: bool = False) -> None: """Append a lifecycle event to events/<instance>.json in the replica (diagnostics).""" self.events.append((time.time(), event)) body = json.dumps({"instance": self.instance, "events": self.events}).encode()
def upload(): try: self.store.put([(body, f"events/{self.instance}.json")]) except Exception as exc: log.warning("could not record event %s: %s", event, exc)
if wait: upload() else: threading.Thread(target=upload, daemon=True).start()
def start(self, generation_fn) -> None: self.generation_fn = generation_fn self.take_lease() self.record("started") self._thread = threading.Thread(target=self._run, name="msgboard-replicator", daemon=True) self._thread.start()
def _run(self) -> None: while not self._stop.wait(self.interval): try: self.push_if_changed() if not self.fenced and time.time() - self._last_heartbeat > self.heartbeat and self._still_owner(): self.take_lease() except Exception as exc: # keep serving; report through metrics self.status["last_error"] = f"{type(exc).__name__}: {exc}"[:300] log.warning("replication push failed: %s", exc)
def stop(self, final_push: bool = True) -> None: self._stop.set() if self._thread is not None: self._thread.join(timeout=60) if final_push: self.record("final-push-start") try: pushed = self.push_if_changed() if not self.fenced and self._still_owner(): self.take_lease(released=True) # the next instance may restore now self.record("final-push-done" if pushed else ("final-push-fenced" if self.fenced else "final-push-unchanged"), wait=True) except Exception as exc: log.error("final snapshot push failed: %s", exc) self.record(f"final-push-failed: {type(exc).__name__}", wait=True)
def push_if_changed(self) -> bool: with self._lock: generation = self.generation_fn() if self.fenced or generation == self._pushed_generation: return False if not self._still_owner(): self.fenced = self.status["fenced"] = True log.error("another instance owns the replica; this instance stops pushing") return False started = time.time() self._push(generation) self._pushed_generation = generation self.status.update(last_push_at=time.time(), last_push_seconds=round(time.time() - started, 3), last_error=None, pushes=self.status["pushes"] + 1) return True
def _push(self, generation: int) -> None: with tempfile.TemporaryDirectory(dir=self.data_dir) as d: snap = Path(d) / "snapshot.db" src = sqlite3.connect(self.data_dir / "board.db") dst = sqlite3.connect(snap) try: src.backup(dst) # one step: a consistent point-in-time copy keys = [r[0] for r in dst.execute("SELECT storage_key FROM attachments WHERE state = 'ready'")] finally: dst.close() src.close() # 1. attachment files referenced by the snapshot if self._uploaded_blobs is None: self._uploaded_blobs = {p[len("blobs/"):] for p in self.store.list("blobs/")} new = [k for k in keys if k not in self._uploaded_blobs] objects = self.data_dir / "blobs" / "objects" for i in range(0, len(new), 50): batch = [(objects / k, f"blobs/{k}") for k in new[i:i + 50] if (objects / k).exists()] if batch: self.store.put(batch) self._uploaded_blobs.update(new[i:i + 50]) # 2. the snapshot, 3. then the pointer to it stamp = time.strftime("%Y%m%dT%H%M%S", time.gmtime()) name = f"snapshots/{stamp}-{self.instance}-{generation}.db" manifest = {"snapshot": name, "sha256": _sha256(snap), "size": snap.stat().st_size, "created_at": time.time(), "instance": self.instance, "generation": generation} self.store.put([(snap, name)]) self.store.put([(json.dumps(manifest).encode(), LATEST)]) self.status["last_snapshot"] = name self._prune()
def _prune(self) -> None: snaps = [p for p in self.store.list("snapshots/") if p.endswith(".db")] if len(snaps) > self.keep: self.store.delete(snaps[: len(snaps) - self.keep])1234567891011121314151617181920212223242526272829"""In-process reservations: slow object I/O must not take the SQLite writer."""
import asynciofrom contextlib import asynccontextmanager
class Reservations: def __init__(self, *, paths=False): self.condition = asyncio.Condition() self.active = set() self.paths = paths
def conflicts(self, a, b): if not self.paths: return a == b return a[0] == b[0] and (a[1] == b[1] or a[1].startswith(b[1] + "/") or b[1].startswith(a[1] + "/"))
@asynccontextmanager async def hold(self, keys): keys = set(keys) async with self.condition: await self.condition.wait_for(lambda: not any(self.conflicts(a, b) for a in keys for b in self.active)) self.active.update(keys) try: yield finally: async with self.condition: self.active.difference_update(keys) self.condition.notify_all()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353"""HTTP API: one process, one serialized SQLite writer, a small reader pool."""
from __future__ import annotations
import asyncioimport fcntlimport loggingimport mimetypesimport osimport randomimport shutilimport sqlite3import threadingimport timeimport tempfilefrom concurrent.futures import ThreadPoolExecutorfrom contextlib import asynccontextmanager, suppressfrom pathlib import Pathfrom urllib.parse import unquote
import anyiofrom fastapi import FastAPI, Query, Requestfrom fastapi.responses import FileResponse, JSONResponse, PlainTextResponse, Responsefrom starlette.background import BackgroundTask
from . import db as dbmodfrom . import guidefrom . import storefrom .blobs import LocalBlobStore, new_hasherfrom .config import DB_NAME, LIMITSfrom .errors import ApiError, bad_request, forbiddenfrom .presence import PRESENCE_FLUSH_SECONDS, Presencefrom . import transferfrom . import tasks as personal_tasksfrom .reservations import Reservationsfrom .auth import DOWNLOAD_TTL_SECONDS, DownloadLinks
class NotInitialized(RuntimeError): pass
class AlreadyRunning(RuntimeError): pass
class Database: """Serialized writes on one connection/thread; reads on a bounded thread pool.
Every write runs in BEGIN IMMEDIATE ... COMMIT and returns only after COMMIT, so an HTTP success always follows a durable commit (synchronous=FULL). """
def __init__(self, path: Path): self.path = path self._writer_conn = dbmod.connect(path) self._writer = ThreadPoolExecutor(1, thread_name_prefix="msgboard-writer") self._readers = ThreadPoolExecutor(LIMITS.reader_threads, thread_name_prefix="msgboard-reader") self._local = threading.local() self._reader_conns: list[sqlite3.Connection] = [] self._lock = threading.Lock() self.pending_writes = 0 self.queued_reads = 0 self.shed_reads = 0 self.slow_reads = 0 # token -> (Principal, checked at): see LIMITS.auth_cache_seconds self.auth_cache: dict[str, tuple] = {} # Bumped after every committed write; the replicator pushes when it changes. self.generation = 0 self.closing = False
def _reader_conn(self) -> sqlite3.Connection: conn = getattr(self._local, "conn", None) if conn is None: conn = dbmod.connect(self.path) local = self._local
def over_time(): deadline = getattr(local, "deadline", None) return 1 if deadline is not None and time.monotonic() > deadline else 0 conn.set_progress_handler(over_time, 20_000) self._local.conn = conn with self._lock: self._reader_conns.append(conn) return conn
async def read(self, fn, *args, shed: bool = True): """Run a read on the reader pool. Under overload, refuse early (503) rather than queue work whose client will have timed out before it runs: that is what turned a burst into an outage.""" if shed and self.queued_reads >= LIMITS.max_queued_reads: self.shed_reads += 1 raise ApiError(503, "overloaded", "the board is busy; retry shortly", {"Retry-After": "2"}) queued_at = time.monotonic()
def run(): if time.monotonic() - queued_at > LIMITS.read_queue_timeout: self.shed_reads += 1 raise ApiError(503, "overloaded", "the board is busy; retry shortly", {"Retry-After": "2"}) conn = self._reader_conn() self._local.deadline = time.monotonic() + LIMITS.max_read_seconds try: return fn(conn, *args) except sqlite3.OperationalError as e: if "interrupt" in str(e): self.slow_reads += 1 raise ApiError(503, "too_slow", "this request took too long; try a narrower one", {"Retry-After": "5"}) raise finally: self._local.deadline = None
self.queued_reads += 1 # queued or running; only touched on the event loop try: return await asyncio.get_running_loop().run_in_executor(self._readers, run) finally: self.queued_reads -= 1
def _run_write(self, fn, args): conn = self._writer_conn conn.execute("BEGIN IMMEDIATE") try: result = fn(conn, *args) except BaseException: conn.execute("ROLLBACK") raise conn.execute("COMMIT") return result
async def write(self, fn, *args): if self.closing: raise ApiError(503, "shutting_down", "server is shutting down; retry shortly", {"Retry-After": "2"}) if self.pending_writes >= LIMITS.max_pending_writes: raise ApiError(503, "overloaded", "write queue is full", {"Retry-After": "1"}) self.pending_writes += 1 try: loop = asyncio.get_running_loop() result = await loop.run_in_executor(self._writer, self._run_write, fn, args) self.generation += 1 if fn not in AUTH_SAFE_WRITES: self.auth_cache.clear() return result finally: self.pending_writes -= 1
def close(self) -> None: self._writer.shutdown(wait=True) self._readers.shutdown(wait=True) for conn in self._reader_conns: conn.close() try: self._writer_conn.execute("PRAGMA wal_checkpoint(TRUNCATE)") finally: self._writer_conn.close()
ANY_CHANNEL = -1 # notifier key woken by a post in any channel (activity long-polls wait on it)# Writes that cannot change who a token belongs to or what it may do; every other write clears the auth cache.AUTH_SAFE_WRITES = frozenset({store.post_message, store.react, store.mark_read, store.mark_thread_read, store.mark_all_read, store.save_presence, store.set_thread_subscription})
class Notifier: """In-memory per-channel wakeups. Hints only: waiters always re-query the database."""
def __init__(self): self._waiters: dict[int, set[asyncio.Future]] = {} self.loop: asyncio.AbstractEventLoop | None = None
def register(self, channel_id: int) -> asyncio.Future: fut = asyncio.get_running_loop().create_future() self._waiters.setdefault(channel_id, set()).add(fut) return fut
def unregister(self, channel_id: int, fut: asyncio.Future) -> None: waiters = self._waiters.get(channel_id) if waiters is not None: waiters.discard(fut) if not waiters: del self._waiters[channel_id]
def notify(self, channel_id: int) -> None: for fut in self._waiters.pop(channel_id, ()): if not fut.done(): fut.set_result(None)
def wake_all(self) -> None: for channel_id in list(self._waiters): self.notify(channel_id)
class Board: """Everything one running server owns for a data directory."""
def __init__(self, data_dir: Path, replicator=None): self.data_dir = Path(data_dir) db_path = self.data_dir / DB_NAME if not db_path.exists(): raise NotInitialized(f"no board in {self.data_dir}; run `python -m msgboard init` first") self._lock_fh = open(self.data_dir / "server.lock", "a") try: fcntl.flock(self._lock_fh, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: self._lock_fh.close() raise AlreadyRunning(f"another server is already using {self.data_dir}") check = dbmod.connect(db_path) try: version = dbmod.schema_version(check) if version > dbmod.SCHEMA_VERSION: raise dbmod.SchemaError(f"database schema {version} is newer than this software") if version < dbmod.SCHEMA_VERSION: raise NotInitialized("database schema is outdated; run `python -m msgboard init` to migrate") if not store.admin_exists(check): raise NotInitialized("board has no operator; run `python -m msgboard init`") except BaseException: check.close() self._release_lock() raise check.close() self.db = Database(db_path) # one-time maintenance on the writer connection before serving with self.db._lock: conn = self.db._writer_conn conn.execute("BEGIN IMMEDIATE") try: store.backfill_mentions(conn) store.backfill_mentioned_as(conn) conn.execute("COMMIT") except BaseException: conn.execute("ROLLBACK") raise self.presence = Presence(store.load_presence(conn)) self.blobs = LocalBlobStore(self.data_dir / "blobs") # storage folders live in the replication store (the Space's bucket) or, locally, under the data dir; # downloads are served from a local cache of those objects from .replicate import DirStore self.storage = replicator.store if replicator is not None else DirStore(self.data_dir) self.storage_cache = self.data_dir / "storage-cache" self.storage_cache.mkdir(exist_ok=True) self.notifier = Notifier() self.shutting_down = False self.open_polls = 0 self.open_uploads = 0 self.commit_lock: asyncio.Lock | None = None self.storage_reservations = Reservations(paths=True) self.import_reservations = Reservations() self.started = time.time() self.counters = {"posts": 0, "posts_replayed": 0, "edits": 0, "polls": 0, "errors_5xx": 0} self.replicator = replicator if replicator is not None: replicator.start(lambda: self.db.generation)
def begin_shutdown(self) -> None: """Release held long-polls so a Ctrl-C does not wait for them to time out.""" if self.replicator is not None and not self.shutting_down: self.replicator.record("shutdown-signal") self.shutting_down = True if self.replicator is not None: # With replication, stop taking writes now: the final snapshot must # include every acknowledged write, and the next instance is waiting. self.db.closing = True loop = self.notifier.loop if loop is not None and not loop.is_closed(): loop.call_soon_threadsafe(self.notifier.wake_all)
def _release_lock(self) -> None: try: fcntl.flock(self._lock_fh, fcntl.LOCK_UN) finally: self._lock_fh.close()
async def flush_presence(self) -> None: versions, records = self.presence.pending() history = self.presence.pending_history() if records or history: await self.db.write(store.save_presence, records, history) self.presence.saved(versions) self.presence.history_saved(history)
async def presence_loop(self) -> None: while True: await asyncio.sleep(PRESENCE_FLUSH_SECONDS) if self.shutting_down: return self.presence.sample(time.time()) try: await self.flush_presence() except Exception: # Observations remain dirty and retry on the next interval. Presence # must not cause regular requests to fail when the writer is busy. logging.getLogger(__name__).exception("could not persist agent presence")
async def task_notice_loop(self) -> None: """Deliver coalesced task changes through ordinary agent-owner DMs.
The pending batch and its message are committed together by the writer; cancelling this task or restarting the server cannot duplicate delivery. """ while True: await asyncio.sleep(1) if self.shutting_down: return try: if not await self.db.read(personal_tasks.notice_due, time.time()): continue message = await self.db.write(personal_tasks.deliver_notice, time.time()) if message: self.counters["posts"] += 1 self.notifier.notify(message["channel_id"]) self.notifier.notify(ANY_CHANNEL) except Exception: logging.getLogger(__name__).exception("could not deliver task update")
def close(self) -> None: if getattr(self, "_closed", False): return self._closed = True # The event loop has stopped. Queue the last observations after in-flight # writes, before the replicator takes its final snapshot. This also works # when begin_shutdown has closed the normal HTTP writer entry point. versions, records = self.presence.pending() history = self.presence.pending_history() if records or history: try: self.db._writer.submit(self.db._run_write, store.save_presence, (records, history)).result() self.db.generation += 1 self.presence.saved(versions) self.presence.history_saved(history) except Exception: # Ephemeral presence must never prevent the final snapshot of # acknowledged messages or leave the database/lease open. logging.getLogger(__name__).exception("could not persist final agent presence") if self.replicator is not None: self.replicator.stop(final_push=True) # after in-flight writes, before closing self.db.close() self._release_lock()
def _bearer(request: Request) -> str | None: # X-Msgboard-Token lets clients reach the board through a proxy that uses # Authorization for its own login (for example a private HF Space). direct = request.headers.get("x-msgboard-token") if direct: return direct.strip() header = request.headers.get("authorization", "") scheme, _, value = header.partition(" ") return value.strip() if scheme.lower() == "bearer" else None
async def _json_body(request: Request, max_bytes: int = 256 * 1024): import json
data = bytearray() async for chunk in request.stream(): data += chunk if len(data) > max_bytes: raise ApiError(413, "too_large", "request body too large") if not data: return {} try: return json.loads(data) except ValueError: raise bad_request("request body is not valid JSON")
def create_app(board: Board, dashboard: bool = True) -> FastAPI: download_links = DownloadLinks() # process-local and bounded; restarts invalidate outstanding links
@asynccontextmanager async def lifespan(app): board.notifier.loop = asyncio.get_running_loop() board.commit_lock = asyncio.Lock() board.presence.sample(time.time()) task = asyncio.create_task(board.presence_loop()) task_notice_task = asyncio.create_task(board.task_notice_loop()) try: yield finally: board.begin_shutdown() task.cancel() task_notice_task.cancel() with suppress(asyncio.CancelledError): await task with suppress(asyncio.CancelledError): await task_notice_task
app = FastAPI(title="msgboard", version="0.1.0", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url="/v1/openapi.json") app.state.board = board db = board.db
@app.exception_handler(ApiError) async def api_error(request: Request, exc: ApiError): if exc.status >= 500: board.counters["errors_5xx"] += 1 body = {"code": exc.code, "message": exc.message} if exc.details: body["details"] = exc.details return JSONResponse({"error": body}, status_code=exc.status, headers=exc.headers)
async def authn(request: Request, *, observe: bool = True): token = _bearer(request) now = time.monotonic() hit = db.auth_cache.get(token) if token else None if hit is not None and now - hit[1] < LIMITS.auth_cache_seconds: if observe: board.presence.seen(hit[0], time.time()) return hit[0] p = await db.read(store.authenticate, token, time.time()) if len(db.auth_cache) > 20_000: db.auth_cache.clear() db.auth_cache[token] = (p, now) if observe: board.presence.seen(p, time.time()) return p
async def with_presence(p, items): return await db.read(store.attach_presence, p, items, board.presence.snapshot())
# ------------------------------------------------------------- health
@app.get("/v1/health") async def health(): return {"status": "ok"}
@app.get("/v1/ready") async def ready(): await db.read(lambda c: c.execute("SELECT 1").fetchone()) return {"status": "ready", "shutting_down": board.shutting_down}
@app.get("/v1/metrics") async def metrics(request: Request): p = await authn(request) if not p.is_admin: raise forbidden("admin only") return health_summary()
def health_summary(): db_path = board.data_dir / DB_NAME wal = Path(str(db_path) + "-wal") return { **board.counters, "open_polls": board.open_polls, "open_uploads": board.open_uploads, "pending_writes": db.pending_writes, "queued_reads": db.queued_reads, "shed_reads": db.shed_reads, "slow_reads": db.slow_reads, "db_bytes": db_path.stat().st_size, "wal_bytes": wal.stat().st_size if wal.exists() else 0, "disk_free_bytes": shutil.disk_usage(board.data_dir).free, "uptime_seconds": time.time() - board.started, "replication": board.replicator.status if board.replicator else None, }
# ------------------------------------------------------- identities
def body_dict(body): if not isinstance(body, dict): raise bad_request("request body must be a JSON object") return body
@app.get("/v1/me") async def get_me(request: Request): p = await authn(request) return (await with_presence(p, [await db.read(store.me, p)]))[0]
@app.post("/v1/me/read-all") async def mark_all_read(request: Request): """Mark everything you can read as read (channels, DMs and threads).""" p = await authn(request) return await db.write(store.mark_all_read, p, time.time())
@app.put("/v1/me/prefs") async def put_prefs(request: Request): p = await authn(request) return await db.write(store.update_prefs, p, await _json_body(request, 64 * 1024), time.time())
@app.get("/v1/principals") async def list_principals(request: Request): p = await authn(request) return {"principals": await with_presence(p, await db.read(store.list_principals, p))}
@app.get("/v1/presence") async def list_presence(request: Request): p = await authn(request) return {"principals": await db.read(store.list_presence, p, board.presence.snapshot())}
@app.patch("/v1/principals/{principal_id}") async def update_principal(principal_id: int, request: Request): p = await authn(request) body = body_dict(await _json_body(request)) result = await db.write(store.update_principal, p, principal_id, body, time.time()) return (await with_presence(p, [result]))[0]
@app.post("/v1/principals/{principal_id}/suspend") async def suspend(principal_id: int, request: Request): p = await authn(request) raw = await request.body() body = body_dict(await _json_body(request)) if raw.strip() else {} return await db.write(store.suspend, p, principal_id, body.get("reason"), time.time())
@app.post("/v1/principals/{principal_id}/unsuspend") async def unsuspend(principal_id: int, request: Request): p = await authn(request) return await db.write(store.unsuspend, p, principal_id, time.time())
@app.get("/v1/suspended") async def list_suspended(request: Request): p = await authn(request) return {"suspended": await db.read(store.list_suspended, p)}
@app.post("/v1/principals/{principal_id}/token") async def rotate_token(principal_id: int, request: Request): p = await authn(request) result = await db.write(store.rotate_agent_token, p, principal_id, time.time()) return JSONResponse(result, status_code=201, headers={"Cache-Control": "no-store"})
@app.post("/v1/principals/{principal_id}/signin-link") async def signin_link(principal_id: int, request: Request): p = await authn(request) result = await db.write(store.create_signin_link, p, principal_id, time.time()) return JSONResponse(result, status_code=201, headers={"Cache-Control": "no-store"})
@app.delete("/v1/tokens/{token_id}") async def revoke_token(token_id: str, request: Request): p = await authn(request) return await db.write(store.revoke_token, p, token_id, time.time())
# ------------------------------------------------- invites and joining
@app.post("/v1/invites") async def create_invite(request: Request): p = await authn(request) body = body_dict(await _json_body(request)) return JSONResponse(await db.write(store.create_invite, p, body, time.time()), status_code=201, headers={"Cache-Control": "no-store"})
@app.get("/v1/invites") async def list_invites(request: Request): p = await authn(request) return {"invites": await db.read(store.list_invites, p, time.time())}
@app.delete("/v1/invites/{invite_id}") async def revoke_invite(invite_id: int, request: Request): p = await authn(request) return await db.write(store.revoke_invite, p, invite_id, time.time())
@app.get("/v1/join/{code}") async def lookup_invite(code: str): return await db.read(store.lookup_invite, code, time.time())
@app.post("/v1/join") async def join(request: Request): body = body_dict(await _json_body(request, 4096)) result = await db.write(store.join, body.get("code"), body.get("name"), body.get("display_name"), time.time()) return JSONResponse(result, status_code=201 if result["created"] else 200, headers={"Cache-Control": "no-store"})
# ------------------------------------------------------------ settings
@app.get("/v1/settings") async def get_settings(request: Request): await authn(request) return await db.read(store.get_settings)
@app.patch("/v1/settings") async def update_settings(request: Request): p = await authn(request) body = body_dict(await _json_body(request)) return await db.write(store.update_settings, p, body, time.time())
# --------------------------------------------------------- channels
@app.get("/v1/channels") async def list_channels(request: Request, name: str | None = None): p = await authn(request) return {"channels": await db.read(store.list_channels, p, name)}
@app.post("/v1/channels") async def create_channel(request: Request): p = await authn(request) body = body_dict(await _json_body(request)) channel, created = await db.write(store.create_channel, p, body.get("name"), body.get("description"), body.get("private", False), time.time()) return JSONResponse(channel, status_code=201 if created else 200)
@app.get("/v1/messages/{message_id}") async def get_message(message_id: int, request: Request): p = await authn(request) return await db.read(store.get_message, p, message_id)
@app.get("/v1/channels/{channel_id}/export") async def export_channel(channel_id: int, request: Request): p = await authn(request) transfer.require_admin(p) manifest, keys = await db.read(transfer.export_manifest, p, channel_id, _origin(request)) scratch = tempfile.TemporaryDirectory(prefix="msgboard-export-") path = Path(scratch.name) / "channel.zip" try: await anyio.to_thread.run_sync(transfer.build_bundle, manifest, keys, board.blobs, path, board.storage) except BaseException: scratch.cleanup() raise return FileResponse(path, media_type="application/zip", filename=f"channel-{channel_id}.zip", background=BackgroundTask(scratch.cleanup))
@app.post("/v1/channels/{channel_id}/import") async def import_channel(channel_id: int, request: Request, dry_run: bool = False, keep_target_doc: bool = False): p = await authn(request, observe=not dry_run) await db.read(transfer.public_channel, p, channel_id) declared = request.headers.get("content-length", "") if declared.isdigit() and int(declared) > transfer.MAX_BUNDLE_BYTES: raise ApiError(413, "too_large", "channel bundle exceeds 512 MiB") with tempfile.TemporaryDirectory(prefix="msgboard-import-") as scratch: path = Path(scratch) / "bundle.zip" with path.open("xb") as fh: size = 0 async for chunk in request.stream(): size += len(chunk) if size > transfer.MAX_BUNDLE_BYTES: raise ApiError(413, "too_large", "channel bundle exceeds 512 MiB") await anyio.to_thread.run_sync(fh.write, chunk) manifest, digest, files = await anyio.to_thread.run_sync(transfer.read_bundle, path, Path(scratch)) if dry_run: report = await db.read(transfer.plan_import, p, channel_id, manifest, digest, keep_target_doc) report = await anyio.to_thread.run_sync(transfer.verify_reused_storage, report, board.storage) else: # A disconnected caller must not remove staged local files while # its publication task is still using them. Retries are idempotent. task = asyncio.create_task(apply_history(p, channel_id, manifest, digest, files, keep_target_doc)) try: report = await asyncio.shield(task) except asyncio.CancelledError: with suppress(Exception): await task raise return {**report, "dry_run": dry_run}
async def apply_history(p, channel_id, manifest, digest, files, keep_target_doc): keys = [("channel", str(channel_id))] + [("author", a["external_id"].lower()) for a in manifest["principals"]] async with board.import_reservations.hold(keys): prepared = await db.write(transfer.prepare_import, p, channel_id, manifest, digest, time.time(), keep_target_doc) paths = [(prepared["people"][f["owner_id"]], f["path"]) for f in manifest["storage_files"]] published = False uploaded_storage, uploaded_attachments = [], [] try: async with board.storage_reservations.hold(paths): try: prepared["report"] = await db.read(transfer.checked_import_plan, p, channel_id, manifest, digest, prepared) await anyio.to_thread.run_sync(transfer.stage_import, channel_id, manifest, files, prepared, board.blobs, board.storage, uploaded_storage, uploaded_attachments) report = await db.write(transfer.import_channel, p, channel_id, manifest, digest, prepared, time.time()) published = True return report finally: if not published: if uploaded_storage: try: await anyio.to_thread.run_sync(board.storage.delete, uploaded_storage) except Exception: logging.getLogger(__name__).exception("could not remove unindexed import files") for key in uploaded_attachments: board.blobs.discard(board.blobs.path_for(key)) finally: if not published: await db.write(transfer.cleanup_ghosts, prepared)
@app.get("/v1/channels/{channel_id}/doc") async def get_doc(channel_id: int, request: Request): p = await authn(request) return await db.read(store.get_doc, p, channel_id)
@app.put("/v1/channels/{channel_id}/doc") async def put_doc(channel_id: int, request: Request): p = await authn(request) doc, changed = await db.write(store.save_doc, p, channel_id, await _json_body(request, store.MAX_DOC_BYTES * 2 + 4096), time.time()) return doc
@app.get("/v1/channels/{channel_id}/doc/versions") async def doc_versions(channel_id: int, request: Request): p = await authn(request) return await db.read(store.doc_versions, p, channel_id)
@app.get("/v1/channels/{channel_id}/doc/versions/{version}") async def doc_version(channel_id: int, version: int, request: Request): p = await authn(request) return await db.read(store.doc_version, p, channel_id, version)
@app.delete("/v1/channels/{channel_id}") async def delete_channel(channel_id: int, request: Request, confirm: str = ""): p = await authn(request) result = await db.write(store.delete_channel, p, channel_id, confirm, time.time()) for key in result.pop("storage_keys"): # the rows are gone; now the files try: board.blobs.path_for(key).unlink() except FileNotFoundError: pass board.notifier.notify(channel_id) return result
@app.get("/v1/channels/{channel_id}/info") async def channel_info(channel_id: int, request: Request): p = await authn(request) result = await db.read(store.channel_info, p, channel_id) result["members"] = await with_presence(p, result["members"]) result["posters"] = await with_presence(p, result["posters"]) return result
@app.patch("/v1/channels/{channel_id}") async def update_channel(channel_id: int, request: Request): p = await authn(request) return await db.write(store.update_channel, p, channel_id, await _json_body(request, 4096), time.time())
@app.post("/v1/channels/{channel_id}/archive") async def archive_channel(channel_id: int, request: Request): p = await authn(request) return await db.write(store.archive_channel, p, channel_id, time.time())
@app.get("/v1/channels/{channel_id}/thread-subscriptions") async def thread_subscriptions(channel_id: int, request: Request, roots: str = Query(..., max_length=4200)): p = await authn(request) try: ids = [int(i) for i in roots.split(",")] except ValueError: raise bad_request("roots must be comma-separated message ids") return await db.read(store.thread_subscriptions, p, channel_id, ids)
@app.get("/v1/channels/{channel_id}/threads/{thread_id}/subscription") async def thread_subscription(channel_id: int, thread_id: int, request: Request): p = await authn(request) return await db.read(store.thread_subscription, p, channel_id, thread_id)
@app.put("/v1/channels/{channel_id}/threads/{thread_id}/subscription") async def set_thread_subscription(channel_id: int, thread_id: int, request: Request): p = await authn(request) return await db.write(store.set_thread_subscription, p, channel_id, thread_id, await _json_body(request, 1024), time.time())
@app.post("/v1/channels/{channel_id}/threads/{thread_id}/read") async def mark_thread_read(channel_id: int, thread_id: int, request: Request): p = await authn(request) body = body_dict(await _json_body(request, 1024)) return await db.write(store.mark_thread_read, p, channel_id, thread_id, body.get("seq"), time.time())
@app.post("/v1/channels/{channel_id}/read") async def mark_read(channel_id: int, request: Request): p = await authn(request) body = body_dict(await _json_body(request, 1024)) return await db.write(store.mark_read, p, channel_id, body.get("seq"), time.time())
@app.get("/v1/activity") async def get_activity(request: Request, limit: int = Query(50, ge=1, le=200), after: int | None = Query(None, ge=0), wait: float = Query(0, ge=0, le=LIMITS.max_wait_seconds), channels: str | None = None, reactions: bool = False, unread: bool = False): """Everything for you (mentions, replies, DMs, plus `channels` you follow). With `after`, a cursor read, oldest first; add `wait` to long-poll it. `unread=true` (without `after`): only what you have not read yet, however old.""" p = await authn(request) parts = [x.strip() for x in channels.split(",") if x.strip()] if channels else [] joined = "joined" in parts # every channel you are a member of try: follow = [int(x) for x in parts if x != "joined"] except ValueError: raise bad_request("channels must be comma-separated channel ids, or `joined`") if joined: follow += await db.read(store.joined_channel_ids, p) if len(follow) > 100: raise bad_request("follow at most 100 channels") if unread and after is not None: raise bad_request("unread lists what you have not read yet: it takes no `after` cursor") if wait > 0 and after is None: raise bad_request("wait needs a cursor: pass `after` (start from the next_cursor of a plain read)") token = board.presence.next_poll() polled_at = time.time() mode = "joined" if joined else ("channels" if follow else "addressed")
def observe(result): board.presence.polled(p, token, polled_at, after, mode, follow, bool(result["messages"]))
if wait <= 0: result = await db.read(store.activity, p, limit, after, follow, reactions, unread) observe(result) return result if board.open_polls >= LIMITS.max_open_polls: raise ApiError(429, "too_many_polls", "too many open long-polls", {"Retry-After": "1"}) board.open_polls += 1 board.counters["polls"] += 1 fut = board.notifier.register(ANY_CHANNEL) try: result = await db.read(store.activity, p, limit, after, follow) observe(result) if result["messages"] or board.shutting_down: return result deadline = time.monotonic() + wait while True: # any post wakes us; keep waiting until one is actually for this caller left = deadline - time.monotonic() if left <= 0: break done, _ = await asyncio.wait({fut}, timeout=left) if done and not board.shutting_down: # let a burst of posts land, then answer them with one query instead of one per post await asyncio.sleep(min(LIMITS.poll_coalesce_seconds * (0.75 + random.random() / 2), max(0.0, deadline - time.monotonic()))) if await request.is_disconnected(): return result board.notifier.unregister(ANY_CHANNEL, fut) fut = board.notifier.register(ANY_CHANNEL) p = await authn(request, observe=False) after = result["next_cursor"] # previous query exhausted the older history result = await db.read(store.activity, p, limit, after, follow, shed=False) board.presence.observed(p, token, bool(result["messages"]), time.time()) if result["messages"] or board.shutting_down: return result return result finally: board.notifier.unregister(ANY_CHANNEL, fut) board.open_polls -= 1
@app.get("/v1/search") async def search(request: Request, q: str = "", channel: int | None = None, sender: int | None = None, after: str | None = None, before: str | None = None, sort: str = "newest", limit: int = Query(20, ge=1, le=100), offset: int = Query(0, ge=0, le=10_000)): """Full-text search over messages you can read, plus matching channel and people names. `q` takes words, "phrases" and filters: from:@name in:#channel after:/before:/on:DATE has:file ...""" p = await authn(request) if len(q) > 500: raise bad_request("q is at most 500 characters") return await db.read(lambda conn: store.search(conn, p, q, channel_id=channel, sender_id=sender, after=after, before=before, sort=sort, limit=limit, offset=offset, now=time.time()))
@app.get("/v1/analytics") async def get_analytics(request: Request, days: int = Query(7, ge=1, le=365), start: float | None = Query(None, alias="from"), end: float | None = Query(None, alias="to"), top_k: int = Query(10, ge=1, le=100)): p = await authn(request) result = await db.read(store.analytics, p, time.time(), days, start, end, top_k, board.presence.pending_history()) result["listening"]["now"] = board.presence.listening_now(time.time()) result["health"] = health_summary() return result
def _origin(request: Request) -> str: proto = request.headers.get("x-forwarded-proto") or request.url.scheme host = request.headers.get("x-forwarded-host") or request.headers.get("host") or request.url.netloc return f"{proto}://{host}{request.scope.get('root_path', '')}"
@app.get("/agents", include_in_schema=False) async def agents_guide(request: Request): return PlainTextResponse(guide.render(_origin(request), public=True), media_type="text/markdown; charset=utf-8")
@app.get("/v1/guide") async def get_guide(request: Request): await authn(request) settings = await db.read(store.get_settings) return PlainTextResponse(guide.render(_origin(request), settings["guidelines"], docs=settings["channel_docs"]), media_type="text/markdown; charset=utf-8")
@app.get("/v1/channels/{channel_id}/members") async def list_members(channel_id: int, request: Request): p = await authn(request) return {"members": await with_presence(p, await db.read(store.list_members, p, channel_id))}
@app.get("/v1/channels/{channel_id}/mention-candidates") async def mention_candidates(channel_id: int, request: Request): p = await authn(request) return {"candidates": await db.read(store.mention_candidates, p, channel_id)}
@app.post("/v1/channels/{channel_id}/members") async def add_member(channel_id: int, request: Request): p = await authn(request) body = body_dict(await _json_body(request)) members = await db.write(store.add_member, p, channel_id, body.get("principal_id"), time.time()) return {"members": await with_presence(p, members)}
@app.delete("/v1/channels/{channel_id}/members/{principal_id}") async def remove_member(channel_id: int, principal_id: int, request: Request): p = await authn(request) result = await db.write(store.remove_member, p, channel_id, principal_id, time.time()) return result if isinstance(result, dict) else {"members": await with_presence(p, result)}
@app.post("/v1/dms") async def open_dm(request: Request): p = await authn(request) body = body_dict(await _json_body(request)) channel, created = await db.write(store.open_dm, p, body.get("with"), time.time()) return JSONResponse(channel, status_code=201 if created else 200)
# --------------------------------------------------------- messages
@app.get("/v1/tasks") async def get_tasks(request: Request, archived: bool = False, sort: str = "manual", direction: str = "asc"): p = await authn(request) return await db.read(personal_tasks.list_items, p, archived, sort, direction)
@app.get("/v1/tasks/items/{item_id}") async def get_task(item_id: int, request: Request): p = await authn(request) return await db.read(personal_tasks.get_item, p, item_id)
@app.get("/v1/tasks/unread") async def unread_tasks(request: Request): return await db.read(personal_tasks.unread, await authn(request))
@app.post("/v1/tasks/read") async def read_tasks(request: Request): p = await authn(request) return await db.write(personal_tasks.mark_read, p, body_dict(await _json_body(request)), time.time())
@app.put("/v1/tasks/items/by-key/{key}") async def put_task(key: str, request: Request): p = await authn(request) payload = body_dict(await _json_body(request)) return await db.write(personal_tasks.put_item, p, key, payload, time.time())
@app.post("/v1/tasks/items/{item_id}/actions") async def task_action(item_id: int, request: Request): p = await authn(request) key = request.headers.get("idempotency-key") if not key or not store.CLIENT_ID.fullmatch(key): raise bad_request("Idempotency-Key header is required and must match " + store.CLIENT_ID.pattern) payload = body_dict(await _json_body(request, LIMITS.max_body_bytes * 2 + 64 * 1024)) result, message, replayed = await db.write(personal_tasks.action, p, item_id, payload, key, time.time()) if message: board.counters["posts"] += 1 board.notifier.notify(message["channel_id"]) board.notifier.notify(ANY_CHANNEL) return JSONResponse(result, headers={"Idempotent-Replayed": "true"} if replayed else None)
@app.post("/v1/tasks/items/{item_id}/move") async def move_task(item_id: int, request: Request): p = await authn(request) return await db.write(personal_tasks.move_item, p, item_id, body_dict(await _json_body(request)), time.time())
@app.post("/v1/channels/{channel_id}/messages") async def post_message(channel_id: int, request: Request): p = await authn(request) request_id = request.headers.get("idempotency-key") if not request_id or not store.CLIENT_ID.match(request_id): raise bad_request("Idempotency-Key header is required and must match " + store.CLIENT_ID.pattern) payload = await _json_body(request, LIMITS.max_body_bytes * 2 + 64 * 1024) normalized, digest = store.normalize_payload(channel_id, payload) message, created = await db.write( store.post_message, p, channel_id, request_id, normalized, digest, time.time()) if created: board.counters["posts"] += 1 board.notifier.notify(channel_id) board.notifier.notify(ANY_CHANNEL) return JSONResponse(message, status_code=201) board.counters["posts_replayed"] += 1 return JSONResponse(message, status_code=200, headers={"Idempotent-Replayed": "true"})
@app.patch("/v1/channels/{channel_id}/messages/{message_id}") async def edit_message(channel_id: int, message_id: int, request: Request): p = await authn(request) payload = await _json_body(request, LIMITS.max_body_bytes * 2 + 1024) message, changed = await db.write(store.edit_message, p, channel_id, message_id, payload, time.time()) if changed: board.counters["edits"] += 1 board.notifier.notify(channel_id) return message
@app.put("/v1/channels/{channel_id}/messages/{message_id}/reactions/{emoji}") async def add_reaction(channel_id: int, message_id: int, emoji: str, request: Request): p = await authn(request) message, changed = await db.write(store.react, p, channel_id, message_id, unquote(emoji), True, time.time()) if changed: board.notifier.notify(channel_id) return message
@app.delete("/v1/channels/{channel_id}/messages/{message_id}/reactions/{emoji}") async def remove_reaction(channel_id: int, message_id: int, emoji: str, request: Request): p = await authn(request) message, changed = await db.write(store.react, p, channel_id, message_id, unquote(emoji), False, time.time()) if changed: board.notifier.notify(channel_id) return message
@app.delete("/v1/channels/{channel_id}/messages/{message_id}") async def delete_message(channel_id: int, message_id: int, request: Request): p = await authn(request) result = await db.write(store.delete_message, p, channel_id, message_id, time.time()) for key in result.pop("storage_keys"): try: board.blobs.path_for(key).unlink() except FileNotFoundError: pass board.notifier.notify(channel_id) return result
@app.get("/v1/channels/{channel_id}/messages/{message_id}/revisions") async def message_revisions(channel_id: int, message_id: int, request: Request): p = await authn(request) return await db.read(store.message_revisions, p, channel_id, message_id)
@app.get("/v1/channels/{channel_id}/messages") async def read_messages( channel_id: int, request: Request, after: int = Query(0, ge=0), limit: int = Query(LIMITS.default_page_size, ge=1, le=LIMITS.max_page_size), wait: float = Query(0, ge=0, le=LIMITS.max_wait_seconds), before: int | None = Query(None, ge=1), top_level: bool = False, thread: int | None = Query(None, ge=1), edits_after: int | None = Query(None, ge=0), ): p = await authn(request) if before is not None or top_level or thread is not None: if wait > 0 or edits_after is not None: raise bad_request("wait and edits_after only work with plain `after` reads") return await db.read(store.read_messages, p, channel_id, after, limit, before, top_level, thread)
async def page(p): result = await db.read(store.read_messages, p, channel_id, after, limit) if edits_after is not None: # also hand back messages edited since this edit cursor result.update(await db.read(store.read_edits, p, channel_id, edits_after, limit)) return result
if wait <= 0: return await page(p) if board.open_polls >= LIMITS.max_open_polls: raise ApiError(429, "too_many_polls", "too many open long-polls", {"Retry-After": "1"}) board.open_polls += 1 board.counters["polls"] += 1 # Register before checking history so a commit between the query and # the wait cannot be missed. fut = board.notifier.register(channel_id) try: result = await page(p) if result["messages"] or result.get("edits") or board.shutting_down: return result await asyncio.wait({fut}, timeout=wait) # Re-authenticate and re-authorize: the token may have been revoked # or the grant removed while this request was held. p = await authn(request) return await page(p) finally: board.notifier.unregister(channel_id, fut) board.open_polls -= 1
# ------------------------------------------------- profiles, invites
@app.get("/v1/principals/{principal_id}/profile") async def get_profile(principal_id: int, request: Request): p = await authn(request) result = await db.read(store.profile, p, principal_id, time.time()) result = (await with_presence(p, [result]))[0] result["agents"] = await with_presence(p, result["agents"]) return result
@app.put("/v1/principals/{principal_id}/avatar") async def put_avatar(principal_id: int, request: Request): p = await authn(request) data = bytearray() async for chunk in request.stream(): data += chunk if len(data) > LIMITS.max_avatar_bytes: raise ApiError(413, "too_large", f"pictures are limited to {LIMITS.max_avatar_bytes // 1024} KB") return await db.write(store.set_avatar, p, principal_id, bytes(data), time.time())
@app.delete("/v1/principals/{principal_id}/avatar") async def delete_avatar(principal_id: int, request: Request): p = await authn(request) return await db.write(store.delete_avatar, p, principal_id, time.time())
@app.put("/v1/principals/{principal_id}/pattern") async def put_pattern(principal_id: int, request: Request): p = await authn(request) body = await _json_body(request, 1024) seed = body.get("seed") if isinstance(body, dict) else None return await db.write(store.set_pattern, p, principal_id, seed, time.time())
@app.get("/v1/principals/{principal_id}/avatar") async def get_avatar(principal_id: int, request: Request): await authn(request) # any member of the board may see pictures ctype, data, digest = await db.read(store.get_avatar, principal_id) return Response(data, media_type=ctype, headers={ "ETag": f'"{digest[:16]}"', "Cache-Control": "private, max-age=86400", "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'"})
# ------------------------------------------------------ attachments
@app.put("/v1/channels/{channel_id}/attachments/{upload_id}") async def upload(channel_id: int, upload_id: str, request: Request): p = await authn(request) declared = request.headers.get("content-length") if declared and declared.isdigit() and int(declared) > LIMITS.max_upload_bytes: raise ApiError(413, "too_large", f"uploads are limited to {LIMITS.max_upload_bytes} bytes") if board.open_uploads >= LIMITS.max_concurrent_uploads: raise ApiError(429, "too_many_uploads", "too many concurrent uploads", {"Retry-After": "1"}) # Browsers can only send ASCII headers, so the filename may be percent-encoded. filename = os.path.basename(unquote(request.headers.get("x-filename", "")))[:255] or None if filename and any(ord(ch) < 32 for ch in filename): raise bad_request("invalid filename") content_type = request.headers.get("content-type", "application/octet-stream")[:128] board.open_uploads += 1 tmp_path = None try: row = await db.write(store.begin_upload, p, channel_id, upload_id, filename, content_type, time.time()) tmp_path, fh = await anyio.to_thread.run_sync(board.blobs.open_temp) hasher, size = new_hasher(), 0 try: async for chunk in request.stream(): size += len(chunk) if size > LIMITS.max_upload_bytes: raise ApiError(413, "too_large", f"uploads are limited to {LIMITS.max_upload_bytes} bytes") hasher.update(chunk) await anyio.to_thread.run_sync(fh.write, chunk) await anyio.to_thread.run_sync(board.blobs.finish_temp, fh) finally: if not fh.closed: fh.close() digest = hasher.hexdigest() expected = request.headers.get("x-checksum-sha256") if expected and expected.lower() != digest: raise bad_request("X-Checksum-Sha256 does not match the uploaded content") async with board.commit_lock: current = await db.read(store.attachment_state, row["id"]) if current["state"] == "ready": result = await db.write(store.finish_upload, row["id"], size, digest) return JSONResponse(result, status_code=200) await anyio.to_thread.run_sync(board.blobs.commit, tmp_path, row["storage_key"]) tmp_path = None result = await db.write(store.finish_upload, row["id"], size, digest) return JSONResponse(result, status_code=201) finally: board.open_uploads -= 1 if tmp_path is not None: board.blobs.discard(tmp_path)
@app.get("/v1/attachments/{att_id}/info") async def attachment_info(att_id: str, request: Request): p = await authn(request) info = await db.read(store.get_attachment, p, att_id) info.pop("storage_key") return info
@app.get("/v1/attachments/{att_id}") async def download(att_id: str, request: Request): p = await authn(request) return await attachment_file(p, att_id)
async def attachment_file(p, att_id: str): info = await db.read(store.get_attachment, p, att_id) return FileResponse( board.blobs.path_for(info["storage_key"]), media_type="application/octet-stream", filename=info["filename"] or att_id, headers={ "X-Checksum-Sha256": info["sha256"], "X-Content-Type-Options": "nosniff", "X-Upload-Content-Type": info["content_type"] or "application/octet-stream", }, )
# ------------------------------------------------------------------ storage folders
def _cache_put(src: Path, sha: str) -> Path: dest = board.storage_cache / sha os.replace(src, dest) files = sorted(board.storage_cache.iterdir(), key=lambda f: f.stat().st_atime) total = sum(f.stat().st_size for f in files) for f in files: # keep the cache under its size, oldest first if total <= LIMITS.storage_cache_bytes or f == dest: continue total -= f.stat().st_size f.unlink(missing_ok=True) return dest
@app.put("/v1/storage/{handle}/{path:path}") async def storage_put(handle: str, path: str, request: Request): p = await authn(request) owner = await db.read(store.storage_owner, p, handle, True) path = store.storage_path(path) declared = request.headers.get("content-length") if declared and declared.isdigit(): await db.read(store.storage_check_quota, owner["id"], path, int(declared)) content_type = (request.headers.get("content-type") or mimetypes.guess_type(path)[0] or "application/octet-stream")[:128] tmp_path, fh = await anyio.to_thread.run_sync(board.blobs.open_temp) try: hasher, size = new_hasher(), 0 try: max_file = (await db.read(store.storage_limits))[0] async for chunk in request.stream(): size += len(chunk) if size > max_file: raise ApiError(413, "too_large", f"files are limited to {store._mb(max_file)} on this board") hasher.update(chunk) await anyio.to_thread.run_sync(fh.write, chunk) await anyio.to_thread.run_sync(board.blobs.finish_temp, fh) finally: if not fh.closed: fh.close() digest = hasher.hexdigest() expected = request.headers.get("x-checksum-sha256") if expected and expected.lower() != digest: raise bad_request("X-Checksum-Sha256 does not match the uploaded content") task = asyncio.create_task(publish_storage(p, owner, path, size, digest, content_type, tmp_path)) try: result = await asyncio.shield(task) except asyncio.CancelledError: with suppress(Exception): await task raise tmp_path = None return JSONResponse(result, status_code=201) finally: if tmp_path is not None: board.blobs.discard(tmp_path)
async def publish_storage(p, owner, path, size, digest, content_type, tmp_path): async with board.storage_reservations.hold([(owner["id"], path)]): await db.read(store.storage_check_quota, owner["id"], path, size) key = store.storage_key(owner["id"], path) # Replacing a file needs a rollback copy in case the final quota # check loses to an unrelated upload. This I/O holds only its path. try: await db.read(store.storage_lookup, p, owner["external_id"], path) replacing = True except ApiError as exc: if exc.status != 404: raise replacing = False with tempfile.TemporaryDirectory(prefix="msgboard-replace-") as scratch: backup = Path(scratch) / "old" backed_up = replacing and await anyio.to_thread.run_sync(board.storage.get, key, backup) changed = recorded = False try: changed = True await anyio.to_thread.run_sync(lambda: board.storage.put([(tmp_path, key)])) await anyio.to_thread.run_sync(_cache_put, tmp_path, digest) result = await db.write(store.storage_record_checked, p, owner["id"], path, size, digest, content_type, time.time()) recorded = True return result finally: if changed and not recorded: if backed_up: await anyio.to_thread.run_sync(lambda: board.storage.put([(backup, key)])) else: await anyio.to_thread.run_sync(board.storage.delete, [key])
@app.get("/v1/storage/{handle}") async def storage_root(handle: str, request: Request, prefix: str = ""): p = await authn(request) return await db.read(store.storage_list, p, handle, prefix)
@app.get("/v1/storage/{handle}/{path:path}") async def storage_get(handle: str, path: str, request: Request, info: bool = False): p = await authn(request) return await storage_file(p, handle, path, info)
async def storage_file(p, handle: str, path: str, info: bool = False): if path.endswith("/"): # a folder: list it return await db.read(store.storage_list, p, handle, path) meta, key = await db.read(store.storage_lookup, p, handle, path) if info: return meta cached = board.storage_cache / meta["sha256"] if not cached.exists(): owner = await db.read(store.storage_owner, p, handle, False, store.storage_path(path)) async with board.storage_reservations.hold([(owner["id"], store.storage_path(path))]): # A replacement may have completed while we waited. Read its # current metadata, never old metadata with newly uploaded bytes. meta, key = await db.read(store.storage_lookup, p, handle, path) cached = board.storage_cache / meta["sha256"] if not cached.exists(): fd, name = tempfile.mkstemp(prefix=".storage-", suffix=".part", dir=board.storage_cache) os.close(fd) tmp = Path(name) try: ok = await anyio.to_thread.run_sync(board.storage.get, key, tmp) if not ok: raise ApiError(503, "storage_unavailable", "the file is listed but could not be fetched from storage; try again") # the cache is named by the recorded hash, so only bytes with that hash may go in it: # a storage object overwritten behind the database (e.g. a mismatched restore) is never served h = new_hasher() with tmp.open("rb") as fh: for chunk in iter(lambda: fh.read(1 << 20), b""): h.update(chunk) if h.hexdigest() != meta["sha256"]: raise ApiError(409, "storage_mismatch", "the stored bytes do not match this file's recorded checksum") os.replace(tmp, cached) finally: tmp.unlink(missing_ok=True) # always a download: never let stored HTML or SVG run on the board's own origin return FileResponse(cached, media_type="application/octet-stream", filename=os.path.basename(meta["path"]), headers={"X-Checksum-Sha256": meta["sha256"], "X-Content-Type-Options": "nosniff", "X-Upload-Content-Type": meta["content_type"] or "application/octet-stream", "Content-Security-Policy": "sandbox", "Cache-Control": "private, no-cache"})
async def download_file(p, file_id: str): if file_id.startswith("storage:"): parts = file_id[8:].split("/", 1) if len(parts) != 2 or not parts[1] or parts[1].endswith("/"): raise bad_request("choose a file, not a storage folder") return await storage_file(p, parts[0], parts[1]) return await attachment_file(p, file_id)
@app.post("/v1/downloads") async def prepare_download(request: Request): p = await authn(request) body = body_dict(await _json_body(request, max_bytes=4096)) file_id = body.get("file_id") if not isinstance(file_id, str) or not file_id or len(file_id) > 1024: raise bad_request("file_id must name an attachment or storage file") # Resolve permissions and fill/verify the storage cache before handing off. No file bytes in this JSON. response = await download_file(p, file_id) if not await anyio.to_thread.run_sync(Path(response.path).is_file): raise ApiError(404, "not_found", "this file is no longer available") key = download_links.issue(p.id, _bearer(request), file_id, response.headers["X-Checksum-Sha256"]) return JSONResponse({"url": f"v1/downloads/{key}", "filename": response.filename, "expires_in": DOWNLOAD_TTL_SECONDS}, headers={"Cache-Control": "no-store"})
@app.api_route("/v1/downloads/{key}", methods=["GET", "HEAD"]) async def browser_download(key: str): link = download_links.get(key) # A capability authorizes only its file/version. Recheck revocation, suspension, ownership and file ACLs. p = await db.read(store.authenticate, link.token, time.time()) if p.id != link.principal_id: raise ApiError(404, "download_expired", "download link expired; click Download again") board.presence.seen(p, time.time()) response = await download_file(p, link.file_id) if response.headers["X-Checksum-Sha256"] != link.sha256: raise ApiError(409, "download_changed", "this file changed; click Download again") response.headers.update({"Cache-Control": "private, no-store", "Referrer-Policy": "no-referrer", "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "sandbox"}) return response
@app.delete("/v1/storage/{handle}/{path:path}") async def storage_delete(handle: str, path: str, request: Request): p = await authn(request) owner = await db.read(store.storage_owner, p, handle, True) path = store.storage_path(path) async with board.storage_reservations.hold([(owner["id"], path)]): out = await db.write(store.storage_remove, p, handle, path, time.time()) keys = out.pop("keys") await anyio.to_thread.run_sync(lambda: board.storage.delete(keys)) return out
if dashboard: page = Path(__file__).with_name("dashboard.html")
@app.get("/", include_in_schema=False) async def dashboard_page(): return FileResponse(page, media_type="text/html", headers={"Cache-Control": "no-cache", "X-Content-Type-Options": "nosniff"})
return app12345678910"""msgboard on a Hugging Face Space.
- `deploy()` creates or updates a board Space and its private bucket (`hub.py`).- `app.py` is what the Space runs; `accounts.py` adds invite links and "Sign in with Hugging Face".- `Dockerfile` and `README.md` (the Space card) are uploaded with the package."""
from .hub import Deployment, DeployError, deploy
__all__ = ["Deployment", "DeployError", "deploy"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250"""Optional Hugging Face accounts for the msgboard Space.
People join with invite links: with a username they pick, or with "Join withHugging Face", which uses their HF username, name and picture and links the account.Once linked (at join or later from their profile), "Sign in with Hugging Face"gives them a token on any device. HF sign-in never creates an account without an invite."""
import hashlibimport htmlimport jsonimport osimport secretsimport timefrom urllib.parse import urlencode
import httpxfrom fastapi import FastAPI, Requestfrom fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from msgboard import storefrom msgboard.errors import ApiErrorfrom msgboard.server import Board
_transport = None # tests inject a fake OAuth provider here
def _page(title: str, body: str, status: int = 200) -> HTMLResponse: return HTMLResponse( f"""<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>{html.escape(title)}</title><body style="font:15px/1.6 -apple-system,Helvetica,Arial,sans-serif;max-width:440px;margin:18vh auto;padding:0 16px;background:#fafaf8;color:#111"><div style="border-top:2px solid #111;padding-top:16px"><div style="font:10.5px ui-monospace,Menlo,monospace;letter-spacing:.08em;text-transform:uppercase;color:#8a8a86">msgboard</div><h1 style="font-size:24px;margin:2px 0 10px">{html.escape(title)}</h1>{body}</div></body>""", status_code=status, headers={"Cache-Control": "no-store"})
def import_shared_invite(board: Board, code: str, operator_token: str): """Keep an invite code from the MSGBOARD_INVITE_CODE secret working as a normal member invite.""" def run(conn): digest = hashlib.sha256(code.encode()).digest() if conn.execute("SELECT 1 FROM invites WHERE code_hash = ?", (digest,)).fetchone(): return op = store.authenticate(conn, operator_token, time.time()) conn.execute("""INSERT INTO invites (code_hash, created_by, created_at, kind, role, identity_type, label) VALUES (?, ?, ?, 'human', 'member', 'user', 'shared link (MSGBOARD_INVITE_CODE)')""", (digest, op.id, time.time())) return board.db.write(run)
HF_API = os.environ.get("MSGBOARD_HF_API", "https://huggingface.co").rstrip("/")
def join_with_hf(conn, code, name, display_name, username: str, now: float) -> dict: """Redeem a people invite and link the HF account in one go; nothing is kept if either fails.""" row = store._find_invite(conn, code) if row is not None and row["kind"] != "human": raise ApiError(400, "invalid_request", "only invites for people can be used with Hugging Face") result = store.join(conn, code, name, display_name, now) store.set_hf_username(conn, result["principal"]["id"], username, now) result["principal"]["hf_username"] = username return result
async def adopt_hf_picture(board: Board, principal_id: int, username: str) -> bool: """Use the Hugging Face profile picture as this account's picture, unless it already has one (an uploaded picture always wins). Best effort: any failure just keeps the generated pattern.""" has = await board.db.read(lambda conn: conn.execute( "SELECT 1 FROM avatars WHERE principal_id = ?", (principal_id,)).fetchone() is not None) if has: return False try: async with httpx.AsyncClient(timeout=15, transport=_transport, follow_redirects=True) as http: url = (await http.get(f"{HF_API}/api/users/{username}/overview")).json().get("avatarUrl") if not url: return False if url.startswith("/"): url = HF_API + url data = (await http.get(url)).content def run(conn): if conn.execute("SELECT 1 FROM avatars WHERE principal_id = ?", (principal_id,)).fetchone(): return False # someone uploaded one meanwhile me = store._principal_obj(store._principal_row(conn, principal_id)) store.set_avatar(conn, me, principal_id, data, time.time()) return True return await board.db.write(run) except Exception: return False # SVG default avatars, too large, network errors
async def adopt_hf_pictures(board: Board) -> int: """Once at startup: linked accounts without a picture get their Hugging Face one.""" rows = await board.db.read(lambda conn: conn.execute( """SELECT p.id, p.hf_username FROM principals p LEFT JOIN avatars a ON a.principal_id = p.id WHERE p.hf_username IS NOT NULL AND p.disabled = 0 AND a.principal_id IS NULL""").fetchall()) n = 0 for pid, username in rows: n += await adopt_hf_picture(board, pid, username) return n
def install(app: FastAPI, board: Board) -> None: provider = os.environ.get("OPENID_PROVIDER_URL", "https://huggingface.co").rstrip("/") client_id = os.environ.get("OAUTH_CLIENT_ID") client_secret = os.environ.get("OAUTH_CLIENT_SECRET") host = os.environ.get("SPACE_HOST") enabled = bool(client_id and client_secret and host) redirect_uri = f"https://{host}/login/callback" pending: dict[str, tuple] = {} # state -> (created, mode, principal to link or invite code) # ticket -> (created, invite code, HF username, HF name): an HF join whose username was taken here tickets: dict[str, tuple[float, str, str, str | None]] = {}
def prune(entries: dict) -> None: now = time.time() for s, entry in list(entries.items()): if now - entry[0] > 600: del entries[s] if len(entries) > 5000: raise ApiError(429, "busy", "too many sign-ins in progress; try again shortly")
def start(mode: str, target: int | str | None) -> str: prune(pending) state = secrets.token_urlsafe(24) pending[state] = (time.time(), mode, target) return f"{provider}/oauth/authorize?" + urlencode({ "client_id": client_id, "redirect_uri": redirect_uri, "scope": "openid profile", "state": state, "response_type": "code"})
@app.get("/auth/config") async def auth_config(): return {"hf_login": enabled}
@app.get("/login") async def login(invite: str | None = None): if not enabled: return _page("Hugging Face sign-in is not set up", "<p>Use an invite link or a token.</p>", 404) return RedirectResponse(start("join", invite) if invite else start("signin", None))
@app.post("/v1/join/hf") async def join_after_name_taken(request: Request): """Finish an HF join with a name the person picked, because their HF username was taken here.""" body = await request.json() if not isinstance(body, dict): raise ApiError(400, "invalid_request", "expected a JSON object") ticket = body.get("ticket") if isinstance(body.get("ticket"), str) else "" entry = tickets.pop(ticket, None) if entry is None or time.time() - entry[0] > 600: raise ApiError(410, "hf_join_expired", "the Hugging Face sign-in expired; join with Hugging Face again") _, code, username, hf_name = entry try: result = await board.db.write(join_with_hf, code, body.get("name"), body.get("display_name") or hf_name, username, time.time()) except ApiError as exc: if exc.status in (400, 409) and exc.code != "hf_linked_elsewhere": tickets[ticket] = entry # let them try another name raise await adopt_hf_picture(board, result["principal"]["id"], username) return JSONResponse(result, status_code=201, headers={"Cache-Control": "no-store"})
@app.post("/v1/me/hf-link") async def link_start(request: Request): p = await board.db.read(store.authenticate, _token(request), time.time()) if not enabled: raise ApiError(404, "not_enabled", "Hugging Face sign-in is not set up on this board") if not p.is_human: raise ApiError(400, "invalid_request", "only people can link a Hugging Face account") return {"url": start("link", p.id)}
@app.delete("/v1/me/hf-link") async def unlink(request: Request): p = await board.db.read(store.authenticate, _token(request), time.time()) await board.db.write(store.set_hf_username, p.id, None, time.time()) return {"hf_username": None}
async def hf_join(code: str, username: str, hf_name: str | None) -> dict | str: """Sign in if this HF account is linked already (the invite stays unused), else join with it. Returns the join result, or where to send the person to pick another name.""" try: return await board.db.write(store.sign_in_with_hf, username, time.time()) except ApiError as exc: if exc.status != 404: raise display = hf_name.strip()[:128] if isinstance(hf_name, str) and hf_name.strip() else None try: return await board.db.write(join_with_hf, code, username, display, username, time.time()) except ApiError as exc: if exc.code != "name_taken": raise prune(tickets) ticket = secrets.token_urlsafe(24) tickets[ticket] = (time.time(), code, username, display) return "/?" + urlencode({"invite": code, "hf": ticket, "hf_user": username})
@app.get("/login/callback") async def callback(request: Request): entry = pending.pop(request.query_params.get("state", ""), None) if entry is None or time.time() - entry[0] > 600: return _page("Sign-in expired", '<p>Please <a href="/">start again</a>.</p>', 400) code = request.query_params.get("code") if not code: return _page("Sign-in cancelled", '<p><a href="/">Back to the board</a></p>', 400) async with httpx.AsyncClient(timeout=20, transport=_transport) as http: tok = await http.post(f"{provider}/oauth/token", auth=(client_id, client_secret), data={ "grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri, "client_id": client_id}) if tok.status_code != 200: return _page("Sign-in failed", "<p>Hugging Face did not accept the sign-in. Please try again.</p>", 502) info = (await http.get(f"{provider}/oauth/userinfo", headers={"Authorization": f"Bearer {tok.json()['access_token']}"})).json() username = info.get("preferred_username") if not username: return _page("Sign-in failed", "<p>No username in the Hugging Face profile.</p>", 502) _, mode, target = entry try: if mode == "link": await board.db.write(store.set_hf_username, target, username, time.time()) await adopt_hf_picture(board, target, username) return _page("Hugging Face account linked", f"<p>You can now sign in as <b>@{html.escape(username)}</b> on any device.</p>" '<p><a href="/">Back to the board</a></p>') if mode == "join": result = await hf_join(target, username, info.get("name")) if isinstance(result, str): return RedirectResponse(result, status_code=303) else: result = await board.db.write(store.sign_in_with_hf, username, time.time()) if result.get("principal", {}).get("id"): await adopt_hf_picture(board, result["principal"]["id"], username) except ApiError as exc: if exc.status == 404 and mode != "join": return _page("No account linked", f"<p>No board account is linked to <b>@{html.escape(username)}</b>.</p>" "<p>Join with an invite link first, then link your Hugging Face account from your " "profile.</p>", 404) return _page("Sign-in failed", f"<p>{html.escape(exc.message)}</p>", exc.status) payload = json.dumps(result["token"]).replace("<", "\\u003c") return HTMLResponse(f"""<!doctype html><meta charset="utf-8"><title>Signed in</title><script>try {{ localStorage.setItem("msgboard:token", {payload}); }} catch (e) {{}}location.replace("/");</script><p>Signed in. <a href="/">Open the board</a>.</p>""", headers={"Cache-Control": "no-store"})
def _token(request: Request) -> str | None: direct = request.headers.get("x-msgboard-token") if direct: return direct.strip() scheme, _, value = request.headers.get("authorization", "").partition(" ") return value.strip() if scheme.lower() == "bearer" else None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190"""msgboard on a Hugging Face Space: local SQLite, snapshots to an HF bucket, dashboard at /.
Environment (Space secrets/variables): MSGBOARD_OPERATOR_TOKEN secret; the operator (admin) board token HF_TOKEN secret; write access to the replica bucket MSGBOARD_REPLICA hf://buckets/<ns>/<bucket>[/<prefix>] MSGBOARD_SNAPSHOT_INTERVAL seconds between snapshots (default 15) MSGBOARD_INVITE_CODE optional secret; kept working as a standing member invite link MSGBOARD_DEMO_BOTS "1" to run the demo's bots (hfspace/demo_bots.py, uploaded by hfspace/deploy.py)
The Space runs `python -m msgboard.space.app`; msgboard.space.deploy() uploads this package to it.
Restarts overlap on Spaces: the new container starts before the old one getsSIGTERM. So this app opens its port at once but answers 503 (Retry-After) untilthe old container has pushed its final snapshot and released the lease. Onlythen does it restore and serve. Clients retry with the same request IDs."""
import asyncioimport hashlibimport jsonimport loggingimport osimport signalimport threadingimport timefrom pathlib import Path
import uvicorn
from msgboard import auth, db, storefrom msgboard.replicate import Replicator, restore, store_from_url, wait_for_releasefrom msgboard.server import Board, create_app
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s")logging.getLogger("httpx").setLevel(logging.WARNING)logging.getLogger("httpx2").setLevel(logging.WARNING)log = logging.getLogger("msgboard.space")
DATA_DIR = Path(os.environ.get("MSGBOARD_DATA_DIR", "/home/user/board-data"))PAGE = Path(__file__).resolve().parents[1] / "dashboard.html"
def ensure_board(data_dir: Path, operator_token: str) -> None: """Create the schema if needed and make the operator credential equal the Space secret.""" parsed = auth.parse_token(operator_token) if parsed is None: raise SystemExit("MSGBOARD_OPERATOR_TOKEN is not a valid board token") data_dir.mkdir(parents=True, exist_ok=True, mode=0o700) conn = db.connect(data_dir / "board.db") try: db.migrate(conn, data_dir / "board.db") conn.execute("BEGIN IMMEDIATE") now = time.time() if not store.admin_exists(conn): store.create_operator(conn, now) pid = conn.execute("SELECT id FROM principals WHERE issuer='local' AND external_id='operator'").fetchone()[0] cred_id, secret = parsed current = conn.execute("SELECT id FROM credentials WHERE principal_id=? AND revoked_at IS NULL", (pid,)).fetchone() if current is None or current[0] != cred_id: conn.execute("UPDATE credentials SET revoked_at=? WHERE principal_id=? AND revoked_at IS NULL", (now, pid)) conn.execute("DELETE FROM credentials WHERE id=?", (cred_id,)) conn.execute("INSERT INTO credentials (id, principal_id, secret_hash, created_at) VALUES (?, ?, ?, ?)", (cred_id, pid, hashlib.sha256(secret).digest(), now)) conn.execute("COMMIT") finally: conn.close()
class Dispatcher: """ASGI app that answers 'starting' until the board is ready, then forwards to it."""
def __init__(self): self.inner = None self.board: Board | None = None self.error: str | None = None self.stop = threading.Event() self._inner_lifespan = None
def _prepare(self) -> Board: operator_token = os.environ["MSGBOARD_OPERATOR_TOKEN"].strip() replica_url = os.environ.get("MSGBOARD_REPLICA") replicator = None if replica_url: replica = store_from_url(replica_url) why = wait_for_release(replica, stop=self.stop, stale_after=float(os.environ.get("MSGBOARD_LEASE_STALE_AFTER", "120"))) log.info("replica handover: %s", why) if why == "stopped": raise RuntimeError("stopped before the replica was handed over") if not (DATA_DIR / "board.db").exists(): manifest = restore(replica, DATA_DIR) log.info("restored %s" % manifest["snapshot"] if manifest else "replica empty; starting a new board") replicator = Replicator(replica, DATA_DIR, interval=float(os.environ.get("MSGBOARD_SNAPSHOT_INTERVAL", "15"))) else: log.warning("MSGBOARD_REPLICA not set: all data is lost when this Space restarts") ensure_board(DATA_DIR, operator_token) return Board(DATA_DIR, replicator=replicator)
async def _start(self) -> None: try: board = await asyncio.to_thread(self._prepare) app = create_app(board) from msgboard.space.accounts import adopt_hf_pictures, import_shared_invite, install as install_accounts
install_accounts(app, board) self._inner_lifespan = app.router.lifespan_context(app) await self._inner_lifespan.__aenter__() self.board, self.inner = board, app shared = os.environ.get("MSGBOARD_INVITE_CODE", "").strip() if shared: await import_shared_invite(board, shared, os.environ["MSGBOARD_OPERATOR_TOKEN"].strip()) log.info("board ready") # linked accounts without a picture get their Hugging Face one (in the background, best effort) self._pictures = asyncio.get_running_loop().create_task(adopt_hf_pictures(board)) if os.environ.get("MSGBOARD_DEMO_BOTS") == "1": try: # not part of the package: only the demo Space has it, next to the package from demo_bots import start_bots except ImportError: log.warning("MSGBOARD_DEMO_BOTS=1 but demo_bots.py is not in the Space; no bots") else: start_bots(f"http://127.0.0.1:{os.environ.get('PORT', '7860')}", os.environ["MSGBOARD_OPERATOR_TOKEN"].strip()) except Exception as exc: self.error = f"{type(exc).__name__}: {exc}" log.exception("board failed to start")
def begin_shutdown(self) -> None: self.stop.set() if self.board is not None: self.board.begin_shutdown()
async def __call__(self, scope, receive, send): if scope["type"] == "lifespan": while True: message = await receive() if message["type"] == "lifespan.startup": self._task = asyncio.create_task(self._start()) await send({"type": "lifespan.startup.complete"}) elif message["type"] == "lifespan.shutdown": if self._inner_lifespan is not None: await self._inner_lifespan.__aexit__(None, None, None) await send({"type": "lifespan.shutdown.complete"}) return if self.inner is not None: return await self.inner(scope, receive, send) if scope["type"] != "http": return path = scope.get("path", "") if path == "/": body, status, ctype, extra = PAGE.read_bytes(), 200, b"text/html", [] elif path == "/v1/health": body, status, ctype, extra = json.dumps({"status": "starting", "error": self.error}).encode(), 200, \ b"application/json", [] else: body = json.dumps({"error": {"code": "starting", "message": self.error or "board is starting; retry shortly"}}).encode() status, ctype, extra = 503, b"application/json", [(b"retry-after", b"2")] await send({"type": "http.response.start", "status": status, "headers": [(b"content-type", ctype), (b"cache-control", b"no-cache")] + extra}) await send({"type": "http.response.body", "body": body})
def main() -> None: dispatcher = Dispatcher()
class SpaceServer(uvicorn.Server): def handle_exit(self, sig, frame): dispatcher.begin_shutdown() super().handle_exit(sig, frame)
def _exit(signum, frame): # see msgboard.cli.run_board: keep cleanup from being skipped raise SystemExit(0)
signal.signal(signal.SIGTERM, _exit) signal.signal(signal.SIGINT, _exit) config = uvicorn.Config(dispatcher, host="0.0.0.0", port=int(os.environ.get("PORT", "7860")), log_level="warning", timeout_graceful_shutdown=5, server_header=False) try: SpaceServer(config).run() finally: if dispatcher.board is not None: dispatcher.board.close() # final snapshot, then release the lease log.info("stopped")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256"""Deploy a board to a Hugging Face Space: `msgboard.space.deploy()`.
The Space runs `msgboard.space.app` from the files of the msgboard install that calls deploy(),keeps its board in SQLite on its own disk and pushes snapshots to a private bucket through theHub API (DEPLOY_SPACES.md explains why it is not a bucket mount)."""
import jsonimport loggingimport refrom dataclasses import dataclass, fieldfrom importlib import metadatafrom pathlib import Path
from .. import auth
log = logging.getLogger("msgboard.space")
TAG = "msgboard" # deploy() puts it in the Space card, and reuses only Spaces that have itSNAPSHOT_INTERVAL = "15" # MSGBOARD_SNAPSHOT_INTERVAL, in seconds_HERE = Path(__file__).resolve().parent_PACKAGE = _HERE.parent # the installed msgboard package, uploaded as-is
class DeployError(Exception): """deploy() refused, before changing anything on the Hub."""
@dataclass(frozen=True)class Deployment: """What deploy() set up."""
space_id: str # "namespace/name"; a bare name gets the logged-in account url: str # the board's base URL, https://<namespace>-<name>.hf.space bucket_id: str # "namespace/name" of the private bucket that holds the snapshots created: bool # True if this call created the Space, False if it reused one private: bool # the Space's visibility; a reused Space keeps its own commit: str # the Space repo commit that holds this deployment # The admin token deploy() made when called without operator_token (None if the caller passed one). # It's left out of repr() so printing or logging a Deployment never shows it. operator_token: str | None = field(default=None, repr=False)
def _resolve_space_id(space_id: str, *, token: str | None = None) -> str: """Return `space_id` as "namespace/name". A bare name goes in the logged-in account, as in Trackio.""" return _Names(_hf_api(_hf_token(token))).full(space_id)
def deploy(space_id: str, *, token: str | None = None, operator_token: str | None = None, bucket_id: str | None = None, private: bool | None = None, title: str | None = None) -> Deployment: """Create or update the board Space `space_id` and return a `Deployment`.
`space_id` is "namespace/name" or a bare name for the logged-in account. A missing Space is created (Docker SDK, CPU Basic) with `private` as its visibility (None: the namespace's default). An existing Space is reused, and keeps its visibility, only if its card has the `msgboard` tag that deploy() puts there. Any other Space raises DeployError without being changed, including one left by a first deploy() that failed before its upload: delete that one and deploy again.
A reused board keeps its bucket, the one its MSGBOARD_REPLICA names. A new board's is `bucket_id`, else "<space_id>-bucket", or -2, -3 ... if that exists, so it never restores the snapshots a deleted Space left behind. The bucket is always private, whatever `private` says: it holds every message, token hash and invite. An existing public bucket is refused. So is anything that would restart a board against an empty bucket: a `bucket_id` other than the board's, a MSGBOARD_REPLICA that isn't the hf://buckets/<namespace>/<bucket> deploy() set, or a bucket that is missing (deleted or not visible to this token). All checks run before the first write.
The Space gets the secrets MSGBOARD_OPERATOR_TOKEN (`operator_token`, from `msgboard.auth.new_token()`; the app makes it the admin credential on every boot) and HF_TOKEN (`token`, default: the logged-in token), and the variables MSGBOARD_REPLICA=hf://buckets/<bucket> and MSGBOARD_SNAPSHOT_INTERVAL=15. That one HF token makes deploy()'s Hub calls and is what the Space writes the bucket with, so it needs write access to both the Space and its bucket.
Without `operator_token`, deploy() makes one with new_token() and returns it as `Deployment.operator_token` (None when you pass one). On a reused board that rotates the admin token: the new one replaces the secret, and the old one stops working once the Space restarts. So omit it only if you'll keep the returned one; a deploy() that raises returns no token, and the next call makes another.
The Space's files become the installed msgboard package, LICENSE, requirements.txt, the Dockerfile and the card, whose title is `title` (default: the Space's name); anything else in the Space repo is deleted.
The Space then builds or restarts, which takes a few minutes: wait with `Client.wait_ready()`. A reused Space keeps answering with its previous container for a while; wait_ready() with the operator token waits until the board accepts that token. A restart or rebuild can still follow after wait_ready() returns: if `operator_token` is the one the Space already has, the old healthy container satisfies wait_ready() before the pending restart. Keep retrying through 503 after it. """ from huggingface_hub import CommitOperationAdd, CommitOperationDelete from huggingface_hub.errors import RepositoryNotFoundError
generated = operator_token is None if generated: operator_token = auth.new_token()[1] elif auth.parse_token(operator_token) is None: raise DeployError("operator_token is not a board token; make one with msgboard.auth.new_token()") token = _hf_token(token) api = _hf_api(token) names = _Names(api) space_id = names.full(space_id) bucket_id = names.full(bucket_id) if bucket_id else None try: info = api.space_info(space_id) except RepositoryNotFoundError: info = None variables: dict[str, str] = {} if info is not None: if TAG not in (info.tags or []): raise DeployError(f"{space_id} exists but is not a msgboard board (no {TAG!r} tag in its card), so it " "was left alone; choose another Space ID") # A restart boots a reused board from its bucket, so never let it come back against an empty one. variables = {k: v.value for k, v in api.get_space_variables(space_id).items()} replica = variables.get("MSGBOARD_REPLICA") current = _bucket_of(replica) if current is None: raise DeployError(f"{space_id} has MSGBOARD_REPLICA={replica!r}, not hf://buckets/<namespace>/<bucket> " "as deploy() sets it; set it back to the bucket that holds the board's snapshots") if bucket_id and bucket_id != current: raise DeployError(f"{space_id} keeps its board in bucket {current}, not {bucket_id}; " "leave bucket_id out to keep using it") bucket_id = current bucket_id = bucket_id or _free_bucket_id(api, f"{space_id}-bucket") bucket = _bucket_info(api, bucket_id) if bucket is None and info is not None: raise DeployError(f"{space_id} is a deployed board, and its bucket {bucket_id} was not found (deleted, " "or not visible to this token); refusing to restart the board against an empty bucket") if bucket is not None and not bucket.private: raise DeployError(f"bucket {bucket_id} is public; a board's bucket must be private, because its " "snapshots hold every message, token hash and invite") dist = _distribution() files = _space_files(space_id, dist, title)
secrets = {"MSGBOARD_OPERATOR_TOKEN": operator_token, "HF_TOKEN": token} wanted = {"MSGBOARD_REPLICA": f"hf://buckets/{bucket_id}", "MSGBOARD_SNAPSHOT_INTERVAL": SNAPSHOT_INTERVAL} created = info is None if created: # secrets and variables come with the Space; nothing runs before the first commit api.create_repo(space_id, repo_type="space", private=private, space_sdk="docker", space_hardware="cpu-basic", space_secrets=[{"key": k, "value": v} for k, v in secrets.items()], space_variables=[{"key": k, "value": v} for k, v in wanted.items()]) if bucket is None: api.create_bucket(bucket_id, private=True, exist_ok=True) if not created: # each of these restarts the board for key, value in secrets.items(): api.add_space_secret(space_id, key, value) for key, value in wanted.items(): if variables.get(key) != value: api.add_space_variable(space_id, key, value) stale = set(api.list_repo_files(space_id, repo_type="space")) - set(files) - {".gitattributes"} operations = [CommitOperationAdd(path, data) for path, data in files.items()] operations += [CommitOperationDelete(path) for path in sorted(stale)] commit = api.create_commit(space_id, repo_type="space", operations=operations, commit_message=f"Deploy msgboard {dist.version}") info = api.space_info(space_id) return Deployment(space_id=space_id, url=(info.host or f"https://{info.subdomain}.hf.space").rstrip("/"), bucket_id=bucket_id, created=created, private=bool(info.private), commit=commit.oid, operator_token=operator_token if generated else None)
def _hf_token(token: str | None) -> str: from huggingface_hub import get_token
token = token or get_token() if not token: raise DeployError("no Hugging Face token: log in with `hf auth login` or set HF_TOKEN") return token
def _hf_api(token: str): from huggingface_hub import HfApi
return HfApi(token=token)
class _Names: """Fills in the logged-in account for bare repo names, asking the Hub at most once."""
def __init__(self, api): self.api = api self._namespace = None
def full(self, repo_id: str) -> str: from huggingface_hub.utils import validate_repo_id
if "/" not in repo_id: self._namespace = self._namespace or self.api.whoami()["name"] repo_id = f"{self._namespace}/{repo_id}" validate_repo_id(repo_id) return repo_id
def _bucket_of(replica: str | None) -> str | None: """The bucket ID in the MSGBOARD_REPLICA deploy() sets, `hf://buckets/<namespace>/<bucket>`.""" match = re.fullmatch(r"hf://buckets/([^/]+/[^/]+)", replica or "") return match[1] if match else None
def _bucket_info(api, bucket_id: str): from huggingface_hub.errors import BucketNotFoundError
try: return api.bucket_info(bucket_id) except BucketNotFoundError: return None
def _free_bucket_id(api, preferred: str) -> str: """`preferred`, or the first of preferred-2, -3 ... that doesn't exist, as Trackio's resolve_auto_bucket_id.""" candidate, n = preferred, 1 while _bucket_info(api, candidate) is not None: n += 1 candidate = f"{preferred}-{n}" if candidate != preferred: log.info("bucket %s already exists; using %s", preferred, candidate) return candidate
def _distribution(): try: return metadata.distribution("msgboard") except metadata.PackageNotFoundError: raise DeployError("msgboard is not installed; deploy() uploads the installed package " "(pip install 'msgboard', or pip install -e . in a checkout)") from None
def _space_files(space_id: str, dist, title: str | None = None) -> dict[str, bytes]: """The Space repo's files by path: card, Dockerfile, requirements.txt, LICENSE and the package.""" # A JSON string is a quoted YAML string, so `true`, `null`, `2024`, ':' or '#' stay the title as written. # ensure_ascii=False keeps an emoji whole (YAML reads JSON's surrogate pair as two lone halves). YAML # reads U+0085/U+2028/U+2029 as line breaks and refuses DEL and C1 controls, so those stay escaped. title = re.sub(r"[\x7f-\x9f\u2028\u2029]", lambda m: f"\\u{ord(m[0]):04x}", json.dumps(title or space_id.split("/")[1], ensure_ascii=False)) card = (_HERE / "README.md").read_text().replace("title: msgboard\n", f"title: {title}\n", 1) files = {"README.md": card.encode(), "Dockerfile": (_HERE / "Dockerfile").read_bytes(), "requirements.txt": _requirements(dist).encode(), "LICENSE": _license(dist)} # An allowlist, so stray files in an editable install's src/msgboard (a test board's token, say) # never reach a public Space. Keep it in step with [tool.setuptools.package-data] in pyproject.toml. for path in sorted(_PACKAGE.rglob("*")): if (path.suffix in (".py", ".html") and "__pycache__" not in path.parts and path.is_file() and path.resolve().is_relative_to(_PACKAGE)): # no symlinks out of the package files["msgboard/" + path.relative_to(_PACKAGE).as_posix()] = path.read_bytes() return files
def _requirements(dist) -> str: """Runtime requirements only; optional extras are left out.""" return "\n".join(req.strip() for req in dist.requires or [] if "extra" not in req.partition(";")[2]) + "\n"
def _license(dist) -> bytes: """LICENSE from the install's dist-info, in licenses/ as setuptools 77+ (PEP 639) puts it.""" for name in dist.metadata.get_all("License-File") or []: text = dist.read_text(f"licenses/{name}") if text: return text.encode() raise DeployError("the installed msgboard has no LICENSE in its metadata; reinstall it with setuptools>=77")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565"""Personal task operations, run on the existing reader or single writer.
Answers and notifications are ordinary messages. Functions do not open or committransactions: the server runs each mutation in one Database.write transaction.Live references become NULL on deletion; original IDs retain destination intent."""
from dataclasses import replacefrom contextlib import contextmanagerimport hashlibimport jsonimport time
from . import auth, storefrom .errors import ApiError, bad_request, conflict, forbidden, not_found, unauthorized
NOTICE_DELAY = 5.0MAX_SOURCES = 20MAX_OPTIONS = 20MAX_BLOCKS = 40
def _digest(value): return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()
def _integer(value, name, *, optional=False): if optional and value is None: return None if not isinstance(value, int) or isinstance(value, bool) or value < 1: raise bad_request(f"{name} must be a positive integer") return value
def _object(payload, allowed): if not isinstance(payload, dict) or set(payload) - allowed: raise bad_request("unsupported task fields or invalid request body")
def _text(value, name, limit, *, empty=False): if not isinstance(value, str) or len(value) > limit or (not empty and not value.strip()): raise bad_request(f"{name} must be {'at most' if empty else 'nonempty and at most'} {limit} characters") return value
def _current(conn, principal_id): row = conn.execute("SELECT * FROM principals WHERE id = ?", (principal_id,)).fetchone() if row is None or row["disabled"]: raise unauthorized("identity is no longer active") p = store._principal_obj(row) if not p.is_human: owner = conn.execute("SELECT * FROM principals WHERE id = ?", (p.owner_id,)).fetchone() # Ownership is normalized to a person by the existing identity migration. # Refuse malformed chains rather than allowing an agent to own a task. if (owner is None or owner["identity_type"] != "user" or owner["disabled"] or owner["role"] not in auth.owner_roles_for(p.role)): raise unauthorized("agent no longer has an active human owner") return p
def _principal(conn, p, now, *, write=False): cred = conn.execute("SELECT * FROM credentials WHERE id = ? AND principal_id = ?", (p.credential_id, p.id)).fetchone() if (cred is None or cred["revoked_at"] is not None or (cred["expires_at"] is not None and cred["expires_at"] <= now)): raise unauthorized("credential is no longer active") fresh = replace(_current(conn, p.id), credential_id=p.credential_id) if write and not fresh.is_human and not fresh.may_post: raise forbidden("read-only agents cannot change tasks") return fresh
def _owner(p): return p.id if p.is_human else p.owner_id
def _channel_visible(conn, p, channel_id): ch = conn.execute("SELECT * FROM channels WHERE id = ?", (channel_id,)).fetchone() return ch is not None and store.can_see(conn, p, ch)
def _sources(conn, item_id): return conn.execute("SELECT * FROM task_sources WHERE item_id = ? ORDER BY position", (item_id,)).fetchall()
def _visible(conn, p, row): if row["owner_id"] != _owner(p): return False if row["channel_id"] is not None and not _channel_visible(conn, p, row["channel_id"]): return False if not p.is_human and row["original_channel_id"] is not None and row["channel_id"] is None: return False for source in _sources(conn, row["id"]): if source["channel_id"] is not None and not _channel_visible(conn, p, source["channel_id"]): return False # Only the owner retains a card with deleted evidence, to close it safely. if not p.is_human and (source["message_id"] is None or source["channel_id"] is None): return False return True
def _row(conn, p, item_id): _integer(item_id, "item id") row = conn.execute("SELECT * FROM task_items WHERE id = ? AND owner_id = ?", (item_id, _owner(p))).fetchone() if row is None or not _visible(conn, p, row): raise not_found("task not found") return row
def _message(conn, p, message_id): if message_id is None: return None row = conn.execute(store.MESSAGE_SELECT + " WHERE m.id = ?", (message_id,)).fetchone() if row is None or not _channel_visible(conn, p, row["channel_id"]): return None out = store._message_json(row) store._attach_mentions(conn, [out]) store._attach_reactions(conn, [out], p.id) return out
def _item(conn, p, row): refs = [] for source in _sources(conn, row["id"]): message = _message(conn, p, source["message_id"]) refs.append({"message_id": source["original_message_id"], "channel_id": source["original_channel_id"], "message": message, "unavailable": message is None}) channel = None if row["channel_id"] is not None: ch = conn.execute("SELECT id, name, kind, archived FROM channels WHERE id = ?", (row["channel_id"],)).fetchone() if ch is not None: channel = dict(ch) specified = row["original_channel_id"] is not None unavailable = specified and (row["channel_id"] is None or (row["original_anchor_id"] is not None and row["anchor_id"] is None)) if specified and channel is not None and not store.can_post(conn, p, channel): unavailable = True if not specified: try: agent = _current(conn, row["agent_id"]) unavailable = agent.is_human or agent.owner_id != row["owner_id"] or not agent.may_post except ApiError: unavailable = True out = {"id": row["id"], "key": row["item_key"], "title": row["title"], "description": row["description"], "blocks": json.loads(row["blocks"]), "agent": store._brief(conn, row["agent_id"]), "channel_id": row["original_channel_id"], "anchor_id": row["original_anchor_id"], "channel": channel, "sources": refs, "options": json.loads(row["options"]), "multiple": bool(row["multiple"]), "version": row["version"], "state": row["state"], "unread": row["state"] == "open" and not row["seen"], "closed_reason": row["closed_reason"], "closed_at": row["closed_at"], "answer": _message(conn, p, row["answer_id"]), "answer_message_id": row["original_answer_id"], "created_at": row["created_at"], "updated_at": row["updated_at"], "rank": row["rank"], "destination_unavailable": bool(unavailable), "destination": {"kind": "thread" if row["original_anchor_id"] is not None else "channel" if specified else "dm", "channel_id": row["original_channel_id"], "anchor_id": row["original_anchor_id"], "agent_id": row["agent_id"]}} return out
def _order_version(conn, owner_id): row = conn.execute("SELECT version FROM task_orders WHERE owner_id = ?", (owner_id,)).fetchone() return row[0] if row is not None else 0
def _bump_order(conn, owner_id): conn.execute("""INSERT INTO task_orders(owner_id, version) VALUES (?, 1) ON CONFLICT(owner_id) DO UPDATE SET version = version + 1""", (owner_id,))
def _listing(conn, p, include_archived, sort, direction): if not isinstance(include_archived, bool): raise bad_request("include_archived must be a boolean") if sort not in ("manual", "latest", "channel", "agent") or direction not in ("asc", "desc"): raise bad_request("sort must be manual/latest/channel/agent; direction must be asc/desc") rows = conn.execute("SELECT * FROM task_items WHERE owner_id = ? ORDER BY rank, id", (_owner(p),)).fetchall() visible = [r for r in rows if _visible(conn, p, r)] counts = {"open": sum(r["state"] == "open" for r in visible), "archived": sum(r["state"] == "closed" for r in visible)} items = [_item(conn, p, r) for r in visible if include_archived or r["state"] == "open"] if sort == "manual": key = lambda i: (i["rank"], i["id"]) elif sort == "latest": key = lambda i: (i["created_at"], i["id"]) elif sort == "channel": key = lambda i: ((i["channel"] or {}).get("name", "").casefold(), i["rank"], i["id"]) else: key = lambda i: ((i["agent"] or {}).get("display_name") or (i["agent"] or {}).get("external_id", ""), i["rank"], i["id"]) items.sort(key=key, reverse=direction == "desc") return {"items": items, "counts": counts, "order_version": _order_version(conn, _owner(p))}
@contextmanagerdef _snapshot(conn): # SQLite autocommit would otherwise pair an old title/options row with a # newer set of public source references during an agent's concurrent edit. # Visibility and the content it protects must use the same read snapshot. own = not conn.in_transaction if own: conn.execute("BEGIN") try: yield finally: if own: conn.execute("ROLLBACK")
def list_items(conn, p, include_archived=False, sort="manual", direction="asc"): with _snapshot(conn): return _listing(conn, _principal(conn, p, time.time()), include_archived, sort, direction)
def get_item(conn, p, item_id): with _snapshot(conn): p = _principal(conn, p, time.time()) return _item(conn, p, _row(conn, p, item_id))
def _unread(conn, p): rows = conn.execute("SELECT * FROM task_items WHERE owner_id = ? AND state = 'open' AND seen = 0", (_owner(p),)).fetchall() return {"unread": sum(_visible(conn, p, row) for row in rows)}
def unread(conn, p): with _snapshot(conn): return _unread(conn, _principal(conn, p, time.time()))
def mark_read(conn, p, payload, now): p = _principal(conn, p, now) if not p.is_human: raise forbidden("only the human can mark tasks read") _object(payload, {"ids"}) ids = payload.get("ids") if not isinstance(ids, list) or len(ids) > 200: raise bad_request("ids must be at most 200 task IDs") ids = list(dict.fromkeys(_integer(i, "task id") for i in ids)) # Validate the complete batch before changing it. A concurrent new item is # never acknowledged by a timestamp or a list-wide high-water mark. for item_id in ids: _row(conn, p, item_id) if ids: marks = ",".join("?" for _ in ids) conn.execute(f"UPDATE task_items SET seen = 1 WHERE owner_id = ? AND id IN ({marks})", (p.id, *ids)) return _unread(conn, p)
def _notice(conn, owner_id, agent_id, now): pending = conn.execute("SELECT id FROM task_notices WHERE owner_id = ? AND agent_id = ? AND state = 'pending'", (owner_id, agent_id)).fetchone() if pending is None: conn.execute("INSERT INTO task_notices(owner_id, agent_id, due_at, updated_at) VALUES (?, ?, ?, ?)", (owner_id, agent_id, now + NOTICE_DELAY, now)) else: conn.execute("UPDATE task_notices SET changes = changes + 1, updated_at = ? WHERE id = ?", (now, pending[0]))
def _content(conn, p, payload): _object(payload, {"title", "description", "blocks", "channel_id", "anchor_id", "sources", "options", "multiple", "base_version"}) if "base_version" in payload: _integer(payload["base_version"], "base_version") title = _text(payload.get("title"), "title", 240) description = _text(payload.get("description", ""), "description", 16000, empty=True) channel_id = _integer(payload.get("channel_id"), "channel_id", optional=True) anchor_id = _integer(payload.get("anchor_id"), "anchor_id", optional=True) owner = _current(conn, p.owner_id) if anchor_id is not None: anchor = conn.execute("SELECT channel_id, thread_id FROM messages WHERE id = ?", (anchor_id,)).fetchone() if anchor is None: raise bad_request("anchor_id must reference an existing message") if channel_id is not None and channel_id != anchor["channel_id"]: raise bad_request("anchor_id must belong to channel_id") channel_id = anchor["channel_id"] # Keep the exact source anchor. Normal post_message resolves its root. if channel_id is not None: store.channel_for(conn, p, channel_id) store.channel_for(conn, owner, channel_id) sources = payload.get("sources", []) if not isinstance(sources, list) or len(sources) > MAX_SOURCES: raise bad_request(f"sources must be at most {MAX_SOURCES} message IDs") sources = list(dict.fromkeys(_integer(s, "source message id") for s in sources)) blocks = payload.get("blocks", []) if not isinstance(blocks, list) or len(blocks) > MAX_BLOCKS: raise bad_request(f"blocks must be a list of at most {MAX_BLOCKS} text or quote blocks") ordered, text_length = [], len(description) for block in blocks: if not isinstance(block, dict): raise bad_request("blocks must contain text or quote objects") if block.get("type") == "text": _object(block, {"type", "text"}) text = _text(block.get("text"), "block text", 16000, empty=True) text_length += len(text) ordered.append({"type": "text", "text": text}) elif block.get("type") == "quote": _object(block, {"type", "message_id"}) message_id = _integer(block.get("message_id"), "quote message_id") ordered.append({"type": "quote", "message_id": message_id}) if message_id not in sources: sources.append(message_id) else: raise bad_request("block type must be text or quote") if text_length > 16000: raise bad_request("description and text blocks together must be at most 16000 characters") if len(sources) > MAX_SOURCES: raise bad_request(f"sources and quotes must reference at most {MAX_SOURCES} unique messages") refs = [] for message_id in sources: source = conn.execute("SELECT channel_id FROM messages WHERE id = ?", (message_id,)).fetchone() if source is None: raise bad_request("sources must reference existing messages") store.channel_for(conn, p, source["channel_id"]) store.channel_for(conn, owner, source["channel_id"]) refs.append((message_id, source["channel_id"])) options = payload.get("options", []) if not isinstance(options, list) or len(options) > MAX_OPTIONS: raise bad_request(f"options must be at most {MAX_OPTIONS} choices") choices, seen = [], set() for option in options: _object(option, {"id", "label"}) option_id = option.get("id") if not isinstance(option_id, str) or not store.CLIENT_ID.fullmatch(option_id) or option_id in seen: raise bad_request("options need unique valid string IDs") choices.append({"id": option_id, "label": _text(option.get("label"), "option label", 8000)}) seen.add(option_id) multiple = payload.get("multiple", False) if not isinstance(multiple, bool): raise bad_request("multiple must be a boolean") content = {"title": title, "description": description, "channel_id": channel_id, "anchor_id": anchor_id, "sources": sources, "options": choices, "multiple": multiple} # Omitting empty blocks preserves the exact v30 content fingerprint, so an # old stable-key retry remains a no-op after the feature/table rename. if ordered: content["blocks"] = ordered return content, refs
def put_item(conn, p, key, payload, now): p = _principal(conn, p, now, write=True) if p.is_human or p.identity_type not in ("agent", "system"): raise forbidden("only your own agents can add tasks") if not isinstance(key, str) or not store.CLIENT_ID.fullmatch(key): raise bad_request("task key must be a valid client ID") content, refs = _content(conn, p, payload) digest = _digest(content) row = conn.execute("SELECT * FROM task_items WHERE owner_id = ? AND agent_id = ? AND item_key = ?", (p.owner_id, p.id, key)).fetchone() if row is not None and row["content_hash"] == digest: # Exact retry is safe, including a retry after the human closed the item. return _item(conn, p, _row(conn, p, row["id"])) if row is not None: _row(conn, p, row["id"]) base = _integer(payload.get("base_version"), "base_version") if base != row["version"]: raise conflict("task_version_conflict", "task changed; reload before updating") conn.execute("""UPDATE task_items SET title = ?, description = ?, channel_id = ?, original_channel_id = ?, anchor_id = ?, original_anchor_id = ?, options = ?, multiple = ?, content_hash = ?, blocks = ?, version = version + 1, updated_at = ? WHERE id = ?""", (content["title"], content["description"], content["channel_id"], content["channel_id"], content["anchor_id"], content["anchor_id"], json.dumps(content["options"]), int(content["multiple"]), digest, json.dumps(content.get("blocks", [])), now, row["id"])) item_id = row["id"] conn.execute("DELETE FROM task_sources WHERE item_id = ?", (item_id,)) else: if "base_version" in payload: raise conflict("task_version_conflict", "task does not exist; omit base_version to create") rank = conn.execute("SELECT COALESCE(MAX(rank), 0) + 1 FROM task_items WHERE owner_id = ?", (p.owner_id,)).fetchone()[0] item_id = conn.execute("""INSERT INTO task_items (owner_id, agent_id, item_key, title, description, channel_id, original_channel_id, anchor_id, original_anchor_id, options, multiple, content_hash, blocks, created_at, updated_at, rank) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", (p.owner_id, p.id, key, content["title"], content["description"], content["channel_id"], content["channel_id"], content["anchor_id"], content["anchor_id"], json.dumps(content["options"]), int(content["multiple"]), digest, json.dumps(content.get("blocks", [])), now, now, rank)).lastrowid _bump_order(conn, p.owner_id) conn.executemany("""INSERT INTO task_sources(item_id, position, message_id, original_message_id, channel_id, original_channel_id) VALUES (?, ?, ?, ?, ?, ?)""", [(item_id, i, mid, mid, cid, cid) for i, (mid, cid) in enumerate(refs)]) _notice(conn, p.owner_id, p.id, now) store.audit(conn, p.id, "task.put", f"task:{item_id}", {"key": key}, now) return _item(conn, p, _row(conn, p, item_id))
def _answer_destination(conn, p, row, now): if row["original_channel_id"] is not None: if row["channel_id"] is None or (row["original_anchor_id"] is not None and row["anchor_id"] is None): raise conflict("task_destination_unavailable", "the specified destination was deleted") return row["channel_id"], row["anchor_id"] try: agent = _current(conn, row["agent_id"]) except ApiError: raise conflict("task_destination_unavailable", "the proposing agent is no longer active") if agent.is_human or agent.owner_id != p.id or not agent.may_post: raise conflict("task_destination_unavailable", "the proposing agent is no longer available to you") channel, _ = store.open_dm(conn, p, agent.id, now) return channel["id"], None
def _replay(conn, p, receipt): row = _row(conn, p, receipt["item_id"]) recorded = json.loads(receipt["result"]) item = _item(conn, p, row) # Preserve the operation's outcome but never replay cached source/message text. for name in ("version", "state", "closed_reason", "closed_at"): item[name] = recorded[name] message = _message(conn, p, recorded["message_id"]) if recorded["action"] == "answer": item["answer"] = message item["answer_message_id"] = recorded["message_id"] return {"item": item, "message": message}, None, True
def action(conn, p, item_id, payload, request_key, now): p = _principal(conn, p, now, write=True) _integer(item_id, "item id") _object(payload, {"action", "version", "body", "option_ids"}) kind = payload.get("action") if kind not in ("answer", "done", "dismiss", "restore"): raise bad_request("action must be answer/done/dismiss/restore") version = _integer(payload.get("version"), "version") if not isinstance(request_key, str) or not store.CLIENT_ID.fullmatch(request_key): raise bad_request("a valid Idempotency-Key is required") if kind == "answer" and not p.is_human: raise forbidden("only the human owner can answer a task") if kind != "answer" and ("body" in payload or "option_ids" in payload): raise bad_request("body and option_ids are only valid for answer") fingerprint = _digest({"item_id": item_id, "payload": payload}) prior = conn.execute("SELECT * FROM task_receipts WHERE actor_id = ? AND request_key = ?", (p.id, request_key)).fetchone() if prior is not None: if prior["payload_hash"] != fingerprint: raise conflict("idempotency_conflict", "this key was already used with different content") return _replay(conn, p, prior) row = _row(conn, p, item_id) if version != row["version"]: raise conflict("task_version_conflict", "task changed; reload before acting") if kind == "restore": if row["state"] != "closed": raise conflict("task_state_conflict", "task is already open") elif row["state"] != "open": raise conflict("task_closed", "task is already closed") message, created_message = None, None if kind == "answer": body = _text(payload.get("body", ""), "body", 65536, empty=True) selected = payload.get("option_ids", []) if (not isinstance(selected, list) or len(selected) > MAX_OPTIONS or any(not isinstance(s, str) for s in selected) or len(set(selected)) != len(selected)): raise bad_request("option_ids must be a list of distinct option IDs") choices = {o["id"]: o["label"] for o in json.loads(row["options"])} if any(s not in choices for s in selected) or (not row["multiple"] and len(selected) > 1): raise bad_request("unknown option or multiple selections are not allowed") parts = [choices[s] for s in selected] if body: parts.append(body) text = "\n".join(parts) if not text.strip(): raise bad_request("choose an answer or write a message") cid, anchor = _answer_destination(conn, p, row, now) normalized, digest = store.normalize_payload(cid, {"body": text, "reply_to": anchor}) # Legacy internal prefixes are stable retry identities, not product labels. # Keep them across the Tasks rename to preserve existing message receipts. internal_key = "#queue-answer:" + str(p.id) + ":" + request_key message, created = store.post_message(conn, p, cid, internal_key, normalized, digest, now) if created: created_message = message conn.execute("UPDATE task_items SET answer_id = ?, original_answer_id = ? WHERE id = ?", (message["id"], message["id"], item_id)) state = "open" if kind == "restore" else "closed" reason = None if kind == "restore" else "answered" if kind == "answer" else "dismissed" if kind == "dismiss" else "done" closed_at = None if kind == "restore" else now conn.execute("""UPDATE task_items SET state = ?, closed_reason = ?, closed_at = ?, version = version + 1, updated_at = ?, seen = 1 WHERE id = ?""", (state, reason, closed_at, now, item_id)) row = _row(conn, p, item_id) recorded = {"action": kind, "version": row["version"], "state": state, "closed_reason": reason, "closed_at": closed_at, "message_id": message["id"] if message else None} conn.execute("""INSERT INTO task_receipts(actor_id, request_key, item_id, payload_hash, result, created_at) VALUES (?, ?, ?, ?, ?, ?)""", (p.id, request_key, item_id, fingerprint, json.dumps(recorded), now)) store.audit(conn, p.id, "task." + kind, f"task:{item_id}", {"message_id": recorded["message_id"]}, now) if not p.is_human: _notice(conn, row["owner_id"], p.id, now) return {"item": _item(conn, p, row), "message": message}, created_message, False
def move_item(conn, p, item_id, payload, now): p = _principal(conn, p, now, write=True) row = _row(conn, p, item_id) _object(payload, {"order_version", "before_id", "after_id"}) version = payload.get("order_version") if not isinstance(version, int) or isinstance(version, bool) or version < 0: raise bad_request("order_version must be a nonnegative integer") if version != _order_version(conn, _owner(p)): raise conflict("task_order_conflict", "task order changed; reload before moving") before = _integer(payload.get("before_id"), "before_id", optional=True) after = _integer(payload.get("after_id"), "after_id", optional=True) if before is not None and after is not None: raise bad_request("specify only before_id or after_id") neighbor = before if before is not None else after if neighbor == item_id: raise bad_request("an item cannot be its own neighbor") if neighbor is not None: _row(conn, p, neighbor) ids = [r[0] for r in conn.execute("SELECT id FROM task_items WHERE owner_id = ? ORDER BY rank, id", (_owner(p),))] old = list(ids) ids.remove(item_id) index = len(ids) if neighbor is None else ids.index(neighbor) + (1 if after is not None else 0) ids.insert(index, item_id) if ids != old: conn.executemany("UPDATE task_items SET rank = ? WHERE id = ?", [(i + 1, mid) for i, mid in enumerate(ids)]) _bump_order(conn, _owner(p)) store.audit(conn, p.id, "task.move", f"task:{row['id']}", {"before_id": before, "after_id": after}, now) return _listing(conn, p, True, "manual", "asc")
def notice_due(conn, now): return conn.execute("SELECT 1 FROM task_notices WHERE state = 'pending' AND due_at <= ? LIMIT 1", (now,)).fetchone() is not None
def deliver_notice(conn, now): notice = conn.execute("SELECT * FROM task_notices WHERE state = 'pending' AND due_at <= ? ORDER BY due_at, id LIMIT 1", (now,)).fetchone() if notice is None: return None try: agent = _current(conn, notice["agent_id"]) owner = _current(conn, notice["owner_id"]) if agent.is_human or not owner.is_human or agent.owner_id != owner.id or not agent.may_post: raise forbidden("task notice is no longer authorized") except ApiError: conn.execute("UPDATE task_notices SET state = 'suppressed' WHERE id = ?", (notice["id"],)) return None # A delivery error must not leave a newly created empty DM committed. Unexpected # failures propagate, rolling back the outer write; expected access failures # roll back this savepoint and suppress the permanently invalid batch. conn.execute("SAVEPOINT task_notice_delivery") try: channel, _ = store.open_dm(conn, agent, owner.id, now) n = notice["changes"] body = f"I updated your tasks ({n} {'change' if n == 1 else 'changes'}). [Open Tasks](#tasks)" normalized, digest = store.normalize_payload(channel["id"], {"body": body}) # Retain the historical internal idempotency prefix for existing batches. message, created = store.post_message(conn, agent, channel["id"], "#queue-notice:" + str(notice["id"]), normalized, digest, now) conn.execute("UPDATE task_notices SET state = 'sent', message_id = ? WHERE id = ?", (message["id"], notice["id"])) conn.execute("RELEASE task_notice_delivery") return message if created else None except ApiError as exc: conn.execute("ROLLBACK TO task_notice_delivery") conn.execute("RELEASE task_notice_delivery") if exc.code == "channel_archived": # Archival is reversible; retain the durable batch and avoid a hot # retry loop while leaving other agents' batches free to deliver. conn.execute("UPDATE task_notices SET due_at = ? WHERE id = ?", (now + NOTICE_DELAY, notice["id"])) return None if exc.status in (401, 403, 404): conn.execute("UPDATE task_notices SET state = 'suppressed' WHERE id = ?", (notice["id"],)) return None raise123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647"""Admin-only, one-channel history transfer. ZIP members are read, never extracted.
The database transaction owns the import decision and publication. Immutable blobfiles are installed before their rows commit; a failed transaction may leave anunreferenced object, but never publishes a row whose bytes are incomplete."""
import hashlibimport jsonimport mathimport reimport shutilimport sqlite3import tempfileimport zipfilefrom itertools import pairwisefrom pathlib import Pathfrom urllib.parse import quote, unquote, urlsplit, urlunsplit
from . import storefrom .config import LIMITSfrom .errors import ApiError, bad_request, conflict, forbidden
MAX_BUNDLE_BYTES = 512 * 1024 * 1024MAX_MANIFEST_BYTES = 32 * 1024 * 1024MAX_MESSAGES = 10_000MAX_ATTACHMENTS = 1_000HASH = re.compile(r"^[0-9a-f]{64}$")ATT_LINK = re.compile(r"(?:/v1/attachments/|#file/)(att_[A-Za-z0-9_-]+)")STORAGE_LINK = re.compile(r"(?:https?://[^\s<>\"'\[\]]+)?/v1/storage/[^/\s<>\"'()\[\]]+/[^\s<>\"'\[\]]+")CODE_SPAN = re.compile(r"(`+)([\s\S]*?)\1|(?m:^ {0,3}(~{3,})[^\n]*\n[\s\S]*?^ {0,3}\3[ \t]*$)")
def storage_links(body): # Preserve offsets so the same matches can drive capture and rewriting. # Paths shown as code are examples, not rendered file links. masked = CODE_SPAN.sub(lambda match: " " * len(match.group()), body) return STORAGE_LINK.finditer(masked)
def storage_reference(text, source_url): """Resolve only this board's file links; never fetch arbitrary URLs.""" suffix = "" # Keep balanced filename parentheses, but leave Markdown's closing delimiter # outside the URL when a rewritten link is put back into the body. depth = 0 for i, char in enumerate(text): if char == "(": depth += 1 elif char == ")": if not depth: text, suffix = text[:i], text[i:] break depth -= 1 url, source = urlsplit(text), urlsplit(source_url) prefix = "/v1/storage/" path = url.path if url.netloc: if (url.scheme, url.netloc) != (source.scheme, source.netloc): return None prefix = source.path.rstrip("/") + prefix if not path.startswith(prefix): return None handle, _, rest = path[len(prefix):].partition("/") if not handle or not rest or rest.endswith("/"): return None return unquote(handle), store.storage_path(unquote(rest)), url, suffix
def require_admin(p): if not p.is_admin: raise forbidden("channel export/import requires an admin")
def public_channel(conn, p, channel_id): require_admin(p) ch = store.channel_for(conn, p, channel_id) if ch["kind"] != "public": raise bad_request("only public channels can be exported or imported") return ch
def canonical(value): return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
def export_manifest(conn, p, channel_id: int, board_url: str): # Reader connections otherwise run in autocommit mode: use one snapshot for # authors, messages, reactions, doc and attachment metadata. conn.execute("BEGIN") try: ch = public_channel(conn, p, channel_id) rows = conn.execute("SELECT * FROM messages WHERE channel_id = ? ORDER BY created_at, seq, id", (channel_id,)).fetchall() if len(rows) > MAX_MESSAGES: raise ApiError(413, "too_large", f"a channel bundle supports at most {MAX_MESSAGES} messages") messages = [{k: r[k] for k in ("id", "seq", "sender_id", "body", "reply_to", "thread_id", "created_at", "edited_at")} | {"attachments": json.loads(r["attachments"] or "[]")} for r in rows] reactions = [dict(r) for r in conn.execute("""SELECT r.* FROM message_reactions r JOIN messages m ON m.id = r.message_id WHERE m.channel_id = ? ORDER BY r.created_at, r.rowid""", (channel_id,))] doc_row = conn.execute("SELECT body, author_id, created_at FROM channel_doc_versions WHERE channel_id = ? AND version = ?", (channel_id, ch["doc_version"])).fetchone() doc = dict(doc_row) if doc_row else None attachment_ids = {a for m in messages for a in m["attachments"]} for body in [m["body"] for m in messages] + ([doc["body"]] if doc else []): # Only this channel's attachments are copied. Links to other channels # retain their original meaning/access rules, like storage links. for aid in ATT_LINK.findall(body): if conn.execute("SELECT 1 FROM attachments WHERE id = ? AND channel_id = ? AND state = 'ready'", (aid, channel_id)).fetchone(): attachment_ids.add(aid) if len(attachment_ids) > MAX_ATTACHMENTS: raise ApiError(413, "too_large", "too many attachments for one bundle") attachments = [] for aid in sorted(attachment_ids): row = conn.execute("SELECT * FROM attachments WHERE id = ? AND channel_id = ? AND state = 'ready'", (aid, channel_id)).fetchone() if not row: raise conflict("export_changed", "an attachment is missing; export again after checking the channel") attachments.append(dict(row)) storage_files = {} for body in [m["body"] for m in messages] + ([doc["body"]] if doc else []): for match in storage_links(body): ref = storage_reference(match.group(), board_url) if ref is None: continue handle, path, _, _ = ref owner = conn.execute("SELECT id FROM principals WHERE external_id = ? OR hf_username = ?", (handle, handle)).fetchone() row = conn.execute("SELECT * FROM storage_files WHERE owner_id = ? AND path = ?", (owner["id"], path)).fetchone() if owner else None if row is None: raise conflict("export_missing_storage", f"linked storage file is missing: {handle}/{path}") record = storage_files.setdefault((row["owner_id"], path), {k: row[k] for k in ("owner_id", "path", "size", "sha256", "content_type", "updated_at")} | {"handles": []}) if handle not in record["handles"]: record["handles"].append(handle) if len(storage_files) + len(attachments) > MAX_ATTACHMENTS: raise ApiError(413, "too_large", "too many attachment/storage files for one bundle") people = {m["sender_id"] for m in messages} | {r["principal_id"] for r in reactions} people |= {a["uploader_id"] for a in attachments} people |= {f["owner_id"] for f in storage_files.values()} if doc: people.add(doc["author_id"]) principals = [dict(conn.execute("SELECT id, external_id, display_name, identity_type FROM principals WHERE id = ?", (pid,)).fetchone()) for pid in sorted(people)] manifest = {"format": "msgboard-channel", "version": 1, "source": {"board_id": conn.execute("SELECT value FROM settings WHERE key = 'transfer_board_id'").fetchone()[0], "board_url": board_url.rstrip("/"), "channel_id": channel_id, "channel_name": ch["name"]}, "principals": principals, "messages": messages, "reactions": reactions, "doc": doc, "storage_files": list(storage_files.values()), "attachments": [{k: a[k] for k in ("id", "uploader_id", "filename", "content_type", "size", "sha256", "created_at")} for a in attachments]} keys = {a["sha256"]: ("attachment", a["storage_key"]) for a in attachments} for f in storage_files.values(): keys.setdefault(f["sha256"], ("storage", store.storage_key(f["owner_id"], f["path"]))) return manifest, keys finally: conn.execute("ROLLBACK")
def build_bundle(manifest, keys, blobs, path: Path, storage=None): validate_manifest(manifest) data = canonical(manifest) if len(data) > MAX_MANIFEST_BYTES: raise ApiError(413, "too_large", "channel manifest is too large") total = len(data) with tempfile.TemporaryDirectory(prefix="msgboard-export-files-") as scratch, zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as z: z.writestr("manifest.json", data) for sha, (kind, key) in keys.items(): digest = hashlib.sha256() try: src_path = blobs.path_for(key) if kind == "attachment" else Path(scratch) / sha if kind == "storage" and not storage.get(key, src_path): raise conflict("export_changed", "linked storage bytes disappeared; retry export") with src_path.open("rb") as src, z.open("blobs/" + sha, "w") as dst: while chunk := src.read(1024 * 1024): total += len(chunk) if total > MAX_BUNDLE_BYTES: raise ApiError(413, "too_large", "channel bundle exceeds 512 MiB") digest.update(chunk) dst.write(chunk) except FileNotFoundError: raise conflict("export_changed", "attachment bytes disappeared; retry the export") if digest.hexdigest() != sha: raise conflict("export_changed", "attachment bytes do not match their recorded checksum") if path.stat().st_size > MAX_BUNDLE_BYTES: raise ApiError(413, "too_large", "channel ZIP exceeds 512 MiB")
def _int(value, what): if type(value) is not int or value < 1: raise bad_request(f"{what} must be a positive integer") return value
def _time(value, what): if type(value) not in (float, int) or not math.isfinite(value) or value < 0: raise bad_request(f"{what} must be a finite UTC timestamp")
def _text(value, what, max_bytes=LIMITS.max_body_bytes): if not isinstance(value, str) or len(value.encode()) > max_bytes: raise bad_request(f"invalid or oversized {what}")
def validate_manifest(m): if not isinstance(m, dict) or m.get("format") != "msgboard-channel" or m.get("version") != 1: raise bad_request("expected a version 1 msgboard-channel bundle") source = m.get("source") if not isinstance(source, dict) or not re.fullmatch(r"[0-9a-f]{32}", str(source.get("board_id", ""))): raise bad_request("invalid source board ID") _int(source.get("channel_id"), "source channel ID") _text(source.get("board_url"), "source URL", 2048) url = urlsplit(source["board_url"]) if url.scheme not in ("http", "https") or not url.netloc or url.username or url.password or url.query or url.fragment: raise bad_request("source URL must be an HTTP(S) board address") for field, limit in [("principals", MAX_MESSAGES + MAX_ATTACHMENTS), ("messages", MAX_MESSAGES), ("reactions", MAX_MESSAGES * 100), ("attachments", MAX_ATTACHMENTS), ("storage_files", MAX_ATTACHMENTS)]: if field == "storage_files": m.setdefault(field, []) if not isinstance(m.get(field), list) or len(m[field]) > limit or any(not isinstance(x, dict) for x in m[field]): raise bad_request(f"invalid or oversized {field} list") people = {} handles = set() for p in m["principals"]: p.setdefault("display_name", None) pid = _int(p.get("id"), "author ID") handle = p.get("external_id") if not isinstance(handle, str) or not store.EXTERNAL_ID.fullmatch(handle) or handle.lower() in handles or pid in people: raise bad_request("duplicate or invalid author handle/ID") if p.get("identity_type") not in ("user", "agent", "system"): raise bad_request("invalid author type") if p.get("display_name") is not None: _text(p["display_name"], "display name", 1024) people[pid] = p handles.add(handle.lower()) attachments = {} for a in m["attachments"]: a.setdefault("filename", None) a.setdefault("content_type", None) aid = a.get("id") if not isinstance(aid, str) or not re.fullmatch(r"att_[A-Za-z0-9_-]{1,120}", aid) or aid in attachments: raise bad_request("duplicate or invalid attachment ID") if a.get("uploader_id") not in people or not HASH.fullmatch(str(a.get("sha256", ""))): raise bad_request("invalid attachment author or checksum") if type(a.get("size")) is not int or not 0 <= a["size"] <= LIMITS.max_upload_bytes: raise bad_request("invalid attachment size") for field, limit in [("filename", 1024), ("content_type", 128)]: if a.get(field) is not None: _text(a[field], field, limit) _time(a.get("created_at"), "attachment timestamp") attachments[aid] = a paths = set() aliases = set() for f in m["storage_files"]: if f.get("owner_id") not in people or not HASH.fullmatch(str(f.get("sha256", ""))): raise bad_request("invalid storage owner or checksum") f["path"] = store.storage_path(f.get("path")) if type(f.get("size")) is not int or not 0 <= f["size"] <= MAX_BUNDLE_BYTES: raise bad_request("invalid storage file size") _time(f.get("updated_at"), "storage timestamp") f.setdefault("content_type", None) if f["content_type"] is not None: _text(f["content_type"], "storage content type", 128) if not isinstance(f.get("handles"), list) or not f["handles"]: raise bad_request("storage handle aliases are required") for handle in f["handles"]: if not isinstance(handle, str) or not store.EXTERNAL_ID.fullmatch(handle) or (handle, f["path"]) in aliases: raise bad_request("invalid or duplicate storage alias") aliases.add((handle, f["path"])) if (f["owner_id"], f["path"]) in paths: raise bad_request("duplicate storage path") paths.add((f["owner_id"], f["path"])) ordered_paths = sorted(paths) if any(owner == next_owner and child.startswith(path + "/") for (owner, path), (next_owner, child) in pairwise(ordered_paths)): raise bad_request("storage files have a file/folder collision") if len(paths) + len(attachments) > MAX_ATTACHMENTS: raise bad_request("too many attachment/storage files") messages = {} seqs = set() for msg in m["messages"]: msg.setdefault("reply_to", None) msg.setdefault("edited_at", None) mid = _int(msg.get("id"), "message ID") seq = _int(msg.get("seq"), "message sequence") if mid in messages or seq in seqs or msg.get("sender_id") not in people: raise bad_request("duplicate message ID/sequence or missing author") _text(msg.get("body"), "message body") _time(msg.get("created_at"), "message timestamp") if msg.get("edited_at") is not None: _time(msg["edited_at"], "edit timestamp") if not isinstance(msg.get("attachments"), list) or len(msg["attachments"]) > LIMITS.max_attachments_per_message: raise bad_request("invalid message attachments") if any(not isinstance(aid, str) or aid not in attachments for aid in msg["attachments"]): raise bad_request("message refers to a missing attachment") messages[mid] = msg seqs.add(seq) # Parent links, not untrusted thread_id, define the thread. Validate the whole # graph before any database writes, including parents with later timestamps. for mid, msg in messages.items(): seen = {mid} parent = msg.get("reply_to") while parent is not None: if type(parent) is not int or parent not in messages or parent in seen: raise bad_request("missing parent or cyclic thread") seen.add(parent) parent = messages[parent].get("reply_to") reactions = set() for r in m["reactions"]: if r.get("message_id") not in messages or r.get("principal_id") not in people: raise bad_request("reaction refers to a missing message or author") store._valid_emoji(r.get("emoji")) _time(r.get("created_at"), "reaction timestamp") key = (r["message_id"], r["principal_id"], r["emoji"]) if key in reactions: raise bad_request("duplicate reaction") reactions.add(key) doc = m.setdefault("doc", None) if doc is not None: if not isinstance(doc, dict) or doc.get("author_id") not in people: raise bad_request("invalid channel doc author") _text(doc.get("body"), "channel doc", store.MAX_DOC_BYTES) _time(doc.get("created_at"), "doc timestamp") for body in [msg["body"] for msg in m["messages"]] + ([doc["body"]] if doc else []): for match in storage_links(body): ref = storage_reference(match.group(), source["board_url"]) if ref is not None and (ref[0], ref[1]) not in aliases: raise bad_request("bundle omits a linked same-board storage file") return m
def read_bundle(path: Path, stage: Path): try: with zipfile.ZipFile(path) as z: entries = z.infolist() names = [e.filename for e in entries] if len(names) != len(set(names)) or len(names) > MAX_ATTACHMENTS + 1: raise bad_request("duplicate ZIP members or too many files") if sum(e.file_size for e in entries) > MAX_BUNDLE_BYTES: raise ApiError(413, "too_large", "expanded bundle exceeds 512 MiB") if z.getinfo("manifest.json").file_size > MAX_MANIFEST_BYTES: raise ApiError(413, "too_large", "manifest exceeds 32 MiB") m = validate_manifest(json.loads(z.read("manifest.json"))) all_files = m["attachments"] + m["storage_files"] hashes = {a["sha256"] for a in all_files} if set(names) != {"manifest.json"} | {"blobs/" + sha for sha in hashes}: raise bad_request("ZIP members must exactly match the manifest's blobs") files = {} for sha in hashes: expected = {a["size"] for a in all_files if a["sha256"] == sha} info = z.getinfo("blobs/" + sha) if expected != {info.file_size}: raise bad_request("attachment length does not match manifest") dest = stage / sha h = hashlib.sha256() with z.open(info) as src, dest.open("xb") as dst: while chunk := src.read(1024 * 1024): h.update(chunk) dst.write(chunk) if h.hexdigest() != sha: raise bad_request("attachment checksum does not match manifest") files[sha] = dest return m, hashlib.sha256(canonical(m)).hexdigest(), files except (zipfile.BadZipFile, KeyError, ValueError, TypeError, UnicodeError, RuntimeError) as exc: raise bad_request("invalid channel bundle") from exc
def plan_import(conn, p, channel_id, m, digest, keep_target_doc=False): ch = public_channel(conn, p, channel_id) existing = conn.execute("SELECT * FROM channel_imports WHERE channel_id = ?", (channel_id,)).fetchone() blockers, mappings = [], [] replay = bool(existing and existing["digest"] == digest) if existing and not replay: blockers.append("target already holds a different import; incremental imports are not supported") if not existing: if conn.execute("SELECT 1 FROM messages WHERE channel_id = ? LIMIT 1", (channel_id,)).fetchone(): blockers.append("initial import requires an empty target channel") if ch["doc_version"] and not keep_target_doc: blockers.append("initial import requires a target with no channel doc") if ch["archived"]: blockers.append("target channel is archived") for author in m["principals"]: rows = conn.execute("SELECT * FROM principals WHERE lower(external_id) = lower(?)", (author["external_id"],)).fetchall() if len(rows) > 1 or (rows and rows[0]["identity_type"] != author["identity_type"]): blockers.append(f"ambiguous or different-type handle: {author['external_id']}") mappings.append({"source_id": author["id"], "handle": author["external_id"], "display_name": author["display_name"], "target_id": rows[0]["id"] if len(rows) == 1 else None, "action": "existing" if rows else "ghost"}) by_author = {a["source_id"]: a for a in mappings} planned_files = [] additions = {} max_file, quota = store.storage_limits(conn) for f in m["storage_files"]: mapping = by_author[f["owner_id"]] owner_id = mapping["target_id"] if owner_id: owner = conn.execute("SELECT disabled, joined_via FROM principals WHERE id = ?", (owner_id,)).fetchone() if owner["disabled"] and owner["joined_via"] != "import": blockers.append(f"mapped storage owner is disabled: {mapping['handle']}") old = conn.execute("SELECT size, sha256 FROM storage_files WHERE owner_id = ? AND path = ?", (owner_id, f["path"])).fetchone() if owner_id else None action = "reuse" if old and old["sha256"] == f["sha256"] and old["size"] == f["size"] else "create" if old and action != "reuse": action = "conflict" blockers.append(f"different target storage file: {mapping['handle']}/{f['path']}") if f["size"] > max_file: blockers.append(f"storage file exceeds target per-file limit: {mapping['handle']}/{f['path']}") if owner_id: occupied = [r[0] for r in conn.execute("SELECT path FROM storage_files WHERE owner_id = ?", (owner_id,))] if any(path.startswith(f["path"] + "/") or f["path"].startswith(path + "/") for path in occupied): blockers.append(f"file/folder collision: {mapping['handle']}/{f['path']}") if not old: additions[f["owner_id"]] = additions.get(f["owner_id"], 0) + f["size"] planned_files.append({"handle": mapping["handle"], "target_id": owner_id, "path": f["path"], "size": f["size"], "sha256": f["sha256"], "action": action}) for source_id, size in additions.items(): mapping = by_author[source_id] used = store.storage_usage(conn, mapping["target_id"]) if mapping["target_id"] else 0 if used + size > quota: blockers.append(f"storage folder exceeds target quota: {mapping['handle']}") counts = {"messages": len(m["messages"]), "attachments": len(m["attachments"]), "storage_files": len(planned_files), "bytes": sum(a["size"] for a in m["attachments"] + m["storage_files"]), "reactions": len(m["reactions"]), "ghosts": sum(a["action"] == "ghost" for a in mappings), "doc": int(m["doc"] is not None)} report = {"source": m["source"], "target_channel_id": channel_id, "digest": digest, "already_imported": replay, "can_import": not blockers, "blockers": blockers, "counts": counts, "would_create": {k: 0 if replay else v for k, v in counts.items()}, "authors": mappings, "storage_files": planned_files} report["would_create"]["storage_files"] = 0 if replay else sum(f["action"] == "create" for f in planned_files) report["document"] = {"action": "keep_target" if keep_target_doc else "import_source" if m["doc"] else "none", "target_version": ch["doc_version"]} if keep_target_doc: report["would_create"]["doc"] = 0 if replay: previous = json.loads(existing["report"]) report["document"] = previous.get("document", report["document"]) return report
def verify_reused_storage(report, storage): """Metadata equality alone cannot prove a mutable bucket key still has its bytes.""" with tempfile.TemporaryDirectory(prefix="msgboard-reuse-") as scratch: for f in report["storage_files"]: if f["action"] != "reuse": continue path = Path(scratch) / "file" ok = storage.get(store.storage_key(f["target_id"], f["path"]), path) digest = hashlib.sha256() if ok and path.stat().st_size == f["size"]: with path.open("rb") as src: while chunk := src.read(1024 * 1024): digest.update(chunk) if not ok or path.stat().st_size != f["size"] or digest.hexdigest() != f["sha256"]: report["blockers"].append(f"target storage bytes unavailable or mismatched: {f['handle']}/{f['path']}") report["can_import"] = False return report
def _rewrite_storage(body, source_url, files, handles): aliases = {(alias, f["path"]): handles[f["owner_id"]] for f in files for alias in f["handles"]} def replace(match): ref = storage_reference(match.group(), source_url) if ref is None or (ref[0], ref[1]) not in aliases: return match.group() handle, path, url, suffix = ref target = aliases[(handle, path)] if not url.netloc and target == handle: return match.group() return urlunsplit(("", "", "/v1/storage/" + quote(target, safe="") + "/" + quote(path, safe="/"), url.query, url.fragment)) + suffix parts, start = [], 0 for match in storage_links(body): parts.extend((body[start:match.start()], replace(match))) start = match.end() parts.append(body[start:]) return "".join(parts)
def _rewrite_attachments(body, source_url, ids): # Absolute links to this source become target-local links. Foreign/storage # links and old textual "msg N" references are deliberately untouched. for old, new in ids.items(): body = body.replace(source_url.rstrip("/") + "/v1/attachments/" + old, "/v1/attachments/" + new) body = re.sub(r"(?<![A-Za-z0-9_./:-])/v1/attachments/" + re.escape(old) + r"(?![A-Za-z0-9_-])", "/v1/attachments/" + new, body) body = re.sub(r"#file/" + re.escape(old) + r"(?![A-Za-z0-9_-])", "#file/" + new, body) return body
def prepare_import(conn, p, channel_id, m, digest, now, keep_target_doc=False): report = plan_import(conn, p, channel_id, m, digest, keep_target_doc) if not report["can_import"]: raise ApiError(409, "import_blocked", "channel import is blocked", details=report) people, created = {}, [] for mapping in report["authors"]: if mapping["target_id"] is None: author = next(a for a in m["principals"] if a["id"] == mapping["source_id"]) cursor = conn.execute("""INSERT INTO principals (issuer, external_id, identity_type, role, display_name, disabled, created_at, created_by, joined_via) VALUES ('import', ?, ?, ?, ?, 1, ?, ?, 'import')""", (author["external_id"], author["identity_type"], "viewer" if author["identity_type"] == "user" else "guest", author["display_name"], now, p.id)) mapping["target_id"] = cursor.lastrowid created.append((cursor.lastrowid, author["external_id"], now)) people[mapping["source_id"]] = mapping["target_id"] return {"report": report, "people": people, "created_ghosts": created, "keep_target_doc": keep_target_doc}
def checked_import_plan(conn, p, channel_id, m, digest, prepared): report = plan_import(conn, p, channel_id, m, digest, prepared.get("keep_target_doc", False)) if any(a["target_id"] != prepared["people"].get(a["source_id"]) for a in report["authors"]): report["blockers"].append("author mappings changed during preparation; retry the import") report["can_import"] = False created = {row[0] for row in prepared["created_ghosts"]} report["counts"]["ghosts"] = len(created) report["would_create"]["ghosts"] = 0 if report["already_imported"] else len(created) for author in report["authors"]: if author["target_id"] in created: author["action"] = "ghost" return report
def cleanup_ghosts(conn, prepared): for pid, handle, created_at in prepared["created_ghosts"]: try: # Never remove an identity another operation has adopted or changed. # Foreign keys leave a referenced ghost intact. conn.execute("""DELETE FROM principals WHERE id = ? AND external_id = ? AND created_at = ? AND joined_via = 'import' AND disabled = 1 AND owner_id IS NULL AND NOT EXISTS (SELECT 1 FROM credentials WHERE principal_id = principals.id) AND NOT EXISTS (SELECT 1 FROM audit_log WHERE target = 'principal:' || principals.id)""", (pid, handle, created_at)) except sqlite3.IntegrityError: pass
def attachment_id(channel_id, source, old_id): return "att_" + hashlib.sha256(canonical([channel_id, source["board_id"], source["channel_id"], old_id])).hexdigest()[:32]
def stage_import(channel_id, m, files, prepared, blobs, storage, uploaded_storage, uploaded_attachments): """All network reads/uploads and local blob I/O run before the writer transaction.""" report = prepared["report"] if not report["can_import"]: raise ApiError(409, "import_blocked", "channel import is blocked", details=report) report = verify_reused_storage(report, storage) if not report["can_import"]: raise ApiError(409, "import_blocked", "channel import is blocked", details=report) if report["already_imported"]: return for f, planned in zip(m["storage_files"], report["storage_files"]): if planned["action"] == "reuse": continue key = store.storage_key(prepared["people"][f["owner_id"]], f["path"]) uploaded_storage.append(key) # also clean up a backend that writes, then raises storage.put([(files[f["sha256"]], key)]) for a in m["attachments"]: aid = attachment_id(channel_id, m["source"], a["id"]) key = f"{aid[4:6]}/{aid}" dest = blobs.path_for(key) if dest.exists(): digest = hashlib.sha256() with dest.open("rb") as src: while chunk := src.read(1024 * 1024): digest.update(chunk) if digest.hexdigest() != a["sha256"] or dest.stat().st_size != a["size"]: raise conflict("import_blob_conflict", "an existing attachment blob has different bytes") continue temp, fh = blobs.open_temp() uploaded_attachments.append(key) try: with files[a["sha256"]].open("rb") as src: shutil.copyfileobj(src, fh) blobs.finish_temp(fh) blobs.commit(temp, key) finally: if not fh.closed: fh.close() blobs.discard(temp)
def import_channel(conn, p, channel_id, m, digest, prepared, now): """Publish metadata only. Bucket and local file I/O has already finished.""" report = checked_import_plan(conn, p, channel_id, m, digest, prepared) if not report["can_import"]: raise ApiError(409, "import_blocked", "channel import is blocked", details=report) if report["already_imported"]: return report people = prepared["people"] source = m["source"] handles = {sid: conn.execute("SELECT external_id FROM principals WHERE id = ?", (pid,)).fetchone()[0] for sid, pid in people.items()} for f in m["storage_files"]: owner_id = people[f["owner_id"]] old = conn.execute("SELECT sha256, size FROM storage_files WHERE owner_id = ? AND path = ?", (owner_id, f["path"])).fetchone() if old: continue # plan and byte verification established that it is identical store.storage_record(conn, p, owner_id, f["path"], f["size"], f["sha256"], f["content_type"], f["updated_at"]) aid_map = {} for a in m["attachments"]: aid = attachment_id(channel_id, source, a["id"]) aid_map[a["id"]] = aid storage_key = f"{aid[4:6]}/{aid}" conn.execute("""INSERT INTO attachments (id, channel_id, uploader_id, upload_id, storage_key, filename, content_type, size, sha256, state, published, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'ready', 1, ?)""", (aid, channel_id, people[a["uploader_id"]], "import:" + aid, storage_key, a["filename"], a["content_type"], a["size"], a["sha256"], a["created_at"])) seq = conn.execute("SELECT next_seq FROM channels WHERE id = ?", (channel_id,)).fetchone()[0] ids = {} ordered = sorted(m["messages"], key=lambda msg: (msg["created_at"], msg["seq"], msg["id"])) for msg in ordered: origin = {"board_url": source["board_url"], "channel_id": source["channel_id"], "message_id": msg["id"]} cursor = conn.execute("""INSERT INTO messages (channel_id, seq, sender_id, body, attachments, request_id, payload_hash, created_at, edited_at, imported, import_source) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?)""", (channel_id, seq, people[msg["sender_id"]], _rewrite_storage(_rewrite_attachments(msg["body"], source["board_url"], aid_map), source["board_url"], m["storage_files"], handles), json.dumps([aid_map[a] for a in msg["attachments"]]), "import:" + hashlib.sha256(canonical([channel_id, source["board_id"], source["channel_id"], msg["id"]])).hexdigest(), digest, msg["created_at"], msg["edited_at"], json.dumps(origin))) ids[msg["id"]] = cursor.lastrowid seq += 1 by_id = {msg["id"]: msg for msg in ordered} for msg in ordered: parent = msg["reply_to"] if parent is not None: root = parent while by_id[root]["reply_to"] is not None: root = by_id[root]["reply_to"] conn.execute("UPDATE messages SET reply_to = ?, thread_id = ? WHERE id = ?", (ids[parent], ids[root], ids[msg["id"]])) for r in m["reactions"]: conn.execute("INSERT INTO message_reactions (message_id, principal_id, emoji, created_at) VALUES (?, ?, ?, ?)", (ids[r["message_id"]], people[r["principal_id"]], r["emoji"], r["created_at"])) if m["doc"] is not None and not prepared.get("keep_target_doc", False): doc = m["doc"] conn.execute("INSERT INTO channel_doc_versions (channel_id, version, body, author_id, created_at) VALUES (?, 1, ?, ?, ?)", (channel_id, _rewrite_storage(_rewrite_attachments(doc["body"], source["board_url"], aid_map), source["board_url"], m["storage_files"], handles), people[doc["author_id"]], doc["created_at"])) conn.execute("UPDATE channels SET doc_version = 1 WHERE id = ?", (channel_id,)) conn.execute("UPDATE channels SET next_seq = ? WHERE id = ?", (seq, channel_id)) conn.execute("""INSERT INTO channel_reads (principal_id, channel_id, last_read_seq, thread_floor, updated_at) SELECT id, ?, ?, ?, ? FROM principals WHERE true ON CONFLICT (principal_id, channel_id) DO UPDATE SET last_read_seq = max(last_read_seq, excluded.last_read_seq), thread_floor = max(thread_floor, excluded.thread_floor)""", (channel_id, seq - 1, seq - 1, now)) conn.execute("INSERT INTO channel_imports VALUES (?, ?, ?, ?, ?, ?)", (channel_id, source["board_id"], source["channel_id"], digest, json.dumps(report), now)) store.audit(conn, p.id, "channel.import", f"channel:{channel_id}", {"source": source, "digest": digest, "counts": report["counts"]}, now) return report12345fastapi>=0.110uvicorn>=0.29httpx>=0.27markdown-it-py>=3huggingface_hub>=1.31DockerfileAdded+13
LICENSEAdded+201
README.md+23-5
msgboard/__init__.pyAdded+3
msgboard/__main__.pyAdded+3
msgboard/analytics.pyAdded+99
msgboard/auth.pyAdded+137
msgboard/blobs.pyAdded+57
msgboard/cli.pyAdded+343
msgboard/client.pyAdded+545
msgboard/config.pyAdded+44
msgboard/dashboard.htmlAdded
msgboard/db.pyAdded+742
msgboard/demo.pyAdded+53
msgboard/demo_agent.pyAdded+59
msgboard/errors.pyAdded+32
msgboard/guide.pyAdded+267
msgboard/local.pyAdded+49
msgboard/presence.pyAdded+124
msgboard/replicate.pyAdded+339
msgboard/reservations.pyAdded+29
msgboard/server.pyAdded+1353
msgboard/space/__init__.pyAdded+10
msgboard/space/accounts.pyAdded+250
msgboard/space/app.pyAdded+190
msgboard/space/hub.pyAdded+256
msgboard/store.pyAdded
msgboard/tasks.pyAdded+565
msgboard/transfer.pyAdded+647
requirements.txtAdded+5