Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226// The shared vocabulary between the ziran runtime and the ziran relay, and// the SyncTransport seam the runtime programs against. Phase 1 has exactly// one transport (the relay, plaintext); phase 2 wraps payloads in MLS; a// later Iroh fast path or Matrix adapter would implement the same interface.
/** A participant as the runtime/relay sees them. Role is a document-defined string; the runtime and relay only enforce write-permission + membership. */export interface Member { did: string; handle?: string; role: string; /** The role's capabilities (NSIDs), resolved from the doc's manifest — what tiles check ("may this person do X"), while `role` stays the human-facing bundle name. */ capabilities?: string[]; /** False when the member is known but not currently around (Spaces presence records aging out). Absent = presence is implicit (relay rosters only list connected members). */ present?: boolean; /** Invited, has not joined yet (their repo has not appeared). */ pending?: boolean;}
/** A role's runtime-enforceable capabilities, declared in the tile manifest under `sync.roles`. Everything else about what a role *means* is the tile's business. */export interface RoleSpec { /** What to call this role in the runtime's chrome ("Player", "Reviewer"). Role *names* are the document's vocabulary and may be terse (`o`); this is what a person should read. Defaults to the capitalized name. */ label?: string; /** May append durable messages to the log. */ write?: boolean; /** May send on the ephemeral presence lane. */ presence?: boolean; /** Roles whose presence/roster entries this role is allowed to see. Absent = sees everyone; [] = sees only itself. */ seesRoles?: string[]; /** Max simultaneous members holding this role (e.g. one `opponent`). */ max?: number; /** May invite others / assign roles / remove members. */ admin?: boolean; /** What this role may DO, as NSIDs — open semantics: the space.ziran.* capabilities have runtime meaning (changeTitle gates the title UI), and a tile may mint its own (com.berjon.tictactoe.playerX). A role is just a labelled bundle of these; the label is what the sharing UI shows, the capabilities are what code checks. Absent = derived from the legacy `write` flag. */ capabilities?: string[];}
/* ——— capabilities with runtime meaning ——— */
export const CAP_READ = 'space.ziran.read';export const CAP_WRITE = 'space.ziran.write';export const CAP_COMMENT = 'space.ziran.comment';export const CAP_CHANGE_TITLE = 'space.ziran.changeTitle';
/** A role's capabilities: the declared bundle, or the legacy `write` flag mapped onto the standard set (write ⇒ read+write+comment+changeTitle; read-only ⇒ read). */export function roleCapabilities(spec: RoleSpec | undefined): string[] { if (!spec) return [CAP_READ]; if (spec.capabilities) return spec.capabilities; return spec.write ? [CAP_READ, CAP_WRITE, CAP_COMMENT, CAP_CHANGE_TITLE] : [CAP_READ];}
export interface SyncManifest { /** The role granted to the document's creator/owner. */ owner: string; roles: Record<string, RoleSpec>; /** Role given to someone who opens a public link without a named invite, if any (absent = invite-only). */ publicRole?: string;}
export interface Invitation { token: string; docId: string; /** Human label for the document, shown in the invitee's inbox. */ title: string; /** The space the document lives in — set ONLY when it differs from the title (doc = space shares one name; legacy multi-doc spaces differ). */ spaceName?: string; /** The doc's model, human-named ("Rich text") — what kind of thing the invitee is being handed. */ modelName?: string; inviterDid: string; inviterHandle?: string; inviteeDid: string; role: string; createdAt: number; /** Opaque to the relay: the MLS Welcome (b64) under E2EE transports, so the invitee can join the group. Absent for plaintext transports, and absent while an invitation is still *pending* — see `pending`. */ payload?: string; /** True when the invitee had published no collaboration keys yet (they had never run Ziran). The invitation is real and waiting: once they sign in and publish, the inviter's runtime completes it with a Welcome. */ pending?: boolean;}
/** Durable, ordered, attributed message delivered to a joined session. */export interface LogMessage { seq: number; author: string; // DID, relay-attested role: string; /** Opaque payload (plaintext in phase 1, MLS ciphertext in phase 2). */ bytes: Uint8Array;}
export interface EphemeralMessage { author: string; role: string; bytes: Uint8Array;}
/** A live attachment to one document's channel. */export interface Session { docId: string; me: Member; roster(): Member[]; /** Append to the durable log; resolves with the assigned seq. */ append(bytes: Uint8Array): Promise<number>; ephemeral(bytes: Uint8Array): void; /** Upload the current document state as the catch-up snapshot, tagged with the log seq it reflects. */ snapshot(bytes: Uint8Array, atSeq: number): Promise<void>; onMessage(handler: (m: LogMessage) => void): () => void; onEphemeral(handler: (m: EphemeralMessage) => void): () => void; onRoster(handler: (roster: Member[]) => void): () => void; leave(): void;}
export interface JoinOptions { /** Replay durable messages with seq greater than this (after loading a snapshot); omit to replay from the start of retained history. */ sinceSeq?: number;}
export interface AcceptResult { docId: string; role: string; snapshot: Uint8Array | null; atSeq: number;}
/** The seam. Implemented by the relay transport (phase 1) and, later, by an MLS-wrapping transport and any fast-path/interop adapters. */export interface SyncTransport { /** Attach to a document's channel as the current user. */ join(docId: string, opts?: JoinOptions): Promise<Session>; /** Create an invitation for an AT identity with a document-defined role. */ invite(docId: string, inviteeDid: string, role: string): Promise<Invitation>; /** Standing subscription to this user's invitation inbox. */ inbox(): AsyncIterable<Invitation>; /** Accept an invitation: returns the snapshot to load before syncing. */ accept(token: string): Promise<AcceptResult>; /** Fetch the latest snapshot blob for a document, if any. */ fetchSnapshot(docId: string): Promise<{ bytes: Uint8Array; atSeq: number } | null>; close(): void;}
// ——— Relay wire protocol (WebSocket, one connection per client) ———//// Frames are JSON with binary payloads base64url-encoded in `b64`. (Phase 2// may switch to a binary framing; kept simple and inspectable for now.)
export type ClientFrame = | { t: 'join'; docId: string; sinceSeq?: number; manifest?: SyncManifest } | { t: 'leave'; docId: string } | { t: 'append'; docId: string; id: string; b64: string } | { t: 'ephemeral'; docId: string; b64: string } | { t: 'snapshot'; docId: string; atSeq: number; b64: string } | { t: 'invite'; docId: string; inviteeDid: string; role: string; id: string; title?: string; payload?: string; pending?: boolean; } // The inviter supplying the Welcome for a pending invitation, once the // invitee has finally published keys. | { t: 'complete-invite'; token: string; payload: string; id: string } | { t: 'accept'; token: string; id: string } | { t: 'sub-inbox' } // KeyPackage directory (stands in for the PDS record until AT sign-in). | { t: 'pub-kp'; b64: string } | { t: 'get-kp'; did: string; id: string } // Fetch an invitation by token (deep-link accepts that beat the inbox). | { t: 'get-invite'; token: string; id: string };
export type ServerFrame = | { t: 'joined'; docId: string; me: Member; roster: Member[] } | { t: 'msg'; docId: string; seq: number; author: string; role: string; b64: string } | { t: 'eph'; docId: string; author: string; role: string; b64: string } | { t: 'roster'; docId: string; roster: Member[] } | { t: 'ack'; id: string; seq?: number } | { t: 'invited'; id: string; invitation: Invitation } | { t: 'accepted'; id: string; result: { docId: string; role: string; atSeq: number; snapshotB64: string | null } } | { t: 'inbox'; invitation: Invitation } /** To the inviter: a pending invitation can now be completed, because the invitee has published collaboration keys. */ | { t: 'invite-ready'; token: string; docId: string; inviteeDid: string } | { t: 'kp'; id: string; b64: string | null } | { t: 'invite-info'; id: string; invitation: Invitation | null } /** docId scopes join failures (join frames carry no request id). */ | { t: 'err'; id?: string; docId?: string; code: string; message: string };
export function toB64(bytes: Uint8Array): string { let bin = ''; for (const b of bytes) bin += String.fromCharCode(b); return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');}
export function fromB64(s: string): Uint8Array { const pad = s.replace(/-/g, '+').replace(/_/g, '/'); const bin = atob(pad + '='.repeat((4 - (pad.length % 4)) % 4)); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out;}