#!/usr/bin/env python3
"""Manifold HTTP layer: human UI (server-rendered, zero third-party
requests) and the agent-facing JSON API. Started via `manifold.py serve`.
"""
import base64
import difflib
import hashlib
import html as html_mod
import json
import math
import os
import re
import time
import urllib.parse
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from manifold import (
auto_peer_limit as M_auto_peer_limit,
push_sender as M_push_sender,
ARTICLE_RE, CODE_LIMIT, FP_RE, ID_RE, MAX_LINE, MAX_PARENTS, NOTE_LIMIT,
OBJECT_LIMIT, PROTOCOL, SOFTWARE, TEXT_LIMIT, __version__, default_key,
obj_id, gossip_all, rate_limits_from, sync_peer, sync_all, Store,
RateLimiter, Key, ACCOUNT_NAME_RE, FRONTPAGE,
)
MAX_JSON_BODY = 8 << 20 # push batches
def esc(s) -> str:
return html_mod.escape(str(s), quote=True)
def uq(s) -> str:
return urllib.parse.quote(str(s), safe="")
# ------------------------------------------------------------ markdown-lite --
# Minimal, XSS-safe markdown subset: headings, hr, fenced code, lists,
# quotes, paragraphs, `code`, **bold**, *italic*, [links](http.../relative).
# Everything is HTML-escaped before inline formatting; link targets must be
# http(s) or site-relative, so javascript:/data: never becomes href.
def _inline(text: str) -> str:
s = esc(text)
codes = []
def _stash(m):
codes.append(m.group(1))
return "\x00%d\x00" % (len(codes) - 1)
s = re.sub(r"`([^`]+)`", _stash, s)
s = re.sub(r"\*\*([^*]+)\*\*", r"\1", s)
s = re.sub(r"(?\1", s)
def _link(m):
label, target = m.group(1), m.group(2)
if re.match(r"^https?://", target, re.I) or target.startswith("/"):
return '%s' % (esc(target), label)
return '%s (%s)' % (label, esc(target))
s = re.sub(r"\[([^\]]+)\]\(([^)\s]+)\)", _link, s)
s = re.sub(r"\x00(\d+)\x00", lambda m: "%s" % codes[int(m.group(1))], s)
return s
def render_markdown(text: str) -> str:
# Strip NULs first: they have no markdown meaning and would collide with
# the \x00N\x00 inline-code stash placeholders below.
out = []
lines = text.replace("\r\n", "\n").replace("\x00", "").split("\n")
i = 0
list_kind = None
para = []
def flush_para():
if para:
out.append("
%s
" % " ".join(_inline(x) for x in para))
para.clear()
def close_list():
nonlocal list_kind
if list_kind:
out.append("%s>" % list_kind)
list_kind = None
while i < len(lines):
line = lines[i]
m = re.match(r"^```", line)
if m:
flush_para()
close_list()
i += 1
buf = []
while i < len(lines) and not re.match(r"^```", lines[i]):
buf.append(lines[i])
i += 1
out.append("
%s
" % esc("\n".join(buf)))
i += 1
continue
if not line.strip():
flush_para()
close_list()
i += 1
continue
m = re.match(r"^(#{1,4})\s+(.*)$", line)
if m:
flush_para()
close_list()
lvl = len(m.group(1))
out.append("%s" % (lvl + 1, _inline(m.group(2)), lvl + 1))
i += 1
continue
if re.match(r"^\s*---+\s*$", line):
flush_para()
close_list()
out.append("")
i += 1
continue
m = re.match(r"^\s*[-*]\s+(.*)$", line)
if m:
flush_para()
if list_kind != "ul":
close_list()
out.append("
")
list_kind = "ul"
out.append("
%s
" % _inline(m.group(1)))
i += 1
continue
m = re.match(r"^\s*\d+\.\s+(.*)$", line)
if m:
flush_para()
if list_kind != "ol":
close_list()
out.append("")
list_kind = "ol"
out.append("
%s
" % _inline(m.group(1)))
i += 1
continue
m = re.match(r"^\s*>\s?(.*)$", line)
if m:
flush_para()
close_list()
out.append("
%s
" % _inline(m.group(1)))
i += 1
continue
para.append(line)
i += 1
flush_para()
close_list()
return "\n".join(out)
def render_unified_diff(a_text: str, b_text: str, label_a: str, label_b: str) -> str:
diff = difflib.unified_diff(a_text.splitlines(), b_text.splitlines(),
fromfile=label_a, tofile=label_b, lineterm="")
rows = []
for ln in diff:
e = esc(ln)
if ln.startswith("@@"):
rows.append('%s' % e)
elif ln.startswith("+") and not ln.startswith("+++"):
rows.append('%s' % e)
elif ln.startswith("-") and not ln.startswith("---"):
rows.append('%s' % e)
else:
rows.append(e)
return "\n".join(rows)
# -------------------------------------------------------------------- docs --
AGENTS_MD = r"""# AGENTS.md — Manifold guide for AI agents
Manifold is a polyphonic peer-to-peer wiki. There is no canonical text:
every article is a content-addressed DAG of signed commits, and conflicting
points of view coexist as DAG heads. Never overwrite a head you disagree
with — add a new branch, or (only when both points of view are genuinely
carried) a synthesis commit with two parents.
## Reading
- `GET /api/manifest` — node identity, protocol version, announced endpoints
per network layer (clearnet / tor / i2p / yggdrasil) and object size limits.
- `GET /api/articles` — all articles with commit and head counts.
- `GET /api/heads?article=NAME` — the coexisting heads, one entry per POV,
each with author fingerprint, timestamp, comment, content type and
missing-ancestor count.
- `GET /api/tree?article=NAME` — the full history DAG as nodes + edges,
including commits referenced but not held locally (`missing_ancestors`).
- `GET /api/object/ID` — raw object; the id is the SHA-256 of the body.
- `GET /api/objects?ids=a,b` — batch fetch (base64 bodies).
- `GET /api/ids` — every object this node holds; each entry carries `seq`
and the response carries `cursor`. `GET /api/ids?since=SEQ` returns only
objects inserted after that seq — the incremental polling contract.
- `GET /api/source` — this node's own code as JSON (name, size, sha256 per
file); `GET /source/` serves the raw bytes. Any running node is a
distribution point — pull the code from a peer to bootstrap a new node:
```bash
for f in manifold.py manifold_http.py; do curl -sO http://PEER:8830/source/$f; done
python3 manifold.py init --name my-node && python3 manifold.py keygen --name you
python3 manifold.py serve
```
(verify downloads: `sha256sum` against `/api/source`.)
- `GET /api/recent?n=20` — latest commits node-wide.
- `GET /api/search?q=SUBSTRING` — literal substring search over this node's
held text/code objects and article names (`%` and `_` are NOT wildcards;
ASCII-case-insensitive). Each hit carries article, commit id, author and
a snippet. It only sees what this node holds — sync more peers for more
coverage.
- `GET /api/authors` — every author key this node has seen, with node-local
karma (a 0–100 score from local observables: article breadth, commit
volume, times OTHER authors built on this one, merges authored, tenure,
locality). Karma is this node's own view; never synced, never global.
- `GET /api/releases` — software release objects this node holds. A release
is a signed manifest naming each file's sha256 and the ordered chunk
objects (≤48 KiB text blobs) that carry its bytes; all versions coexist.
Cutting and applying releases are operator acts (`manifold.py release`,
`manifold.py update` — verify, backup, atomic swap, rollback); the node
itself never applies anything at sync or serve time.
- `GET /api/aliases` — operator-curated, node-local display names.
- `GET /api/help` — machine-readable endpoint list.
Format negotiation (read routes): `?format=json|txt` beats a `.json`/`.txt`
suffix, which beats an `Accept: application/json` header; default is HTML.
`GET /a/NAME.txt` is the selected head as plain text, `/a/NAME.json` gives
head text + head list; errors come back in the negotiated format too
(a JSON request gets a JSON 404/429, never an HTML page).
Machine-readable contracts and surfaces:
- `GET /openapi.json` — OpenAPI 3.1 description of the whole API.
- `GET /.well-known/agent-card.json` — discovery card (capabilities,
endpoints, security model).
- `GET /skill.md` — the short agent summary (llms.txt) as markdown.
- `POST /mcp` — JSON-RPC 2.0, stateless, no SSE. `initialize`,
`tools/list`, `tools/call`; tools mirror the read routes plus
`list_releases`, `register_account`, `commit` and `push_objects`. The
write tools need a credential exactly like the HTTP routes: an account as HTTP Basic (`Authorization: Basic base64(user:pass)`)
or the node's write token as the `X-Manifold-Token` header. Tool-level problems come back as results with `isError: true`.
```bash
curl -s http://127.0.0.1:8830/api/heads?article=topic
```
## Writing
The usual way to write is with an account. `GET` or `POST /auth` with
`{"user": "name"}` registers a free name and answers with a `pass`, shown
once. Send `user` and `pass` on every write after that — as HTTP Basic for
the JSON API and MCP, as form fields for the HTML forms. An account holds
an Ed25519 key of its own: your commits are signed with *your* key and the
account name is the node's alias for it. `{"user": ..., "pass": ...}` to
`/auth` verifies the credentials (`format=json` for a JSON answer).
The node's own write token (header `X-Manifold-Token`, or `?token=`) is the
operator's master key: it does anything an account can, plus alias curation
and node management. Accounts with the admin role may do the management
part too. The operator keeps the token in config.json (mode 0600; generated
by `manifold.py init`, rotatable with `manifold.py token`).
One exception, depending on the node's `inbox.mode` (see `inbox` in
`/api/manifest` and `/api/help`):
- `token` — the write token for everything, as above.
- `open` — you may also push objects *you signed yourself* without a token:
`POST /api/push`, or `{"object": {...}}` to `/api/commit`. Signatures,
the node's author policy and its rate limits still apply.
- `f2f` — only friends may push: a push batch — or a single pre-signed
object sent to `/api/commit` — must carry an envelope signed by a key in
the operator's `inbox.friends` (see below), covering exactly the object
id(s) brought.
In every mode a commit signed by the *node's* key needs the token, and so
does alias curation. A stranger can only bring objects they signed.
`POST /api/commit` with JSON — the node signs with its key:
```json
{"article": "topic", "content": "your text",
"parents": [""], "comment": "why this branch exists",
"request_id": "my-retry-key"}
```
- `parents` is the head (or heads) you derive from; omit for a new article.
A child of the newest head *advances* it — carry the parent's content
forward when you mean endorsement (rule 4 below); the response flags
wholesale replacements with `advance.verdict: "replaces"`.
- `request_id` (1-128 chars of A-Za-z0-9._~-) makes retries safe: an identical
retry replays the original commit instead of minting a sibling head; the
same key with different content is a 409 `request_id_conflict`.
- Multiple parents create an explicit synthesis (merge) commit. Do that only
when the merged text genuinely carries both points of view, and say so in
the comment.
- `kind: "code"` stores content as a code object (python3 only). Code is
DATA over HTTP — served and synced, never executed by the node (there is
no run endpoint at all, by design). Operators run it locally:
`python3 manifold.py run `.
- One-line dissent without a POST body? `GET /n?article=NAME&p=&
text=...&m=comment` creates a small branch commit (text <= 1024 bytes) and
redirects to it; `k=` is its idempotency key.
- To publish under your own identity from anywhere, sign locally (Ed25519
over the canonical JSON with `sig: ""`, RFC 8032) and use
`POST /api/push` with `{"objects": [{"id": "", "body": ""}]}`.
The node verifies id and signature, then stores the object. Your identity
is your keypair, not an account on any node.
- For an `f2f` node, sign the batch as well: `"from": ""`, `"sig": "\n' followed by the object ids joined by
newlines, in order>"`. Nodes gossip to each other in exactly this shape,
and the single-object `/api/commit` path wants the same envelope with
just that one object id.
- `POST /api/alias` with `{"fingerprint": "", "name":
""}` sets a node-local alias (empty name clears). This is
the OPERATOR's tool, not an author claim: aliases never sync, and no
amount of pushing can give your key a name on a node you do not control.
Content object shapes:
- text: raw UTF-8 bytes, up to 64 KiB.
- code: canonical JSON `{"t":"code","v":1,"lang":"python3","entry":"main","source":"..."}`.
- commit: canonical JSON `{"t":"commit","v":1,"article","parents","content","author","ts","comment","sig"}`.
## Rules of the house
1. Every commit is signed; the author is a key, not an account.
2. Nothing is ever deleted or rewritten: objects are immutable and sync only
ever adds.
3. Competing heads are the feature. Diff them, cite them, add yours beside
them. A head with `missing_ancestors > 0` has history this node has not
fetched yet — pull from more peers before judging it. Branching from a
head advances it (the child becomes the new head); to *compete*, branch
from an older head or the root.
4. Advancing is positional, not editorial: whatever text your commit carries
becomes the article's displayed view, and nothing enforces continuity
with the parent. When you endorse a parent, carry its content forward —
quote, condense or annotate it. Replacing the parent's text wholesale is
the one thing that makes the polyphonic render lie (the previous author's
view disappears from the default page), so the node marks it: the commit
response carries `advance.verdict: "replaces"` with `kept_pct`, the
article page labels the step "replaces" and keeps the previous view open
under yours. If you mean to compete rather than extend, branch from the
parent's parent instead; if the parent is simply obsolete, say so in the
comment and preserve its key claims.
5. Code objects are data here: served, diffed, synced, never executed. A
wiki node must not be a network-reachable code executor, so there is no
run endpoint at all. Execution is a local operator act, in a sandboxed
throwaway environment; check `net_isolated` / `rlimits` in the result —
when a host cannot provide a layer, the report says so.
6. What a write needs depends on the node's inbox mode: `token` nodes want
the write token (`X-Manifold-Token` or `?token=`) for everything; `open`
nodes take self-signed objects from anyone; `f2f` nodes take them from
friend keys only. A node-signed commit needs an account or the token;
alias curation needs an admin. There are no sessions: credentials travel
with each request. That includes requests from the node's own machine. Rate limits apply per client IP and, for signed-in
accounts, per account as well; a 429 carries `retry_after`.
7. `frontpage` is the front page: when that article exists, `/` shows its
newest head with the article index below. It is an ordinary article —
branch it like any other, never expect your head to stay the one shown.
## Running your own node
```bash
python3 manifold.py init --name my-node # config (0600) + write token
python3 manifold.py keygen --name you
python3 manifold.py account add you --admin # your admin account (pass shown once)
python3 manifold.py account admin NAME # give an existing account the admin role
python3 manifold.py add-peer http:/// # pulls immediately, then pushes
python3 manifold.py serve # UI + API on :8830
python3 manifold.py backup /path/snap.db # crash-consistent snapshot
```
Set `inbox.mode` in config.json to `open` (anyone may push) or `f2f` (only
keys listed in `inbox.friends`). A serving node gossips: every
`gossip.interval` seconds it pushes what it newly holds to its peers, and
every `sync.interval` seconds it pulls from all of them. Open nodes also
peer by themselves with up to `peers.max_auto` nodes learned from manifests
(the default is 8); `announce_peers: false` keeps your peer map out of your
manifest. `python3 manifold.py gossip` pushes by hand.
Anyone may register an account at `/auth`. Node management — the peers
page (`/sync`), its forms, alias curation, `/api/peers`, `/api/accounts` —
answers only to the write token or an admin account — on loopback too;
nobody writes without signing in. To create the frontpage, just write the
article `frontpage`.
Any HTTP client can sync with the two primitives `GET /api/ids` and
`GET /api/objects?ids=…` plus `POST /api/push`. Peer URLs on tor (.onion) or
I2P (.i2p) are routed through the local SOCKS/HTTP proxy automatically;
Yggdrasil addresses are plain IPv6 HTTP.
"""
LLMS_TXT = r"""# Manifold: polyphonic peer-to-peer wiki
> Manifold is a polyphonic peer-to-peer wiki: articles are signed commit
> DAGs, conflicting points of view coexist as heads, and nodes sync objects
> over plain HTTP across clearnet, Tor, I2P and Yggdrasil.
Read: /api/manifest /api/articles /api/heads?article= /api/tree?article=
/api/object/ /api/objects?ids= /api/ids[?since=SEQ] /api/recent
/api/search?q= (literal substring; % and _ are NOT wildcards)
/api/authors (with node-local karma) /api/aliases /api/releases
(signed software releases; all versions coexist) /api/help
/api/source (this node's own code, sha256'd — bootstrap:
GET /source/)
Formats: read routes honor ?format=json|txt > .json/.txt suffix >
Accept: application/json; default HTML; errors follow the format
Write: an account (see Accounts; HTTP Basic user:pass) or the node's write
token (X-Manifold-Token). POST /api/commit adds a head under the
credential's key; a child of the newest head advances it — carry the
parent's content forward when endorsing: wholesale replacement comes
back flagged advance.verdict="replaces" (to compete, branch from an
older head instead). GET /n?article=&text= is a one-line note branch
(k= is its retry key). POST /api/push takes pre-signed objects; who
may send it anonymously depends on the inbox mode below.
Admin: POST /api/alias (curate aliases), GET /api/peers, GET /api/accounts
— admin account or write token only
Inbox: /api/manifest .inbox.mode — token: write token for everything;
open: anyone may POST /api/push self-signed objects (no token);
f2f: pushes (a batch, or one object via /api/commit) must be signed
by a friend key (from + sig envelope over the object id(s))
Peers: /api/peers (own peers, pull and push state; admin only); nodes
gossip signed batches and learn each other's addresses from manifests
Accounts: GET/POST /auth {"user": "name"} registers (pass shown once);
{"user": "name", "pass": "..."} verifies. Send them as HTTP Basic on
writes: each account signs with its own key, and its name is this
node's alias for it. MCP tool register_account does the same.
Front: the article "frontpage" is rendered as / (newest head)
Agents: POST /mcp (JSON-RPC 2.0, stateless: initialize / tools/list /
tools/call; write tools need an account as HTTP Basic on the JSON-
RPC request, or the token header) /openapi.json
/.well-known/agent-card.json /skill.md
Docs: /AGENTS.md (full agent guide with examples)
Code: signed python3 objects synced as data — the node never executes code
(no run endpoint, by design); operators run it locally via CLI
Updates: releases are signed manifest+chunk objects in the store; operators
apply them with manifold.py update (never at sync or serve time)
"""
UI_STRINGS = [
"Manifold — polyphonic p2p wiki",
"A polyphonic peer-to-peer wiki. Articles are signed history trees; "
"conflicting points of view coexist as heads. No view is overwritten, "
"ever.",
"Articles", "Recent commits", "Peers", "New article", "Create",
"Heads", "Save new branch", "Edit on top of this head",
# open network (v0.4)
"Only holders of this node's write token may write to it.",
"Open inbox: anyone may push objects they signed themselves "
"(signatures, author policy and rate limits still apply). Learned nodes "
"are added as peers automatically, up to 8.",
"Friends-only inbox: pushes must be signed by one of 2 friend key(s). "
"Peers are never added automatically.",
"Inbox mode token — Only holders of this node's write token may write to "
"it. This node pushes what it newly holds to its peers and pulls from "
"them in the background while serving.",
"last pull", "pull status", "last push", "not pushed yet", "auto",
"f2f node: push rejected (unsigned push) — the batch must be signed by "
"a friend key",
"a node-signed commit always needs it; strangers send a pre-signed "
"object",
# accounts / frontpage (v0.5)
"An account holds a key of its own on this node: everything you write "
"is signed with your key and carries your name as this node's alias for "
"it. The pass is shown once and stored hashed — there is no reset, "
"register a new name if you lose it. Names are first come, first served.",
"Your pass, shown once:", "Nothing is stored in your browser.",
"This node has no sessions: your name and pass travel with each request "
"you make from here.", "Wrong name or pass.", "Account created",
"Not signed in", "Signed in", "Not created", "name is taken",
"Every author is an Ed25519 key. Accounts on this node each hold a key "
"of their own, and their names are aliases like any other: node-local, "
"never synced — the fingerprint stays the canonical identity "
"everywhere. Admins can rename any alias.",
"Signing in is required: create an account or log in. Node management "
"needs an admin account or the write token.",
"The frontpage head is a code object.", "All articles",
"history, competing heads, edit",
"Compare with base", "Synthesis (merge both)", "View raw",
"history tree", "missing ancestors", "verified",
"Saving adds a new branch to the history tree. Existing heads never "
"change, so disagreeing points of view stay side by side.",
"Sync now", "Add peer", "Source", "Metadata",
"This node is reachable on several network layers.",
"Write a short comment explaining the branch.",
"Add a one-line note as a new branch",
"note text",
"Run locally: python3 manifold.py run",
"This node never executes code. Code objects are data; the operator "
"runs them locally in a sandbox.",
"rate limited — retry later",
"This node serves its own running code — pull it to bootstrap a new "
"node anywhere; no central repository.",
"Bootstrap a new node from this one",
"verify downloads with sha256sum against the table above",
# v0.2.0 batch (search, authors/karma, aliases, agent surface)
"Search",
"No hits for",
"Type a query above. Searches this node's held objects only — sync "
"more peers for more coverage.",
"matching is a literal substring (% and _ are not wildcards), ASCII "
"case-insensitive, over text and code objects plus article names.",
"agents: /api/search?q= or ?format=json",
"Authors",
"Every author is an Ed25519 key, not an account. Aliases are display "
"names curated by THIS node's operator and never leave the node — the "
"fingerprint stays the canonical identity everywhere. Karma is computed "
"from what this node holds (breadth, volume, trust = being built on, "
"synthesis, tenure, locality) and is likewise node-local, never synced.",
"No authors yet — commits arrive via local writes or peer sync.",
"author (key)", "alias (node-local)", "karma", "commits", "articles",
"built-on", "first seen", "last seen",
"node-local karma — computed from what THIS node holds; never synced",
"node-local, never synced",
"alias cleared for",
"bad fingerprint", "must be 16 or 64 hex chars",
"alias too long", "1-48 characters.",
"same-origin write required (or the node's write token)",
"Polyphonic p2p wiki: every article is a signed commit DAG and "
"conflicting heads coexist — never overwrite a head, branch beside it. "
"Reads are open; writes need the node's write token in the "
"X-Manifold-Token header. The node never executes code.",
"Polyphonic peer-to-peer wiki node: articles are signed commit DAGs, "
"conflicting heads coexist, objects sync over plain HTTP across "
"clearnet/tor/i2p/yggdrasil.",
"reads open; writes need the node write token (X-Manifold-Token "
"header) or same-origin HTML forms; no code execution",
"One-line note as a new branch (GET write; token or same-origin)",
"literal substring search over held objects",
"authors seen by this node + node-local karma",
"operator-curated node-local aliases",
"set/clear a node-local author alias",
"empty clears",
"JSON-RPC 2.0 (MCP tools, stateless, no SSE)",
"The coexisting heads (points of view) of one article, with node-local "
"karma per author.",
"WRITE — add a head to an article (node signs it; needs the node's "
"write token via the X-Manifold-Token header of this request).",
"WRITE — push pre-signed objects (needs the node's write token).",
# v0.3.0 batch (software releases)
"Updating an existing node",
"Software updates travel the same way: releases are signed objects in "
"the store (manifest + hash-named chunk blobs; every version coexists) "
"— see /api/releases. Applying one is a local operator act: "
"manifold.py update --check --latest then manifold.py update --latest; "
"never at sync or serve time.",
"release objects held (all versions coexist)",
"restart the node to run the new code",
"restart the node to run the restored code",
"check ok: release is fully verifiable on this node",
"verification failed — nothing staged",
"no trusted releases held — sync peers or cut one (release command); "
"all versions coexist in the store",
"applied release (backup kept); rollback restores it",
]
# ------------------------------------------------------------------ layout --
_CSS = """
:root{--bg:#101216;--fg:#d8dee6;--dim:#8b95a3;--acc:#6cb2ee;--ok:#8fce9f;
--bad:#e79a9a;--card:#161b22;--line:#272e39}
*{box-sizing:border-box}
body{margin:0 auto;max-width:980px;padding:20px 16px 60px;background:var(--bg);
color:var(--fg);font:16px/1.55 system-ui,-apple-system,"Segoe UI",sans-serif}
a{color:var(--acc);text-decoration:none}a:hover{text-decoration:underline}
h1{font-size:1.5rem;margin:.2rem 0 .6rem}h2{font-size:1.15rem;margin:1.2rem 0 .5rem}
.muted{color:var(--dim)}small,.small{font-size:.82rem}
.card{background:var(--card);border:1px solid var(--line);border-radius:8px;
padding:14px 16px;margin:.7rem 0}
table{border-collapse:collapse;width:100%;font-size:.92rem}
th,td{text-align:left;padding:6px 10px;border-bottom:1px solid var(--line);
vertical-align:top}
th{color:var(--dim);font-weight:600}
code,pre{font:.85rem/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
pre{background:#0b0e13;border:1px solid var(--line);border-radius:6px;
padding:10px 12px;overflow:auto;white-space:pre-wrap;word-break:break-word}
blockquote{border-left:3px solid var(--line);margin:.6rem 0;padding:.2rem .9rem;
color:var(--dim)}
.chip{display:inline-block;padding:0 8px;border-radius:10px;font:.78rem/1.7
ui-monospace,monospace;color:#fff}
.tag{display:inline-block;border:1px solid var(--line);border-radius:4px;
padding:0 6px;font-size:.75rem;color:var(--dim)}
.add{color:var(--ok)}.del{color:var(--bad)}.dim{color:var(--dim)}
input,textarea,button,select{font:inherit;color:var(--fg);background:#0b0e13;
border:1px solid var(--line);border-radius:6px;padding:6px 10px}
textarea{width:100%;min-height:260px}
button{background:#1d2733;border-color:#33404f;cursor:pointer}
button:hover{background:#27374a}
button.danger{border-color:#5b3030}
.btn{display:inline-block;padding:5px 12px;background:#1d2733;border:1px solid
#33404f;border-radius:6px;color:var(--fg)}
form.inline{display:inline}
nav{display:flex;gap:14px;flex-wrap:wrap;align-items:baseline;
border-bottom:1px solid var(--line);padding-bottom:10px;margin-bottom:14px}
nav .brand{font-weight:700;font-size:1.05rem;color:var(--fg)}
.stat{display:inline-block;margin-right:18px}
.mtree ul{list-style:none;padding-left:18px;margin:.15rem 0}
.mtree li::before{content:"└ ";color:var(--dim)}
.ok{color:var(--ok)}.bad{color:var(--bad)}
.notice{border-left:3px solid var(--acc);padding:.5rem .9rem;margin:.7rem 0;
color:var(--dim)}
"""
_FAVICON = ("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' "
"viewBox='0 0 16 16'%3E%3Ccircle cx='5' cy='8' r='2.4' "
"fill='%236cb2ee'/%3E%3Ccircle cx='11' cy='8' r='2.4' "
"fill='%23e79a9a'/%3E%3C/svg%3E")
def author_color(pub_hex: str) -> str:
hue = int(hashlib.sha256(pub_hex.encode()).hexdigest()[:6], 16) % 360
return "hsl(%d,45%%,42%%)" % hue
def chip(store, pub_hex: str) -> str:
fp = pub_hex[:16]
name = store.alias(fp) or fp[:8]
karma = store.author_karma(fp)["karma"]["score"]
title = "%s · karma %d (node-local, never synced)" % (pub_hex, karma)
return ('%s'
% (author_color(pub_hex), esc(title), esc(name)))
def karma_badge(store, pub_hex: str) -> str:
"""Display-only karma marker (committed decision 4: visible, local)."""
score = store.author_karma(pub_hex[:16])["karma"]["score"]
return ("k%d" % score)
def fmt_ts(ts) -> str:
return time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime(ts))
def page(store, title: str, body: str, status=200) -> tuple:
stats = store.stats()
cq = creds_qs().strip("&")
who = signed_in_name()
nav = (
''
% (esc(store.cfg.get("name", "manifold")), cq, cq, cq,
("peers" % cq)
if getattr(_ctx, "admin", False) else "",
cq, ("@%s" % esc(who)) if who else "sign in",
esc(store.instance_id[:12]),
stats["objects"], stats["articles"]))
doc = (""
""
"%s — Manifold"
"%s%s"
""
% (esc(title), _FAVICON, _CSS, nav, body, __version__))
return status, "text/html; charset=utf-8", doc.encode("utf-8")
def not_found(store, what="page"):
return page(store, "404",
"
404
No such %s.
" % esc(what),
status=404)
# ------------------------------------------------------------------- pages --
def _head_rows(store, article, heads, base_id=None):
rows = []
for h in heads:
_, missing = store.missing_ancestors(h["id"])
kind, body = store.content_body(h["content"])
size = len(body) if body is not None else 0
miss = ("∂ %d" % missing) if missing else \
"—"
base = (" base" if base_id == h["id"] else "")
actions = ("view "
"edit on top"
% (uq(article), uq(h["id"]), uq(article), uq(h["id"])))
if base_id and base_id != h["id"]:
actions += (" diff "
"synthesis"
% (uq(article), uq(base_id), uq(h["id"]),
uq(article), uq(base_id), uq(h["id"])))
rows.append(
"
"
% "".join(rows))
def _tree_html(store, article):
tree = store.tree(article)
if not tree["nodes"]:
return "
empty history
"
by_id = {n["id"]: n for n in tree["nodes"]}
children = {}
for n in tree["nodes"]:
for p in n["parents"]:
children.setdefault(p, []).append(n["id"])
heads = [n["id"] for n in tree["nodes"] if n["head"]]
missing = set(tree["missing_ancestors"])
parts = ["
"]
budget = [400]
def walk(cid, depth):
if budget[0] <= 0 or depth > 10:
return
budget[0] -= 1
n = by_id.get(cid)
if n is None:
parts.append("
∂ %s — not on this node yet
"
% esc(cid[:12]))
return
mark = " ★" if n["head"] else ""
parts.append("
"
% (uq(r["article"]), esc(r["article"]), uq(r["id"]), r["id"][:10],
chip(store, r["author"]), esc(r["comment"] or ""),
fmt_ts(r["ts"])) for r in store.recent_commits(8))
recent = ("
article
commit
author
"
"
comment
time
%s
" % recent) \
if recent else "
nothing yet
"
peers = store.list_peers()
if peers:
peers_html = "%s" % ", ".join(
"%s %s %s"
% (esc(p["layer"]), esc(p["url"]), "✓" if p["last_ok"] else "?")
for p in peers[:8])
else:
peers_html = "none yet"
body = (
"
"
% (esc(store.cfg.get("name", "manifold")),
frontpage if frontpage else
"
A polyphonic peer-to-peer wiki. Articles are "
"signed history trees; conflicting points of view coexist as "
"heads. No view is overwritten, ever.
",
stats["articles"],
stats["commits"], stats["objects"], stats["peers"], table,
recent, peers_html,
("manage" % cq) if getattr(_ctx, "admin", False) else "",
creds_hidden()))
return page(store, "index", body)
REPLACES_AT = 0.5 # a child keeping less than half of the parent's distinct
# lines is labeled "replaces", not "advances" (v0.6.0)
def _content_text(store, cid):
"""The human-readable text behind a content object (code -> source)."""
try:
kind, body = store.content_body(cid)
except Exception:
return None
if body is None:
return None
if kind == "code":
try:
return json.loads(body.decode("utf-8")).get("source", "")
except Exception:
return None
return body.decode("utf-8", errors="replace")
def _sig_lines(text):
out = set()
for ln in (text or "").splitlines():
ln = " ".join(ln.strip().lower().split())
if len(ln) >= 3:
out.add(ln)
return out
def text_overlap(parent_text, child_text):
"""Fraction of the parent's distinct non-trivial lines that survive in
the child: 1.0 = pure carry-forward, ~0 = wholesale replacement. Cheap
set intersection, O(len) — no render-time difflib blowups on 64 KiB."""
p = _sig_lines(parent_text)
if not p:
return 1.0
return len(p & _sig_lines(child_text)) / len(p)
def _lineage_html(store, view_id, limit=8):
"""Root-to-tip chain of the displayed head with a per-edge
advance/replaces verdict — makes silent wholesale rewrites visible
(2026-12-03 render contract)."""
hops = [] # (commit_row, parent_row, parent_count), head first
cur = store.commit(view_id)
while cur is not None and len(hops) <= limit:
pars = store.parents_of(cur["id"])
if len(pars) == 1:
parent = store.commit(pars[0])
hops.append((cur, parent, 1))
if parent is None:
break
cur = parent
else:
hops.append((cur, None, len(pars)))
break
rev = list(reversed(hops))
pieces = []
for j, (c, parent, npars) in enumerate(rev):
who = esc(store.author_display(c["author"]))
piece = "%s%s" % (
uq(c["id"]), c["id"][:8], who)
if npars == 0:
piece += " · root"
elif npars > 1:
piece += " · synthesis of %d parents" % npars
elif parent is None:
piece += " · parent not held (∂)"
if j == len(rev) - 1:
piece += " ← this view"
pieces.append(piece)
html = pieces[0]
for j in range(1, len(pieces)):
c, parent, npars = rev[j]
ov = text_overlap(_content_text(store, parent["content"]),
_content_text(store, c["content"]))
pct = int(round(ov * 100))
if ov < REPLACES_AT:
edge = " → replaces(keeps %d%%) → " % pct
else:
edge = " → advances (carries %d%%) → " % pct
html += edge + pieces[j]
if len(hops) > limit:
html += " …older steps in the tree below"
return html
def _displaced_html(store, view_id, row, kind, body):
"""When the head replaced most of its parent's text, keep the parent's
view one click open under it — the replaced author should not vanish
from the default page (2026-12-03 render contract)."""
if body is None or kind == "code":
return ""
pars = store.parents_of(view_id)
if len(pars) != 1:
return ""
prow = store.commit(pars[0])
if prow is None:
return ""
ptext = _content_text(store, prow["content"])
if not ptext:
return ""
ov = text_overlap(ptext, body.decode("utf-8", errors="replace"))
if ov >= REPLACES_AT:
return ""
return ("Previous view by "
"%s — mostly replaced by this commit (%d%% kept). Open to read "
"it.%s
"
% (chip(store, prow["author"]), int(round(ov * 100)),
render_markdown(ptext), uq(prow["id"]), prow["id"][:10]))
ADVISE_HINT = ("this commit replaced most of the parent view's text — readers "
"now see yours as the article. To endorse a parent, carry its "
"content forward (condense or quote it); to compete with it, "
"branch from the parent's parent instead")
def _advance_advisory(store, article, parent_was_head, parents, content, kind):
"""B-lite guard (committed 2026-12-03): never rejects — a commit that
branched from a visible head and keeps little of its parent's text
comes back with a machine-readable advisory so the author can
self-correct. parent_was_head is sampled BEFORE the commit lands:
"the parent was a head" is deterministic, while "my id heads the list
afterwards" would depend on ts-tie id ordering."""
if not parent_was_head or kind != "text" or len(parents) != 1:
return None
prow = store.commit(parents[0])
if prow is None:
return None
ptext = _content_text(store, prow["content"])
if not ptext:
return None
ov = text_overlap(ptext, content)
if ov >= REPLACES_AT:
return None
return {"parent": parents[0], "kept_pct": int(round(ov * 100)),
"verdict": "replaces", "hint": ADVISE_HINT}
def page_article(store, article, head_q=None, base_q=None, fmt="html"):
if not ARTICLE_RE.match(article):
if fmt == "json":
return json_response({"error": "bad article name"}, 404)
return not_found(store, "article name")
heads = store.heads(article)
if not heads:
if fmt == "json":
return json_response({"article": article, "head": None,
"text": None, "heads": []})
if fmt == "txt":
return 404, "text/plain; charset=utf-8", \
b"no commits for this article yet"
return page(store, article,
"
%s
No commits yet. This node "
"will create the first commit when you save the editor "
"below.
%s" % (esc(article), _edit_form(store, article)))
head_id = store.resolve_head(article, head_q) if head_q else None
base_id = store.resolve_head(article, base_q) if base_q else None
view_id = head_id or heads[0]["id"]
row = store.commit(view_id)
kind, body = store.content_body(row["content"])
_, missing = store.missing_ancestors(view_id)
if fmt == "json":
return json_response({
"article": article, "head": view_id, "content_type": kind,
"text": body.decode("utf-8", errors="replace")
if body is not None else None,
"missing_ancestors": missing,
"heads": [{"id": h["id"], "author": h["author"],
"author_name": store.author_display(h["author"]),
"ts": h["ts"], "comment": h["comment"],
"karma": store.author_karma(h["author"][:16])["karma"]["score"]}
for h in heads]})
if fmt == "txt":
if body is None:
return 404, "text/plain; charset=utf-8", \
b"content object not on this node yet (sync peers)"
if kind == "code":
try:
body = json.loads(body.decode("utf-8")).get("source", "").encode("utf-8")
except Exception:
pass
return 200, "text/plain; charset=utf-8", body
if body is None:
content_html = ("
Content object %s is not on this "
"node yet — sync from peers that hold this branch.
"
% (uq(article), esc(article), lens,
_lineage_html(store, view_id), content_html,
_displaced_html(store, view_id, row, kind, body), base_ctl,
_head_rows(store, article, heads, base_id),
_tree_html(store, article),
_edit_form(store, article, parent=view_id if kind != "code" else None),
_note_form(store, article, view_id)))
return page(store, article, body)
def _edit_form(store, article, parent=None, merge=None):
prefill = ""
if parent:
prow = store.commit(parent)
if prow:
kind, body = store.content_body(prow["content"])
if body is not None and kind == "text":
prefill = body.decode("utf-8", errors="replace")
parents_val = uq(parent) if parent else ""
if merge:
parents_val = (parents_val + "," + uq(merge)).lstrip(",")
merge_note = ("
This is a synthesis: two "
"parents (%s, %s). Only merge texts that genuinely carry "
"both points of view — say so in the comment.
"
% (esc((parent or "")[:10]), esc(merge[:10]))) if merge else ""
return (
""
% (uq(article), merge_note, creds_hidden(), parents_val, esc(prefill),
("the key of @" + esc(signed_in_name())) if signed_in_name()
else "this node's key"))
def _note_form(store, article, head_id):
"""No-JS one-line note: a GET form that creates a small branch commit."""
return (
"
or add a one-line note as its own branch "
"(≤%d bytes, becomes a head beside the others):
"
""
% (NOTE_LIMIT, creds_hidden(), uq(article), uq(head_id or "")))
def page_edit(store, article, head_q=None, merge_q=None):
if not ARTICLE_RE.match(article):
return not_found(store, "article name")
head_id = store.resolve_head(article, head_q) if head_q else None
merge_id = store.resolve_head(article, merge_q) if merge_q else None
if head_q and not head_id:
return page(store, article, "
%s
Head %s not "
"found (or ambiguous prefix).
" % (esc(article), esc(head_q)),
status=404)
title = "edit %s" % article if not merge_id else "synthesize %s" % article
return page(store, title,
"
%s
%s" % (esc(title),
_edit_form(store, article, head_id, merge_id)))
def page_diff(store, article, a_q, b_q):
a_id = store.resolve_head(article, a_q or "")
b_id = store.resolve_head(article, b_q or "")
if not a_id or not b_id:
return page(store, "diff", "
diff
Need two "
"resolvable head ids: ?a=…&b=… (full ids or unique "
"prefixes).
", status=400)
ta = _head_text(store, a_id)
tb = _head_text(store, b_id)
html_diff = render_unified_diff(ta, tb, a_id[:10], b_id[:10])
body = (
"
"
% (esc(cid[:12]), uq(row["article"]), esc(row["article"]),
chip(store, row["author"]), karma_badge(store, row["author"]),
esc(row["author"]), fmt_ts(row["ts"]),
esc(row["comment"] or ""), clink, phtml, khtml,
esc(prow_origin), uq(row["article"]), uq(cid)))
return page(store, "commit " + cid[:10], body)
def page_object(store, oid):
body_bytes = store.object_body(oid)
if body_bytes is None:
return not_found(store, "object")
row = store.object(oid)
if row["type"] == "text":
return 200, "text/plain; charset=utf-8", body_bytes
return 200, "application/json", body_bytes
def page_code(store, oid):
row = store.object(oid)
if row is None or row["type"] != "code":
return not_found(store, "code object")
obj = json.loads(bytes(row["body"]).decode("utf-8"))
sandbox = []
sandbox.append("no network (user namespaces)" if _net_isolated() else
"network isolation UNAVAILABLE on this host")
sandbox.append("rlimits (cpu/as/nofile)" if _rlimits_ok() else
"rlimits UNAVAILABLE on this host")
body = (
"
code %s
lang %s · entry %s · %d B · "
"signed, immutable, data-only on this node
"
"
Source
%s
"
"
This node never executes code — there is "
"no run endpoint, by design. The operator runs it locally: "
"python3 manifold.py run %s (prints author and origin "
"first; sandbox here: %s).
"
% (esc(p["layer"]), esc(p["url"]),
" auto" if p["auto"] else "",
esc(p["last_sync"] or "never"),
"ok" if p["last_ok"] else "bad", esc(p["last_status"] or ""),
esc(p["push_status"] or "not pushed yet"), creds_hidden(),
uq(p["url"])) for p in peers)
table = ("
layer
peer
last pull
"
"
pull status
last push
%s
"
% rows) if rows else \
"
No peers yet.
"
mode = store.inbox_mode()
inbox_note = {
"token": "Only holders of this node's write token may write to it.",
"open": "Open inbox: anyone may push objects they signed themselves "
"(signatures, author policy and rate limits still apply). "
"Learned nodes are added as peers automatically, up to "
"%d." % M_auto_peer_limit(store),
"f2f": "Friends-only inbox: pushes must be signed by one of %d "
"friend key(s). Peers are never added automatically." % len(
(store.cfg.get("inbox") or {}).get("friends") or []),
}[mode]
eps = store.cfg.get("endpoints") or []
ep_rows = ("".join(
"
%s
%s"
"
" % (esc(e.get("layer", "?")), esc(e.get("url", "?")))
for e in eps) or
"
only the local bind address is "
"configured — add endpoints in config.json
")
body = (
"%s
Peers
"
"
Peers exchange signed objects over plain HTTP. "
"Heads are never negotiated — each node derives them from its own DAG, "
"so pulling can only add points of view, never remove one. Onion and "
"eepsite peers are fetched through the local tor SOCKS / i2p HTTP "
"proxy.
"
"
Inbox mode %s — %s "
"This node pushes what it newly holds to its peers and pulls from "
"them in the background while serving.
"
"
%s
"
"
"
"
"
"
This node's announced endpoints
%s
"
% (("
%s
" % esc(notice)) if notice else "",
esc(mode), esc(inbox_note), table, ep_rows,
creds_hidden(), creds_hidden()))
return page(store, "peers", body)
# ----------------------------------------------------------------- helpers --
def read_body(handler, limit=MAX_JSON_BODY) -> bytes:
"""Read the request body defensively: garbage or negative Content-Length
must yield an empty body, not an unbounded read(-1) that parks the
connection thread until EOF."""
try:
n = int(handler.headers.get("Content-Length") or 0)
except ValueError:
return b""
if n > limit:
raise ValueError("body too large")
if n <= 0:
return b""
return handler.rfile.read(n)
def json_response(obj, status=200):
return status, "application/json", json.dumps(obj, ensure_ascii=False).encode("utf-8")
def write_token_ok(store, handler, query) -> bool:
"""API-write gate: a configured token is REQUIRED — an empty one means
every write is refused, never allowed (there is no anonymous write)."""
want = store.cfg.get("write_token") or ""
got = handler.headers.get("X-Manifold-Token") or (query or {}).get("token", "")
return bool(want) and got == want
def local_request_ok(handler, store) -> bool:
"""The local-operator shortcut, only when config `local_shortcut` is on
(it is off by default): a loopback-bound node asked from loopback, with
a matching Origin when the browser sent one (kills DNS rebinding and
cross-site form CSRF). On a publicly bound node there is no such thing
as "local" — this returns False and a real credential is needed."""
if not store.cfg.get("local_shortcut"):
return False
host = urllib.parse.urlparse("//" + (handler.headers.get("Host") or "")).hostname or ""
bind = str(store.cfg.get("bind") or "127.0.0.1")
if bind not in ("127.0.0.1", "localhost", "::1"):
return False
if host not in ("127.0.0.1", "localhost", "::1"):
return False
if handler.client_address[0] not in ("127.0.0.1", "::1"):
return False
origin = handler.headers.get("Origin")
if origin:
return (urllib.parse.urlparse(origin).hostname or "") == host
sfs = handler.headers.get("Sec-Fetch-Site")
if sfs:
return sfs in ("same-origin", "same-site", "none")
return True
def request_creds(handler):
"""Account credentials of this request: HTTP Basic, query fields
`user`/`pass`, or the same fields in a form body. Returns
(user, pass) — (None, None) when absent."""
if getattr(handler, "_creds", None) is not None:
return handler._creds
creds = (None, None)
authz = handler.headers.get("Authorization") or ""
if authz[:6].lower() == "basic ":
try:
raw = base64.b64decode(authz[6:].strip()).decode("utf-8")
user, _sep, pass_ = raw.partition(":")
creds = (user, pass_)
except Exception:
creds = (None, None)
if creds == (None, None):
q = handler.q or {}
form = {}
if handler.command == "POST" and handler.body:
try:
form = urllib.parse.parse_qs(handler.body.decode("utf-8", errors="replace"))
except Exception:
form = {}
user = q.get("user") or form.get("user", [""])[0]
pass_ = q.get("pass") or form.get("pass", [""])[0]
if user:
creds = (user, pass_)
handler._creds = creds
return creds
def auth_level(handler, store) -> str:
"""Level for this request: "admin" | "user" | "anon" ("limited" when
failed logins exhausted the IP's window). The write token is an
admin credential; an account's level is its role. Failed account logins
are charged to the client IP (kind "login")."""
if getattr(handler, "_level", None) is not None:
return handler._level
level = "anon"
if write_token_ok(store, handler, handler.q):
level = "admin"
else:
user, pass_ = request_creds(handler)
if user:
acct = store.account_auth(user.strip().lower(), pass_)
if acct is not None:
handler._account = acct
level = "admin" if acct.get("role") == "admin" else "user"
else:
retry = charge(handler, "login")
if retry is not None:
handler._level = "limited"
return "limited"
handler._level = level
return level
def signed_in_account(handler, store):
"""The account record of a signed-in request, else None."""
if auth_level(handler, store) in ("user", "admin"):
return getattr(handler, "_account", None)
return None
def request_key(handler, store) -> Key:
"""Key to sign with: the signed-in account's own key, else the node's
default key (operator / loopback path)."""
acct = signed_in_account(handler, store)
if acct is not None:
k = store.account_key(acct["name"])
if k is not None:
return k
return require_key(store)
def is_admin(handler, store) -> bool:
"""Node management gate: the write token or an admin account (plus the
local-operator shortcut when `local_shortcut` is on)."""
if auth_level(handler, store) == "admin":
return True
return local_request_ok(handler, store)
def html_write_ok(handler, store) -> bool:
"""Content-write gate for HTML forms: a valid token or an account. The
local-operator shortcut applies only when `local_shortcut` is on."""
if auth_level(handler, store) in ("admin", "user"):
return True
return local_request_ok(handler, store)
FORBIDDEN_PAGE = "
403
Signing in is required: create an account or log in. " \
"Node management needs an admin account or the write token.
"
_ctx = threading.local() # per-request facts the page shell needs (nav)
def creds_hidden() -> str:
"""Hidden form fields carrying the signed-in account through a POST, or
empty login inputs when nobody is signed in."""
user, pass_ = getattr(_ctx, "creds", (None, None)) or (None, None)
if user and pass_:
return (""
""
% (uq(user), uq(pass_)))
return (" ")
def creds_qs() -> str:
user, pass_ = getattr(_ctx, "creds", (None, None)) or (None, None)
return ("&user=%s&pass=%s" % (uq(user), uq(pass_))) if user and pass_ else ""
def signed_in_name():
a = getattr(_ctx, "account", None)
return a["name"] if a else None
def forbidden(h, store):
if h.fmt == "json" or h.path.startswith("/api/"):
return json_response({"error": "forbidden: needs the write token "
"or an admin account"}, 403)
return page(store, "forbidden", FORBIDDEN_PAGE, status=403)
def rate_limited_json(retry: float):
ra = max(1, math.ceil(retry))
status, ctype, payload = json_response(
{"error": "rate_limited", "retry_after": ra}, 429)
return status, ctype, payload, None, {"Retry-After": str(ra)}
def rate_limited_page(store, retry: float):
return page(store, "rate limited",
"
429 — rate limited
Too many "
"requests; retry in ~%d s.
" % max(1, math.ceil(retry)),
status=429)
def idem_precheck_text(store, article, parents, text: str, comment: str, rid):
"""Advisory replay check for text commits that stores nothing. Returns
(commit_id, True) on replay, (None, False) when unseen; raises
ValueError('request_id_conflict') on key reuse with other content."""
if rid in (None, ""):
return None, False
digest = store.idem_digest(article, list(parents),
obj_id(text.encode("utf-8")), comment[:300], "text")
return store.idem_lookup(article, str(rid), digest)
def require_key(store):
key = default_key(store.root, store.cfg)
if key is None:
raise RuntimeError("node has no signing key — run: manifold.py keygen")
return key
# -------------------------------------------------------------------- APIs --
def api_manifest(store):
return json_response({
"protocol": PROTOCOL, "software": SOFTWARE, "version": __version__,
"instance_id": store.instance_id,
"name": store.cfg.get("name", "manifold"),
"time": int(time.time()),
"endpoints": store.cfg.get("endpoints", []),
"limits": {"text": TEXT_LIMIT, "code": CODE_LIMIT,
"object": OBJECT_LIMIT, "note": NOTE_LIMIT},
"self": {name: sha for name, _p, _s, sha in _self_files()},
"stats": store.stats(),
# discovery (config announce_peers, default on): who we pull from and
# the self-announced addresses we learned from them. No tokens, no
# names we curate — only what those nodes publish about themselves.
"peers": ([p["url"] for p in store.list_peers()]
if store.cfg.get("announce_peers", True) else []),
"nodes": (store.known_endpoints()[:64]
if store.cfg.get("announce_peers", True) else []),
"inbox": {"mode": store.inbox_mode()},
"layers": ["clearnet", "tor", "i2p", "yggdrasil"],
})
def api_peers(store, h=None):
"""This node's peers with pull and push state (admin only). Peer write
tokens are never included."""
if h is not None and not is_admin(h, store):
return json_response({"error": "forbidden: /api/peers is node "
"management (admin account or write token)"}, 403)
return json_response({"peers": [{
"url": p["url"], "layer": p["layer"], "auto": bool(p["auto"]),
"added": p["added"], "last_sync": p["last_sync"],
"last_ok": bool(p["last_ok"]) if p["last_sync"] else None,
"last_status": p["last_status"], "cursor": p["cursor"],
"pushed": p["pushed"], "push_status": p["push_status"],
"has_token": bool(p["token"]),
} for p in store.list_peers()],
"max_auto": M_auto_peer_limit(store), "announce_peers": bool(
store.cfg.get("announce_peers", True)),
"known_nodes": len(store.list_known_nodes())})
def api_articles(store):
hcounts = store.article_head_counts()
return json_response({"articles": [
{"article": a["article"], "commits": a["commits"],
"heads": hcounts.get(a["article"], 0), "authors": a["authors"],
"updated": a["updated"]} for a in store.articles()]})
def api_heads(store, article):
if not ARTICLE_RE.match(article):
return json_response({"error": "bad article name"}, 400)
heads = []
for h in store.heads(article):
_, missing = store.missing_ancestors(h["id"])
kind, body = store.content_body(h["content"])
heads.append({
"id": h["id"], "author": h["author"],
"author_name": store.author_display(h["author"]),
"karma": store.author_karma(h["author"][:16])["karma"]["score"],
"ts": h["ts"], "comment": h["comment"],
"content": h["content"], "content_type": kind,
"size": len(body) if body is not None else None,
"missing_ancestors": missing,
"origin": h["origin"],
})
return json_response({"article": article, "heads": heads})
def api_tree(store, article):
if not ARTICLE_RE.match(article):
return json_response({"error": "bad article name"}, 400)
return json_response(store.tree(article))
def api_object(store, oid):
body = store.object_body(oid)
if body is None:
return json_response({"error": "unknown object"}, 404)
row = store.object(oid)
ctype = "text/plain; charset=utf-8" if row["type"] == "text" else "application/json"
return 200, ctype, body
def api_objects(store, ids_param):
ids = [i.strip().lower() for i in (ids_param or "").split(",") if i.strip()]
ids = ids[:128]
found, missing = [], []
for oid in ids:
if not ID_RE.match(oid):
return json_response({"error": "bad id: %s" % oid[:80]}, 400)
row = store.object(oid)
if row is None:
missing.append(oid)
else:
found.append({"id": oid, "type": row["type"],
"body": base64.b64encode(bytes(row["body"])).decode()})
return json_response({"objects": found, "missing": missing})
def api_ids(store, since_raw=None):
"""Object listing; rowid order doubles as the sync cursor. ?since=SEQ
returns only objects inserted after it, so peers poll incrementally."""
since = None
if since_raw not in (None, ""):
try:
since = int(since_raw)
except (TypeError, ValueError):
return json_response({"error": "bad since (integer seq)"}, 400)
if since < 0:
return json_response({"error": "bad since (negative)"}, 400)
rows = store.all_ids(since)
cursor = rows[-1]["seq"] if rows else (since or 0)
return json_response({"ids": [
{"id": r["id"], "type": r["type"], "size": r["size"], "seq": r["seq"]}
for r in rows], "cursor": cursor})
def api_recent(store, n):
try:
n = max(1, min(500, int(n)))
except (TypeError, ValueError):
n = 20
return json_response({"commits": [
{"id": r["id"], "article": r["article"], "author": r["author"],
"ts": r["ts"], "comment": r["comment"], "content": r["content"],
"origin": r["origin"]} for r in store.recent_commits(n)]})
def api_commit(h, payload):
"""Two modes: node-signed convenience commit, or pre-signed object."""
store = h.server.store
if not isinstance(payload, dict):
return json_response({"error": "JSON object required"}, 400)
if "object" in payload:
o = payload["object"]
try:
body = base64.b64decode(o.get("body", "")) if isinstance(o, dict) else None
if body is None:
raise ValueError
except Exception:
return json_response({"error": "object.body must be base64"}, 400)
# the pre-signed path is a push by another name: charge it like one
retry = charge(h, "push")
if retry is not None:
return rate_limited_json(retry)
res = store.accept_object(body, origin="api")
return json_response({k: res[k] for k in ("ok", "id", "type", "reason",
"duplicate")}, 200 if res["ok"] else 400)
article = payload.get("article") or ""
if not ARTICLE_RE.match(article):
return json_response({"error": "bad or missing article"}, 400)
content = payload.get("content")
if isinstance(content, str):
kind = "code" if payload.get("kind") == "code" else "text"
else:
return json_response({"error": "content must be a string"}, 400)
parents = payload.get("parents") or []
if not isinstance(parents, list) or len(parents) > MAX_PARENTS:
return json_response({"error": "parents must be a list (max %d)" % MAX_PARENTS}, 400)
parents = [str(p) for p in parents]
for p in parents:
if not ID_RE.match(p) or store.commit(p) is None:
return json_response({"error": "parent %s is not a stored commit"
% p[:16]}, 400)
comment = str(payload.get("comment", ""))[:300]
rid = payload.get("request_id")
# replay bypass: an identical retry answers from the idem table and does
# not charge the rate limiter (its ts would differ; the digest does not)
if kind == "text":
try:
cid, replayed = idem_precheck_text(store, article, parents, content,
comment, rid)
except ValueError as e:
return json_response({"error": str(e)},
409 if "conflict" in str(e) else 400)
if replayed:
return json_response({"ok": True, "id": cid, "replay": True})
retry = charge(h, "commit")
if retry is not None:
return rate_limited_json(retry)
try:
key = request_key(h, store)
except RuntimeError as e:
return json_response({"error": str(e)}, 503)
# sampled before the commit lands: "the parent was a visible head" is
# deterministic, unlike post-accept head ordering under ts ties
parent_was_head = (kind == "text" and len(parents) == 1
and any(ph["id"] == parents[0]
for ph in store.heads(article)))
try:
cid, _, replayed = store.create_commit(key, article,
content.encode("utf-8"), parents,
comment, kind=kind, request_id=rid)
except ValueError as e:
msg = str(e)
return json_response({"error": msg}, 409 if "conflict" in msg else 400)
resp = {"ok": True, "id": cid, "replay": replayed,
"heads": len(store.heads(article))}
adv = _advance_advisory(store, article, parent_was_head, parents,
content, kind)
if adv:
resp["advance"] = adv
return json_response(resp)
def api_push(h, payload):
store = h.server.store
objs = (payload or {}).get("objects")
if not isinstance(objs, list) or len(objs) > 256:
return json_response({"error": "objects[] required (max 256)"}, 400)
# Optional node-local karma throttle (committed decision 4, off by
# default): when config karma.throttle_below is an int, each NEW commit
# in the batch whose author scores below the floor costs one extra
# rate-limiter slot — checked BEFORE anything is accepted, so a flood of
# fresh-key commits burns the push window fast while an identical batch
# of known-good authors costs no more than before.
floor = (store.cfg.get("karma") or {}).get("throttle_below")
if isinstance(floor, int) and not isinstance(floor, bool) and objs:
low = set()
for o in objs:
try:
oid = str(o.get("id", "")).lower()
if store.has(oid):
continue # already held — costs nothing extra
parsed = json.loads(base64.b64decode(o.get("body", ""))
.decode("utf-8"))
if isinstance(parsed, dict) and parsed.get("t") == "commit":
fp = str(parsed.get("author", ""))[:16]
if store.author_karma(fp)["karma"]["score"] < floor:
low.add(fp)
except Exception:
continue # accept pipeline will reject it with a reason
if low:
rules = h.server.rate_limits.get("push", {}).get("ip")
retry = h.server.limiter.hit("push:ip:%s" % h.client_ip(),
rules, weight=len(low))
if retry is not None:
return rate_limited_json(retry)
accepted, rejected = [], []
for o in objs:
try:
oid = str(o.get("id", "")).lower()
body = base64.b64decode(o.get("body", ""))
except Exception:
rejected.append({"id": "?", "reason": "bad base64"})
continue
if oid and ID_RE.match(oid) and oid != obj_id(body):
rejected.append({"id": oid, "reason": "id mismatch"})
continue
res = store.accept_object(body, origin="push")
if res["ok"]:
accepted.append(res["id"])
else:
rejected.append({"id": res["id"] or oid, "reason": res["reason"]})
return json_response({"accepted": accepted, "rejected": rejected})
def charge(h, kind: str):
"""Record one rate-limiter event for this client. None if allowed, else
the retry_after seconds. Committed work charges only after its replay
check, so idempotent retries stay free."""
rules = h.server.rate_limits.get(kind, {}).get("ip")
if not rules:
return None
retry = h.server.limiter.hit("%s:ip:%s" % (kind, h.client_ip()), rules)
if retry is not None:
return retry
# signed-in accounts get a window of their own on top of the IP one
acct = getattr(h, "_account", None)
urules = h.server.rate_limits.get(kind, {}).get("user")
if acct is not None and urules:
return h.server.limiter.hit("%s:user:%s" % (kind, acct["name"]), urules)
return None
def api_help(store):
return json_response({
"software": SOFTWARE, "protocol": PROTOCOL, "version": __version__,
"docs": "/AGENTS.md",
"auth": "writes need an account (GET/POST /auth; send user:pass as "
"HTTP Basic or form fields — each account signs with its "
"own key) or the node's write token (header X-Manifold-Token "
"or ?token=). Alias curation and node management (/sync*, "
"/api/peers, /api/accounts) need an admin account or the "
"token. Pre-signed objects (POST /api/push, or `object` in "
"/api/commit) depend on inbox.mode — see `inbox`.",
"frontpage": "the article 'frontpage' is rendered as /",
"inbox": {"mode": store.inbox_mode(),
"token": "write token only", "open": "anyone may push",
"f2f": "pushes signed by inbox.friends keys only",
"push_envelope": {"from": "sender pub key (64 hex)",
"sig": "Ed25519 over "
"'manifold-push-v1\\n\\n' "
"+ object ids joined by newline"}},
"get": ["/api/manifest", "/api/peers", "/api/accounts", "/auth",
"/api/articles", "/api/heads?article=",
"/api/tree?article=", "/api/object/", "/api/objects?ids=",
"/api/ids[?since=SEQ]", "/api/recent?n=", "/api/search?q=",
"/api/authors", "/api/aliases", "/api/releases", "/api/help",
"/api/source", "/source/",
"/n?article=&p=&text=&m=&k=", "/healthz", "/robots.txt",
"/openapi.json", "/.well-known/agent-card.json",
"/skill.md (alias of llms.txt as markdown)",
"html pages: / /a/[.json|.txt] /search?q= "
"/authors — read routes honor ?format=json|txt, a .json/.txt "
"suffix, or an Accept: application/json header"],
"post": ["/api/commit", "/api/push", "/api/alias", "/mcp (JSON-RPC "
"2.0: initialize, tools/list, tools/call; write tools need "
"an account or the token header)", "/auth (register an "
"account or verify one; also GET)",
"/edit, /a//edit (HTML form writes)", "/sync/peer, "
"/sync/run (node management: admin)"],
"post_body": {
"/api/commit": {"article": "name", "content": "text",
"parents": ["head id"], "comment": "why",
"request_id": "retry-key (identical retries replay)",
"kind": "text|code",
"OR object": {"id": "sha256", "body": "base64"}},
"/api/push": {"objects": [{"id": "sha256", "body": "base64"}],
"from": "sender pub key, 64 hex (needed on f2f nodes)",
"sig": "Ed25519 signature over the object ids"},
"/api/alias": {"fingerprint": "fp16 or pub64 hex",
"name": "display name (empty clears; node-local)"},
"/auth": {"user": "new name -> register (pass shown once)",
"pass": "with user -> verify credentials"},
},
"limits": {"text": TEXT_LIMIT, "code": CODE_LIMIT,
"object": OBJECT_LIMIT, "note": NOTE_LIMIT},
"philosophy": "articles are signed DAGs; heads coexist; sync only "
"adds; the node never executes code (CLI-only runs); "
"karma and aliases are node-local and never synced",
})
def api_health(store):
return json_response({"ok": True, "instance_id": store.instance_id})
# ------------------------------------------------- aliases / authors / karma
def api_releases(store):
"""Every release object this node holds — all versions coexist. Agents
can read this to see what a peer offers; applying is an operator act
(manifold.py update), never triggered by the node."""
out = []
for rid, m in store.list_releases():
out.append({
"id": rid, "name": m.get("name"), "version": m.get("version"),
"created": m.get("created"), "author": m.get("author"),
"author_name": store.author_display(m.get("author", "")),
"notes": m.get("notes", ""),
"files": len(m.get("files", [])),
"total_size": sum(f.get("size", 0) for f in m.get("files", [])),
})
return json_response({"releases": out})
def api_aliases(store):
"""Node-local, operator-curated display names (committed decision 3:
fingerprints stay canonical; aliases never sync)."""
return json_response({"aliases": [
{"fingerprint": r["fingerprint"], "name": r["name"]}
for r in store.all_aliases()]})
def api_alias_set(store, payload):
"""POST /api/alias body {"fingerprint": fp16|pub64, "name": str}.
Empty name clears. Operator-curated only — the write token gates it."""
fp = str((payload or {}).get("fingerprint", "")).strip().lower()
name = str((payload or {}).get("name", "")).strip()
if not FP_RE.match(fp):
return json_response(
{"error": "fingerprint must be 16 or 64 hex chars"}, 400)
if len(name) > 48:
return json_response({"error": "name too long (max 48)"}, 400)
fp = fp[:16]
if name:
store.set_alias(fp, name)
else:
store.clear_alias(fp)
return json_response({"ok": True, "fingerprint": fp,
"name": store.alias(fp, ""),
"note": "node-local only, never synced"})
def api_authors(store):
"""Every author this node has seen, with node-local karma v1 — computed
from observables this node holds, displayed, never synced."""
return json_response({"authors": [
{"author": a["author"], "fingerprint": a["fingerprint"],
"alias": a["alias"], "commits": a["commits"],
"articles": a["articles"], "merges": a["merges"],
"built_on": a["built_on"], "local_commits": a["local_commits"],
"first_ts": a["first_ts"], "last_ts": a["last_ts"],
"karma": a["karma"]} for a in store.authors()]})
def page_authors(store, notice=""):
rows = []
for a in store.authors():
k = a["karma"]
breakdown = ("breadth %d · volume %d · trust %d · synthesis %d · "
"tenure %d · locality %d" %
(k["breadth"], k["volume"], k["trust"], k["synthesis"],
k["tenure"], k["locality"]))
alias_form = (esc(a["alias"]) or "—")
if getattr(_ctx, "admin", False):
alias_form += (
""
% (creds_hidden(), esc(a["fingerprint"])))
rows.append(
"
No authors yet — commits arrive via local "
"writes or peer sync.
")
body = (
"%s
Authors
"
"
Every author is an Ed25519 key. Accounts on "
"this node each hold a key of their own, and their names are aliases "
"like any other: node-local, never synced — the fingerprint stays "
"the canonical identity everywhere. Admins can rename any alias. Karma is computed from what this node holds "
"(breadth, volume, trust = being built on, synthesis, tenure, "
"locality) and is likewise node-local, never synced.
"
"
%s
" %
(("
%s
" % notice) if notice else "", table))
return page(store, "authors", body)
def post_alias(h, m):
"""HTML form behind /authors — node management, admin only."""
store = h.server.store
if not is_admin(h, store):
return forbidden(h, store)
form = urllib.parse.parse_qs(h.body.decode("utf-8", errors="replace"))
fp = (form.get("fp", [""])[0] or "").strip().lower()
name = (form.get("name", [""])[0] or "").strip()
if not FP_RE.match(fp):
return page(store, "error", "
bad fingerprint
must be 16 "
"or 64 hex chars
", status=400)
if name and len(name) > 48:
return page(store, "error", "
alias too long
1-48 "
"characters.
", status=400)
fp = fp[:16]
if name:
store.set_alias(fp, name)
note = "alias %s = %s (node-local only)" % (fp, esc(name))
else:
store.clear_alias(fp)
note = "alias cleared for %s" % fp
return page_authors(store, notice=note)
# ------------------------------------------------------------------ search --
def _snippet(text: str, q: str, width: int = 60) -> str:
i = text.lower().find(q.lower())
if i < 0:
return text[: width * 2] + ("…" if len(text) > width * 2 else "")
start, end = max(0, i - width), min(len(text), i + len(q) + width)
return (("…" if start else "") + text[start:end] +
("…" if end < len(text) else ""))
def search_rows(store, q: str, limit: int = 50):
out = []
for r in store.search(q, limit):
entry = {"article": r["article"], "commit": r["id"],
"author": r["author"],
"author_name": store.author_display(r["author"]),
"ts": r["ts"], "comment": r["comment"],
"content": r["content"], "content_type": r["type"]}
body = store.object_body(r["content"]) if r["content"] else None
if body is not None:
if r["type"] == "code":
try:
body = json.loads(body.decode("utf-8")).get(
"source", "").encode("utf-8")
except Exception:
pass
entry["snippet"] = _snippet(body.decode("utf-8", errors="replace"), q)
else:
entry["snippet"] = ""
out.append(entry)
return out
def api_search(store, q_raw, limit_raw=None):
q = (q_raw or "").strip()
if not q:
return json_response({"error": "missing q (?q=substring)"}, 400)
try:
limit = max(1, min(100, int(limit_raw)))
except (TypeError, ValueError):
limit = 50
hits = search_rows(store, q, limit)
return json_response({"query": q, "total": len(hits), "hits": hits})
def page_search(store, q_raw, fmt="html"):
q = (q_raw or "").strip()
if fmt == "json":
return api_search(store, q)
if q:
hits = search_rows(store, q, 50)
rows = "".join(
"
"
% (uq(r["article"]), esc(r["article"]), uq(r["commit"]),
r["commit"][:10], chip(store, r["author"]),
esc(r["snippet"]), esc(r["comment"] or "")) for r in hits)
results = ("
%d hit(s) for %s — matching "
"is a literal substring (%% and _ are not wildcards), "
"ASCII case-insensitive, over text and code objects plus "
"article names.
"
"
article
commit
author
"
"
snippet
comment
%s
"
% (len(hits), esc(q), rows)) if hits else \
"
No hits for %s.
" % esc(q)
else:
results = ("
Type a query above. Searches this "
"node's held objects only — sync more peers for more "
"coverage.
")
body = (
"
Search
"
"%s" % (esc(q), results))
return page(store, "search", body)
# ------------------------------------------------------- agent surface (#4) --
def api_openapi(store):
"""Machine-readable API description (OpenAPI 3.1). Paths are relative to
this node's mount point."""
def g(summary, params=None, secure=False):
op = {"summary": summary, "responses": {"200": {"description": "JSON"}}}
if params:
op["parameters"] = params
if secure:
op["security"] = ([{"Account": []}, {"WriteToken": []}]
if secure == "admin" else [{"WriteToken": []}])
return {"get": op}
def p(name, where="query", required=True, schema=None):
return {"name": name, "in": where, "required": required,
"schema": schema or {"type": "string"}}
def post_op(summary, schema, secure=True):
op = {"summary": summary,
"requestBody": {"content": {"application/json":
{"schema": schema}},
"required": True},
"responses": {"200": {"description": "JSON"}}}
if secure:
op["security"] = ([{"Account": []}, {"WriteToken": []}]
if secure == "admin" else [{"WriteToken": []}])
return {"post": op}
schema_commit = {"type": "object", "properties": {
"article": {"type": "string"}, "content": {"type": "string"},
"parents": {"type": "array", "items": {"type": "string"}},
"comment": {"type": "string"}, "request_id": {"type": "string"},
"kind": {"enum": ["text", "code"]}}}
schema_push = {"type": "object", "properties": {"objects": {
"type": "array", "items": {"type": "object", "properties": {
"id": {"type": "string"},
"body": {"type": "string", "description": "base64"}}}},
"from": {"type": "string",
"description": "sender public key, 64 hex — the gossip "
"envelope; required on f2f nodes"},
"sig": {"type": "string",
"description": "Ed25519 hex over 'manifold-push-v1\\n"
"\\n' + object ids joined by newlines"}}}
schema_alias = {"type": "object", "properties": {
"fingerprint": {"type": "string"},
"name": {"type": "string", "description": "empty clears"}}}
spec = {
"openapi": "3.1.0",
"info": {"title": "Manifold node API", "version": __version__,
"summary": "Polyphonic p2p wiki: signed commit DAGs, "
"coexisting heads, object sync over plain HTTP",
"description": "Reads are open. Writes need an account "
"(register at /auth; HTTP Basic user:pass — "
"each account signs with its own key) or the "
"node's write token (X-Manifold-Token). "
"Self-signed objects may also be pushed "
"anonymously on nodes whose inbox mode is "
"open, or by friend keys on f2f nodes. Node "
"management needs an admin. The article "
"'frontpage' is rendered as /. The node "
"never executes code."},
"servers": [{"url": "/"}],
"components": {"securitySchemes": {
"WriteToken": {"type": "apiKey", "in": "header",
"name": "X-Manifold-Token"},
"Account": {"type": "http", "scheme": "basic",
"description": "a /auth account; admin role needed "
"for management routes"}}},
"paths": {
"/api/manifest": g("node identity, endpoints, limits, stats, "
"inbox mode, learned nodes"),
"/api/peers": g("this node's peers with pull and push state "
"(admin; tokens never included)",
secure="admin"),
"/api/accounts": g("accounts of this node: name, key, role "
"(admin)", secure="admin"),
"/api/articles": g("all articles with commit/head counts"),
"/api/heads": g("coexisting heads of one article",
[p("article")]),
"/api/tree": g("full history DAG of one article",
[p("article")]),
"/api/search": g("literal substring search over held objects",
[p("q"), p("limit", required=False)]),
"/api/authors": g("authors seen by this node + node-local karma"),
"/api/releases": g("release objects held (all versions coexist)"),
"/source/{file}": g("this node's own code file, raw",
[p("file", where="path")]),
"/AGENTS.md": g("agent guide"),
"/llms.txt": g("this summary"),
"/skill.md": g("llms.txt as text/markdown"),
"/.well-known/agent-card.json": g("discovery card"),
"/api/aliases": g("operator-curated node-local aliases"),
"/api/object/{id}": g("raw object by sha256 id",
[p("id", where="path")]),
"/api/objects": g("batch fetch (base64 bodies)",
[p("ids", schema={"type": "string",
"description": "comma-separated ids"})]),
"/api/ids": g("object listing with sync cursor",
[p("since", required=False,
schema={"type": "integer"})]),
"/api/recent": g("latest commits node-wide",
[p("n", required=False)]),
"/api/source": g("this node's own code: names, sizes, sha256"),
"/api/help": g("machine-readable endpoint list"),
"/healthz": g("liveness"),
"/auth": g("register an account (user) or verify one "
"(user + pass); answers JSON with ?format=json",
[p("user"), p("pass", required=False)]),
"/n": g("one-line note as a new branch (GET write: account or "
"token)",
[p("article"), p("text"),
p("p", required=False),
p("m", required=False),
p("k", required=False)]),
"/api/commit": post_op(
"node-signed commit (or pre-signed object push-in)",
schema_commit),
"/api/push": post_op("push pre-signed objects", schema_push),
"/api/alias": post_op(
"set/clear a node-local author alias (admin)", schema_alias,
secure="admin"),
"/mcp": post_op("JSON-RPC 2.0 (MCP tools, stateless, no SSE)",
{"type": "object"}, secure=False),
},
}
return json_response(spec)
def agent_card(h):
"""Discovery card for agents (A2A-style agent-card.json)."""
store = h.server.store
return json_response({
"name": store.cfg.get("name", "manifold"),
"software": SOFTWARE, "version": __version__, "protocol": PROTOCOL,
"instance_id": store.instance_id,
"description": "Polyphonic peer-to-peer wiki node: articles are "
"signed commit DAGs, conflicting heads coexist, "
"objects sync over plain HTTP across clearnet/tor/"
"i2p/yggdrasil.",
"service_url": request_origin(h, store),
"capabilities": ["read-articles", "read-heads", "read-tree",
"search", "authors", "aliases", "commit", "push",
"pull-sync", "mcp-tools", "format-negotiation",
"source-bootstrap", "accounts", "releases",
"frontpage"],
"endpoints": {"manifest": "/api/manifest", "help": "/api/help",
"openapi": "/openapi.json", "mcp": "/mcp",
"agents_guide": "/AGENTS.md", "skill_md": "/skill.md",
"llms_txt": "/llms.txt"},
"security": {"reads": "open",
"writes": "an account (register at /auth; HTTP Basic "
"user:pass — each account signs with its own "
"key) or the node's write token "
"(X-Manifold-Token header)",
"admin": "admin account or write token: peers, aliases",
"code_execution": "none — the node never executes code"},
"auth": {"register": "/auth or MCP register_account",
"scheme": "http basic", "inbox": store.inbox_mode()},
})
def _doc_skill(h):
"""LLMs.txt-served-as-skill: same content, markdown type."""
return _doc(h, _llms_text(h), "text/markdown; charset=utf-8")
def _llms_text(h) -> str:
path = os.path.join(h.server.store.root, "llms.txt")
try:
with open(path, encoding="utf-8") as f:
return f.read()
except OSError:
return LLMS_TXT
# ------------------------------------------------------------------- MCP --
# POST /mcp: JSON-RPC 2.0, stateless, no SSE — one complete call per HTTP
# request, tools mirror the routes. Write tools enforce the same write-token
# gate as their /api/* twins.
MCP_PROTOCOL_VERSION = "2025-06-18"
class _McpLimited(Exception):
def __init__(self, retry: float):
super().__init__("rate_limited")
self.retry = max(1, math.ceil(retry))
def _mcp_result(call_id, result):
return json_response({"jsonrpc": "2.0", "id": call_id, "result": result})
def _mcp_error(call_id, code, message, status=200, data=None):
err = {"code": code, "message": message}
if data:
err["data"] = data
body = {"jsonrpc": "2.0", "id": call_id, "error": err}
return status, "application/json", \
json.dumps(body, ensure_ascii=False).encode("utf-8")
def _mcp_tools():
schema_obj = {"type": "object", "properties": {}}
return [
{"name": "node_manifest", "description":
"Node identity, announced endpoints, size limits, stats "
"(GET /api/manifest).", "inputSchema": schema_obj},
{"name": "list_articles", "description":
"All articles with commit and head counts (GET /api/articles).",
"inputSchema": schema_obj},
{"name": "get_heads", "description":
"The coexisting heads (points of view) of one article, with "
"node-local karma per author.", "inputSchema": {
"type": "object", "required": ["article"],
"properties": {"article": {"type": "string"}}}},
{"name": "get_tree", "description":
"Full history DAG of one article (nodes + edges + missing "
"ancestors).", "inputSchema": {
"type": "object", "required": ["article"],
"properties": {"article": {"type": "string"}}}},
{"name": "search_content", "description":
"Literal substring search over this node's held text/code "
"objects and article names (% and _ are NOT wildcards).",
"inputSchema": {"type": "object", "required": ["q"],
"properties": {"q": {"type": "string"},
"limit": {"type": "integer"}}}},
{"name": "get_object", "description":
"One object by sha256 id; text decoded when UTF-8.",
"inputSchema": {"type": "object", "required": ["id"],
"properties": {"id": {"type": "string"}}}},
{"name": "get_objects", "description":
"Batch fetch objects (base64 bodies) by ids.",
"inputSchema": {"type": "object", "required": ["ids"],
"properties": {"ids": {"type": "array",
"items": {"type": "string"}}}}},
{"name": "list_ids", "description":
"Object listing with the incremental sync cursor.",
"inputSchema": {"type": "object",
"properties": {"since": {"type": "integer"}}}},
{"name": "recent_commits", "description":
"Latest commits node-wide.", "inputSchema": {
"type": "object",
"properties": {"n": {"type": "integer"}}}},
{"name": "list_authors", "description":
"Authors seen by this node with node-local karma (never "
"synced).", "inputSchema": schema_obj},
{"name": "list_aliases", "description":
"Operator-curated node-local display names.",
"inputSchema": schema_obj},
{"name": "api_help", "description": "Machine-readable endpoint list.",
"inputSchema": schema_obj},
{"name": "list_releases", "description":
"Signed software releases held by this node (all versions "
"coexist).", "inputSchema": schema_obj},
{"name": "register_account", "description":
"WRITE — register an account (a free name; gets a key of its "
"own). Returns the pass ONCE: send it as HTTP Basic "
"(user:pass) on later calls. Registering is rate limited per "
"IP.", "inputSchema": {
"type": "object", "required": ["user"],
"properties": {"user": {"type": "string"}}}},
{"name": "commit", "description":
"WRITE — add a head to an article, signed with the caller's key: "
"an account (HTTP Basic user:pass on this request; see "
"register_account) or the node's write token "
"(X-Manifold-Token header).", "inputSchema": {
"type": "object", "required": ["article", "content"],
"properties": {
"article": {"type": "string"},
"content": {"type": "string"},
"parents": {"type": "array", "items": {"type": "string"}},
"comment": {"type": "string"},
"request_id": {"type": "string"},
"kind": {"enum": ["text", "code"]}}}},
{"name": "push_objects", "description":
"WRITE — push pre-signed objects. Needs an account (HTTP Basic) "
"or the write token, unless this node's inbox mode is open.",
"inputSchema": {
"type": "object", "required": ["objects"],
"properties": {"objects": {
"type": "array",
"items": {"type": "object",
"properties": {"id": {"type": "string"},
"body": {"type": "string"}}}}}}},
]
def _mcp_call(h, name, args):
store = h.server.store
args = args if isinstance(args, dict) else {}
def res(obj):
return {"content": [{"type": "text",
"text": json.dumps(obj, ensure_ascii=False)}],
"structuredContent": obj}
def bad(msg):
return {"content": [{"type": "text", "text": msg}], "isError": True}
def from_api(payload_bytes):
"""api_* payloads are (status, ctype, bytes); an {"error": ...} body
becomes an isError tool result per MCP semantics."""
obj = json.loads(payload_bytes)
if isinstance(obj, dict) and "error" in obj:
return bad(str(obj["error"]))
return res(obj)
if name == "node_manifest":
return from_api(api_manifest(store)[2])
if name == "list_articles":
return from_api(api_articles(store)[2])
if name == "get_heads":
return from_api(api_heads(store, str(args.get("article", "")))[2])
if name == "get_tree":
return from_api(api_tree(store, str(args.get("article", "")))[2])
if name == "search_content":
return from_api(api_search(
store, str(args.get("q", "")), args.get("limit"))[2])
if name == "get_object":
oid = str(args.get("id", ""))
body = store.object_body(oid)
if body is None:
return bad("unknown object %s" % oid[:12])
row = store.object(oid)
obj = {"id": oid, "type": row["type"], "size": row["size"]}
try:
obj["text"] = body.decode("utf-8")
except UnicodeDecodeError:
obj["body_base64"] = base64.b64encode(body).decode()
return res(obj)
if name == "get_objects":
ids = ",".join(str(i) for i in (args.get("ids") or [])[:128])
return from_api(api_objects(store, ids)[2])
if name == "list_ids":
return from_api(api_ids(store, args.get("since"))[2])
if name == "recent_commits":
return from_api(api_recent(store, args.get("n"))[2])
if name == "list_authors":
return from_api(api_authors(store)[2])
if name == "list_aliases":
return from_api(api_aliases(store)[2])
if name == "api_help":
return from_api(api_help(store)[2])
if name == "list_releases":
return from_api(api_releases(store)[2])
if name == "register_account":
retry = charge(h, "register")
if retry is not None:
raise _McpLimited(retry)
user = str((args or {}).get("user") or "").strip().lower()
if store.account_name_taken(user):
raise ValueError("name %s is taken" % user[:32])
try:
key, pass_ = store.account_create(user)
except ValueError as e:
raise ValueError(str(e))
return {"ok": True, "user": user, "role": "user",
"fingerprint": key.fp, "pass": pass_,
"note": "pass shown once; send it as HTTP Basic user:pass"}
if name == "commit":
# write tool: same gate + limiter as POST /api/commit
if auth_level(h, store) not in ("admin", "user"):
raise PermissionError("sign in (Authorization: Basic user:pass) "
"or use the write token")
return from_api(api_commit(h, args)[2])
if name == "push_objects":
# same inbox rule as POST /api/push: open nodes take anonymous batches
if auth_level(h, store) == "anon" and store.inbox_mode() != "open":
raise PermissionError("sign in (Authorization: Basic user:pass) or "
"use the write token; f2f nodes take signed "
"batches via /api/push")
retry = charge(h, "push")
if retry is not None:
raise _McpLimited(retry)
return from_api(api_push(h, {"objects": args.get("objects")})[2])
raise KeyError(name)
def post_mcp(h, m):
"""JSON-RPC 2.0, stateless: initialize / tools/list / tools/call (+ping).
Errors keep JSON-RPC shape; the HTTP status mirrors them."""
store = h.server.store
try:
req = json.loads(h.body.decode("utf-8"))
except Exception:
return _mcp_error(None, -32700, "parse error")
if isinstance(req, list):
return _mcp_error(None, -32600,
"batch requests not supported (stateless single "
"calls only)", status=400)
if not isinstance(req, dict) or req.get("jsonrpc") != "2.0" \
or not isinstance(req.get("method"), str):
return _mcp_error(req.get("id") if isinstance(req, dict) else None,
-32600, "invalid request", status=400)
call_id = req.get("id")
method = req.get("method", "")
if method == "initialize":
return _mcp_result(call_id, {
"protocolVersion": MCP_PROTOCOL_VERSION,
"capabilities": {"tools": {"listChanged": False}},
"serverInfo": {"name": SOFTWARE, "version": __version__,
"instance_id": store.instance_id},
"instructions":
"Polyphonic p2p wiki: every article is a signed commit DAG "
"and conflicting heads coexist — never overwrite a head, "
"branch beside it. Reads are open. To write, register an "
"account (tool register_account — the pass is returned "
"once) and send it as HTTP Basic on every later request; "
"the node's write token in the X-Manifold-Token header also "
"works and is admin. Self-signed objects may be pushed "
"anonymously only on nodes whose inbox mode is open. The "
"node never executes code.",
})
if method.startswith("notifications/"):
return 202, "application/json", b""
if method == "ping":
return _mcp_result(call_id, {})
if method == "tools/list":
return _mcp_result(call_id, {"tools": _mcp_tools()})
if method == "tools/call":
params = req.get("params") or {}
name = str(params.get("name", ""))
try:
return _mcp_result(call_id,
_mcp_call(h, name, params.get("arguments")))
except KeyError:
return _mcp_error(call_id, -32602, "unknown tool: %s" % name[:64],
status=400)
except PermissionError as e:
return _mcp_error(call_id, -32000, str(e), status=403,
data={"status": 403})
except _McpLimited as e:
out = _mcp_error(call_id, -32000, "rate limited", status=429,
data={"status": 429, "retry_after": e.retry})
return out[0], out[1], out[2], None, {"Retry-After": str(e.retry)}
except ValueError as e:
return _mcp_result(call_id, {"content": [{"type": "text",
"text": str(e)}], "isError": True})
except Exception as e:
return _mcp_result(call_id, {"content": [{"type": "text",
"text": "internal: %s" % str(e)[:200]}],
"isError": True})
return _mcp_error(call_id, -32601, "method not found: %s" % method[:64],
status=404)
# ----------------------------------------------------------------- server --
GET_ROUTES = [
(re.compile(r"^/$"), lambda h, m: page_index(h.server.store, h.fmt), "read"),
(re.compile(r"^/healthz$"), lambda h, m: api_health(h.server.store), "read"),
(re.compile(r"^/n$"), lambda h, m: get_note(h, m), None), # charges commit
(re.compile(r"^/robots\.txt$"), lambda h, m: _doc(h, ROBOTS_TXT,
"text/plain; charset=utf-8"), None),
(re.compile(r"^/a/([^/]+)/edit$"), lambda h, m: page_edit(
h.server.store, m[0], h.q.get("h"), h.q.get("merge")), "read"),
(re.compile(r"^/a/([^/]+)/diff$"), lambda h, m: page_diff(
h.server.store, m[0], h.q.get("a"), h.q.get("b")), "read"),
(re.compile(r"^/a/([^/]+)$"), lambda h, m: page_article(
h.server.store, m[0], h.q.get("h"), h.q.get("base"), h.fmt), "read"),
(re.compile(r"^/c/([0-9a-f]{64})$"), lambda h, m: page_commit(
h.server.store, m[0]), "read"),
(re.compile(r"^/o/([0-9a-f]{64})$"), lambda h, m: page_object(
h.server.store, m[0]), "read"),
(re.compile(r"^/code/([0-9a-f]{64})$"), lambda h, m: page_code(
h.server.store, m[0]), "read"),
(re.compile(r"^/sync$"), lambda h, m: page_sync(h.server.store) if is_admin(h, h.server.store) else forbidden(h, h.server.store), "read"),
(re.compile(r"^/auth$"), lambda h, m: page_auth(h), "read"),
(re.compile(r"^/api/accounts$"), lambda h, m: api_accounts(h.server.store, h), "read"),
(re.compile(r"^/search$"), lambda h, m: page_search(
h.server.store, h.q.get("q"), h.fmt), "read"),
(re.compile(r"^/authors$"), lambda h, m: page_authors(h.server.store), "read"),
(re.compile(r"^/(AGENTS\.md|agents\.md)$"), lambda h, m: _doc_agents(h), None),
(re.compile(r"^/llms\.txt$"), lambda h, m: _doc_llms(h), None),
(re.compile(r"^/skill\.md$"), lambda h, m: _doc_skill(h), None),
(re.compile(r"^/openapi\.json$"), lambda h, m: api_openapi(h.server.store), "read"),
(re.compile(r"^/\.well-known/agent-card\.json$"), lambda h, m: agent_card(
h), "read"),
(re.compile(r"^/source$"), lambda h, m: page_source(h), "read"),
(re.compile(r"^/source/([A-Za-z0-9._-]{1,64})$"), lambda h, m: serve_source_file(
h.server.store, m[0]), "read"),
(re.compile(r"^/api/source$"), lambda h, m: api_source(h.server.store), "read"),
(re.compile(r"^/api/source/([A-Za-z0-9._-]{1,64})$"), lambda h, m: serve_source_file(
h.server.store, m[0]), "read"),
(re.compile(r"^/api/manifest$"), lambda h, m: api_manifest(h.server.store), "read"),
(re.compile(r"^/api/peers$"), lambda h, m: api_peers(h.server.store, h), "read"),
(re.compile(r"^/api/articles$"), lambda h, m: api_articles(h.server.store), "read"),
(re.compile(r"^/api/heads$"), lambda h, m: api_heads(
h.server.store, h.q.get("article", "")), "read"),
(re.compile(r"^/api/tree$"), lambda h, m: api_tree(
h.server.store, h.q.get("article", "")), "read"),
(re.compile(r"^/api/search$"), lambda h, m: api_search(
h.server.store, h.q.get("q"), h.q.get("limit")), "read"),
(re.compile(r"^/api/authors$"), lambda h, m: api_authors(h.server.store), "read"),
(re.compile(r"^/api/releases$"), lambda h, m: api_releases(h.server.store), "read"),
(re.compile(r"^/api/aliases$"), lambda h, m: api_aliases(h.server.store), "read"),
(re.compile(r"^/api/object/([0-9a-f]{64})$"), lambda h, m: api_object(
h.server.store, m[0]), "read"),
(re.compile(r"^/api/objects$"), lambda h, m: api_objects(
h.server.store, h.q.get("ids")), "read"),
(re.compile(r"^/api/ids$"), lambda h, m: api_ids(
h.server.store, h.q.get("since")), "read"),
(re.compile(r"^/api/recent$"), lambda h, m: api_recent(
h.server.store, h.q.get("n")), "read"),
(re.compile(r"^/api/help$"), lambda h, m: api_help(h.server.store), "read"),
]
POST_ROUTES = [
(re.compile(r"^/edit$"), lambda h, m: post_edit(h, m), None), # charges commit
(re.compile(r"^/a/([^/]+)/edit$"), lambda h, m: post_edit(h, m), None),
(re.compile(r"^/alias$"), lambda h, m: post_alias(h, m), None),
# /sync/peer + /sync/run charge "push" inside their handlers, after the
# admin gate — a route-table kind here would charge every event twice
(re.compile(r"^/sync/peer$"), lambda h, m: post_peer_add(h, m), None),
(re.compile(r"^/sync/run$"), lambda h, m: post_sync_run(h, m), None),
(re.compile(r"^/auth$"), lambda h, m: page_auth(h), None), # charges itself
(re.compile(r"^/api/commit$"), lambda h, m: post_api(h, m, "commit"), None),
(re.compile(r"^/api/push$"), lambda h, m: post_api(h, m, "push"), "push"),
(re.compile(r"^/api/alias$"), lambda h, m: post_api(h, m, "alias"), None),
(re.compile(r"^/mcp$"), lambda h, m: post_mcp(h, m), None),
]
ROBOTS_TXT = ("User-agent: *\n"
"Allow: /\n"
"Disallow: /n\n")
# ------------------------------------------------------------------ source --
# The node's own code, served for bootstrap and inspection (roadmap item 1,
# bootstrap primitive). Fixed allowlist only — no user-controlled paths.
SELF_FILES = ("manifold.py", "manifold_http.py", "README.md", "AGENTS.md",
"llms.txt", "LICENSE")
def _self_dir() -> str:
"""Directory of the RUNNING code (not the node data dir)."""
return os.path.dirname(os.path.abspath(__file__))
def _self_files():
"""[(name, path, size, sha256)] for the allowlisted files that exist."""
out = []
base = _self_dir()
for name in SELF_FILES:
path = os.path.join(base, name)
try:
with open(path, "rb") as f:
data = f.read()
except OSError:
continue
out.append((name, path, len(data),
hashlib.sha256(data).hexdigest()))
return out
def page_source(h):
store = h.server.store
rows = "".join(
"
"
% (uq(name), esc(name), size, sha[:16])
for name, _path, size, sha in _self_files())
bootstrap = " · ".join("curl -sO %s/source/%s" % (request_origin(h, store),
n)
for n in ("manifold.py", "manifold_http.py"))
body = (
"
Source
"
"
This node serves its own running code "
"(Manifold v%s, MIT) — pull it to bootstrap a new node anywhere; "
"no central repository. Hashes as JSON: "
"/api/source.
"
"
What you need
"
"
Python ≥ 3.8 — nothing else. Both "
"files are pure stdlib: zero dependencies, no packages to install "
"(the optional cryptography package only speeds up "
"Ed25519 signing). One process, ~10 MB RAM; runs on Linux, macOS, "
"BSD and Windows. The node binds 127.0.0.1:8830 by "
"default — edit config.json to change port or bind."
"
"
"
file
size
"
"
sha256
%s
"
"
Bootstrap a new node from this one
"
"
%s
"
"
then: python3 manifold.py --dir "
"my-node init --name my-node && python3 manifold.py --dir "
"my-node keygen --name you && python3 manifold.py --dir "
"my-node serve — if port 8830 is taken, edit "
"my-node/config.json first. Verify downloads with "
"sha256sum against the table above.
"
"
Updating an existing node
"
"
Software updates travel the same way: "
"releases are signed objects in the store (manifest + hash-named "
"chunk blobs; every version coexists) — see "
"/api/releases. Applying one is a local operator act: "
"manifold.py update --check --latest then "
"manifold.py update --latest; never at sync or serve "
"time.
"
% (__version__, rows, esc(bootstrap)))
return page(store, "source", body)
def _bind_url(store) -> str:
bind = str(store.cfg.get("bind") or "127.0.0.1")
port = int(store.cfg.get("port") or 8830)
host = "127.0.0.1" if bind in ("0.0.0.0", "::") else bind
return "http://%s:%d" % (host, port)
_HOST_RE = re.compile(
r"^(?:[A-Za-z0-9][A-Za-z0-9.\-]*|\[[0-9a-fA-F:.]+\])(?::[0-9]{1,5})?$")
def request_origin(h, store) -> str:
"""URL of the door the caller is actually using: request Host first
(correct on every layer — clearnet, onion, i2p, loopback), then the
node's announced endpoints, then the bind address. The Host header is
validated (it is caller-controlled); the scheme follows
X-Forwarded-Proto only when trust_proxy is set, because a direct
client could otherwise upgrade the printed URL spuriously."""
host = str((getattr(h, "headers", None) or {}).get("Host") or "").strip()
if host and len(host) <= 253 and _HOST_RE.match(host):
proto = str((getattr(h, "headers", None) or {}).get(
"X-Forwarded-Proto") or "").strip().lower()
scheme = ("https" if proto == "https" else "http") \
if store.cfg.get("trust_proxy") else "http"
return "%s://%s" % (scheme, host)
for ep in (store.cfg.get("endpoints") or []):
url = str((ep or {}).get("url") or "")
if url.startswith("http://") or url.startswith("https://"):
return url.rstrip("/")
return _bind_url(store)
def api_source(store):
return json_response({
"software": SOFTWARE, "version": __version__,
"files": [{"name": name, "size": size, "sha256": sha}
for name, _p, size, sha in _self_files()],
"note": "GET /source/ fetches the raw file; verify hashes "
"after download",
})
def serve_source_file(store, name):
if name not in SELF_FILES:
return not_found(store, "source file")
for fname, path, _size, _sha in _self_files():
if fname == name:
with open(path, "rb") as f:
return 200, "text/plain; charset=utf-8", f.read()
return not_found(store, "source file")
def _doc(handler, text, ctype="text/markdown; charset=utf-8"):
return 200, ctype, text.encode("utf-8")
def _doc_agents(h):
path = os.path.join(h.server.store.root, "AGENTS.md")
try:
with open(path, encoding="utf-8") as f:
return _doc(h, f.read())
except OSError:
return _doc(h, AGENTS_MD)
def _doc_llms(h):
return _doc(h, _llms_text(h), "text/plain; charset=utf-8")
def _article_from(handler, m):
article = m[0] if len(m) == 1 else (handler.q.get("article") or m[0])
return article
def post_edit(h, m):
store = h.server.store
if not html_write_ok(h, store):
return forbidden(h, store)
form = urllib.parse.parse_qs(h.body.decode("utf-8", errors="replace"))
article = (m[0] if m else form.get("article", [""])[0]).strip()
if not ARTICLE_RE.match(article):
return page(store, "error", "
bad article name
", status=400)
text = form.get("text", [""])[0]
comment = form.get("comment", [""])[0][:300]
rid = form.get("request_id", [""])[0] or None
parents_raw = form.get("parents", [""])[0]
parents = []
for p in [x.strip() for x in parents_raw.split(",") if x.strip()]:
resolved = store.resolve_head(article, p)
if resolved:
parents.append(resolved)
if not parents and store.heads(article):
parents = [store.heads(article)[0]["id"]]
try:
cid, replayed = idem_precheck_text(store, article, parents, text,
comment, rid)
except ValueError:
return page(store, "conflict", "
request_id_conflict
that "
"retry key was used with different content.
", status=409)
if replayed:
return 303, "text/plain", b"", "/a/%s?h=%s" % (uq(article), uq(cid))
retry = charge(h, "commit")
if retry is not None:
return rate_limited_page(store, retry)
try:
key = request_key(h, store)
except RuntimeError as e:
return page(store, "error", "
no key
%s
" % esc(e), status=503)
try:
cid, _, _ = store.create_commit(key, article, text.encode("utf-8"),
parents, comment, request_id=rid)
except ValueError as e:
status = 409 if "conflict" in str(e) else 400
return page(store, "error", "
rejected
%s
" % esc(e), status=status)
return 303, "text/plain", b"", "/a/%s?h=%s" % (uq(article), uq(cid))
def get_note(h, m):
"""GET /n — the one small GET-write surface: a one-line note becomes a
new branch commit. Token or same-origin required; idempotent via k=."""
store = h.server.store
if h.command != "GET":
return 405, "text/plain", b"method not allowed"
if len(h.path) > MAX_LINE:
return page(store, "error", "
request line too long
"
"
notes are capped at %d bytes of text.
" % NOTE_LIMIT,
status=400)
if not html_write_ok(h, store):
return forbidden(h, store)
q = h.q
article = (q.get("article") or "").strip()
if not ARTICLE_RE.match(article):
return 400, "text/plain", b"bad or missing article"
text = q.get("text") or ""
if not text.strip():
return 400, "text/plain", b"empty note text"
if len(text.encode("utf-8")) > NOTE_LIMIT:
return 400, "text/plain", ("note exceeds %d bytes" % NOTE_LIMIT).encode()
comment = (q.get("m") or "")[:300]
rid = q.get("k") or None
p = (q.get("p") or "").strip()
parents = []
if p:
resolved = store.resolve_head(article, p)
if not resolved:
return 400, "text/plain", b"parent is not a resolvable head"
parents = [resolved]
elif store.heads(article):
parents = [store.heads(article)[0]["id"]]
try:
cid, replayed = idem_precheck_text(store, article, parents, text,
comment, rid)
except ValueError:
body = json_response({"error": "request_id_conflict"}, 409)
return body if q.get("format") == "json" else \
page(store, "conflict", "
request_id_conflict
", status=409)
if replayed:
if q.get("format") == "json":
return json_response({"ok": True, "id": cid, "replay": True})
return 303, "text/plain", b"", "/a/%s?h=%s" % (uq(article), uq(cid))
retry = charge(h, "commit")
if retry is not None:
if q.get("format") == "json":
return rate_limited_json(retry)
return rate_limited_page(store, retry)
try:
key = request_key(h, store)
except RuntimeError as e:
return 503, "text/plain", str(e).encode()
try:
cid, _, replayed = store.create_commit(key, article,
text.encode("utf-8"), parents,
comment, request_id=rid)
except ValueError as e:
status = 409 if "conflict" in str(e) else 400
if q.get("format") == "json":
return json_response({"error": str(e)}, status)
return page(store, "error", "
rejected
%s
" % esc(e), status=status)
if q.get("format") == "json":
return json_response({"ok": True, "id": cid, "replay": replayed})
return 303, "text/plain", b"", "/a/%s?h=%s" % (uq(article), uq(cid))
def _limited(h, store):
if h.fmt == "json":
return rate_limited_json(60)
return rate_limited_page(store, 60)
def page_auth(h):
"""GET/POST /auth — flatboard-style accounts, stateless.
`user` alone registers a free name (pass shown once); `user` + `pass`
verifies. JSON callers get the same answers as objects."""
store = h.server.store
form = {}
if h.command == "POST" and h.body:
try:
form = urllib.parse.parse_qs(h.body.decode("utf-8", errors="replace"))
except Exception:
form = {}
# agents post JSON here too — the docs show {"user": ...}; accept
# both shapes (a form body never parses as JSON, no ambiguity)
try:
j = json.loads(h.body.decode("utf-8"))
if isinstance(j, dict):
form = {k: [v] for k, v in j.items() if isinstance(v, str)}
except Exception:
pass
user = (h.q.get("user") or form.get("user", [""])[0] or "").strip().lower()
pass_ = h.q.get("pass") or form.get("pass", [""])[0] or ""
as_json = h.fmt == "json"
if auth_level(h, store) == "limited":
return _limited(h, store)
login_form = (
""
"")
intro = (
"
An account holds a key of its own on this node: "
"everything you write is signed with your key and carries your "
"name as this node's alias for it. The pass is shown once and stored "
"hashed — there is no reset, register a new name if you lose it. "
"Names are first come, first served.
")
if not user:
return page(store, "account", "
Account
%s%s" % (intro, login_form))
if not pass_:
retry = charge(h, "register")
if retry is not None:
return _limited(h, store)
if not ACCOUNT_NAME_RE.match(user):
msg, status = "bad name: 2-32 chars, a-z 0-9 _ -", 400
elif store.account_name_taken(user):
msg, status = "name %s is taken" % esc(user), 409
else:
key, newpass = store.account_create(user)
if as_json:
return json_response({"ok": True, "user": user, "role": "user",
"fingerprint": key.fp, "pass": newpass,
"note": "pass shown once"}, 201)
return page(store, "account", (
"
Account created
You are "
"@%s — key %s
"
"
Your pass, shown once:
%s"
"
Every form on this node accepts it "
"in the user/pass fields. Nothing is stored in your browser.
"
% (esc(acct["name"]), " (admin)" if acct["role"] == "admin" else "",
esc(acct["fp"]), cq, cq,
(" peers" % cq)
if acct["role"] == "admin" else "")))
def api_accounts(store, h):
if not is_admin(h, store):
return json_response({"error": "forbidden: account list is node "
"management (admin account or write token)"}, 403)
return json_response({"accounts": [{
"name": a["name"], "fingerprint": a["fp"], "role": a["role"],
"created": a.get("created")} for a in store.accounts()]})
def post_peer_add(h, m):
store = h.server.store
if not is_admin(h, store):
return forbidden(h, store)
form = urllib.parse.parse_qs(h.body.decode("utf-8", errors="replace"))
url = (form.get("url", [""])[0] or "").strip()
layer = (form.get("layer", [""])[0] or "").strip() or None
if not re.match(r"^https?://", url):
return page(store, "error", "
bad peer url
", status=400)
retry = charge(h, "push")
if retry is not None:
return rate_limited_page(store, retry)
store.add_peer(url, layer)
rep = sync_peer(store, url, layer, store.cfg)
note = rep.get("status") or rep.get("error") or "synced"
return page_sync(store, notice="peer %s added — %s" % (url, note))
def post_sync_run(h, m):
store = h.server.store
if not is_admin(h, store):
return forbidden(h, store)
form = urllib.parse.parse_qs(h.body.decode("utf-8", errors="replace"))
url = (form.get("url", [""])[0] or "").strip()
retry = charge(h, "push")
if retry is not None:
return rate_limited_page(store, retry)
reports = sync_all(store, url or None)
notes = "; ".join(r.get("status") or r.get("error") or "?" for r in reports)
return page_sync(store, notice=notes or "no peers configured")
_TOKEN_NEEDED = {"error": "sign in first (POST /auth) or use the node's write "
"token (X-Manifold-Token or ?token=) — operator: python3 "
"manifold.py token"}
def post_api(h, m, which):
"""API write gate. Levels: the write token and admin accounts may do
anything; a user account may bring objects and get node-keyed commits
(signed with the account's own key); an anonymous caller depends on
inbox.mode — in `open` and `f2f` a stranger may bring objects they
signed themselves (a pre-signed /api/commit object, or /api/push); in
`f2f` the push batch must also be signed by a friend's key. Alias
curation is always admin-only."""
store = h.server.store
level = auth_level(h, store)
if level == "limited":
return rate_limited_json(60)
if level == "admin":
pass
elif which == "alias":
return json_response({"error": "alias curation needs the write token "
"or an admin account"}, 403)
elif level == "user":
pass
elif store.inbox_mode() == "token":
return json_response(dict(_TOKEN_NEEDED), 403)
try:
payload = json.loads(h.body.decode("utf-8"))
except Exception:
return json_response({"error": "invalid JSON body"}, 400)
if level == "anon":
if which == "commit" and not (isinstance(payload, dict) and "object" in payload):
return json_response(dict(_TOKEN_NEEDED, error=(
_TOKEN_NEEDED["error"] + " — a node-signed commit always "
"needs it; strangers send a pre-signed `object`")), 403)
# f2f: whatever an anonymous caller brings — a push batch or one
# pre-signed object via /api/commit — must carry the friend
# envelope, and it must cover exactly the object(s) being brought.
# The signature verifies FIRST; the friend check runs on the proven
# sender, never on the claimed one. Open mode requires no envelope.
if store.inbox_mode() == "f2f":
batch = payload if which == "push" else {
"objects": [payload.get("object")],
"from": payload.get("from"), "sig": payload.get("sig")}
ok, fp, why = M_push_sender(store, batch)
if not (ok and store.is_friend(fp)):
return json_response({"error": "f2f node: push rejected (%s) — "
"the batch must be signed by a friend key"
% (why or "sender %s is not a friend" % fp)},
403)
if which == "commit":
return api_commit(h, payload)
if which == "alias":
return api_alias_set(store, payload)
return api_push(h, payload)
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
server_version = "Manifold/" + __version__
# Kill stalled connections (slowloris) instead of parking a thread forever.
timeout = 30
def log_message(self, fmt, *args):
# credentials travel in query strings (stateless, flatboard-style):
# never let them reach the log
line = re.sub(r"(pass|token)=[^&\s\"']+", r"\1=", fmt % args)
sys_stderr_write("%s %s\n" % (self.address_string(), line))
# parsed per-request state
q = {}
body = b""
fmt = "html"
def client_ip(self) -> str:
"""Rate-limit key. X-Forwarded-For is honored only when the operator
set trust_proxy — otherwise it is trivially spoofable."""
if getattr(self.server, "trust_proxy", False):
xff = self.headers.get("X-Forwarded-For")
if xff:
return xff.split(",")[0].strip()
return self.client_address[0]
def _negotiate(self, path: str, table=None):
"""Read-route content negotiation: ?format= beats a .json/.txt
suffix, which beats the Accept header; default html. Decided BEFORE
any route runs so every response — success or error — honors it
(errors in the requested format, not the server's mood). Suffixes
mean a format on /a/ and /search (article names may contain
dots). Elsewhere a suffix is honored only when the path matches NO
route: a resource path like /openapi.json or /source/llms.txt is
served untouched, while /whatever.json gets its 404 in JSON."""
want = (self.q.get("format") or "").strip().lower()
if want in ("json", "txt", "text"):
return path, ("txt" if want in ("txt", "text") else "json")
if want == "html":
return path, "html"
if path.startswith("/a/") or path == "/search" \
or path.startswith("/search."):
m = re.search(r"\.(json|txt)$", path)
if m:
return path[: m.start()], m.group(1)
m = re.search(r"\.(json|txt)$", path)
if m and table is not None:
if not any(rx.match(path) for rx, _f, _k in table):
stripped = path[: m.start()]
if any(rx.match(stripped) for rx, _f, _k in table):
return stripped, m.group(1)
return path, m.group(1)
accept = (self.headers.get("Accept") or "").lower()
if "application/json" in accept and "text/html" not in accept:
return path, "json"
return path, "html"
def _try_routes(self, table, path) -> bool:
for rx, fn, kind in table:
m = rx.match(path)
if not m:
continue
if kind:
retry = charge(self, kind)
if retry is not None:
if self.fmt == "json" or path.startswith("/api/"):
self._send(rate_limited_json(retry))
else:
self._send(rate_limited_page(self.server.store, retry))
return True
self._send(fn(self, m.groups()))
return True
return False
def _dispatch(self, method):
parsed = urllib.parse.urlparse(self.path)
path = parsed.path
self.q = {k: v[-1] for k, v in
urllib.parse.parse_qs(parsed.query, keep_blank_values=True).items()}
path, self.fmt = self._negotiate(path, GET_ROUTES)
# a keep-alive connection reuses this instance: nothing of the previous
# request's identity may survive
self._creds = self._level = self._account = None
_ctx.creds = (None, None)
_ctx.account = None
_ctx.admin = False
try:
if method == "POST":
self.body = read_body(self)
if self.path.startswith(("/api/", "/sync", "/auth")) or method == "POST" \
or request_creds(self)[0]:
level = auth_level(self, self.server.store)
if level == "limited":
self._send(_limited(self, self.server.store))
return
_ctx.creds = request_creds(self) if level in ("user", "admin") else (None, None)
_ctx.account = getattr(self, "_account", None)
_ctx.admin = is_admin(self, self.server.store)
table = POST_ROUTES if method == "POST" else GET_ROUTES
if self._try_routes(table, path):
return
if method == "GET":
if self.fmt == "json":
self._send(json_response({"error": "not found"}, 404))
else:
self._send(not_found(self.server.store))
else:
self._send((405, "text/plain", b"method not allowed"))
except (BrokenPipeError, ConnectionResetError):
pass
except Exception as e: # keep the thread alive, report cleanly
try:
if path.startswith("/api/") or self.fmt == "json":
self._send(json_response({"error": "internal: %s" % str(e)[:200]}, 500))
else:
msg = "
500
%s
" % esc(str(e)[:400])
self._send(page(self.server.store, "error", msg, status=500))
except Exception:
pass
def _send(self, out):
status, ctype, payload = out[0], out[1], out[2]
self.send_response(status)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(payload)))
if len(out) > 3 and out[3]:
self.send_header("Location", out[3])
if len(out) > 4 and out[4]:
for k, v in out[4].items():
self.send_header(k, v)
self.send_header("X-Content-Type-Options", "nosniff")
self.end_headers()
if self.command != "HEAD":
self.wfile.write(payload)
def do_GET(self):
self._dispatch("GET")
def do_HEAD(self):
self._dispatch("GET")
def do_POST(self):
self._dispatch("POST")
sys_stderr_write = sys.stderr.write
def build_server(store: Store) -> ThreadingHTTPServer:
httpd = ThreadingHTTPServer((store.cfg.get("bind", "127.0.0.1"),
int(store.cfg.get("port", 8830))), Handler)
httpd.daemon_threads = True
httpd.store = store
httpd.limiter = RateLimiter()
httpd.rate_limits = rate_limits_from(store.cfg)
httpd.trust_proxy = bool(store.cfg.get("trust_proxy"))
return httpd
def net_loop(store: Store, httpd) -> None:
"""Background network loop of `serve`: push newly held objects to peers
every gossip.interval seconds and pull from all peers every
sync.interval seconds (0 = off). Objects are immutable and gossip keeps
per-peer cursors, so a round is a no-op when nothing changed; failures
are recorded on the peer row, never raised."""
gi = max(1, int((store.cfg.get("gossip") or {}).get("interval", 10) or 10))
si = int((store.cfg.get("sync") or {}).get("interval", 300) or 0)
last_pull = time.monotonic()
while not getattr(httpd, "net_stop", False):
try:
time.sleep(gi)
if getattr(httpd, "net_stop", False):
return
if store.list_peers():
gossip_all(store)
if si and time.monotonic() - last_pull >= si:
last_pull = time.monotonic()
sync_all(store)
gossip_all(store)
except Exception as e:
sys.stderr.write("net loop: %s\n" % str(e)[:200])
def serve(store: Store) -> None:
cfg = store.cfg
httpd = build_server(store)
print("Manifold v%s — node %s (instance %s)" % (
__version__, cfg.get("name", "manifold"), store.instance_id))
print(" local UI/API : http://%s:%d/" % (cfg.get("bind", "127.0.0.1"),
int(cfg.get("port", 8830))))
tok = cfg.get("write_token")
print(" write token : %s" % ("set (config.json, 0600)" if tok else
"NOT SET — every write is refused; run: python3 manifold.py token"))
mode = store.inbox_mode()
print(" inbox : %s%s" % (mode, (
" (%d friends)" % len((cfg.get("inbox") or {}).get("friends") or [])
if mode == "f2f" else "")))
print(" code runs : none over HTTP (by design); operator CLI: "
"python3 manifold.py run ")
for e in cfg.get("endpoints", []):
print(" %-13s : %s" % (e.get("layer", "?"), e.get("url", "?")))
if not cfg.get("endpoints"):
print(" endpoints : none announced yet (config.json: endpoints[]; "
"clearnet/tor/i2p/yggdrasil)")
print(" agents : /AGENTS.md /llms.txt /api/help /robots.txt")
peers = store.list_peers()
print(" peers : %d configured (%d auto)" % (
len(peers), sum(1 for p in peers if p["auto"])))
print(" gossip : every %ss; pull every %ss%s" % (
(cfg.get("gossip") or {}).get("interval", 10),
(cfg.get("sync") or {}).get("interval", 300) or "off",
"" if store.cfg.get("announce_peers", True) else
"; peer map NOT announced"))
threading.Thread(target=net_loop, args=(store, httpd), daemon=True).start()
try:
httpd.serve_forever()
except KeyboardInterrupt:
httpd.net_stop = True
print("\nbye")