@xenosystem/primitives 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,6 +7,7 @@ XENO back-end rung 1. Two families, one subpath each:
7
7
  - `@xenosystem/primitives/secrets` – envelope-encrypted credentials; the OS store holds one key per person per machine.
8
8
  - `@xenosystem/primitives/secrets/testing` – an in-memory key store for tests only.
9
9
  - `@xenosystem/primitives/updates` – an installed app updates only for an account allowed to: points electron-updater at the platform's gated feed (`/api/updates/<slug>/feed`) with the account's own fresh token. Signed out and no plan are states, not errors.
10
+ - `@xenosystem/primitives/live` – be live with others on a shared thing through XENO Multiplayer (`wss://live.xenosystem.ai`, protocol `xeno-live.v1`): presence, a shared Yjs document that survives going offline, leases for anything that cannot be merged, and signals. `joinLive({ type, id, ticket, Y })`; the app passes its own Yjs and asks the platform for the ticket.
10
11
 
11
12
  Authority: `XENO LOCAL HOME - SPEC.md` (LOCKED). Zero runtime dependencies. Proprietary (`UNLICENSED`).
12
13
 
@@ -0,0 +1,137 @@
1
+ /**
2
+ * `@xenosystem/primitives/live` — the client every XENO app uses to be live with others on a shared thing.
3
+ *
4
+ * Owner, 2026-10-28: multiplayer is "a proper service at XENO level that we will inherit on all our apps". The service
5
+ * is XENO Multiplayer (repo xeno-multiplayer, `wss://live.xenosystem.ai`); its protocol, `xeno-live.v1`, is its SPEC.md.
6
+ * This family is the ONE client for it, so presence, the shared document, leases and signals cannot be implemented
7
+ * differently per app.
8
+ *
9
+ * Dependency-free like the rest of this package: the app passes its own Yjs module (one copy per app; Yjs breaks when
10
+ * two copies meet), its own WebSocket where the platform has none built in, and a function that asks the platform for
11
+ * a ticket. Nothing here stores a ticket.
12
+ *
13
+ * What you join is the shared thing itself, `<type>/<id>` (`spawn.canvas/<uuid>`) — no "room" or "space".
14
+ *
15
+ * Reconnection is automatic, with a fresh ticket each time; on every join both sides exchange state vectors, so a
16
+ * returning client downloads only what it lacks and sends the edits it made offline. It stops for good when access
17
+ * ended (4403), when the request is malformed or too large (4400, 4413), when tickets keep being refused, or on close().
18
+ */
19
+ /** The slice of a Yjs `Doc` this uses. */
20
+ export interface LiveDoc {
21
+ on(event: 'update', fn: (update: Uint8Array, origin: unknown) => void): void;
22
+ off(event: 'update', fn: (update: Uint8Array, origin: unknown) => void): void;
23
+ }
24
+ /** The slice of the Yjs module this uses. Pass the app's own `import * as Y from 'yjs'`. */
25
+ export interface LiveYjs<D extends LiveDoc = LiveDoc> {
26
+ Doc: new () => D;
27
+ applyUpdate(doc: D, update: Uint8Array, origin?: unknown): void;
28
+ encodeStateVector(doc: D): Uint8Array;
29
+ encodeStateAsUpdate(doc: D, stateVector?: Uint8Array): Uint8Array;
30
+ }
31
+ /** The slice of a WebSocket this uses (the browser's, Node's built-in one, or the `ws` package). */
32
+ export interface LiveSocket {
33
+ binaryType: string;
34
+ readyState: number;
35
+ send(data: string | Uint8Array): void;
36
+ close(code?: number, reason?: string): void;
37
+ onopen: ((ev: unknown) => void) | null;
38
+ onmessage: ((ev: {
39
+ data: unknown;
40
+ }) => void) | null;
41
+ onclose: ((ev: {
42
+ code: number;
43
+ reason: string;
44
+ }) => void) | null;
45
+ onerror: ((ev: unknown) => void) | null;
46
+ }
47
+ export type LiveSocketConstructor = new (url: string, protocols: string[]) => LiveSocket;
48
+ export interface LiveParticipant {
49
+ conn: string;
50
+ sub: string;
51
+ name: string;
52
+ kind: 'human' | 'agent' | 'service';
53
+ /** For an agent: the person it acts for. */
54
+ act: {
55
+ sub: string;
56
+ } | null;
57
+ role: 'owner' | 'editor' | 'viewer';
58
+ state: unknown;
59
+ }
60
+ export type LiveStatus = 'connecting' | 'open' | 'reconnecting' | 'ended';
61
+ export interface LiveEnd {
62
+ code: number;
63
+ reason: string;
64
+ }
65
+ export interface LiveOptions<D extends LiveDoc = LiveDoc> {
66
+ /** The kind of shared thing, `<app>.<kind>`: `spawn.canvas`, `docs.doc`. */
67
+ type: string;
68
+ /** The thing's own stable id. */
69
+ id: string;
70
+ /** Asks the platform for a join ticket for `<type>/<id>`; called before every connection. */
71
+ ticket: (resource: string) => Promise<string>;
72
+ /** The app's own Yjs module. */
73
+ Y: LiveYjs<D>;
74
+ /** The document to keep live; a new one is made if omitted. */
75
+ doc?: D;
76
+ /** Default `wss://live.xenosystem.ai`. */
77
+ url?: string;
78
+ /** Default the platform's own `WebSocket`. */
79
+ WebSocket?: LiveSocketConstructor;
80
+ /** Reconnection back-off. */
81
+ retry?: {
82
+ minMs?: number;
83
+ maxMs?: number;
84
+ };
85
+ }
86
+ export interface LiveEvents {
87
+ status: LiveStatus;
88
+ participants: LiveParticipant[];
89
+ leases: Record<string, LiveParticipant>;
90
+ 'lease.refused': {
91
+ key: string;
92
+ holder: LiveParticipant | null;
93
+ };
94
+ /** `takenFrom` is set when someone took a lease over from someone else. */
95
+ 'lease.taken': {
96
+ key: string;
97
+ holder: LiveParticipant;
98
+ takenFrom: LiveParticipant;
99
+ };
100
+ signal: {
101
+ from: LiveParticipant;
102
+ data: unknown;
103
+ };
104
+ error: {
105
+ code: string;
106
+ message: string;
107
+ };
108
+ }
109
+ export interface LiveConnection<D extends LiveDoc = LiveDoc> {
110
+ readonly doc: D;
111
+ readonly status: LiveStatus;
112
+ /** This connection as the others see it, once open. */
113
+ readonly self: LiveParticipant | null;
114
+ /** Why it ended, once `status` is `ended`. */
115
+ readonly ended: LiveEnd | null;
116
+ /** Everyone else here now, with their presence. */
117
+ participants(): LiveParticipant[];
118
+ /** Who holds each lease now. */
119
+ leases(): Record<string, LiveParticipant>;
120
+ /** Replaces this connection's presence (cursor, selection, viewport…); kept across reconnects. */
121
+ setPresence(state: unknown): void;
122
+ /** Sends an ephemeral app event to everyone, or to one connection. Dropped while offline. */
123
+ signal(data: unknown, to?: string): void;
124
+ requestLease(key: string): void;
125
+ releaseLease(key: string): void;
126
+ /** Takes a held lease over; the previous holder is told. */
127
+ takeLease(key: string): void;
128
+ on<E extends keyof LiveEvents>(event: E, fn: (value: LiveEvents[E]) => void): () => void;
129
+ /** Leaves for good. */
130
+ close(): void;
131
+ }
132
+ export declare const LIVE_PROTOCOL = "xeno-live.v1";
133
+ export declare const LIVE_URL = "wss://live.xenosystem.ai";
134
+ /** A human-readable reason for a close code (SPEC §5). */
135
+ export declare function liveCloseReason(code: number): string;
136
+ /** Join a shared thing and keep it live until `close()`. */
137
+ export declare function joinLive<D extends LiveDoc>(options: LiveOptions<D>): LiveConnection<D>;
@@ -0,0 +1,261 @@
1
+ "use strict";
2
+ /**
3
+ * `@xenosystem/primitives/live` — the client every XENO app uses to be live with others on a shared thing.
4
+ *
5
+ * Owner, 2026-10-28: multiplayer is "a proper service at XENO level that we will inherit on all our apps". The service
6
+ * is XENO Multiplayer (repo xeno-multiplayer, `wss://live.xenosystem.ai`); its protocol, `xeno-live.v1`, is its SPEC.md.
7
+ * This family is the ONE client for it, so presence, the shared document, leases and signals cannot be implemented
8
+ * differently per app.
9
+ *
10
+ * Dependency-free like the rest of this package: the app passes its own Yjs module (one copy per app; Yjs breaks when
11
+ * two copies meet), its own WebSocket where the platform has none built in, and a function that asks the platform for
12
+ * a ticket. Nothing here stores a ticket.
13
+ *
14
+ * What you join is the shared thing itself, `<type>/<id>` (`spawn.canvas/<uuid>`) — no "room" or "space".
15
+ *
16
+ * Reconnection is automatic, with a fresh ticket each time; on every join both sides exchange state vectors, so a
17
+ * returning client downloads only what it lacks and sends the edits it made offline. It stops for good when access
18
+ * ended (4403), when the request is malformed or too large (4400, 4413), when tickets keep being refused, or on close().
19
+ */
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.LIVE_URL = exports.LIVE_PROTOCOL = void 0;
22
+ exports.liveCloseReason = liveCloseReason;
23
+ exports.joinLive = joinLive;
24
+ exports.LIVE_PROTOCOL = 'xeno-live.v1';
25
+ exports.LIVE_URL = 'wss://live.xenosystem.ai';
26
+ const SYNC_REQUEST = 0x00, UPDATE = 0x01, STATE = 0x02, VECTOR = 0x03;
27
+ const TYPE = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/;
28
+ const ID = /^[A-Za-z0-9_-]{1,128}$/;
29
+ /** Close codes after which reconnecting cannot help. */
30
+ const FINAL = new Set([4400, 4403, 4413]);
31
+ const MAX_REFUSALS = 3;
32
+ /** A human-readable reason for a close code (SPEC §5). */
33
+ function liveCloseReason(code) {
34
+ switch (code) {
35
+ case 4400: return 'the request was not understood';
36
+ case 4401: return 'the platform did not admit this connection';
37
+ case 4403: return 'your access to this has ended';
38
+ case 4413: return 'too large';
39
+ case 4429: return 'too many messages';
40
+ default: return 'the connection was lost';
41
+ }
42
+ }
43
+ /** Join a shared thing and keep it live until `close()`. */
44
+ function joinLive(options) {
45
+ const { type, id, ticket, Y } = options;
46
+ if (!TYPE.test(type))
47
+ throw new TypeError(`not a shared-thing type: ${JSON.stringify(type)} (expected <app>.<kind>)`);
48
+ if (!ID.test(id))
49
+ throw new TypeError(`not a shared-thing id: ${JSON.stringify(id)}`);
50
+ const found = options.WebSocket ?? globalThis.WebSocket;
51
+ if (!found)
52
+ throw new TypeError('no WebSocket: pass one as options.WebSocket');
53
+ const Socket = found;
54
+ const resource = `${type}/${id}`;
55
+ const endpoint = `${(options.url ?? exports.LIVE_URL).replace(/\/+$/, '')}/v1/${resource}`;
56
+ const minMs = options.retry?.minMs ?? 500, maxMs = options.retry?.maxMs ?? 30_000;
57
+ const doc = options.doc ?? new Y.Doc();
58
+ const REMOTE = Symbol('xeno-live-remote');
59
+ let status = 'connecting';
60
+ let ended = null;
61
+ let self = null;
62
+ let socket = null;
63
+ let presence = null;
64
+ let attempt = 0, refusals = 0;
65
+ let timer = null;
66
+ let closedByUs = false;
67
+ const people = new Map();
68
+ let held = {};
69
+ const listeners = new Map();
70
+ function emit(event, value) {
71
+ for (const fn of listeners.get(event) ?? []) {
72
+ try {
73
+ fn(value);
74
+ }
75
+ catch { /* a listener's failure is its own */ }
76
+ }
77
+ }
78
+ const setStatus = (s) => { if (status !== s) {
79
+ status = s;
80
+ emit('status', s);
81
+ } };
82
+ const emitPeople = () => emit('participants', [...people.values()]);
83
+ const open = () => socket !== null && socket.readyState === 1;
84
+ const sendJson = (m) => { if (open())
85
+ socket.send(JSON.stringify(m)); };
86
+ const frame = (t, body) => { const f = new Uint8Array(body.byteLength + 1); f[0] = t; f.set(body, 1); return f; };
87
+ const onLocalUpdate = (update, origin) => {
88
+ // While offline nothing is queued here: the next join's state-vector exchange sends exactly what the service lacks.
89
+ if (origin !== REMOTE && open() && self && self.role !== 'viewer')
90
+ socket.send(frame(UPDATE, update));
91
+ };
92
+ doc.on('update', onLocalUpdate);
93
+ function end(code, reason) {
94
+ if (status === 'ended')
95
+ return;
96
+ ended = { code, reason };
97
+ if (timer)
98
+ clearTimeout(timer);
99
+ doc.off('update', onLocalUpdate);
100
+ people.clear();
101
+ held = {};
102
+ self = null;
103
+ setStatus('ended');
104
+ }
105
+ function scheduleReconnect() {
106
+ setStatus('reconnecting');
107
+ const delay = Math.min(maxMs, minMs * 2 ** attempt) * (0.8 + Math.random() * 0.4);
108
+ attempt++;
109
+ timer = setTimeout(() => { timer = null; void connect(); }, delay);
110
+ }
111
+ async function connect() {
112
+ if (status === 'ended')
113
+ return;
114
+ let jwt;
115
+ try {
116
+ jwt = await ticket(resource);
117
+ }
118
+ catch {
119
+ // The platform could not be asked (offline, signed out): try again later; nothing is lost.
120
+ return scheduleReconnect();
121
+ }
122
+ // close() may have run while the ticket was being fetched
123
+ if (status === 'ended')
124
+ return;
125
+ const ws = new Socket(endpoint, [exports.LIVE_PROTOCOL, `ticket.${jwt}`]);
126
+ ws.binaryType = 'arraybuffer';
127
+ socket = ws;
128
+ let welcomed = false;
129
+ ws.onmessage = (ev) => {
130
+ if (socket !== ws)
131
+ return;
132
+ if (typeof ev.data === 'string')
133
+ return onControl(ev.data, () => { welcomed = true; });
134
+ const bytes = ev.data instanceof ArrayBuffer ? new Uint8Array(ev.data) : ev.data instanceof Uint8Array ? ev.data : null;
135
+ if (!bytes || bytes.byteLength < 1)
136
+ return;
137
+ const body = bytes.subarray(1);
138
+ if (bytes[0] === VECTOR) {
139
+ ws.send(frame(SYNC_REQUEST, Y.encodeStateVector(doc)));
140
+ if (self?.role !== 'viewer') {
141
+ const lacks = Y.encodeStateAsUpdate(doc, body);
142
+ if (lacks.byteLength > 2)
143
+ ws.send(frame(UPDATE, lacks));
144
+ }
145
+ }
146
+ else if (bytes[0] === STATE || bytes[0] === UPDATE) {
147
+ Y.applyUpdate(doc, body, REMOTE);
148
+ }
149
+ };
150
+ ws.onclose = (ev) => {
151
+ if (socket !== ws)
152
+ return;
153
+ socket = null;
154
+ people.clear();
155
+ if (Object.keys(held).length) {
156
+ held = {};
157
+ emit('leases', {});
158
+ }
159
+ emitPeople();
160
+ if (closedByUs)
161
+ return end(1000, 'closed');
162
+ if (FINAL.has(ev.code))
163
+ return end(ev.code, ev.reason || liveCloseReason(ev.code));
164
+ if (ev.code === 4401 && !welcomed && ++refusals >= MAX_REFUSALS)
165
+ return end(4401, ev.reason || liveCloseReason(4401));
166
+ scheduleReconnect();
167
+ };
168
+ ws.onerror = () => { };
169
+ }
170
+ function onControl(text, onWelcome) {
171
+ let m;
172
+ try {
173
+ m = JSON.parse(text);
174
+ }
175
+ catch {
176
+ return;
177
+ }
178
+ switch (m.t) {
179
+ case 'welcome': {
180
+ onWelcome();
181
+ attempt = 0;
182
+ refusals = 0;
183
+ self = m.self;
184
+ people.clear();
185
+ for (const p of m.participants)
186
+ people.set(p.conn, p);
187
+ held = { ...m.leases };
188
+ setStatus('open');
189
+ if (presence !== null)
190
+ sendJson({ t: 'presence', state: presence });
191
+ emitPeople();
192
+ emit('leases', { ...held });
193
+ return;
194
+ }
195
+ case 'join': {
196
+ const p = m.participant;
197
+ people.set(p.conn, p);
198
+ return emitPeople();
199
+ }
200
+ case 'leave': {
201
+ people.delete(m.conn);
202
+ return emitPeople();
203
+ }
204
+ case 'presence': {
205
+ const p = people.get(m.conn);
206
+ if (p) {
207
+ p.state = m.state;
208
+ emitPeople();
209
+ }
210
+ return;
211
+ }
212
+ case 'lease': {
213
+ const key = m.key, holder = m.holder;
214
+ if (holder)
215
+ held[key] = holder;
216
+ else
217
+ delete held[key];
218
+ emit('leases', { ...held });
219
+ if (holder && m.takenFrom)
220
+ emit('lease.taken', { key, holder, takenFrom: m.takenFrom });
221
+ return;
222
+ }
223
+ case 'lease.refused': return emit('lease.refused', { key: m.key, holder: m.holder ?? null });
224
+ case 'signal': return emit('signal', { from: m.from, data: m.data });
225
+ case 'error': return emit('error', { code: String(m.code), message: String(m.message) });
226
+ default: return;
227
+ }
228
+ }
229
+ void connect();
230
+ return {
231
+ doc,
232
+ get status() { return status; },
233
+ get self() { return self; },
234
+ get ended() { return ended; },
235
+ participants: () => [...people.values()],
236
+ leases: () => ({ ...held }),
237
+ setPresence(state) { presence = state ?? null; sendJson({ t: 'presence', state: presence }); },
238
+ signal(data, to) { sendJson(to === undefined ? { t: 'signal', data } : { t: 'signal', data, to }); },
239
+ requestLease(key) { sendJson({ t: 'lease.request', key }); },
240
+ releaseLease(key) { sendJson({ t: 'lease.release', key }); },
241
+ takeLease(key) { sendJson({ t: 'lease.take', key }); },
242
+ on(event, fn) {
243
+ let set = listeners.get(event);
244
+ if (!set)
245
+ listeners.set(event, (set = new Set()));
246
+ set.add(fn);
247
+ return () => { set.delete(fn); };
248
+ },
249
+ close() {
250
+ closedByUs = true;
251
+ if (timer) {
252
+ clearTimeout(timer);
253
+ timer = null;
254
+ }
255
+ if (socket)
256
+ socket.close(1000, 'closed');
257
+ else
258
+ end(1000, 'closed');
259
+ },
260
+ };
261
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * `@xenosystem/primitives/live` — the client every XENO app uses to be live with others on a shared thing.
3
+ *
4
+ * Owner, 2026-10-28: multiplayer is "a proper service at XENO level that we will inherit on all our apps". The service
5
+ * is XENO Multiplayer (repo xeno-multiplayer, `wss://live.xenosystem.ai`); its protocol, `xeno-live.v1`, is its SPEC.md.
6
+ * This family is the ONE client for it, so presence, the shared document, leases and signals cannot be implemented
7
+ * differently per app.
8
+ *
9
+ * Dependency-free like the rest of this package: the app passes its own Yjs module (one copy per app; Yjs breaks when
10
+ * two copies meet), its own WebSocket where the platform has none built in, and a function that asks the platform for
11
+ * a ticket. Nothing here stores a ticket.
12
+ *
13
+ * What you join is the shared thing itself, `<type>/<id>` (`spawn.canvas/<uuid>`) — no "room" or "space".
14
+ *
15
+ * Reconnection is automatic, with a fresh ticket each time; on every join both sides exchange state vectors, so a
16
+ * returning client downloads only what it lacks and sends the edits it made offline. It stops for good when access
17
+ * ended (4403), when the request is malformed or too large (4400, 4413), when tickets keep being refused, or on close().
18
+ */
19
+ /** The slice of a Yjs `Doc` this uses. */
20
+ export interface LiveDoc {
21
+ on(event: 'update', fn: (update: Uint8Array, origin: unknown) => void): void;
22
+ off(event: 'update', fn: (update: Uint8Array, origin: unknown) => void): void;
23
+ }
24
+ /** The slice of the Yjs module this uses. Pass the app's own `import * as Y from 'yjs'`. */
25
+ export interface LiveYjs<D extends LiveDoc = LiveDoc> {
26
+ Doc: new () => D;
27
+ applyUpdate(doc: D, update: Uint8Array, origin?: unknown): void;
28
+ encodeStateVector(doc: D): Uint8Array;
29
+ encodeStateAsUpdate(doc: D, stateVector?: Uint8Array): Uint8Array;
30
+ }
31
+ /** The slice of a WebSocket this uses (the browser's, Node's built-in one, or the `ws` package). */
32
+ export interface LiveSocket {
33
+ binaryType: string;
34
+ readyState: number;
35
+ send(data: string | Uint8Array): void;
36
+ close(code?: number, reason?: string): void;
37
+ onopen: ((ev: unknown) => void) | null;
38
+ onmessage: ((ev: {
39
+ data: unknown;
40
+ }) => void) | null;
41
+ onclose: ((ev: {
42
+ code: number;
43
+ reason: string;
44
+ }) => void) | null;
45
+ onerror: ((ev: unknown) => void) | null;
46
+ }
47
+ export type LiveSocketConstructor = new (url: string, protocols: string[]) => LiveSocket;
48
+ export interface LiveParticipant {
49
+ conn: string;
50
+ sub: string;
51
+ name: string;
52
+ kind: 'human' | 'agent' | 'service';
53
+ /** For an agent: the person it acts for. */
54
+ act: {
55
+ sub: string;
56
+ } | null;
57
+ role: 'owner' | 'editor' | 'viewer';
58
+ state: unknown;
59
+ }
60
+ export type LiveStatus = 'connecting' | 'open' | 'reconnecting' | 'ended';
61
+ export interface LiveEnd {
62
+ code: number;
63
+ reason: string;
64
+ }
65
+ export interface LiveOptions<D extends LiveDoc = LiveDoc> {
66
+ /** The kind of shared thing, `<app>.<kind>`: `spawn.canvas`, `docs.doc`. */
67
+ type: string;
68
+ /** The thing's own stable id. */
69
+ id: string;
70
+ /** Asks the platform for a join ticket for `<type>/<id>`; called before every connection. */
71
+ ticket: (resource: string) => Promise<string>;
72
+ /** The app's own Yjs module. */
73
+ Y: LiveYjs<D>;
74
+ /** The document to keep live; a new one is made if omitted. */
75
+ doc?: D;
76
+ /** Default `wss://live.xenosystem.ai`. */
77
+ url?: string;
78
+ /** Default the platform's own `WebSocket`. */
79
+ WebSocket?: LiveSocketConstructor;
80
+ /** Reconnection back-off. */
81
+ retry?: {
82
+ minMs?: number;
83
+ maxMs?: number;
84
+ };
85
+ }
86
+ export interface LiveEvents {
87
+ status: LiveStatus;
88
+ participants: LiveParticipant[];
89
+ leases: Record<string, LiveParticipant>;
90
+ 'lease.refused': {
91
+ key: string;
92
+ holder: LiveParticipant | null;
93
+ };
94
+ /** `takenFrom` is set when someone took a lease over from someone else. */
95
+ 'lease.taken': {
96
+ key: string;
97
+ holder: LiveParticipant;
98
+ takenFrom: LiveParticipant;
99
+ };
100
+ signal: {
101
+ from: LiveParticipant;
102
+ data: unknown;
103
+ };
104
+ error: {
105
+ code: string;
106
+ message: string;
107
+ };
108
+ }
109
+ export interface LiveConnection<D extends LiveDoc = LiveDoc> {
110
+ readonly doc: D;
111
+ readonly status: LiveStatus;
112
+ /** This connection as the others see it, once open. */
113
+ readonly self: LiveParticipant | null;
114
+ /** Why it ended, once `status` is `ended`. */
115
+ readonly ended: LiveEnd | null;
116
+ /** Everyone else here now, with their presence. */
117
+ participants(): LiveParticipant[];
118
+ /** Who holds each lease now. */
119
+ leases(): Record<string, LiveParticipant>;
120
+ /** Replaces this connection's presence (cursor, selection, viewport…); kept across reconnects. */
121
+ setPresence(state: unknown): void;
122
+ /** Sends an ephemeral app event to everyone, or to one connection. Dropped while offline. */
123
+ signal(data: unknown, to?: string): void;
124
+ requestLease(key: string): void;
125
+ releaseLease(key: string): void;
126
+ /** Takes a held lease over; the previous holder is told. */
127
+ takeLease(key: string): void;
128
+ on<E extends keyof LiveEvents>(event: E, fn: (value: LiveEvents[E]) => void): () => void;
129
+ /** Leaves for good. */
130
+ close(): void;
131
+ }
132
+ export declare const LIVE_PROTOCOL = "xeno-live.v1";
133
+ export declare const LIVE_URL = "wss://live.xenosystem.ai";
134
+ /** A human-readable reason for a close code (SPEC §5). */
135
+ export declare function liveCloseReason(code: number): string;
136
+ /** Join a shared thing and keep it live until `close()`. */
137
+ export declare function joinLive<D extends LiveDoc>(options: LiveOptions<D>): LiveConnection<D>;
@@ -0,0 +1,256 @@
1
+ /**
2
+ * `@xenosystem/primitives/live` — the client every XENO app uses to be live with others on a shared thing.
3
+ *
4
+ * Owner, 2026-10-28: multiplayer is "a proper service at XENO level that we will inherit on all our apps". The service
5
+ * is XENO Multiplayer (repo xeno-multiplayer, `wss://live.xenosystem.ai`); its protocol, `xeno-live.v1`, is its SPEC.md.
6
+ * This family is the ONE client for it, so presence, the shared document, leases and signals cannot be implemented
7
+ * differently per app.
8
+ *
9
+ * Dependency-free like the rest of this package: the app passes its own Yjs module (one copy per app; Yjs breaks when
10
+ * two copies meet), its own WebSocket where the platform has none built in, and a function that asks the platform for
11
+ * a ticket. Nothing here stores a ticket.
12
+ *
13
+ * What you join is the shared thing itself, `<type>/<id>` (`spawn.canvas/<uuid>`) — no "room" or "space".
14
+ *
15
+ * Reconnection is automatic, with a fresh ticket each time; on every join both sides exchange state vectors, so a
16
+ * returning client downloads only what it lacks and sends the edits it made offline. It stops for good when access
17
+ * ended (4403), when the request is malformed or too large (4400, 4413), when tickets keep being refused, or on close().
18
+ */
19
+ export const LIVE_PROTOCOL = 'xeno-live.v1';
20
+ export const LIVE_URL = 'wss://live.xenosystem.ai';
21
+ const SYNC_REQUEST = 0x00, UPDATE = 0x01, STATE = 0x02, VECTOR = 0x03;
22
+ const TYPE = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/;
23
+ const ID = /^[A-Za-z0-9_-]{1,128}$/;
24
+ /** Close codes after which reconnecting cannot help. */
25
+ const FINAL = new Set([4400, 4403, 4413]);
26
+ const MAX_REFUSALS = 3;
27
+ /** A human-readable reason for a close code (SPEC §5). */
28
+ export function liveCloseReason(code) {
29
+ switch (code) {
30
+ case 4400: return 'the request was not understood';
31
+ case 4401: return 'the platform did not admit this connection';
32
+ case 4403: return 'your access to this has ended';
33
+ case 4413: return 'too large';
34
+ case 4429: return 'too many messages';
35
+ default: return 'the connection was lost';
36
+ }
37
+ }
38
+ /** Join a shared thing and keep it live until `close()`. */
39
+ export function joinLive(options) {
40
+ const { type, id, ticket, Y } = options;
41
+ if (!TYPE.test(type))
42
+ throw new TypeError(`not a shared-thing type: ${JSON.stringify(type)} (expected <app>.<kind>)`);
43
+ if (!ID.test(id))
44
+ throw new TypeError(`not a shared-thing id: ${JSON.stringify(id)}`);
45
+ const found = options.WebSocket ?? globalThis.WebSocket;
46
+ if (!found)
47
+ throw new TypeError('no WebSocket: pass one as options.WebSocket');
48
+ const Socket = found;
49
+ const resource = `${type}/${id}`;
50
+ const endpoint = `${(options.url ?? LIVE_URL).replace(/\/+$/, '')}/v1/${resource}`;
51
+ const minMs = options.retry?.minMs ?? 500, maxMs = options.retry?.maxMs ?? 30_000;
52
+ const doc = options.doc ?? new Y.Doc();
53
+ const REMOTE = Symbol('xeno-live-remote');
54
+ let status = 'connecting';
55
+ let ended = null;
56
+ let self = null;
57
+ let socket = null;
58
+ let presence = null;
59
+ let attempt = 0, refusals = 0;
60
+ let timer = null;
61
+ let closedByUs = false;
62
+ const people = new Map();
63
+ let held = {};
64
+ const listeners = new Map();
65
+ function emit(event, value) {
66
+ for (const fn of listeners.get(event) ?? []) {
67
+ try {
68
+ fn(value);
69
+ }
70
+ catch { /* a listener's failure is its own */ }
71
+ }
72
+ }
73
+ const setStatus = (s) => { if (status !== s) {
74
+ status = s;
75
+ emit('status', s);
76
+ } };
77
+ const emitPeople = () => emit('participants', [...people.values()]);
78
+ const open = () => socket !== null && socket.readyState === 1;
79
+ const sendJson = (m) => { if (open())
80
+ socket.send(JSON.stringify(m)); };
81
+ const frame = (t, body) => { const f = new Uint8Array(body.byteLength + 1); f[0] = t; f.set(body, 1); return f; };
82
+ const onLocalUpdate = (update, origin) => {
83
+ // While offline nothing is queued here: the next join's state-vector exchange sends exactly what the service lacks.
84
+ if (origin !== REMOTE && open() && self && self.role !== 'viewer')
85
+ socket.send(frame(UPDATE, update));
86
+ };
87
+ doc.on('update', onLocalUpdate);
88
+ function end(code, reason) {
89
+ if (status === 'ended')
90
+ return;
91
+ ended = { code, reason };
92
+ if (timer)
93
+ clearTimeout(timer);
94
+ doc.off('update', onLocalUpdate);
95
+ people.clear();
96
+ held = {};
97
+ self = null;
98
+ setStatus('ended');
99
+ }
100
+ function scheduleReconnect() {
101
+ setStatus('reconnecting');
102
+ const delay = Math.min(maxMs, minMs * 2 ** attempt) * (0.8 + Math.random() * 0.4);
103
+ attempt++;
104
+ timer = setTimeout(() => { timer = null; void connect(); }, delay);
105
+ }
106
+ async function connect() {
107
+ if (status === 'ended')
108
+ return;
109
+ let jwt;
110
+ try {
111
+ jwt = await ticket(resource);
112
+ }
113
+ catch {
114
+ // The platform could not be asked (offline, signed out): try again later; nothing is lost.
115
+ return scheduleReconnect();
116
+ }
117
+ // close() may have run while the ticket was being fetched
118
+ if (status === 'ended')
119
+ return;
120
+ const ws = new Socket(endpoint, [LIVE_PROTOCOL, `ticket.${jwt}`]);
121
+ ws.binaryType = 'arraybuffer';
122
+ socket = ws;
123
+ let welcomed = false;
124
+ ws.onmessage = (ev) => {
125
+ if (socket !== ws)
126
+ return;
127
+ if (typeof ev.data === 'string')
128
+ return onControl(ev.data, () => { welcomed = true; });
129
+ const bytes = ev.data instanceof ArrayBuffer ? new Uint8Array(ev.data) : ev.data instanceof Uint8Array ? ev.data : null;
130
+ if (!bytes || bytes.byteLength < 1)
131
+ return;
132
+ const body = bytes.subarray(1);
133
+ if (bytes[0] === VECTOR) {
134
+ ws.send(frame(SYNC_REQUEST, Y.encodeStateVector(doc)));
135
+ if (self?.role !== 'viewer') {
136
+ const lacks = Y.encodeStateAsUpdate(doc, body);
137
+ if (lacks.byteLength > 2)
138
+ ws.send(frame(UPDATE, lacks));
139
+ }
140
+ }
141
+ else if (bytes[0] === STATE || bytes[0] === UPDATE) {
142
+ Y.applyUpdate(doc, body, REMOTE);
143
+ }
144
+ };
145
+ ws.onclose = (ev) => {
146
+ if (socket !== ws)
147
+ return;
148
+ socket = null;
149
+ people.clear();
150
+ if (Object.keys(held).length) {
151
+ held = {};
152
+ emit('leases', {});
153
+ }
154
+ emitPeople();
155
+ if (closedByUs)
156
+ return end(1000, 'closed');
157
+ if (FINAL.has(ev.code))
158
+ return end(ev.code, ev.reason || liveCloseReason(ev.code));
159
+ if (ev.code === 4401 && !welcomed && ++refusals >= MAX_REFUSALS)
160
+ return end(4401, ev.reason || liveCloseReason(4401));
161
+ scheduleReconnect();
162
+ };
163
+ ws.onerror = () => { };
164
+ }
165
+ function onControl(text, onWelcome) {
166
+ let m;
167
+ try {
168
+ m = JSON.parse(text);
169
+ }
170
+ catch {
171
+ return;
172
+ }
173
+ switch (m.t) {
174
+ case 'welcome': {
175
+ onWelcome();
176
+ attempt = 0;
177
+ refusals = 0;
178
+ self = m.self;
179
+ people.clear();
180
+ for (const p of m.participants)
181
+ people.set(p.conn, p);
182
+ held = { ...m.leases };
183
+ setStatus('open');
184
+ if (presence !== null)
185
+ sendJson({ t: 'presence', state: presence });
186
+ emitPeople();
187
+ emit('leases', { ...held });
188
+ return;
189
+ }
190
+ case 'join': {
191
+ const p = m.participant;
192
+ people.set(p.conn, p);
193
+ return emitPeople();
194
+ }
195
+ case 'leave': {
196
+ people.delete(m.conn);
197
+ return emitPeople();
198
+ }
199
+ case 'presence': {
200
+ const p = people.get(m.conn);
201
+ if (p) {
202
+ p.state = m.state;
203
+ emitPeople();
204
+ }
205
+ return;
206
+ }
207
+ case 'lease': {
208
+ const key = m.key, holder = m.holder;
209
+ if (holder)
210
+ held[key] = holder;
211
+ else
212
+ delete held[key];
213
+ emit('leases', { ...held });
214
+ if (holder && m.takenFrom)
215
+ emit('lease.taken', { key, holder, takenFrom: m.takenFrom });
216
+ return;
217
+ }
218
+ case 'lease.refused': return emit('lease.refused', { key: m.key, holder: m.holder ?? null });
219
+ case 'signal': return emit('signal', { from: m.from, data: m.data });
220
+ case 'error': return emit('error', { code: String(m.code), message: String(m.message) });
221
+ default: return;
222
+ }
223
+ }
224
+ void connect();
225
+ return {
226
+ doc,
227
+ get status() { return status; },
228
+ get self() { return self; },
229
+ get ended() { return ended; },
230
+ participants: () => [...people.values()],
231
+ leases: () => ({ ...held }),
232
+ setPresence(state) { presence = state ?? null; sendJson({ t: 'presence', state: presence }); },
233
+ signal(data, to) { sendJson(to === undefined ? { t: 'signal', data } : { t: 'signal', data, to }); },
234
+ requestLease(key) { sendJson({ t: 'lease.request', key }); },
235
+ releaseLease(key) { sendJson({ t: 'lease.release', key }); },
236
+ takeLease(key) { sendJson({ t: 'lease.take', key }); },
237
+ on(event, fn) {
238
+ let set = listeners.get(event);
239
+ if (!set)
240
+ listeners.set(event, (set = new Set()));
241
+ set.add(fn);
242
+ return () => { set.delete(fn); };
243
+ },
244
+ close() {
245
+ closedByUs = true;
246
+ if (timer) {
247
+ clearTimeout(timer);
248
+ timer = null;
249
+ }
250
+ if (socket)
251
+ socket.close(1000, 'closed');
252
+ else
253
+ end(1000, 'closed');
254
+ },
255
+ };
256
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@xenosystem/primitives",
3
- "version": "0.3.2",
4
- "description": "XENO back-end rung 1 primitives: dirs (the XENO local home), secrets (envelope-encrypted credentials) and updates (the gated app updater).",
3
+ "version": "0.4.0",
4
+ "description": "XENO back-end rung 1 primitives: dirs (the XENO local home), secrets (envelope-encrypted credentials) updates (the gated app updater) and live (the client for XENO Multiplayer).",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
7
7
  "sideEffects": false,
@@ -43,6 +43,16 @@
43
43
  "default": "./dist/cjs/updates/index.js"
44
44
  }
45
45
  },
46
+ "./live": {
47
+ "import": {
48
+ "types": "./dist/esm/live/index.d.ts",
49
+ "default": "./dist/esm/live/index.js"
50
+ },
51
+ "require": {
52
+ "types": "./dist/cjs/live/index.d.ts",
53
+ "default": "./dist/cjs/live/index.js"
54
+ }
55
+ },
46
56
  "./secrets/testing": {
47
57
  "import": {
48
58
  "types": "./dist/esm/secrets/testing.d.ts",