@xenosystem/primitives 0.3.1 → 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 +7 -0
- package/dist/cjs/dirs/migrate.js +81 -4
- package/dist/cjs/generated/contract.js +15 -0
- package/dist/cjs/live/index.d.ts +137 -0
- package/dist/cjs/live/index.js +261 -0
- package/dist/esm/dirs/migrate.js +82 -5
- package/dist/esm/generated/contract.js +15 -0
- package/dist/esm/live/index.d.ts +137 -0
- package/dist/esm/live/index.js +256 -0
- package/package.json +12 -2
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
|
|
|
@@ -20,6 +21,12 @@ never followed). `resolvePlatformNativeRoots` names the old locations for a prod
|
|
|
20
21
|
segments `['plugins', '{path}']` copies every file below `plugins/`, keeping the structure. Links inside are refused;
|
|
21
22
|
the rule must copy and name the remainder with exactly one `{path}` segment.
|
|
22
23
|
|
|
24
|
+
**A tree moves whole or not at all (0.3.2).** When two sources would write into one destination tree, or the
|
|
25
|
+
destination tree already holds files the source would not put there (or different bytes), every file of that tree is
|
|
26
|
+
held back and reported as `held back: …`, and none is copied: half of two plugin stores merged is worse than either. A
|
|
27
|
+
repeated run over an identical copy is not held back. Built-in rule `extensions-cli-plugins` moves the CLI's
|
|
28
|
+
`~/.xeno-agent/plugins` into `data/extensions/plugins` under that rule.
|
|
29
|
+
|
|
23
30
|
```ts
|
|
24
31
|
import { createDirs } from '@xenosystem/primitives/dirs';
|
|
25
32
|
import { createSecretStore, createOsKeyStore } from '@xenosystem/primitives/secrets';
|
package/dist/cjs/dirs/migrate.js
CHANGED
|
@@ -52,6 +52,48 @@ function matchRule(rule, rel) {
|
|
|
52
52
|
const last = got[got.length - 1];
|
|
53
53
|
return globMatch(want[want.length - 1], last) ? { file: last, rest: [] } : null;
|
|
54
54
|
}
|
|
55
|
+
/** The destination folder a tree rule copies into: its target with the '{path}' segment and everything after dropped. */
|
|
56
|
+
const treeRoot = (rule) => rule.match.split('/').pop() === TREE && rule.action === 'copy'
|
|
57
|
+
? `${rule.target.kind}:${[rule.target.area, ...rule.target.segments.slice(0, rule.target.segments.indexOf(PATH_TOKEN))].join('/')}`
|
|
58
|
+
: null;
|
|
59
|
+
/**
|
|
60
|
+
* Why an existing destination tree is not just a partial copy of these entries (null when it is, or is absent): a file
|
|
61
|
+
* no entry would write there, a link, or bytes different from the entry's source.
|
|
62
|
+
*/
|
|
63
|
+
function destinationTreeDiffers(root, entries, sep) {
|
|
64
|
+
let st;
|
|
65
|
+
try {
|
|
66
|
+
st = (0, node_fs_1.lstatSync)(root);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
if (!st.isDirectory() || st.isSymbolicLink())
|
|
72
|
+
return 'it is not a folder';
|
|
73
|
+
const bySource = new Map(entries.map((e) => [e.dest, e]));
|
|
74
|
+
const pending = [root];
|
|
75
|
+
while (pending.length > 0) {
|
|
76
|
+
const dir = pending.pop();
|
|
77
|
+
for (const name of (0, node_fs_1.readdirSync)(dir)) {
|
|
78
|
+
const abs = dir + sep + name;
|
|
79
|
+
const s = (0, node_fs_1.lstatSync)(abs);
|
|
80
|
+
if (s.isSymbolicLink())
|
|
81
|
+
return `a link at ${abs.slice(root.length + 1)}`;
|
|
82
|
+
if (s.isDirectory()) {
|
|
83
|
+
pending.push(abs);
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
const entry = bySource.get(abs);
|
|
87
|
+
if (entry === undefined)
|
|
88
|
+
return `${abs.slice(root.length + 1)} is not in this source`;
|
|
89
|
+
const same = s.size === entry.bytes
|
|
90
|
+
&& (0, node_crypto_1.createHash)('sha256').update((0, node_fs_1.readFileSync)(abs)).digest('hex') === (0, node_crypto_1.createHash)('sha256').update((0, node_fs_1.readFileSync)(entry.source)).digest('hex');
|
|
91
|
+
if (!same)
|
|
92
|
+
return `${abs.slice(root.length + 1)} differs`;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
55
97
|
const fill = (s, file) => s.split('{file}').join(file);
|
|
56
98
|
/** A target's segments with `{file}` filled and a whole `{path}` segment expanded into the matched remainder. */
|
|
57
99
|
const expand = (segments, m) => segments.flatMap((x) => (x === PATH_TOKEN ? m.rest : [fill(x, m.file)]));
|
|
@@ -90,6 +132,8 @@ function planMigration(options) {
|
|
|
90
132
|
const names = options.legacyHomes ?? contract_ts_1.INPUTS_JSON.legacyHomes;
|
|
91
133
|
const homes = [];
|
|
92
134
|
const entries = [];
|
|
135
|
+
/** The destination tree of each entry a tree rule produced. */
|
|
136
|
+
const trees = new Map();
|
|
93
137
|
const refused = [];
|
|
94
138
|
const unplaced = { count: 0, sample: [], truncated: false };
|
|
95
139
|
let visited = 0;
|
|
@@ -168,7 +212,11 @@ function planMigration(options) {
|
|
|
168
212
|
if (rule.action === 'copy') {
|
|
169
213
|
const segs = expand(rule.target.segments, m);
|
|
170
214
|
const dest = options.dirs.path(rule.target.kind, rule.target.area, ...segs);
|
|
171
|
-
|
|
215
|
+
const entry = { rule: rule.id, action: 'copy', legacyHome: name, sourceRel: r, source: abs, bytes: s.size, dest, destRel: [rule.target.area, ...segs].join('/'), destKind: rule.target.kind };
|
|
216
|
+
const tree = treeRoot(rule);
|
|
217
|
+
if (tree !== null)
|
|
218
|
+
trees.set(entry, tree);
|
|
219
|
+
entries.push(entry);
|
|
172
220
|
}
|
|
173
221
|
else {
|
|
174
222
|
const sn = fill(rule.target.name, m.file);
|
|
@@ -258,13 +306,42 @@ function planMigration(options) {
|
|
|
258
306
|
const byDest = new Map();
|
|
259
307
|
for (const e of entries)
|
|
260
308
|
byDest.set(`${e.destKind}:${e.destRel}`, [...(byDest.get(`${e.destKind}:${e.destRel}`) ?? []), e]);
|
|
309
|
+
// A tree is one unit (an installed plugin store has a registry naming its folders), so a collision anywhere in a
|
|
310
|
+
// destination tree holds back EVERY source copying into it: half of two trees merged is worse than neither.
|
|
311
|
+
const heldTrees = new Map();
|
|
312
|
+
for (const group of byDest.values())
|
|
313
|
+
if (group.length > 1)
|
|
314
|
+
for (const e of group) {
|
|
315
|
+
const t = trees.get(e);
|
|
316
|
+
if (t !== undefined)
|
|
317
|
+
heldTrees.set(t, `held back: another source also copies into ${t.slice(t.indexOf(':') + 1)} and collides there, so neither tree is merged`);
|
|
318
|
+
}
|
|
319
|
+
// The same holds against what is already there: a destination tree holding files this plan would not put there, or
|
|
320
|
+
// different bytes, is another store, and copying into it would merge two. A resumed run (identical bytes) passes.
|
|
321
|
+
for (const t of new Set(trees.values())) {
|
|
322
|
+
if (heldTrees.has(t))
|
|
323
|
+
continue;
|
|
324
|
+
const mine = entries.filter((e) => trees.get(e) === t);
|
|
325
|
+
const kind = t.slice(0, t.indexOf(':'));
|
|
326
|
+
const root = options.dirs.root(kind) + sep + t.slice(t.indexOf(':') + 1).split('/').join(sep);
|
|
327
|
+
const why = destinationTreeDiffers(root, mine, sep);
|
|
328
|
+
if (why !== null)
|
|
329
|
+
heldTrees.set(t, `held back: ${t.slice(t.indexOf(':') + 1)} already holds another store (${why}), so it is not merged into`);
|
|
330
|
+
}
|
|
261
331
|
const clean = [];
|
|
262
332
|
for (const group of byDest.values()) {
|
|
263
|
-
if (group.length
|
|
264
|
-
clean.push(group[0]);
|
|
265
|
-
else
|
|
333
|
+
if (group.length > 1) {
|
|
266
334
|
for (const e of group)
|
|
267
335
|
refused.push({ path: e.source, reason: `destination collision: ${group.length} sources map to ${e.destRel}` });
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
const e = group[0];
|
|
339
|
+
const t = trees.get(e);
|
|
340
|
+
const held = t === undefined ? undefined : heldTrees.get(t);
|
|
341
|
+
if (held !== undefined)
|
|
342
|
+
refused.push({ path: e.source, reason: held });
|
|
343
|
+
else
|
|
344
|
+
clean.push(e);
|
|
268
345
|
}
|
|
269
346
|
clean.sort((a, b) => { const x = a.legacyHome + a.sourceRel, y = b.legacyHome + b.sourceRel; return x < y ? -1 : x > y ? 1 : 0; });
|
|
270
347
|
return { id: planId(clean), homes, entries: clean, refused, unplaced };
|
|
@@ -251,6 +251,21 @@ exports.LEGACY_MAP_JSON = {
|
|
|
251
251
|
},
|
|
252
252
|
"source": "XENO LOCAL HOME - SPEC.md section 5 (extensions: config, data, cache) and xeno-primitives/ADOPTION.md 0.3.1: the Agent host plugin/MCP store (xeno-agent-interface PluginMcpManagerService) moves from ~/.xeno/{plugins,mcp}; installed plugins, their registry, trust decisions and event log are one tree owned by the SDK plugin host"
|
|
253
253
|
},
|
|
254
|
+
{
|
|
255
|
+
"id": "extensions-cli-plugins",
|
|
256
|
+
"legacyHome": ".xeno-agent",
|
|
257
|
+
"match": "plugins/**",
|
|
258
|
+
"action": "copy",
|
|
259
|
+
"target": {
|
|
260
|
+
"kind": "data",
|
|
261
|
+
"area": "extensions",
|
|
262
|
+
"segments": [
|
|
263
|
+
"plugins",
|
|
264
|
+
"{path}"
|
|
265
|
+
]
|
|
266
|
+
},
|
|
267
|
+
"source": "XENO LOCAL HOME - SPEC.md section 5 and xeno-primitives/ADOPTION.md 0.3.2: xeno-agent-cli kept its SDK plugin host store in ~/.xeno-agent/plugins; from CLI 0.5.139 it uses the Agent host store, so both surfaces manage one set of plugins. Same tree format as extensions-plugins; when both legacy trees hold files, neither is merged (a tree collision holds back the whole tree)"
|
|
268
|
+
},
|
|
254
269
|
{
|
|
255
270
|
"id": "extensions-mcp-servers",
|
|
256
271
|
"legacyHome": ".xeno",
|
|
@@ -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
|
+
}
|
package/dist/esm/dirs/migrate.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
-
import { createReadStream, createWriteStream, lstatSync, readdirSync, promises as fsp } from 'node:fs';
|
|
2
|
+
import { createReadStream, createWriteStream, lstatSync, readdirSync, readFileSync, promises as fsp } from 'node:fs';
|
|
3
3
|
import { basename, dirname, join } from 'node:path';
|
|
4
4
|
import { INPUTS_JSON, LEGACY_MAP_JSON } from "../generated/contract.js";
|
|
5
5
|
import { atomicWriteFile } from "./atomic.js";
|
|
@@ -43,6 +43,48 @@ function matchRule(rule, rel) {
|
|
|
43
43
|
const last = got[got.length - 1];
|
|
44
44
|
return globMatch(want[want.length - 1], last) ? { file: last, rest: [] } : null;
|
|
45
45
|
}
|
|
46
|
+
/** The destination folder a tree rule copies into: its target with the '{path}' segment and everything after dropped. */
|
|
47
|
+
const treeRoot = (rule) => rule.match.split('/').pop() === TREE && rule.action === 'copy'
|
|
48
|
+
? `${rule.target.kind}:${[rule.target.area, ...rule.target.segments.slice(0, rule.target.segments.indexOf(PATH_TOKEN))].join('/')}`
|
|
49
|
+
: null;
|
|
50
|
+
/**
|
|
51
|
+
* Why an existing destination tree is not just a partial copy of these entries (null when it is, or is absent): a file
|
|
52
|
+
* no entry would write there, a link, or bytes different from the entry's source.
|
|
53
|
+
*/
|
|
54
|
+
function destinationTreeDiffers(root, entries, sep) {
|
|
55
|
+
let st;
|
|
56
|
+
try {
|
|
57
|
+
st = lstatSync(root);
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
if (!st.isDirectory() || st.isSymbolicLink())
|
|
63
|
+
return 'it is not a folder';
|
|
64
|
+
const bySource = new Map(entries.map((e) => [e.dest, e]));
|
|
65
|
+
const pending = [root];
|
|
66
|
+
while (pending.length > 0) {
|
|
67
|
+
const dir = pending.pop();
|
|
68
|
+
for (const name of readdirSync(dir)) {
|
|
69
|
+
const abs = dir + sep + name;
|
|
70
|
+
const s = lstatSync(abs);
|
|
71
|
+
if (s.isSymbolicLink())
|
|
72
|
+
return `a link at ${abs.slice(root.length + 1)}`;
|
|
73
|
+
if (s.isDirectory()) {
|
|
74
|
+
pending.push(abs);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
const entry = bySource.get(abs);
|
|
78
|
+
if (entry === undefined)
|
|
79
|
+
return `${abs.slice(root.length + 1)} is not in this source`;
|
|
80
|
+
const same = s.size === entry.bytes
|
|
81
|
+
&& createHash('sha256').update(readFileSync(abs)).digest('hex') === createHash('sha256').update(readFileSync(entry.source)).digest('hex');
|
|
82
|
+
if (!same)
|
|
83
|
+
return `${abs.slice(root.length + 1)} differs`;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
46
88
|
const fill = (s, file) => s.split('{file}').join(file);
|
|
47
89
|
/** A target's segments with `{file}` filled and a whole `{path}` segment expanded into the matched remainder. */
|
|
48
90
|
const expand = (segments, m) => segments.flatMap((x) => (x === PATH_TOKEN ? m.rest : [fill(x, m.file)]));
|
|
@@ -81,6 +123,8 @@ export function planMigration(options) {
|
|
|
81
123
|
const names = options.legacyHomes ?? INPUTS_JSON.legacyHomes;
|
|
82
124
|
const homes = [];
|
|
83
125
|
const entries = [];
|
|
126
|
+
/** The destination tree of each entry a tree rule produced. */
|
|
127
|
+
const trees = new Map();
|
|
84
128
|
const refused = [];
|
|
85
129
|
const unplaced = { count: 0, sample: [], truncated: false };
|
|
86
130
|
let visited = 0;
|
|
@@ -159,7 +203,11 @@ export function planMigration(options) {
|
|
|
159
203
|
if (rule.action === 'copy') {
|
|
160
204
|
const segs = expand(rule.target.segments, m);
|
|
161
205
|
const dest = options.dirs.path(rule.target.kind, rule.target.area, ...segs);
|
|
162
|
-
|
|
206
|
+
const entry = { rule: rule.id, action: 'copy', legacyHome: name, sourceRel: r, source: abs, bytes: s.size, dest, destRel: [rule.target.area, ...segs].join('/'), destKind: rule.target.kind };
|
|
207
|
+
const tree = treeRoot(rule);
|
|
208
|
+
if (tree !== null)
|
|
209
|
+
trees.set(entry, tree);
|
|
210
|
+
entries.push(entry);
|
|
163
211
|
}
|
|
164
212
|
else {
|
|
165
213
|
const sn = fill(rule.target.name, m.file);
|
|
@@ -249,13 +297,42 @@ export function planMigration(options) {
|
|
|
249
297
|
const byDest = new Map();
|
|
250
298
|
for (const e of entries)
|
|
251
299
|
byDest.set(`${e.destKind}:${e.destRel}`, [...(byDest.get(`${e.destKind}:${e.destRel}`) ?? []), e]);
|
|
300
|
+
// A tree is one unit (an installed plugin store has a registry naming its folders), so a collision anywhere in a
|
|
301
|
+
// destination tree holds back EVERY source copying into it: half of two trees merged is worse than neither.
|
|
302
|
+
const heldTrees = new Map();
|
|
303
|
+
for (const group of byDest.values())
|
|
304
|
+
if (group.length > 1)
|
|
305
|
+
for (const e of group) {
|
|
306
|
+
const t = trees.get(e);
|
|
307
|
+
if (t !== undefined)
|
|
308
|
+
heldTrees.set(t, `held back: another source also copies into ${t.slice(t.indexOf(':') + 1)} and collides there, so neither tree is merged`);
|
|
309
|
+
}
|
|
310
|
+
// The same holds against what is already there: a destination tree holding files this plan would not put there, or
|
|
311
|
+
// different bytes, is another store, and copying into it would merge two. A resumed run (identical bytes) passes.
|
|
312
|
+
for (const t of new Set(trees.values())) {
|
|
313
|
+
if (heldTrees.has(t))
|
|
314
|
+
continue;
|
|
315
|
+
const mine = entries.filter((e) => trees.get(e) === t);
|
|
316
|
+
const kind = t.slice(0, t.indexOf(':'));
|
|
317
|
+
const root = options.dirs.root(kind) + sep + t.slice(t.indexOf(':') + 1).split('/').join(sep);
|
|
318
|
+
const why = destinationTreeDiffers(root, mine, sep);
|
|
319
|
+
if (why !== null)
|
|
320
|
+
heldTrees.set(t, `held back: ${t.slice(t.indexOf(':') + 1)} already holds another store (${why}), so it is not merged into`);
|
|
321
|
+
}
|
|
252
322
|
const clean = [];
|
|
253
323
|
for (const group of byDest.values()) {
|
|
254
|
-
if (group.length
|
|
255
|
-
clean.push(group[0]);
|
|
256
|
-
else
|
|
324
|
+
if (group.length > 1) {
|
|
257
325
|
for (const e of group)
|
|
258
326
|
refused.push({ path: e.source, reason: `destination collision: ${group.length} sources map to ${e.destRel}` });
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
const e = group[0];
|
|
330
|
+
const t = trees.get(e);
|
|
331
|
+
const held = t === undefined ? undefined : heldTrees.get(t);
|
|
332
|
+
if (held !== undefined)
|
|
333
|
+
refused.push({ path: e.source, reason: held });
|
|
334
|
+
else
|
|
335
|
+
clean.push(e);
|
|
259
336
|
}
|
|
260
337
|
clean.sort((a, b) => { const x = a.legacyHome + a.sourceRel, y = b.legacyHome + b.sourceRel; return x < y ? -1 : x > y ? 1 : 0; });
|
|
261
338
|
return { id: planId(clean), homes, entries: clean, refused, unplaced };
|
|
@@ -248,6 +248,21 @@ export const LEGACY_MAP_JSON = {
|
|
|
248
248
|
},
|
|
249
249
|
"source": "XENO LOCAL HOME - SPEC.md section 5 (extensions: config, data, cache) and xeno-primitives/ADOPTION.md 0.3.1: the Agent host plugin/MCP store (xeno-agent-interface PluginMcpManagerService) moves from ~/.xeno/{plugins,mcp}; installed plugins, their registry, trust decisions and event log are one tree owned by the SDK plugin host"
|
|
250
250
|
},
|
|
251
|
+
{
|
|
252
|
+
"id": "extensions-cli-plugins",
|
|
253
|
+
"legacyHome": ".xeno-agent",
|
|
254
|
+
"match": "plugins/**",
|
|
255
|
+
"action": "copy",
|
|
256
|
+
"target": {
|
|
257
|
+
"kind": "data",
|
|
258
|
+
"area": "extensions",
|
|
259
|
+
"segments": [
|
|
260
|
+
"plugins",
|
|
261
|
+
"{path}"
|
|
262
|
+
]
|
|
263
|
+
},
|
|
264
|
+
"source": "XENO LOCAL HOME - SPEC.md section 5 and xeno-primitives/ADOPTION.md 0.3.2: xeno-agent-cli kept its SDK plugin host store in ~/.xeno-agent/plugins; from CLI 0.5.139 it uses the Agent host store, so both surfaces manage one set of plugins. Same tree format as extensions-plugins; when both legacy trees hold files, neither is merged (a tree collision holds back the whole tree)"
|
|
265
|
+
},
|
|
251
266
|
{
|
|
252
267
|
"id": "extensions-mcp-servers",
|
|
253
268
|
"legacyHome": ".xeno",
|
|
@@ -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.
|
|
4
|
-
"description": "XENO back-end rung 1 primitives: dirs (the XENO local home), secrets (envelope-encrypted credentials)
|
|
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",
|