Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ OAuth validation and MCP Events are implemented and tested. A real provider logi

Use [participant setup](docs/participants.md) for invited agents belonging to another owner, or separate Codex/Cursor sessions. Schema 3 binds each credential to an immutable `owner.client.instance` ID, with explicit enrollment, expiry, directed conversation grants and revocation. No real invitation or access is enabled by the examples. This is one trusted operator's guest bridge: the private operator retains global bridge visibility and approval authority; guests receive only granted communication.

Use the [readable directory](docs/directory.md) for display names, platform/role headers, and unambiguous short recipient handles. Canonical identities and legacy callers remain supported.

See the [client capability matrix and config examples](docs/clients.md) for Codex, Cursor, dots, Grokbot and Muse. Tool access and native wake delivery are distinct. A shared client credential is a shared Babel identity, and an identical OAuth subject/client pair cannot identify two simultaneous dots by label. New sessions use fresh IDs; retired credentials and old histories cannot be recycled into them.

## Run locally
Expand Down
29 changes: 18 additions & 11 deletions babel/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from urllib.parse import urlsplit
from .core import AGENTS, BridgeError, fields, MAX_HOPS
from .session_replies import reply_routes
from . import directory

TOKEN = re.compile(r"[A-Za-z0-9_-]{32,256}\Z")
DIGEST = re.compile(r"[a-f0-9]{64}\Z")
Expand Down Expand Up @@ -178,24 +179,28 @@ def stage(self, source, recipient, **kwargs):
self.guard()
if not isinstance(source,str) or not isinstance(recipient,str) or source != self.role:
raise BridgeError("Agent route is not permitted", 403)
parent = kwargs.get("reply_to")
parent_row = self.message_status(parent, self.role) if parent else None
recipient, conversation = directory.resolve(self.policy, source, recipient,
kwargs.get("conversation_id"), self.contacts(self.role), parent_row)
if conversation is not None:
kwargs["conversation_id"] = conversation
# Only a current trusted return capability may extend a captured scope.
if recipient not in self.recipients and (not self.policy or
(kwargs.get("conversation_id"),source,recipient) not in reply_routes(self.policy)):
raise BridgeError("Agent route is not permitted", 403)
if self.policy:
self.policy.assert_route(kwargs.get("conversation_id"),source,recipient)
kwargs["policy"]=self.policy
parent = kwargs.get("reply_to")
if parent:
self.message_status(parent, self.role)
return self.store.stage(source, recipient, **kwargs)
result = self.store.stage(source, recipient, **kwargs)
return {**result, "message": directory.annotate(self.policy, result["message"])}

def inbox(self, role, **kwargs):
self.guard()
if role != self.role:
raise BridgeError("Agent identity mismatch", 403)
if self.policy: kwargs["visibility"]=self.policy.visible_pairs(role)
return self.store.inbox(role, **kwargs)
return [directory.annotate(self.policy, row) for row in self.store.inbox(role, **kwargs)]

def contacts(self, role):
self.guard()
Expand All @@ -205,8 +210,7 @@ def contacts(self, role):
routes=self.policy.visible_pairs(role)
else:
routes=[(None,role,recipient) for recipient in sorted(self.recipients)]
return [{"recipient":recipient,"conversation_id":conversation}
for conversation,source,recipient in routes if source==role]
return directory.contacts(self.policy, role, routes)

def acknowledge(self, message_id, role, claim_id=None):
self.guard()
Expand All @@ -217,14 +221,14 @@ def acknowledge(self, message_id, role, claim_id=None):
raise BridgeError("Message not available to recipient", 404)
if claim_id is None:
raise BridgeError("Public receipt requires claim_message and its claim_id", 409)
return self.store.acknowledge_claim(message_id, role, claim_id)
return directory.annotate(self.policy, self.store.acknowledge_claim(message_id, role, claim_id))

def history(self, role, **kwargs):
self.guard()
if role != self.role:
raise BridgeError("Agent identity mismatch", 403)
if self.policy: kwargs["visibility"]=self.policy.visible_pairs(role)
return self.store.history(role, **kwargs)
return [directory.annotate(self.policy, row) for row in self.store.history(role, **kwargs)]

def message_status(self, message_id, role):
self.guard()
Expand All @@ -235,7 +239,7 @@ def message_status(self, message_id, role):
if self.policy:
try: self.policy.check_row(row)
except BridgeError: raise BridgeError("Bridge message not found",404) from None
return row
return directory.annotate(self.policy, row)

def claim_message(self, message_id, role, claim_id):
self.guard()
Expand All @@ -244,4 +248,7 @@ def claim_message(self, message_id, role, claim_id):
row = self.message_status(message_id, role)
if row["recipient"] != role:
raise BridgeError("Bridge message not found", 404)
return self.store.claim_message(message_id, role, claim_id)
result = self.store.claim_message(message_id, role, claim_id)
if "message" in result:
result = {**result, "message": directory.annotate(self.policy, result["message"])}
return result
128 changes: 128 additions & 0 deletions babel/directory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
"""Presentation and route selection only. Canonical IDs remain the authority."""
import hashlib
import json
import re
from .core import AGENTS, BridgeError

METADATA = ("display_name", "platform", "role", "aliases")
ALIAS = re.compile(r"[a-z][a-z0-9_-]{0,31}\Z")


def validate_metadata(entry):
for key in ("display_name", "platform", "role"):
if key in entry:
value = entry[key]
if (not isinstance(value, str) or not 1 <= len(value) <= 64
or value != value.strip() or "/" in value
or not value.isprintable()):
raise BridgeError(key + " must be 1–64 printable characters without / or surrounding whitespace")
aliases = entry.get("aliases", [])
if (not isinstance(aliases, list) or len(aliases) > 8
or any(not isinstance(a, str) or not ALIAS.fullmatch(a) for a in aliases)
or len(set(aliases)) != len(aliases)):
raise BridgeError("Aliases must be up to 8 distinct lowercase short names")
# A display name must not shadow an immutable ID or the route-handle namespace.
name = entry.get("display_name", "").casefold()
if name.startswith("contact:") or (name and name.count(".") == 2):
raise BridgeError("Display name must not shadow a canonical ID or contact handle")


def describe(policy, pid):
entry = policy.participants.get(pid, {}) if policy and policy.multi_owner else {}
return {"id": pid, "display_name": entry.get("display_name", pid),
"platform": entry.get("platform", entry.get("client")), "client": entry.get("client"),
"role": entry.get("role"),
"owner": entry.get("owner"), "name_configured": "display_name" in entry}


def label(contact):
return " · ".join(str(contact[k]) for k in ("display_name", "platform", "role", "owner") if contact.get(k))


def operator_labels(policy, participants):
"""Compact, distinct labels for the operator's global identity inventory."""
base = {pid: label(describe(policy, pid)) for pid in participants}
result = dict(base)
lengths = {pid: 0 for pid in base}
while True:
groups = {}
for pid, value in result.items():
groups.setdefault(value.casefold(), []).append(pid)
collisions = [group for group in groups.values() if len(group) > 1]
if not collisions:
return result
for group in collisions:
for pid in group:
lengths[pid] = max(8, lengths[pid] + 4)
if lengths[pid] > 64:
# Even a full digest collision must remain distinguishable.
return {p: p for p in base}
tag = hashlib.sha256(pid.encode()).hexdigest()[:lengths[pid]]
result[pid] = base[pid] + " [#" + tag + "]"


def handle(source, recipient, conversation):
binding = json.dumps([source, recipient, conversation], separators=(",", ":"))
return "contact:" + hashlib.sha256(binding.encode()).hexdigest()[:20]


def contacts(policy, source, routes):
result = []
for conversation, sender, recipient in routes:
if sender != source:
continue
info = describe(policy, recipient)
entry = policy.participants[recipient] if policy and policy.multi_owner else {}
result.append({"recipient": recipient, "conversation_id": conversation,
"send_to": handle(source, recipient, conversation),
**{k: v for k, v in info.items() if k != "id"},
"aliases": list(entry.get("aliases", []))})
return result


def annotate(policy, row):
"""Fresh annotations, never persisted or included in message fingerprints."""
source = describe(policy, row["source"])
recipient = describe(policy, row["recipient"])
return {**row, "source_contact": source, "recipient_contact": recipient,
"header": label(source) + " → " + label(recipient)}


def resolve(policy, source, selector, conversation, choices, parent=None):
if not isinstance(selector, str) or not selector or len(selector) > 128:
raise BridgeError("Recipient must be a canonical ID, send_to handle, or exact directory name")
if conversation is not None and not isinstance(conversation, str):
raise BridgeError("Invalid conversation route", 403)
# Canonical IDs always retain their original meaning, even when unavailable.
canonical = ((selector in AGENTS and (not policy or not policy.multi_owner))
or (policy and selector in policy.agents))
if canonical:
return selector, conversation if conversation is not None else (parent["conversation_id"] if parent else None)
candidates = []
for contact in choices:
if conversation is not None and contact["conversation_id"] != conversation:
continue
if selector.startswith("contact:"):
matches = selector == contact["send_to"]
else:
owner, separator, name = selector.partition("/")
if not separator:
name, owner = owner, None
# Friendly names are scoped to the sender's owner. Cross-owner
# contacts require an explicit owner/name or the listed route handle.
namespace = owner if separator else describe(policy, source)["owner"]
matches = (namespace == contact["owner"] and name.casefold() in
[contact["display_name"].casefold(), *contact["aliases"]])
if matches:
candidates.append(contact)
if parent:
# Never resolve a renamed/reused alias into a different reply route.
candidates = [c for c in candidates if c["recipient"] == parent["source"]
and c["conversation_id"] == parent["conversation_id"]]
if not candidates:
raise BridgeError("Recipient is unavailable in this scope; refresh list_contacts and use its send_to handle", 403)
if len(candidates) != 1:
options = [{"name": label(c), "send_to": c["send_to"], "conversation_id": c["conversation_id"]}
for c in candidates]
raise BridgeError("Ambiguous recipient; choose a send_to handle: " + json.dumps(options, ensure_ascii=False), 409)
return candidates[0]["recipient"], candidates[0]["conversation_id"]
28 changes: 28 additions & 0 deletions babel/enrollment.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,21 @@ def change(config, action, **args):
raise BridgeError("Invitation expiry must be future and within the client lifetime limit")
result["participants"][pid]={"owner":owner,"client":client,"session":session,"state":"invited",
"accepted":False,"expires":expires,"activated_at":0}
elif action=="directory":
from .directory import METADATA
metadata=args["metadata"]
if (not isinstance(metadata,dict) or not metadata
or set(metadata)-set(result["participants"])):
raise BridgeError("Directory metadata must name existing canonical participant IDs only")
for pid, labels in metadata.items():
fields(labels,METADATA)
result["participants"][pid].update(labels)
elif action=="label":
entry=result["participants"].get(args["participant"])
if not entry: raise BridgeError("Participant is not configured")
for key in ("display_name", "platform", "role", "aliases"):
if args.get(key) is not None:
entry[key]=args[key]
elif action=="expiry":
entry=result["participants"].get(args["participant"])
now=int(time.time()); expires=args["expires"]
Expand Down Expand Up @@ -127,6 +142,11 @@ def edit(filename, action, **args):
original=path.read_bytes()
config=json.loads(original); validate(config)
if action=="validate": return
if action=="directory":
metadata_path=Path(args.pop("metadata_file"))
if metadata_path.is_symlink() or not metadata_path.is_file() or metadata_path.stat().st_size>16384:
raise BridgeError("Directory metadata must be a regular file of at most 16 KiB")
args["metadata"]=json.loads(metadata_path.read_bytes())
result=change(config,action,**args)
raw=(json.dumps(result,indent=2)+"\n").encode()
if len(raw)>65536: raise BridgeError("Policy capacity reached")
Expand Down Expand Up @@ -159,6 +179,14 @@ def add_parser(modes):
for name in ("owner","session"): invite.add_argument("--"+name,required=True)
invite.add_argument("--client",required=True,choices=CLIENTS)
invite.add_argument("--expires",type=int,help="Optional finite expiry; omitted means persistent until closed or revoked")
directory=actions.add_parser("directory",help="Apply reviewed display metadata to existing IDs only")
directory.add_argument("--metadata-file",required=True)
label=actions.add_parser("label",help="Presentation metadata only; never changes identity or grants")
label.add_argument("--participant",required=True)
label.add_argument("--display-name")
label.add_argument("--platform")
label.add_argument("--role")
label.add_argument("--aliases",nargs="*")
expiry=actions.add_parser("expiry"); expiry.add_argument("--participant",required=True); expiry.add_argument("--expires",required=True,type=int)
actions.add_parser("persistent").add_argument("--participant",required=True)
activate=actions.add_parser("activate"); activate.add_argument("--participant",required=True)
Expand Down
8 changes: 4 additions & 4 deletions babel/mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def schema(properties, required=()):
"before": {"type": "integer", "minimum": 1}}),
"annotations": {"readOnlyHint": True, "destructiveHint": False,
"idempotentHint": True, "openWorldHint": False}},
{"name": "list_contacts", "description": "Discover currently permitted outgoing recipients and their conversation IDs. Auto-session return contacts require reply_to an approved incoming message in that conversation. Call again when instances join or leave; this never exposes unrelated owners or sessions.",
{"name": "list_contacts", "description": "Discover currently permitted outgoing recipients with display name, platform, role, owner, aliases and send_to route handle. Names are presentation only. Auto-session return contacts require reply_to an approved incoming message in that conversation. Call again when instances join or leave; this never exposes unrelated owners or sessions.",
"inputSchema": schema({}),
"annotations": {"readOnlyHint": True, "destructiveHint": False,
"idempotentHint": True, "openWorldHint": False}},
Expand Down Expand Up @@ -91,10 +91,10 @@ def error(code, message):
tools=copy.deepcopy(TOOLS)
policy=getattr(store,"policy",None)
if policy and policy.multi_owner:
tools[0]["description"] += " Use list_contacts send_to for an unambiguous short route; canonical recipient/conversation_id remain supported."
stage=tools[0]["inputSchema"]
stage["properties"]["recipient"]={"type":"string","description":"A current permitted recipient from list_contacts."}
stage["properties"]["conversation_id"]={"type":"string","description":"The matching current conversation ID from list_contacts."}
stage["required"].append("conversation_id")
stage["properties"]["recipient"]={"type":"string","description":"A send_to handle from list_contacts (recommended), canonical participant ID, or exact name/alias. Bare names stay within your owner; owner/name selects an explicitly permitted cross-owner contact. Collisions require a send_to handle."}
stage["properties"]["conversation_id"]={"type":"string","description":"Matching conversation ID; optional with send_to or a unique name. Replies stay in the parent conversation."}
synthetic = getattr(store, "synthetic", None)
if synthetic is not None and synthetic.available(store):
from .synthetic import TOOL
Expand Down
7 changes: 5 additions & 2 deletions babel/participants.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import re
import time
from .core import AGENTS, BridgeError, fields, MAX_HOPS, MAX_CONFIGURED_HOPS
from .directory import METADATA, validate_metadata

COMPONENT = re.compile(r"[a-z][a-z0-9_-]{0,31}\Z")
CLIENTS = ("dots","grokbot","codex","cursor","claude","opencode","muse")
Expand Down Expand Up @@ -36,8 +37,9 @@ def configure(policy, config, oauth_roles):
seen=set(); policy.credential_digests={}
for pid, entry in participants.items():
if not PARTICIPANT.fullmatch(pid): raise BridgeError("Participant ID must be owner.client.instance")
fields(entry,("owner","client","session","state","accepted","expires","activated_at","sha256"),
fields(entry,("owner","client","session","state","accepted","expires","activated_at","sha256",*METADATA),
("owner","client","session","state","accepted","expires","activated_at"))
validate_metadata(entry)
if (entry["owner"] not in owners or entry["client"] not in CLIENTS
or pid != entry["owner"]+"."+entry["client"]+"."+entry["session"]):
raise BridgeError("Participant identity must match its explicit owner, client and session")
Expand Down Expand Up @@ -88,5 +90,6 @@ def configure(policy, config, oauth_roles):
policy.conversations=conversations; policy.routes=frozenset(routes); policy.agents={}
for pid, entry in participants.items():
permissions=sorted(r for r in routes if pid in r[1:])
policy.agents[pid]=(digest([entry,owners[entry["owner"]],permissions]),
authority={k:v for k,v in entry.items() if k not in METADATA}
policy.agents[pid]=(digest([authority,owners[entry["owner"]],permissions]),
frozenset(r[2] for r in routes if r[1]==pid))
Loading
Loading