diff --git a/README.md b/README.md index 94d1e7e..45c58d3 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/babel/auth.py b/babel/auth.py index 836a21b..b81cad8 100644 --- a/babel/auth.py +++ b/babel/auth.py @@ -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") @@ -178,6 +179,12 @@ 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)): @@ -185,17 +192,15 @@ def stage(self, source, recipient, **kwargs): 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() @@ -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() @@ -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() @@ -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() @@ -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 diff --git a/babel/directory.py b/babel/directory.py new file mode 100644 index 0000000..88db90a --- /dev/null +++ b/babel/directory.py @@ -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"] diff --git a/babel/enrollment.py b/babel/enrollment.py index 58cef5f..acbb95f 100644 --- a/babel/enrollment.py +++ b/babel/enrollment.py @@ -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"] @@ -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") @@ -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) diff --git a/babel/mcp.py b/babel/mcp.py index 0481a65..4d99ddf 100644 --- a/babel/mcp.py +++ b/babel/mcp.py @@ -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}}, @@ -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 diff --git a/babel/participants.py b/babel/participants.py index abc260d..ac3f0a5 100644 --- a/babel/participants.py +++ b/babel/participants.py @@ -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") @@ -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") @@ -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)) diff --git a/babel/server.py b/babel/server.py index 37e8542..aec42e5 100644 --- a/babel/server.py +++ b/babel/server.py @@ -151,7 +151,12 @@ def do_GET(self): except BridgeError: continue participants.append(pid) conversations=[cid for cid,c in policy.conversations.items() if c["state"]=="active"] - self.respond(200, {"csrf": self.server.csrf, "agents": participants, "conversations":conversations}) + from .directory import operator_labels + # Retired identities can still appear in approval/history views. + known=policy.participants if policy and policy.multi_owner else participants + directory=operator_labels(policy,known) + self.respond(200, {"csrf": self.server.csrf, "agents": participants, + "conversations":conversations, "directory":directory}) elif path == "/api/health": self.respond(200, {"status": "ok", "network": "loopback-only", "live_adapters": False, "events": False, "mcp": "tools-only", "version": "0.4.0"}) diff --git a/deploy/directory.bits255.json b/deploy/directory.bits255.json new file mode 100644 index 0000000..1853b31 --- /dev/null +++ b/deploy/directory.bits255.json @@ -0,0 +1,21 @@ +{ + "bits255.dots.ada_20261002": { + "display_name": "Ember", + "platform": "ChatGPT Work", + "aliases": ["ember"] + }, + "bits255.grokbot.grok_20261002": { + "display_name": "Ada", + "platform": "Grok", + "aliases": ["ada"] + }, + "bits255.muse.ai_20261002": { + "display_name": "Nova", + "aliases": ["nova"] + }, + "bits255.claude.duet_20261025": { + "display_name": "Claude", + "platform": "Anthropic", + "aliases": ["claude"] + } +} diff --git a/docs/directory.md b/docs/directory.md new file mode 100644 index 0000000..ee17bd3 --- /dev/null +++ b/docs/directory.md @@ -0,0 +1,132 @@ +# Readable contacts and sending + +Schema 3 participants may have operator-managed `display_name`, `platform`, `role` +and `aliases` metadata. The immutable `owner.client.instance` ID, explicit client, +credentials, owner, activation, expiry and grants remain authoritative. Metadata +never enrolls a participant or changes permissions, approval, hop or rate limits. +Unconfigured names fall back to the canonical ID and return `name_configured:false`; +Babel does not derive persona names from historical session slugs. `platform` +defaults to the explicit client; `role` is a descriptive label, never an access role. + +`list_contacts` retains `recipient` and `conversation_id` for existing callers and +adds `display_name`, `platform`, `client`, `role`, `owner`, `aliases`, +`name_configured` and `send_to`. Only currently permitted outgoing routes appear. +The short `send_to` handle binds **sender + recipient + conversation**. Copying it +into `stage_message.recipient` selects that exact route without carrying dated +participant IDs or a conversation ID into the send request: + +```json +{"recipient":"contact:HANDLE_FROM_LIST_CONTACTS","text":"Selected text","message_id":"stable-message-001"} +``` + +The handle is a selector, not a credential or capability. Each call rechecks current +authentication, scope, participant lifecycle and route grants. A handle from another +sender, an inactive contact, or a closed route cannot authorize a send. Handles do +not change when a participant is renamed. A hash collision returns an ambiguity +error; it cannot silently pick a destination. + +An exact display name or alias also works, case-insensitively, when it selects one +permitted route. Bare names resolve inside the authenticated sender's owner. +An explicitly granted cross-owner contact requires `owner/name` or its `send_to` +handle. Names matching multiple contacts or conversations return an ambiguity error +with readable candidates and handles. Specify a handle or, where sufficient, a +conversation ID. There is no fuzzy matching, slug guessing, or default-owner +fallback. Full canonical IDs keep their exact meaning. Legacy schema 1/2 IDs +`ada`, `grokbot`, and `muse` retain their original behavior; in schema 3 these +strings can be directory names because all canonical IDs use the full participant +format. + +Replies still require `reply_to`. Babel first authorizes that exact parent and +pins name resolution to its canonical sender and conversation. A reused name cannot +redirect an old reply. Explicitly wrong recipient/conversation pairs still fail. +Prefer the route handle for durable retries, or the existing canonical pair. +A stable message ID retry deduplicates against the resolved canonical route and +exact text/parent. If a name was removed or reassigned, a retry fails or conflicts; +it never overwrites the earlier message. + +Stage, receive, claim, status, history and acknowledgment responses add a readable +`header` plus `source_contact` and `recipient_contact`. These are **current directory +annotations**, not historical snapshots. The original source/recipient, owner, +conversation, message/root/parent IDs and receipt fields remain intact. Labels are +not stored in messages, used in wake payloads, or included in message fingerprints. +Changing presentation metadata does not invalidate credentials, claims, receipts, +or subscriptions; changing authorization retains its existing effect. + +## Operator display and collisions + +The private compose dropdowns and approval/history headers append a compact identity +tag only when readable labels collide. Tags are derived from canonical identity, +remain stable across display-name edits, and lengthen if their prefixes collide. +A full hash collision falls back to canonical IDs instead of hiding the distinction. +Retired identities participate in this comparison, so an old draft and a new worker +cannot become visually indistinguishable. These tags are presentation only; they +are not `send_to` route handles or new identities. + +Expandable canonical-route details show the selected sender, recipient, and +conversation before composition and on every message/approval card. Dropdown +options also expose canonical IDs in their titles. Refreshing directory labels +preserves the selected canonical values. If a selection becomes inactive, it stays +visibly unavailable and composition stops until a current contact is chosen. + +## Operator workflow + +No public tool can edit the directory. Review metadata against actual canonical +IDs, then use the existing host-only policy editor on the intended private policy: + +```sh +python3 -m babel policy --file /path/to/private/participants.json label \ + --participant owner.codex.existing_session \ + --display-name Juniper --platform Codex --role 'Build worker' --aliases build +``` + +Names, platforms and roles are 1–64 printable characters without control characters, +`/`, or surrounding whitespace. Names cannot masquerade as full canonical IDs or +contact handles. Aliases are up to eight distinct lowercase names, each 1–32 ASCII +letters/digits/underscores/hyphens, starting with a letter. Duplicate names across +participants are permitted and deliberately produce explicit ambiguity errors. +Use `--aliases` with no values to clear aliases. Omitted fields stay unchanged. +All existing file validation, locking, atomic replacement and mode preservation +apply. Metadata is excluded from authorization fingerprints; all existing +authorization fields remain included. + +[Reviewed bits255 naming metadata](../deploy/directory.bits255.json) records the +user-confirmed names below. It contains no credentials or grants and is **not +loaded automatically**. A read-only `list_contacts` check confirmed current +outgoing entries for Ada, Nova and Claude; the Ember source mapping is user-confirmed. +No live policy or deployment was changed. Recheck current IDs and lifecycle before application: + +| Canonical participant | Confirmed display name | Platform annotation | +| --- | --- | --- | +| `bits255.dots.ada_20261002` | Ember | ChatGPT Work | +| `bits255.grokbot.grok_20261002` | Ada | Grok | +| `bits255.muse.ai_20261002` | Nova | existing explicit client (`muse`) | +| `bits255.claude.duet_20261025` | Claude | Anthropic | + +After reviewing the actual policy, the complete metadata file can be applied with: + +```sh +python3 -m babel policy --file /path/to/private/participants.json directory \ + --metadata-file deploy/directory.bits255.json +``` + +The batch edit rejects the whole change if any canonical ID is missing, any +metadata key attempts to change authority, or validation fails. It never creates +participants. Temporary workers retain their existing labels until an explicit +name is verified; no historical worker is assigned “Relay.” Existing messages, +roots and routes are never rewritten. + +## Safe executable rollback + +There is no database migration for this feature. Older executables reject the new +participant metadata keys. Before reverting to such an executable, remove **only** +`display_name`, `platform`, `role` and `aliases` from each participant in the +**current** private policy, or prepare a reviewed current policy compatible with +the older executable. Preserve every owner, canonical ID, credential binding, +lifecycle value, grant, approval setting and limit from the current policy. + +Do not restore a historical policy wholesale: it could undo later revocations, +grants, approval changes or other authority edits. Coordinate the metadata-only +policy edit and executable rollback through the existing operator rollout process; +validate the prepared policy with the target executable before switching. Keep the +same database and histories. No roots, routes, credentials or approvals need to be +rewritten or reset for a presentation rollback. diff --git a/integrations/opencode/babel-wake.mjs b/integrations/opencode/babel-wake.mjs index 80b4c19..cc3b601 100644 --- a/integrations/opencode/babel-wake.mjs +++ b/integrations/opencode/babel-wake.mjs @@ -110,13 +110,13 @@ export default async function BabelWake({ client, directory }, options = {}) { babel: { description: 'Use Babel through this exact session mailbox. No setup or filesystem access is needed. ' + 'Verify list_contacts first; claim and acknowledge wake messages with their exact reserved claim. ' + - 'stage_message arguments are recipient, conversation_id, text, message_id, optional reply_to; use text, never message. ' + + 'stage_message arguments are recipient, text, message_id, optional conversation_id and reply_to; prefer list_contacts send_to as recipient; use text, never message. ' + 'claim_message and acknowledge_message arguments are message_id and claim_id. ' + 'stage_report is the local compact reporting tool.', args: { operation: { type: 'string', enum: TOOLS }, arguments: { type: 'object', additionalProperties: true, description: - 'Operation arguments. stage_message requires recipient, conversation_id, text, message_id (optional reply_to). ' + + 'Operation arguments. stage_message requires recipient, text, message_id (optional conversation_id and reply_to). Use list_contacts send_to as recipient to bind the conversation. ' + 'claim_message and acknowledge_message require message_id and claim_id. list_contacts takes {}.', properties: { text: { type: 'string', description: 'Exact selected message body for stage_message; the key message is unsupported.' }, recipient: { type: 'string' }, conversation_id: { type: 'string' }, message_id: { type: 'string' }, @@ -129,7 +129,7 @@ export default async function BabelWake({ client, directory }, options = {}) { throw new Error('Invalid Babel operation/arguments; session and credential routing are not inputs.'); } if (input.operation === 'stage_message' && (typeof input.arguments.text !== 'string' || 'message' in input.arguments)) { - throw new Error('stage_message requires arguments.text, plus recipient, conversation_id and message_id; arguments.message is unsupported.'); + throw new Error('stage_message requires arguments.text, plus recipient and message_id; arguments.message is unsupported.'); } const sid = context.sessionID; if (disposed || context.directory !== directory || !sessions.has(sid)) { @@ -192,9 +192,9 @@ export default async function BabelWake({ client, directory }, options = {}) { 'Routine progress/tool/status activity stays local. Questions use question_state pending/resolved plus revision; ' + 'experiment transitions use from_state/to_state. Retry stable logical IDs. Read selected private details with read_report, not account files.', 'For a user-requested introduction, call babel with valid JSON such as ' + - '{"operation":"stage_message","arguments":{"recipient":"bits255.dots.ada_20261002","conversation_id":"ID_FROM_LIST_CONTACTS","text":"Your selected message","message_id":"stable-logical-id"}}. ' + - 'Replace the example conversation and message IDs with the actual contact and stable task IDs. Add reply_to only for a reply. ' + - 'The exact body key is text, never message. Use recipient/conversation_id from list_contacts and stable message_id. ' + + '{"operation":"stage_message","arguments":{"recipient":"SEND_TO_FROM_LIST_CONTACTS","text":"Your selected message","message_id":"stable-logical-id"}}. ' + + 'Replace the example recipient with the listed send_to and use a stable message ID. Add reply_to only for a reply. ' + + 'The exact body key is text, never message. Use send_to from list_contacts as recipient (or canonical recipient/conversation_id) and stable message_id. ' + 'For claim_message and acknowledge_message, arguments are {message_id,claim_id}, using the exact reserved claim. ' + 'Queued means approved for delivery, draft means awaiting owner approval. Never infer wake or completion from queue acceptance. ' + 'Keep credentials/private account content out of messages and reports.', diff --git a/tests/test_directory.py b/tests/test_directory.py new file mode 100644 index 0000000..686b25a --- /dev/null +++ b/tests/test_directory.py @@ -0,0 +1,327 @@ +"""Synthetic directory labels never replace authenticated durable identities.""" +import copy +import json +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch +from babel.auth import Policy, ScopedStore +from babel.core import BridgeError, Store +from babel.directory import handle +from babel.enrollment import change, edit +from babel.mcp import dispatch +from babel.account_wake import fingerprint +from tests.test_participants import fixture, DOT, CODEX, SECOND, GUEST, GROK, TOKENS, wake +from tests.test_cloud import FakeTransport, KEY +from babel.events import EventService, EVENT_NAME + +CID = 'directory-chat-01' + + +class DirectoryTests(unittest.TestCase): + def setUp(self): + self.cfg = fixture() + self.cfg['participants'][DOT].update(display_name='Coordinator', role='Coordinator', aliases=['coord']) + self.cfg['participants'][CODEX].update(display_name='Juniper', role='Build worker', aliases=['build']) + self.cfg['participants'][GUEST].update(display_name='Juniper', role='Guest worker', aliases=['build']) + self.cfg['conversations'][CID] = {'state':'active', 'participants':[DOT,CODEX,SECOND], + 'routes':[{'sender':DOT,'recipient':CODEX}, {'sender':CODEX,'recipient':DOT}, + {'sender':DOT,'recipient':SECOND}, {'sender':SECOND,'recipient':DOT}]} + self.store = Store(':memory:') + self.reload() + self.store.policy_provider = lambda: self.policy + + def tearDown(self): + self.store.close() + + def reload(self): + self.policy = Policy(copy.deepcopy(self.cfg)) + self.store.sync_policy(self.policy) + + def scope(self, role=DOT): + return ScopedStore(self.store, role, self.policy.agents[role][1], self.policy) + + def send(self, recipient='build', role=DOT, **kwargs): + return self.scope(role).stage(role, recipient, text='Selected text', + message_id=kwargs.pop('message_id','directory-message-001'), **kwargs) + + def test_labels_platform_role_and_unconfigured_fallback(self): + contacts = self.scope().contacts(DOT) + c = next(c for c in contacts if c['recipient'] == CODEX) + self.assertEqual((c['display_name'],c['platform'],c['role'],c['owner']), + ('Juniper','codex','Build worker','owner_a')) + self.assertEqual(c['aliases'], ['build']) + self.assertEqual(c['send_to'], handle(DOT,CODEX,CID)) + unknown = next(c for c in contacts if c['recipient'] == SECOND) + self.assertFalse(unknown['name_configured']) + self.assertEqual(unknown['display_name'], SECOND) + self.assertNotIn(GROK, str(contacts)) + + def test_unique_names_aliases_and_handles_resolve_before_persistence(self): + for i, selector in enumerate(('JUNIPER', 'build', 'owner_a/build', handle(DOT,CODEX,CID))): + row = self.send(selector, message_id='directory-send-'+str(i))['message'] + self.assertEqual((row['source'],row['recipient'],row['conversation_id']), (DOT,CODEX,CID)) + self.assertEqual(row['status'],'draft') + self.assertIn('Juniper · codex · Build worker · owner_a',row['header']) + self.assertEqual(row['recipient_contact']['id'], CODEX) + raw = self.store.history()[0] + self.assertNotIn('header', raw) + self.assertNotIn('recipient_contact', raw) + + def test_canonical_ids_keep_legacy_contract_and_dedup(self): + with self.assertRaises(BridgeError): self.send(CODEX) + first = self.send(CODEX, conversation_id=CID) + self.assertTrue(self.send()['duplicate']) + self.assertFalse(first['duplicate']) + self.assertEqual(len(self.store.history()),1) + self.assertEqual(self.send(handle(DOT,CODEX,CID))['message']['id'], first['message']['id']) + + def test_cross_owner_names_require_explicit_namespace_or_handle(self): + self.assertEqual(self.send('Juniper')['message']['recipient'], CODEX) + other = self.send('owner_b/Juniper',message_id='cross-owner-message')['message'] + self.assertEqual((other['recipient'],other['conversation_id']), (GUEST,'chat_shared_01')) + # Granted foreign names never become a fallback for a bare local name. + self.cfg['participants'][CODEX]['aliases']=[] + self.cfg['participants'][CODEX]['display_name']='Local worker' + self.reload() + with self.assertRaises(BridgeError): self.send('Juniper', message_id='foreign-fallback-01') + with self.assertRaises(BridgeError): self.send('owner_b/unknown') + foreign_handle=handle(DOT,GUEST,'chat_shared_01') + with self.assertRaises(BridgeError): self.send(foreign_handle,role=SECOND) + + def test_duplicate_names_aliases_and_conversations_require_explicit_choice(self): + self.cfg['participants'][SECOND].update(display_name='JUNIPER', aliases=['build']) + self.reload() + for selector in ('Juniper','build','owner_a/build'): + with self.assertRaises(BridgeError) as exc: self.send(selector) + self.assertEqual(exc.exception.status,409) + self.assertIn('Ambiguous recipient',str(exc.exception)) + self.assertIn(handle(DOT,SECOND,CID),str(exc.exception)) + self.assertNotIn(GROK,str(exc.exception)) + self.assertEqual(self.send(handle(DOT,CODEX,CID))['message']['recipient'], CODEX) + self.cfg['conversations']['directory-chat-02']=copy.deepcopy(self.cfg['conversations'][CID]) + self.reload() + with self.assertRaises(BridgeError): self.send('build') + with self.assertRaises(BridgeError): self.send(handle(DOT,CODEX,CID),conversation_id='directory-chat-02') + self.assertEqual(self.send(handle(DOT,CODEX,CID))['message']['conversation_id'],CID) + + def test_handle_collision_fails_closed(self): + with patch('babel.directory.handle',return_value='contact:collision'): + with self.assertRaisesRegex(BridgeError,'Ambiguous'): self.send('contact:collision') + + def test_rename_preserves_handles_fingerprints_claims_and_receipts(self): + row=self.send()['message']; self.store.approve(row['id']) + recipient=self.scope(CODEX) + claimed=recipient.claim_message(row['id'],CODEX,'directory-claim-001') + self.assertTrue(claimed['claimed']) + row=claimed["message"] + before=self.policy.agents[CODEX][0] + self.cfg['participants'][CODEX].update(display_name='Cedar',role='Reviewer',aliases=['review']) + self.reload() + self.assertEqual(self.policy.agents[CODEX][0],before) + current=self.scope().message_status(row['id'],DOT) + self.assertEqual(fingerprint(row),fingerprint(current)) + self.assertIn('Cedar · codex · Reviewer',current['header']) + self.assertEqual(self.send(handle(DOT,CODEX,CID))['duplicate'],True) + with self.assertRaises(BridgeError): self.send('build') + ack=self.scope(CODEX).acknowledge(row['id'],CODEX,'directory-claim-001') + self.assertEqual(ack['status'],'acknowledged') + self.assertEqual(ack['recipient_contact']['display_name'],'Cedar') + self.assertFalse(self.scope(CODEX).claim_message(row['id'],CODEX,'directory-claim-002')['claimed']) + + def test_reused_name_cannot_redirect_old_reply_or_message_retry(self): + parent=self.send('coord',role=CODEX,message_id='reply-parent-0001')['message'] + self.store.approve(parent['id']) + self.cfg['participants'][CODEX].update(display_name='Cedar',aliases=['review']) + self.cfg['participants'][SECOND].update(display_name='Juniper',aliases=['build']) + self.reload() + with self.assertRaises(BridgeError): self.send('build',reply_to=parent['id']) + reply=self.send(handle(DOT,CODEX,CID),reply_to=parent['id'])['message'] + self.assertEqual((reply['recipient'],reply['root_id'],reply['hops']),(CODEX,parent['id'],2)) + with self.assertRaises(BridgeError) as exc: self.send('build') + self.assertEqual(exc.exception.status,409) + self.assertEqual(self.store.message_status(reply['id'],DOT)['recipient'],CODEX) + + def test_inactive_and_ungranted_contacts_cannot_be_selected(self): + old=handle(DOT,CODEX,CID) + self.cfg['participants'][CODEX]['state']='closed'; self.reload() + self.assertNotIn(CODEX,str(self.scope().contacts(DOT))) + for selector in ('Juniper','build',old,CODEX): + with self.assertRaises(BridgeError): self.send(selector,conversation_id=CID) + self.cfg['participants'][GROK].update(display_name='Secret worker',aliases=['secret']) + self.reload() + for selector in ('owner_b/secret','owner_b/Secret worker',handle(DOT,GROK,'chat_private_01')): + with self.assertRaises(BridgeError) as exc: self.send(selector) + self.assertNotIn(GROK,str(exc.exception)) + + def test_metadata_does_not_change_authorization_or_wake_subscription(self): + service=EventService(self.store,self.policy,wake(),FakeTransport()) + service.subscribe(GUEST,{'name':EVENT_NAME,'arguments':{'recipient':GUEST}, + 'delivery':{'mode':'webhook','url':'https://guest.example.com/callback','secret':KEY}}) + before=self.policy.agents[GUEST][0] + self.cfg['participants'][GUEST].update(display_name='Cedar',aliases=['cedar'],role='Review') + self.reload() + self.assertEqual(before,self.policy.agents[GUEST][0]) + self.assertEqual(self.store.wake_status()['active_subscriptions'],1) + self.assertEqual(self.policy.authenticate('Bearer '+TOKENS[GUEST]),GUEST) + self.cfg['conversations']['chat_shared_01']['routes']=[]; self.reload() + self.assertEqual(self.store.wake_status()['active_subscriptions'],0) + with self.assertRaises(BridgeError): self.send('owner_b/Cedar') + + def test_all_tool_message_surfaces_include_readable_headers(self): + row=self.send()['message']; self.store.approve(row['id']) + def call(role,name,**args): + rpc={'jsonrpc':'2.0','id':1,'method':'tools/call','params':{'name':name,'arguments':args}} + result=dispatch(self.scope(role),role,rpc)['result'] + self.assertFalse(result['isError'],result) + return json.loads(result['content'][0]['text']) + for name in ('receive_messages','bridge_history'): + self.assertIn('Juniper',call(CODEX,name)['messages'][0]['header']) + self.assertIn('Juniper',call(DOT,'message_status',message_id=row['id'])['message']['header']) + self.assertIn('Juniper',call(CODEX,'claim_message',message_id=row['id'],claim_id='tool-claim-0001')['message']['header']) + self.assertIn('Juniper',call(CODEX,'acknowledge_message',message_id=row['id'],claim_id='tool-claim-0001')['message']['header']) + + def test_legacy_scoped_callers_keep_canonical_routes(self): + cfg={'schema_version':1,'agents':{'ada':{'sha256':'1'*64,'recipients':['grokbot']}, + 'grokbot':{'sha256':'2'*64,'recipients':['ada']}}} + policy=Policy(cfg); scope=ScopedStore(self.store,'ada',policy.agents['ada'][1],policy) + contacts=scope.contacts('ada');self.assertEqual(contacts[0]['recipient'],'grokbot') + row=scope.stage('ada','grokbot',text='Legacy',message_id='legacy-directory-001')['message'] + self.assertIsNone(row['conversation_id']); self.assertEqual(row['source'],'ada') + self.assertTrue(scope.stage('ada',contacts[0]['send_to'],text='Legacy',message_id=row['id'])['duplicate']) + + def test_metadata_validation_and_host_only_label_edit(self): + for field,value in (('display_name',CODEX),('display_name','contact:123'), + ('display_name','Bad\nName'),('display_name','\u202eevil'),('display_name','line\u2028break'),('role',' x'), + ('aliases',['contact:bad']),('aliases',['Not normalized']),('aliases',['x','x']), + ('aliases','worker'),('display_name',''),('role',42)): + cfg=copy.deepcopy(self.cfg);cfg['participants'][CODEX][field]=value + with self.subTest(field=field,value=value), self.assertRaises(BridgeError): Policy(cfg) + updated=change(self.cfg,'label',participant=CODEX,display_name='Cedar',role='Reviewer',aliases=['cedar']) + self.assertEqual(Policy(updated).agents,self.policy.agents) + with tempfile.TemporaryDirectory() as folder: + path=Path(folder)/'policy.json';path.write_text(json.dumps(self.cfg));path.chmod(0o600) + edit(path,'label',participant=CODEX,display_name='Cedar') + self.assertEqual(json.loads(path.read_text())['participants'][CODEX]['display_name'],'Cedar') + self.assertEqual(path.stat().st_mode & 0o777,0o600) + + def test_confirmed_mapping_batch_preserves_authority_and_supports_ada(self): + from babel.core import ROOT + metadata=json.loads((ROOT/'deploy/directory.bits255.json').read_text()) + cfg=fixture(); source='bits255.claude.duet_20261025'; target='bits255.grokbot.grok_20261002' + cfg['owners']={'bits255':{'enabled':True}}; cfg['participants']={}; cfg['conversations']={} + for i,pid in enumerate(metadata): + owner,client,session=pid.split('.') + entry=copy.deepcopy(fixture()['participants'][CODEX]) + entry.update(owner=owner,client=client,session=session,sha256=str(i+1)*64) + cfg['participants'][pid]=entry + cfg['conversations'][CID]={'state':'active','participants':[source,target], + 'routes':[{'sender':source,'recipient':target}]} + before=Policy(cfg) + after=change(cfg,'directory',metadata=metadata); policy=Policy(after) + self.assertEqual(before.agents,policy.agents) + scope=ScopedStore(self.store,source,policy.agents[source][1],policy) + row=scope.stage(source,'ada',text='Selected',message_id='confirmed-name-001')['message'] + self.assertEqual(row['recipient'],target) + self.assertIn('Claude · Anthropic',row['header']); self.assertIn('Ada · Grok',row['header']) + with tempfile.TemporaryDirectory() as folder: + path=Path(folder)/'policy.json';path.write_text(json.dumps(cfg));path.chmod(0o600) + edit(path,'directory',metadata_file=str(ROOT/'deploy/directory.bits255.json')) + self.assertEqual(json.loads(path.read_text()),after) + saved=path.read_bytes() + bad=Path(folder)/'bad.json';bad.write_text(json.dumps({source:{'sha256':'9'*64}})) + with self.assertRaises(BridgeError): edit(path,'directory',metadata_file=str(bad)) + self.assertEqual(path.read_bytes(),saved) + with self.assertRaises(BridgeError): change(self.cfg,'directory',metadata=metadata) + with self.assertRaises(BridgeError): change(cfg,'directory',metadata={source:{'owner':'owner_b'}}) + + def test_authenticated_mcp1_and_mcp2_short_route_round_trips(self): + import threading + from urllib.request import Request, ProxyHandler, build_opener + from babel.gateway import Gateway + from babel import mcp2 + server=Gateway(0,self.policy,'https://bridge.example.com',self.store,transport=FakeTransport()) + thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start() + opener=build_opener(ProxyHandler({})) + def call(modern,role,name,**args): + params={'name':name,'arguments':args} + headers={'Host':'bridge.example.com','X-Forwarded-Proto':'https', + 'Authorization':'Bearer '+TOKENS[role], 'Content-Type':'application/json', + 'Accept':'application/json, text/event-stream'} + if modern: + params['_meta']={mcp2.PREFIX+'protocolVersion':mcp2.VERSION, + mcp2.PREFIX+'clientCapabilities':{}} + headers.update({'MCP-Protocol-Version':mcp2.VERSION,'Mcp-Method':'tools/call','Mcp-Name':name}) + body={'jsonrpc':'2.0','id':1,'method':'tools/call','params':params} + req=Request('http://127.0.0.1:'+str(server.port)+('/mcp' if modern else '/mcp/v1'), + data=json.dumps(body).encode(),headers=headers) + with opener.open(req,timeout=3) as response: result=json.load(response)['result'] + self.assertFalse(result.get('isError'),result) + return json.loads(result['content'][0]['text']) + try: + for modern in (False,True): + contacts=call(modern,DOT,'list_contacts')['contacts'] + contact=next(c for c in contacts if c['recipient']==CODEX) + row=call(modern,DOT,'stage_message',recipient=contact['send_to'],text='Selected', + message_id='transport-directory-'+str(modern))['message'] + self.assertEqual(row['recipient'],CODEX);self.assertIn('Juniper',row['header']) + self.store.approve(row['id']) + incoming=call(modern,CODEX,'receive_messages')['messages'] + self.assertEqual([r['id'] for r in incoming],[row['id']]) + claim='transport-claim-'+str(modern) + self.assertTrue(call(modern,CODEX,'claim_message',message_id=row['id'],claim_id=claim)['claimed']) + call(modern,CODEX,'acknowledge_message',message_id=row['id'],claim_id=claim) + answer=call(modern,CODEX,'stage_message',recipient='coord',text='Answer', + message_id='transport-reply-'+str(modern),reply_to=row['id'])['message'] + self.assertEqual((answer['recipient'],answer['conversation_id'],answer['root_id']), (DOT,CID,row['id'])) + finally: + server.shutdown();server.server_close();thread.join() + + def test_operator_collision_labels_are_distinct_and_retired_names_stay_distinct(self): + from babel.directory import operator_labels + self.cfg['participants'][SECOND].update(display_name='Juniper',role='Build worker',aliases=['build']) + self.reload() + labels=operator_labels(self.policy,self.policy.participants) + self.assertNotEqual(labels[CODEX],labels[SECOND]) + self.assertIn('Juniper · codex · Build worker · owner_a [#',labels[CODEX]) + self.assertLess(len(labels[CODEX].split('[#')[1].rstrip(']')),len(CODEX)) + self.assertNotIn(CODEX,labels[CODEX]) + self.cfg['participants'][SECOND]['state']='closed';self.reload() + retired=operator_labels(self.policy,self.policy.participants) + self.assertEqual(retired[CODEX],labels[CODEX]);self.assertEqual(retired[SECOND],labels[SECOND]) + with patch('babel.directory.hashlib.sha256') as sha: + sha.return_value.hexdigest.return_value='a'*64 + fallback=operator_labels(self.policy,self.policy.participants) + self.assertEqual(fallback[CODEX],CODEX);self.assertEqual(fallback[SECOND],SECOND) + + def test_private_operator_session_disambiguates_canonical_compose_and_approval_targets(self): + import threading + from urllib.request import Request, ProxyHandler, build_opener + from babel.server import Server + self.cfg['participants'][SECOND].update(display_name='Juniper',role='Build worker',aliases=['build']) + self.reload() + with tempfile.TemporaryDirectory() as folder: + path=Path(folder)/'policy.json';path.write_text(json.dumps(self.cfg)) + with patch.dict('os.environ',{'BABEL_AUTH_FILE':str(path)}): server=Server(0,self.store) + thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start() + opener=build_opener(ProxyHandler({}));base='http://127.0.0.1:'+str(server.port) + def call(route,body=None,csrf=None): + headers={'Content-Type':'application/json'} + if csrf: headers['X-Babel-CSRF']=csrf + request=Request(base+route,data=None if body is None else json.dumps(body).encode(),headers=headers) + with opener.open(request,timeout=3) as response:return json.load(response) + try: + session=call('/api/session') + self.assertNotEqual(session['directory'][CODEX],session['directory'][SECOND]) + self.assertIn(CODEX,session['agents']);self.assertIn(SECOND,session['agents']) + for index,recipient in enumerate((CODEX,SECOND)): + row=call('/api/stage',{'source':DOT,'recipient':recipient,'text':'Same selected content', + 'conversation_id':CID,'message_id':'operator-collision-'+str(index)},session['csrf'])['message'] + self.assertEqual(row['recipient'],recipient);self.assertEqual(row['status'],'draft') + rows=call('/api/history')['messages'];self.assertEqual({r['recipient'] for r in rows},{CODEX,SECOND}) + self.cfg['participants'][SECOND]['state']='closed';path.write_text(json.dumps(self.cfg)) + session=call('/api/session') + self.assertNotIn(SECOND,session['agents']) + self.assertNotEqual(session['directory'][CODEX],session['directory'][SECOND]) + finally: + server.shutdown();server.server_close();thread.join() diff --git a/tests/test_participants.py b/tests/test_participants.py index 784cdd0..20755b0 100644 --- a/tests/test_participants.py +++ b/tests/test_participants.py @@ -139,7 +139,7 @@ def test_persistent_participants_stay_connected_and_still_revoke(self): with patch("time.time",return_value=time.time()+10*365*86400): self.store.sync_policy(self.policy) self.assertEqual(self.policy.authenticate("Bearer "+TOKENS[DOT]),DOT) - self.assertEqual(self.scoped(DOT).contacts(DOT),[{"recipient":GUEST,"conversation_id":"chat_shared_01"}]) + self.assertEqual([(c["recipient"], c["conversation_id"]) for c in self.scoped(DOT).contacts(DOT)], [(GUEST,"chat_shared_01")]) cfg["participants"][GUEST]["state"]="revoked";self.replace_policy(cfg) with self.assertRaises(BridgeError):self.policy.authenticate("Bearer "+TOKENS[GUEST]) cfg["participants"][GUEST]["state"]="active" @@ -219,8 +219,8 @@ def test_tool_catalog_exposes_only_own_routes_and_no_admin_tools(self): stage=tools[0]["inputSchema"] self.assertNotIn("enum",stage["properties"]["recipient"]) self.assertNotIn("enum",stage["properties"]["conversation_id"]) - self.assertEqual(self.scoped(DOT).contacts(DOT),[{"recipient":GUEST,"conversation_id":"chat_shared_01"}]) - self.assertIn("conversation_id",stage["required"]) + self.assertEqual([(c["recipient"], c["conversation_id"]) for c in self.scoped(DOT).contacts(DOT)], [(GUEST,"chat_shared_01")]) + self.assertNotIn("conversation_id",stage["required"]) self.assertNotIn("policy",str(tools));self.assertNotIn(CODEX,str(tools)) for name in ("approve_message","enroll_participant","run_command"): result=dispatch(self.scoped(GUEST),GUEST,{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":name,"arguments":{}}}) @@ -238,7 +238,7 @@ def test_contact_discovery_updates_without_stale_cached_recipient_enums(self): fresh=Policy.load(path);fresh_scope=ScopedStore(self.store,DOT,fresh.agents[DOT][1],fresh) rpc={"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"list_contacts","arguments":{}}} contacts=json.loads(dispatch(fresh_scope,DOT,rpc)["result"]["content"][0]["text"])["contacts"] - self.assertIn({"recipient":CODEX,"conversation_id":"dynamic_chat_01"},contacts) + self.assertIn((CODEX,"dynamic_chat_01"), [(c["recipient"],c["conversation_id"]) for c in contacts]) self.assertNotIn(SECOND,str(contacts)) cfg["participants"][CODEX]["state"]="closed";path.write_text(json.dumps(cfg)) fresh=Policy.load(path) diff --git a/tests/test_session_replies.py b/tests/test_session_replies.py index 5b6a346..2e67e4c 100644 --- a/tests/test_session_replies.py +++ b/tests/test_session_replies.py @@ -75,7 +75,7 @@ def test_approved_acknowledged_parent_discovery_reply_and_dedup(self): ember = self.scope() self.assertFalse(self.contacts()) parent = self.incoming() - self.assertEqual(self.contacts(), [dict(recipient=WORKER, conversation_id=CID)]) + self.assertEqual([(c["recipient"],c["conversation_id"]) for c in self.contacts()], [(WORKER,CID)]) ember.claim_message(parent['id'], EMBER, 'reply-claim-0001') ember.acknowledge(parent['id'], EMBER, 'reply-claim-0001') row = self.reply(scope=ember)['message'] @@ -104,7 +104,7 @@ def test_unrelated_and_cross_owner_senders_do_not_get_return_grants(self): self.policy.session_generations[GUEST] = 1 self.leases.row = lambda pid: (dict(self.row) if pid == WORKER else dict(self.row, participant=GUEST, conversation='guest_incoming_01') if pid == GUEST else None) - self.assertEqual(self.contacts(), [dict(recipient=WORKER, conversation_id=CID)]) + self.assertEqual([(c["recipient"],c["conversation_id"]) for c in self.contacts()], [(WORKER,CID)]) for role in (OTHER, GUEST): self.assertNotIn(dict(recipient=WORKER, conversation_id=CID), self.contacts(role)) with self.assertRaises(BridgeError): @@ -241,7 +241,7 @@ def call(role, name, **arguments): message_id='http-question-0001', text='Question?')['message'] call(EMBER, 'claim_message', message_id=parent['id'], claim_id='http-claim-0001') call(EMBER, 'acknowledge_message', message_id=parent['id'], claim_id='http-claim-0001') - self.assertEqual(call(EMBER, 'list_contacts')['contacts'], [dict(recipient=WORKER, conversation_id=CID)]) + self.assertEqual([(c["recipient"],c["conversation_id"]) for c in call(EMBER, 'list_contacts')['contacts']], [(WORKER,CID)]) reply = call(EMBER, 'stage_message', recipient=WORKER, conversation_id=CID, reply_to=parent['id'], message_id='http-reply-000001', text='Approved answer.')['message'] self.assertEqual([m['id'] for m in call(WORKER, 'receive_messages')['messages']], [reply['id']]) diff --git a/tests/test_web_directory.py b/tests/test_web_directory.py new file mode 100644 index 0000000..92be4b5 --- /dev/null +++ b/tests/test_web_directory.py @@ -0,0 +1,14 @@ +"""Exercise operator UI behavior through the existing Python CI entrypoint.""" +from pathlib import Path +import shutil +import subprocess +import unittest + + +class OperatorDirectoryUITests(unittest.TestCase): + @unittest.skipUnless(shutil.which('node'), 'Node is required for operator UI contract tests') + def test_duplicate_names_and_canonical_selections(self): + result = subprocess.run([shutil.which('node'), '--test', + str(Path(__file__).with_name('web_directory.test.mjs'))], + capture_output=True, text=True, timeout=20) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) diff --git a/tests/web_directory.test.mjs b/tests/web_directory.test.mjs new file mode 100644 index 0000000..7e3d0b6 --- /dev/null +++ b/tests/web_directory.test.mjs @@ -0,0 +1,125 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFile} from 'node:fs/promises'; +import vm from 'node:vm'; + +const source = await readFile(new URL('../web/app.js', import.meta.url), 'utf8'); +const coordinator = 'owner_a.dots.coordinator'; +const first = 'owner_a.codex.run_01'; +const second = 'owner_a.codex.run_02'; +const cid = 'directory-ui-chat'; + +class Element { + constructor(tag = 'div') { this.tag = tag; this.children = []; this.handlers = {}; this.hidden = false; this._value = null; this.selectedIndex = 0; } + appendChild(child) { this.children.push(child); return child; } + replaceChildren() { this.children = []; this._value = null; this.selectedIndex = 0; } + addEventListener(name, action) { this.handlers[name] = action; } + get value() { return this._value ?? this.children[this.selectedIndex]?.value ?? ''; } + set value(value) { this._value = value; } + querySelector(tag) { return this.children.find(child => child.tag === tag); } + scrollIntoView() {} + focus() {} +} +const descendants = node => [node, ...node.children.flatMap(descendants)]; + +async function fixture() { + const ids = ['source','recipient','inbox_agent','conversation_id','compose','messages','list_title','older','notice', + 'refresh','receive','copy','copy_text','close_handoff','handoff','text','reply_to','conversation_label', + 'source_identity','recipient_identity','conversation_identity','inbox_identity']; + const elements = Object.fromEntries(ids.map(id => [id, new Element(['source','recipient','inbox_agent','conversation_id'].includes(id) ? 'select' : 'div')])); + elements.compose.appendChild(new Element('button')); + const state = { + session: {csrf: 'synthetic-csrf', agents: [coordinator,first,second], conversations: [cid], directory: { + [coordinator]: 'Coordinator · dots · owner_a', + [first]: 'Juniper · codex · Build worker · owner_a [#11111111]', + [second]: 'Juniper · codex · Build worker · owner_a [#22222222]'}}, + messages: [first,second].map((recipient,index) => ({id:'ui-draft-'+index, source:coordinator,recipient, + status:'draft',text:'Same selected text',hops:1,provenance:'manual',conversation_id:cid})), + calls: [], + }; + const context = vm.createContext({document: {getElementById: id => elements[id], createElement: tag => new Element(tag)}, + TextEncoder, crypto: {randomUUID: () => 'synthetic-ui-id-'+state.calls.length}, window: {confirm: () => true}, + fetch: async (path, options) => { + const body = options?.body ? JSON.parse(options.body) : undefined; + state.calls.push({path,body}); + let result; + if (path === '/api/session') result = structuredClone(state.session); + else if (path.startsWith('/api/history')) result = {messages: structuredClone(state.messages)}; + else if (path === '/api/stage') result = {message: body, duplicate: false}; + else if (path === '/api/approve') result = {message: state.messages.find(row => row.id === body.message_id)}; + else throw new Error('Unexpected route '+path); + return {ok:true, json:async () => result}; + }}); + vm.runInContext(source, context); + await new Promise(setImmediate); + return {state,e:elements,context}; +} + +test('duplicate worker labels stay distinct in compose, approval cards, and inspectable identity details', async () => { + const {state,e} = await fixture(); + for (const field of ['source','recipient','inbox_agent']) { + const one = e[field].children.find(option => option.value === first); + const two = e[field].children.find(option => option.value === second); + assert.notEqual(one.textContent,two.textContent); + assert.equal(one.title,'Canonical identity: '+first); + assert.equal(two.title,'Canonical identity: '+second); + } + e.recipient.value = second; e.recipient.handlers.change(); + assert.equal(e.recipient_identity.textContent,'To: '+second); + assert.equal(e.recipient.title,'Canonical identity: '+second); + const cards = e.messages.children; + const headings = cards.map(card => card.children.find(node => node.tag === 'strong')); + assert.notEqual(headings[0].textContent,headings[1].textContent); + for (let index=0;index<2;index++) { + const details = cards[index].children.find(node => node.tag === 'details'); + assert.ok(descendants(details).some(node => node.textContent === 'To: '+[first,second][index])); + assert.ok(descendants(details).some(node => node.textContent === 'Conversation: '+cid)); + } + const approve = descendants(cards[1]).find(node => node.tag === 'button' && node.textContent === 'Approve into local queue'); + await approve.handlers.click(); + assert.equal(state.calls.find(call => call.path === '/api/approve').body.message_id,'ui-draft-1'); +}); + +test('refresh and rename retain the explicitly selected canonical sender and recipient when staging', async () => { + const {state,e} = await fixture(); + e.source.value = coordinator; e.recipient.value = second; e.text.value = 'Selected text'; + state.session.directory[second] = 'Cypress · codex · Build worker · owner_a'; + await e.compose.handlers.submit({preventDefault(){},target:e.compose}); + const sent = state.calls.find(call => call.path === '/api/stage').body; + assert.equal(sent.source,coordinator); assert.equal(sent.recipient,second); + assert.equal(sent.conversation_id,cid); assert.equal(sent.text,'Selected text'); + assert.equal(e.recipient_identity.textContent,'To: '+second); + assert.equal(e.recipient.children.find(option => option.value === second).textContent,state.session.directory[second]); +}); + +test('inactive selected worker remains visibly unavailable and is never replaced with its namesake', async () => { + const {state,e,context} = await fixture(); + e.recipient.value = second; + state.session.agents = [coordinator,first]; + await vm.runInContext('reload()',context); + assert.equal(e.recipient.value,second); + const retired = e.recipient.children.find(option => option.value === second); + assert.equal(retired.disabled,true); assert.match(retired.textContent,/^Unavailable:/); + assert.equal(e.recipient_identity.textContent,'To: '+second); + e.text.value = 'Selected text'; + await e.compose.handlers.submit({preventDefault(){},target:e.compose}); + assert.equal(state.calls.filter(call => call.path === '/api/stage').length,0); + assert.match(e.notice.textContent,/Selected identity is unavailable/); + const headings = e.messages.children.map(card => card.children.find(node => node.tag === 'strong').textContent); + assert.notEqual(headings[0],headings[1]); +}); + +test('reply to an inactive worker keeps the exact canonical route inspectable and cannot substitute another worker', async () => { + const {state,e,context} = await fixture(); + state.session.agents = [coordinator,first]; state.messages[1].status = 'queued'; + await vm.runInContext('reload()',context); + const reply = descendants(e.messages.children[1]).find(node => node.tag === 'button' && node.textContent === 'Draft an explicit reply'); + await reply.handlers.click(); + assert.equal(e.source.value,second); assert.equal(e.recipient.value,coordinator); + assert.equal(e.source_identity.textContent,'From: '+second); + assert.equal(e.source.children.find(option => option.value === second).disabled,true); + assert.equal(e.reply_to.value,'ui-draft-1'); + e.text.value = 'Reply selected text'; + await e.compose.handlers.submit({preventDefault(){},target:e.compose}); + assert.equal(state.calls.filter(call => call.path === '/api/stage').length,0); +}); diff --git a/web/app.js b/web/app.js index 69e685e..9a7b60d 100644 --- a/web/app.js +++ b/web/app.js @@ -3,7 +3,10 @@ let pendingSubmission = null; let displayed = []; let inboxMode = false; const $ = id => document.getElementById(id); -const label = name => ({ada: "Ada / ChatGPT", grokbot: "Grokbot", muse: "Muse (future)"}[name] || name); +let directory = {}; +let activeAgents = new Set(); +let sessionLoaded = false; +const label = name => directory[name] || ({ada: "Ada / ChatGPT", grokbot: "Grokbot", muse: "Muse (future)"}[name] || name); function tell(message, bad = false) { $("notice").textContent = message; $("notice").className = bad ? "error" : ""; } async function api(path, body) { const response = await fetch(path, body === undefined ? {} : { @@ -27,7 +30,57 @@ function button(parent, text, action, kind = "secondary") { finally { node.disabled = false; } }); } +function inspectSelectedIdentities() { + for (const [field, target, caption] of [["source", "source_identity", "From"], ["recipient", "recipient_identity", "To"], + ["inbox_agent", "inbox_identity", "Inbox"]]) { + const identity = $(field).value; + $(target).textContent = caption + ": " + identity; + $(field).title = "Canonical identity: " + identity; + } + $("conversation_identity").textContent = "Conversation: " + ($("conversation_id").value || "legacy route"); +} +function selectCanonical(field, value) { + if (!Array.from($(field).children).some(option => option.value === value)) { + const unavailable = add($(field), "option", "Unavailable: " + (field === "conversation_id" ? value : label(value))); + unavailable.value = value; unavailable.disabled = true; + } + $(field).value = value; +} +async function refreshDirectory() { + const session = await api("/api/session"); + csrf = session.csrf; directory = session.directory || {}; activeAgents = new Set(session.agents); + for (const field of ["source", "recipient", "inbox_agent"]) { + const previous = sessionLoaded ? $(field).value : null; + $(field).replaceChildren(); + for (const name of session.agents) { + const option = add($(field), "option", label(name)); option.value = name; + option.title = "Canonical identity: " + name; + } + if (previous !== null) { + if (!activeAgents.has(previous)) { + const unavailable = add($(field), "option", "Unavailable: " + label(previous)); + unavailable.value = previous; unavailable.disabled = true; + } + $(field).value = previous; + } else if (field === "recipient" && session.agents.length > 1) $(field).selectedIndex = 1; + } + const previousConversation = sessionLoaded ? $("conversation_id").value : null; + $("conversation_id").replaceChildren(); + const conversations = session.conversations || []; + $("conversation_label").hidden = conversations.length === 0; + for (const cid of conversations) { const option = add($("conversation_id"), "option", cid); option.value = cid; } + if (previousConversation) { + if (!conversations.includes(previousConversation)) { + const unavailable = add($("conversation_id"), "option", "Unavailable: " + previousConversation); + unavailable.value = previousConversation; unavailable.disabled = true; + $("conversation_label").hidden = false; + } + $("conversation_id").value = previousConversation; + } + sessionLoaded = true; inspectSelectedIdentities(); +} async function reload() { + await refreshDirectory(); inboxMode = false; displayed = (await api("/api/history")).messages; $("list_title").textContent = "Bridge history"; @@ -39,11 +92,16 @@ function render(messages) { if (!messages.length) { add($("messages"), "p", "No bridge messages here yet.", "empty"); return; } for (const message of messages) { const card = add($("messages"), "article", undefined, "message"); - add(card, "strong", label(message.source) + " → " + label(message.recipient)); + const header = add(card, "strong", label(message.source) + " → " + label(message.recipient)); + header.title = message.source + " → " + message.recipient; add(card, "span", message.status, "badge " + message.status); + const identity = add(card, "details"); + add(identity, "summary", "Inspect canonical route"); + add(identity, "small", "From: " + message.source); + add(identity, "small", "To: " + message.recipient); + if (message.conversation_id) add(identity, "small", "Conversation: " + message.conversation_id); add(card, "pre", message.text); add(card, "small", message.id + " · hop " + message.hops + "/4 · " + message.provenance); - if (message.conversation_id) add(card,"small","Conversation: "+message.conversation_id); if (message.reply_to) add(card, "small", "Reply to " + message.reply_to); if (message.receipt) add(card, "small", "Receipt evidence: " + message.receipt + " (does not confirm task completion)"); const actions = add(card, "div", undefined, "actions"); @@ -69,8 +127,9 @@ function render(messages) { }); } if (message.status === "queued" || message.status === "acknowledged") button(actions, "Draft an explicit reply", () => { - if (message.conversation_id) $("conversation_id").value=message.conversation_id; - $("source").value = message.recipient; $("recipient").value = message.source; + if (message.conversation_id) selectCanonical("conversation_id", message.conversation_id); + selectCanonical("source", message.recipient); selectCanonical("recipient", message.source); + inspectSelectedIdentities(); $("reply_to").value = message.id; $("text").value = ""; $("text").focus(); $("compose").scrollIntoView({behavior: "smooth"}); tell("Select the reply text yourself, then create a new draft."); }); @@ -88,6 +147,9 @@ $("compose").addEventListener("submit", async event => { event.preventDefault(); const submit = event.target.querySelector("button"); submit.disabled = true; try { + await refreshDirectory(); + if (!activeAgents.has($("source").value) || !activeAgents.has($("recipient").value)) + throw new Error("Selected identity is unavailable. Choose a current contact explicitly."); const text = $("text").value; if (new TextEncoder().encode(text).length > 16384) throw new Error("Message exceeds 16 KiB in UTF-8."); const input = {source: $("source").value, recipient: $("recipient").value, text}; @@ -111,6 +173,8 @@ $("older").onclick = async () => { }; $("receive").onclick = async () => { try { + await refreshDirectory(); + if (!activeAgents.has($("inbox_agent").value)) throw new Error("Selected inbox is unavailable."); const result = await api("/api/receive", {recipient: $("inbox_agent").value}); inboxMode = true; $("older").hidden = true; $("list_title").textContent = label($("inbox_agent").value) + " — local queued inbox"; @@ -123,8 +187,6 @@ $("copy").onclick = async () => { } catch (_) { $("copy_text").select(); tell("Select and copy this text manually with Ctrl/Cmd+C."); } }; $("close_handoff").onclick = () => { $("handoff").hidden = true; $("copy_text").value = ""; }; -(async () => { const session=await api("/api/session"); csrf=session.csrf; - for (const field of ["source","recipient","inbox_agent"]) { $(field).replaceChildren(); for (const name of session.agents) { const option=add($(field),"option",label(name)); option.value=name; } } - if (session.agents.length>1) $("recipient").selectedIndex=1; - if (session.conversations && session.conversations.length) { $("conversation_label").hidden=false; for (const cid of session.conversations) { const option=add($("conversation_id"),"option",cid); option.value=cid; } } - await reload(); })().catch(error => tell(error.message, true)); +for (const field of ["source", "recipient", "inbox_agent", "conversation_id"]) + $(field).addEventListener("change", inspectSelectedIdentities); +reload().catch(error => tell(error.message, true)); diff --git a/web/index.html b/web/index.html index 4287d20..ce4eafb 100644 --- a/web/index.html +++ b/web/index.html @@ -10,12 +10,15 @@
Read approved messages for a selected recipient. This does not acknowledge them.
Prepared locally only. Copy this into the chosen agent yourself. The bridge cannot verify delivery.
diff --git a/web/style.css b/web/style.css index 336425e..df19d59 100644 --- a/web/style.css +++ b/web/style.css @@ -15,3 +15,5 @@ pre{white-space:pre-wrap;overflow-wrap:anywhere;font:15px/1.6 system-ui,sans-ser small{display:block;color:var(--muted);font-size:12px;overflow-wrap:anywhere}.actions{margin-top:14px}footer{font-size:12px;color:var(--muted);padding:12px} #notice{padding:12px 0;font-weight:600;color:var(--accent);overflow-wrap:anywhere}#notice.error{color:#a62c35} @media(max-width:550px){main{padding:24px 14px}h1{font-size:38px}section{padding:18px}.route{grid-template-columns:1fr;gap:0}} + +details{margin:10px 0;font-size:13px;color:var(--muted)}summary{cursor:pointer}details small{margin:4px 0}