@mostra/runtime 0.11.0 → 0.12.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/dist/bin.js +152 -32
- package/dist/bin.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/{instance-DCiUHvgZ.js → instance-CBUlOmzG.js} +1215 -43
- package/dist/instance-CBUlOmzG.js.map +1 -0
- package/dist/reference/cli.md +112 -2
- package/dist/reference/diagnostics.json +27 -0
- package/dist/reference/errors/MOSTRA_TEAM_PRESENCE_RATE_LIMITED.md +23 -0
- package/dist/reference/errors/MOSTRA_TEAM_ROSTER_POLICY.md +23 -0
- package/dist/reference/errors/MOSTRA_TEAM_ROSTER_TOO_LARGE.md +23 -0
- package/dist/skill/SKILL.md +5 -3
- package/dist/skill/references/answers.md +3 -1
- package/dist/skill/references/mcp.md +2 -2
- package/dist/skill/references/teams.md +78 -0
- package/package.json +6 -6
- package/src/gateway/browser.ts +84 -1
- package/src/gateway/index.ts +40 -1
- package/src/gateway/team.ts +181 -0
- package/src/instance/index.ts +2 -1
- package/src/interaction/ephemeral.ts +21 -0
- package/src/interaction/events.ts +17 -0
- package/src/interaction/index.ts +265 -20
- package/src/interaction/roster.ts +585 -0
- package/src/interaction/team.ts +426 -0
- package/src/interaction/wait.ts +150 -0
- package/src/ledger/migrations.ts +35 -0
- package/src/link/hosted.ts +14 -3
- package/src/link/manager.ts +31 -1
- package/src/server/directory.ts +22 -0
- package/src/server/feed.ts +89 -3
- package/src/server/hosted.ts +54 -22
- package/src/server/index.ts +10 -0
- package/src/server/operator.ts +87 -28
- package/src/share/index.ts +50 -2
- package/src/verify/index.ts +7 -0
- package/src/verify/runner.ts +5 -1
- package/dist/instance-DCiUHvgZ.js.map +0 -1
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Team traffic to pages (D168; CO-03, CO-04, CO-07): each view's roster as it may see it, and who
|
|
3
|
+
* is present with the cursors and selections they share. Nothing here is stored (D47): presence
|
|
4
|
+
* lives in this process's memory under short leases, and both reach pages only as ephemeral
|
|
5
|
+
* messages on their streams and polls, each view's under the artifact's visibility policy.
|
|
6
|
+
*
|
|
7
|
+
* - **Respondents.** A view that reads its roster (`respondents`) follows it for a minute; when the
|
|
8
|
+
* interaction core says an artifact's respondents may have changed, every following view is sent
|
|
9
|
+
* its roster again, at most every {@link RESPONDENTS_SETTLE_MS} per artifact, and only when it
|
|
10
|
+
* differs from what that view last got.
|
|
11
|
+
* - **Presence.** A view that posts presence is present for {@link PRESENCE_LEASE_MS}; what it
|
|
12
|
+
* shares replaces what it shared before. Each view may post {@link PRESENCE_RATE} updates a second
|
|
13
|
+
* (more is refused, `MOSTRA_TEAM_PRESENCE_RATE_LIMITED`), and an artifact's present views are sent
|
|
14
|
+
* who is present at most every {@link PRESENCE_FANOUT_MS}, so many fast cursors cost each reader a
|
|
15
|
+
* bounded rate of messages.
|
|
16
|
+
*/
|
|
17
|
+
import type {
|
|
18
|
+
PresencePeer,
|
|
19
|
+
PresenceRequest,
|
|
20
|
+
PresenceState,
|
|
21
|
+
RosterForPage,
|
|
22
|
+
TeamVisibility,
|
|
23
|
+
} from "@mostra/protocol";
|
|
24
|
+
import type { EphemeralBus } from "./ephemeral.ts";
|
|
25
|
+
import type { RosterViewer } from "./roster.ts";
|
|
26
|
+
|
|
27
|
+
/** How long a page stays present without posting again; pages post every 10 s. */
|
|
28
|
+
export const PRESENCE_LEASE_MS = 30_000;
|
|
29
|
+
|
|
30
|
+
/** The most presence updates one view may post in a second (a burst of as many). */
|
|
31
|
+
export const PRESENCE_RATE = 20;
|
|
32
|
+
|
|
33
|
+
/** The shortest time between two presence messages to one artifact's pages. */
|
|
34
|
+
export const PRESENCE_FANOUT_MS = 50;
|
|
35
|
+
|
|
36
|
+
/** How long a view follows its roster after it read it; pages read again every 20 s. */
|
|
37
|
+
export const RESPONDENTS_LEASE_MS = 60_000;
|
|
38
|
+
|
|
39
|
+
/** The shortest time between two roster messages to one artifact's pages. */
|
|
40
|
+
export const RESPONDENTS_SETTLE_MS = 100;
|
|
41
|
+
|
|
42
|
+
/** The most present viewers a page is told of by name; more are counted. */
|
|
43
|
+
export const PRESENCE_PEERS_MAX = 200;
|
|
44
|
+
|
|
45
|
+
/** What team traffic reads of the interaction core. */
|
|
46
|
+
export interface TeamSource {
|
|
47
|
+
visibility(artifactId: string): TeamVisibility;
|
|
48
|
+
isOwner(viewerId: string): boolean;
|
|
49
|
+
peer(artifactId: string, viewerId: string): { readonly key: string } & RosterViewer;
|
|
50
|
+
rosterForPage(page: { readonly artifactId: string; readonly viewerId: string }): RosterForPage;
|
|
51
|
+
rostersForPages(artifactId: string, viewerIds: readonly string[]): RosterForPage[];
|
|
52
|
+
onTeam(listener: (artifactId: string) => void): () => void;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** One view's presence. */
|
|
56
|
+
interface Present {
|
|
57
|
+
readonly artifactId: string;
|
|
58
|
+
readonly viewId: string;
|
|
59
|
+
readonly viewerId: string;
|
|
60
|
+
cursor?: { readonly x: number; readonly y: number };
|
|
61
|
+
selection?: { readonly element?: string; readonly start?: number; readonly end?: number };
|
|
62
|
+
at: number;
|
|
63
|
+
until: number;
|
|
64
|
+
/** The presence this view last got, so it hears only a change of what it may see. */
|
|
65
|
+
last?: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* A view's token bucket: the posts it may still make now. It outlives the view's presence (a
|
|
70
|
+
* leave keeps it), so leaving and joining again never refills it; it goes once unused for a lease.
|
|
71
|
+
*/
|
|
72
|
+
interface Bucket {
|
|
73
|
+
tokens: number;
|
|
74
|
+
refilled: number;
|
|
75
|
+
/** The highest `seq` the view posted with, so an older post that arrives later changes nothing. */
|
|
76
|
+
seq?: number;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** A view that follows its roster. */
|
|
80
|
+
interface Following {
|
|
81
|
+
readonly artifactId: string;
|
|
82
|
+
readonly viewerId: string;
|
|
83
|
+
until: number;
|
|
84
|
+
last?: string;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The answer to a presence post: the state, or how long to wait. */
|
|
88
|
+
export type PresenceAnswer =
|
|
89
|
+
| { readonly state: PresenceState }
|
|
90
|
+
| { readonly limited: true; readonly retryAfterMs: number };
|
|
91
|
+
|
|
92
|
+
/** Team traffic for one gateway. */
|
|
93
|
+
export interface TeamTraffic {
|
|
94
|
+
/** A view's presence post (CO-04): joins, shares, or leaves. */
|
|
95
|
+
presence(
|
|
96
|
+
page: { readonly artifactId: string; readonly viewerId: string },
|
|
97
|
+
request: PresenceRequest,
|
|
98
|
+
): PresenceAnswer;
|
|
99
|
+
/** A view reads its roster (CO-03) and follows it for a minute. */
|
|
100
|
+
respondents(
|
|
101
|
+
page: { readonly artifactId: string; readonly viewerId: string },
|
|
102
|
+
viewId: string,
|
|
103
|
+
): RosterForPage;
|
|
104
|
+
/** How many views are present now, across artifacts. */
|
|
105
|
+
presentCount(): number;
|
|
106
|
+
/** Stops the timers. */
|
|
107
|
+
close(): void;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Creates team traffic over a bus. */
|
|
111
|
+
export function createTeamTraffic(options: {
|
|
112
|
+
readonly bus: EphemeralBus;
|
|
113
|
+
readonly source: TeamSource;
|
|
114
|
+
readonly now?: () => number;
|
|
115
|
+
readonly log?: { error(event: string, fields: Record<string, unknown>): void };
|
|
116
|
+
}): TeamTraffic {
|
|
117
|
+
const { bus, source } = options;
|
|
118
|
+
const now = options.now ?? Date.now;
|
|
119
|
+
const present = new Map<string, Present>();
|
|
120
|
+
/** Each artifact's present views, so a fan-out reads only its own artifact's (Opus review 9). */
|
|
121
|
+
const presentOn = new Map<string, Set<string>>();
|
|
122
|
+
const put = (entry: Present): void => {
|
|
123
|
+
present.set(entry.viewId, entry);
|
|
124
|
+
let views = presentOn.get(entry.artifactId);
|
|
125
|
+
if (!views) {
|
|
126
|
+
views = new Set();
|
|
127
|
+
presentOn.set(entry.artifactId, views);
|
|
128
|
+
}
|
|
129
|
+
views.add(entry.viewId);
|
|
130
|
+
};
|
|
131
|
+
const drop = (viewId: string): void => {
|
|
132
|
+
const entry = present.get(viewId);
|
|
133
|
+
if (!entry) return;
|
|
134
|
+
present.delete(viewId);
|
|
135
|
+
const views = presentOn.get(entry.artifactId);
|
|
136
|
+
views?.delete(viewId);
|
|
137
|
+
if (views?.size === 0) presentOn.delete(entry.artifactId);
|
|
138
|
+
};
|
|
139
|
+
const presentFor = function* (artifactId: string): Generator<Present> {
|
|
140
|
+
for (const viewId of presentOn.get(artifactId) ?? []) {
|
|
141
|
+
const entry = present.get(viewId);
|
|
142
|
+
if (entry) yield entry;
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
const buckets = new Map<string, Bucket>();
|
|
146
|
+
const following = new Map<string, Following>();
|
|
147
|
+
const fanout = new Map<string, ReturnType<typeof setTimeout>>();
|
|
148
|
+
const settle = new Map<string, ReturnType<typeof setTimeout>>();
|
|
149
|
+
|
|
150
|
+
/** Lookups for one fan-out: each viewer's peer, the owner check and the visibility, read once. */
|
|
151
|
+
const memo = (artifactId: string) => {
|
|
152
|
+
const peers = new Map<string, { readonly key: string } & RosterViewer>();
|
|
153
|
+
const owners = new Map<string, boolean>();
|
|
154
|
+
let visibility: TeamVisibility | undefined;
|
|
155
|
+
return {
|
|
156
|
+
visibility: () => (visibility ??= source.visibility(artifactId)),
|
|
157
|
+
isOwner: (viewerId: string) => {
|
|
158
|
+
let owner = owners.get(viewerId);
|
|
159
|
+
if (owner === undefined) {
|
|
160
|
+
owner = source.isOwner(viewerId);
|
|
161
|
+
owners.set(viewerId, owner);
|
|
162
|
+
}
|
|
163
|
+
return owner;
|
|
164
|
+
},
|
|
165
|
+
peer: (viewerId: string) => {
|
|
166
|
+
let peer = peers.get(viewerId);
|
|
167
|
+
if (!peer) {
|
|
168
|
+
peer = source.peer(artifactId, viewerId);
|
|
169
|
+
peers.set(viewerId, peer);
|
|
170
|
+
}
|
|
171
|
+
return peer;
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
/** Who is present on an artifact, as one viewer may see it. */
|
|
177
|
+
const stateFor = (
|
|
178
|
+
artifactId: string,
|
|
179
|
+
viewerId: string,
|
|
180
|
+
lookups: ReturnType<typeof memo> = memo(artifactId),
|
|
181
|
+
): PresenceState => {
|
|
182
|
+
const visibility = lookups.visibility();
|
|
183
|
+
const sees: TeamVisibility = lookups.isOwner(viewerId) ? "names" : visibility;
|
|
184
|
+
const at = now();
|
|
185
|
+
// One entry per viewer: their most recent view's cursor and selection.
|
|
186
|
+
const byViewer = new Map<string, Present>();
|
|
187
|
+
for (const entry of presentFor(artifactId)) {
|
|
188
|
+
if (entry.until <= at) continue;
|
|
189
|
+
const kept = byViewer.get(entry.viewerId);
|
|
190
|
+
if (!kept || kept.at < entry.at) byViewer.set(entry.viewerId, entry);
|
|
191
|
+
}
|
|
192
|
+
const peerOf = (entry: Present): PresencePeer => {
|
|
193
|
+
const peer = lookups.peer(entry.viewerId);
|
|
194
|
+
return {
|
|
195
|
+
key: peer.key,
|
|
196
|
+
self: entry.viewerId === viewerId,
|
|
197
|
+
kind: peer.kind,
|
|
198
|
+
...(peer.name !== undefined ? { name: peer.name } : {}),
|
|
199
|
+
...(peer.verified !== undefined ? { verified: peer.verified } : {}),
|
|
200
|
+
...(entry.cursor ? { cursor: entry.cursor } : {}),
|
|
201
|
+
...(entry.selection ? { selection: entry.selection } : {}),
|
|
202
|
+
at: new Date(entry.at).toISOString(),
|
|
203
|
+
};
|
|
204
|
+
};
|
|
205
|
+
const own = byViewer.get(viewerId);
|
|
206
|
+
const others = [...byViewer.values()].filter((entry) => entry.viewerId !== viewerId);
|
|
207
|
+
const peers: PresencePeer[] = own ? [peerOf(own)] : [];
|
|
208
|
+
if (sees === "names") {
|
|
209
|
+
others.sort((a, b) => b.at - a.at);
|
|
210
|
+
for (const entry of others.slice(0, PRESENCE_PEERS_MAX)) peers.push(peerOf(entry));
|
|
211
|
+
}
|
|
212
|
+
return {
|
|
213
|
+
visibility,
|
|
214
|
+
peers,
|
|
215
|
+
...(sees !== "private" ? { others: others.length } : {}),
|
|
216
|
+
};
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Sends each present view of an artifact what it may see now, when that differs from what it
|
|
221
|
+
* last got: a view under `private` sees only itself, so others coming, moving and going send it
|
|
222
|
+
* nothing (Opus review 2), and under `counts` only a change of the count does.
|
|
223
|
+
*/
|
|
224
|
+
const fanOut = (artifactId: string): void => {
|
|
225
|
+
fanout.delete(artifactId);
|
|
226
|
+
const at = now();
|
|
227
|
+
const lookups = memo(artifactId);
|
|
228
|
+
for (const entry of presentFor(artifactId)) {
|
|
229
|
+
if (entry.until <= at) continue;
|
|
230
|
+
try {
|
|
231
|
+
const presence = stateFor(artifactId, entry.viewerId, lookups);
|
|
232
|
+
const text = JSON.stringify(presence);
|
|
233
|
+
if (text === entry.last) continue;
|
|
234
|
+
entry.last = text;
|
|
235
|
+
bus.send(artifactId, entry.viewId, { kind: "presence", presence });
|
|
236
|
+
} catch (error) {
|
|
237
|
+
options.log?.error("team.presence_failed", { error });
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
/** Schedules the artifact's next presence message, at most every {@link PRESENCE_FANOUT_MS}. */
|
|
243
|
+
const changedPresence = (artifactId: string): void => {
|
|
244
|
+
if (fanout.has(artifactId)) return;
|
|
245
|
+
const timer = setTimeout(() => fanOut(artifactId), PRESENCE_FANOUT_MS);
|
|
246
|
+
timer.unref?.();
|
|
247
|
+
fanout.set(artifactId, timer);
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
/** Sends each following view its roster when it changed, from one read for all of them. */
|
|
251
|
+
const sendRosters = (artifactId: string): void => {
|
|
252
|
+
settle.delete(artifactId);
|
|
253
|
+
const at = now();
|
|
254
|
+
const views: [string, Following][] = [];
|
|
255
|
+
for (const [viewId, entry] of following) {
|
|
256
|
+
if (entry.artifactId !== artifactId) continue;
|
|
257
|
+
if (entry.until <= at) following.delete(viewId);
|
|
258
|
+
else views.push([viewId, entry]);
|
|
259
|
+
}
|
|
260
|
+
if (views.length === 0) return;
|
|
261
|
+
let rosters: RosterForPage[];
|
|
262
|
+
try {
|
|
263
|
+
rosters = source.rostersForPages(
|
|
264
|
+
artifactId,
|
|
265
|
+
views.map(([, entry]) => entry.viewerId),
|
|
266
|
+
);
|
|
267
|
+
} catch (error) {
|
|
268
|
+
options.log?.error("team.respondents_failed", { error });
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
views.forEach(([viewId, entry], index) => {
|
|
272
|
+
const roster = rosters[index];
|
|
273
|
+
if (!roster) return;
|
|
274
|
+
const text = JSON.stringify(roster);
|
|
275
|
+
if (text === entry.last) return;
|
|
276
|
+
entry.last = text;
|
|
277
|
+
try {
|
|
278
|
+
bus.send(artifactId, viewId, { kind: "respondents", respondents: roster });
|
|
279
|
+
} catch (error) {
|
|
280
|
+
options.log?.error("team.respondents_failed", { error });
|
|
281
|
+
}
|
|
282
|
+
});
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
const stopTeam = source.onTeam((artifactId) => {
|
|
286
|
+
let any = false;
|
|
287
|
+
for (const entry of following.values()) {
|
|
288
|
+
if (entry.artifactId === artifactId) {
|
|
289
|
+
any = true;
|
|
290
|
+
break;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
if (!any || settle.has(artifactId)) return;
|
|
294
|
+
const timer = setTimeout(() => sendRosters(artifactId), RESPONDENTS_SETTLE_MS);
|
|
295
|
+
timer.unref?.();
|
|
296
|
+
settle.set(artifactId, timer);
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
// Expired presence ends, and the artifact's pages hear who left.
|
|
300
|
+
const sweep = setInterval(() => {
|
|
301
|
+
const at = now();
|
|
302
|
+
const left = new Set<string>();
|
|
303
|
+
for (const [viewId, entry] of present) {
|
|
304
|
+
if (entry.until <= at) {
|
|
305
|
+
drop(viewId);
|
|
306
|
+
left.add(entry.artifactId);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
for (const [viewId, entry] of following) if (entry.until <= at) following.delete(viewId);
|
|
310
|
+
for (const [viewId, bucket] of buckets) {
|
|
311
|
+
if (bucket.refilled + PRESENCE_LEASE_MS <= at) buckets.delete(viewId);
|
|
312
|
+
}
|
|
313
|
+
for (const artifactId of left) changedPresence(artifactId);
|
|
314
|
+
}, 1_000);
|
|
315
|
+
sweep.unref?.();
|
|
316
|
+
|
|
317
|
+
return {
|
|
318
|
+
presence(page, request) {
|
|
319
|
+
const at = now();
|
|
320
|
+
const viewId = request.viewId;
|
|
321
|
+
let entry = present.get(viewId);
|
|
322
|
+
if (entry && (entry.artifactId !== page.artifactId || entry.viewerId !== page.viewerId)) {
|
|
323
|
+
drop(viewId);
|
|
324
|
+
entry = undefined;
|
|
325
|
+
}
|
|
326
|
+
// Posts of one page can arrive out of order (a cursor update in flight when the page left):
|
|
327
|
+
// one older than the newest the view sent changes nothing, so a leave is never undone by an
|
|
328
|
+
// update that overtook it (Opus review 7). The count lives in the view's bucket, which
|
|
329
|
+
// outlives its presence by a lease.
|
|
330
|
+
const known = buckets.get(viewId);
|
|
331
|
+
const stale =
|
|
332
|
+
request.seq !== undefined && known?.seq !== undefined && request.seq <= known.seq;
|
|
333
|
+
if (request.seq !== undefined && !stale) {
|
|
334
|
+
const remembered = known ?? { tokens: PRESENCE_RATE, refilled: at };
|
|
335
|
+
remembered.seq = request.seq;
|
|
336
|
+
buckets.set(viewId, remembered);
|
|
337
|
+
}
|
|
338
|
+
// A present view's leave is always honored: it removes what the others see, and a page sends
|
|
339
|
+
// it as it goes, however fast it moved before.
|
|
340
|
+
if (request.leave === true && entry && !stale) {
|
|
341
|
+
drop(viewId);
|
|
342
|
+
changedPresence(page.artifactId);
|
|
343
|
+
return { state: stateFor(page.artifactId, page.viewerId) };
|
|
344
|
+
}
|
|
345
|
+
// Every other post takes a token (a leave of a view that isn't present too):
|
|
346
|
+
// PRESENCE_RATE a second, in bursts of as many, from a bucket a leave never refills.
|
|
347
|
+
const bucket = buckets.get(viewId) ?? { tokens: PRESENCE_RATE, refilled: at };
|
|
348
|
+
bucket.tokens = Math.min(
|
|
349
|
+
PRESENCE_RATE,
|
|
350
|
+
bucket.tokens + ((at - bucket.refilled) / 1000) * PRESENCE_RATE,
|
|
351
|
+
);
|
|
352
|
+
bucket.refilled = at;
|
|
353
|
+
buckets.set(viewId, bucket);
|
|
354
|
+
if (bucket.tokens < 1) {
|
|
355
|
+
return {
|
|
356
|
+
limited: true,
|
|
357
|
+
retryAfterMs: Math.ceil(((1 - bucket.tokens) / PRESENCE_RATE) * 1000),
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
bucket.tokens -= 1;
|
|
361
|
+
// A stale post takes its token like any, so sending old counts never escapes the rate.
|
|
362
|
+
if (stale || request.leave === true)
|
|
363
|
+
return { state: stateFor(page.artifactId, page.viewerId) };
|
|
364
|
+
if (!entry) {
|
|
365
|
+
entry = {
|
|
366
|
+
artifactId: page.artifactId,
|
|
367
|
+
viewId,
|
|
368
|
+
viewerId: page.viewerId,
|
|
369
|
+
at,
|
|
370
|
+
until: at + PRESENCE_LEASE_MS,
|
|
371
|
+
};
|
|
372
|
+
put(entry);
|
|
373
|
+
}
|
|
374
|
+
if (request.cursor !== undefined) {
|
|
375
|
+
if (request.cursor === null) delete entry.cursor;
|
|
376
|
+
else entry.cursor = { x: request.cursor.x, y: request.cursor.y };
|
|
377
|
+
}
|
|
378
|
+
if (request.selection !== undefined) {
|
|
379
|
+
if (request.selection === null) delete entry.selection;
|
|
380
|
+
else
|
|
381
|
+
entry.selection = {
|
|
382
|
+
...(request.selection.element !== undefined
|
|
383
|
+
? { element: request.selection.element }
|
|
384
|
+
: {}),
|
|
385
|
+
...(request.selection.start !== undefined ? { start: request.selection.start } : {}),
|
|
386
|
+
...(request.selection.end !== undefined ? { end: request.selection.end } : {}),
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
entry.at = at;
|
|
390
|
+
entry.until = at + PRESENCE_LEASE_MS;
|
|
391
|
+
changedPresence(page.artifactId);
|
|
392
|
+
// The answer is what the view sees now: the fan-out sends it again only once that changes.
|
|
393
|
+
const state = stateFor(page.artifactId, page.viewerId);
|
|
394
|
+
entry.last = JSON.stringify(state);
|
|
395
|
+
return { state };
|
|
396
|
+
},
|
|
397
|
+
respondents(page, viewId) {
|
|
398
|
+
const roster = source.rosterForPage(page);
|
|
399
|
+
following.set(viewId, {
|
|
400
|
+
artifactId: page.artifactId,
|
|
401
|
+
viewerId: page.viewerId,
|
|
402
|
+
until: now() + RESPONDENTS_LEASE_MS,
|
|
403
|
+
last: JSON.stringify(roster),
|
|
404
|
+
});
|
|
405
|
+
return roster;
|
|
406
|
+
},
|
|
407
|
+
presentCount() {
|
|
408
|
+
const at = now();
|
|
409
|
+
let count = 0;
|
|
410
|
+
for (const entry of present.values()) if (entry.until > at) count += 1;
|
|
411
|
+
return count;
|
|
412
|
+
},
|
|
413
|
+
close() {
|
|
414
|
+
clearInterval(sweep);
|
|
415
|
+
present.clear();
|
|
416
|
+
presentOn.clear();
|
|
417
|
+
buckets.clear();
|
|
418
|
+
following.clear();
|
|
419
|
+
stopTeam();
|
|
420
|
+
for (const timer of fanout.values()) clearTimeout(timer);
|
|
421
|
+
for (const timer of settle.values()) clearTimeout(timer);
|
|
422
|
+
fanout.clear();
|
|
423
|
+
settle.clear();
|
|
424
|
+
},
|
|
425
|
+
};
|
|
426
|
+
}
|
package/src/interaction/wait.ts
CHANGED
|
@@ -61,6 +61,153 @@ function submissionEvent(db: LedgerDb, row: SubmissionRow): EventRecord {
|
|
|
61
61
|
};
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
+
/**
|
|
65
|
+
* The latest roster event at or before `upTo` (`roster.changed` or `roster.completed`), or the
|
|
66
|
+
* roster's state a compaction summary kept for the events it replaced (DATA_MODEL §4).
|
|
67
|
+
*/
|
|
68
|
+
function latestRosterState(
|
|
69
|
+
db: LedgerDb,
|
|
70
|
+
artifactId: string,
|
|
71
|
+
upTo: number,
|
|
72
|
+
): { readonly complete: boolean; readonly completed?: EventRecord } | undefined {
|
|
73
|
+
const row = db.get<EventRow>(
|
|
74
|
+
"SELECT * FROM event WHERE artifact_id = ? AND cursor <= ? AND type IN ('roster.changed', 'roster.completed', ?) ORDER BY cursor DESC LIMIT 1",
|
|
75
|
+
artifactId,
|
|
76
|
+
upTo,
|
|
77
|
+
COMPACTED,
|
|
78
|
+
);
|
|
79
|
+
if (!row) return undefined;
|
|
80
|
+
const payload = JSON.parse(row.payload_json) as Record<string, unknown>;
|
|
81
|
+
if (row.type === COMPACTED) {
|
|
82
|
+
const kept = payload["roster"] as
|
|
83
|
+
| { readonly complete: boolean; readonly completed?: EventRecord }
|
|
84
|
+
| undefined;
|
|
85
|
+
return kept;
|
|
86
|
+
}
|
|
87
|
+
const lastCompleted = (): EventRecord | undefined => {
|
|
88
|
+
const completed = db.get<EventRow>(
|
|
89
|
+
"SELECT * FROM event WHERE artifact_id = ? AND cursor <= ? AND type = 'roster.completed' ORDER BY cursor DESC LIMIT 1",
|
|
90
|
+
artifactId,
|
|
91
|
+
upTo,
|
|
92
|
+
);
|
|
93
|
+
if (completed) return eventRecord(completed);
|
|
94
|
+
const summary = db.get<EventRow>(
|
|
95
|
+
`SELECT * FROM event WHERE artifact_id = ? AND cursor <= ? AND type = '${COMPACTED}' ORDER BY cursor DESC LIMIT 1`,
|
|
96
|
+
artifactId,
|
|
97
|
+
upTo,
|
|
98
|
+
);
|
|
99
|
+
if (!summary) return undefined;
|
|
100
|
+
return (JSON.parse(summary.payload_json) as { roster?: { completed?: EventRecord } }).roster
|
|
101
|
+
?.completed;
|
|
102
|
+
};
|
|
103
|
+
if (row.type === "roster.completed") return { complete: true, completed: eventRecord(row) };
|
|
104
|
+
if (payload["complete"] !== true) return { complete: false };
|
|
105
|
+
const completed = lastCompleted();
|
|
106
|
+
return completed ? { complete: true, completed } : { complete: true };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* `submitted:all` and `submitted:<N>` (D168, CO-02), under `once` per-viewer and `epochs`:
|
|
111
|
+
* - `submitted:all` is the roster's completion. Under `once` per-viewer without an explicit
|
|
112
|
+
* cursor it is level-triggered: the roster is complete now (its latest event says so), and the
|
|
113
|
+
* latest `roster.completed` answers. Otherwise it is the first `roster.completed` after the
|
|
114
|
+
* cursor, so an agent waits for each next completion (a roster that grew, an `epochs` round).
|
|
115
|
+
* It is read from durable events only, so an owner instance answers it for a hosted artifact
|
|
116
|
+
* from the events it follows.
|
|
117
|
+
* - `submitted:<N>` counts submissions: under `once` per-viewer without an explicit cursor all of
|
|
118
|
+
* them, otherwise those after the cursor; the N-th one's `submission.created` answers.
|
|
119
|
+
* Under `once` per-artifact (one submission in all) only `submitted:1` can ever hold:
|
|
120
|
+
* `MOSTRA_TEAM_ROSTER_POLICY` for the rest; under `none`, `MOSTRA_SUBMIT_POLICY_NONE`.
|
|
121
|
+
*/
|
|
122
|
+
function checkTeamCondition(
|
|
123
|
+
db: LedgerDb,
|
|
124
|
+
artifactId: string,
|
|
125
|
+
until: string,
|
|
126
|
+
after: number,
|
|
127
|
+
upTo: number,
|
|
128
|
+
explicitAfter: boolean,
|
|
129
|
+
): { readonly event: EventRecord } | { readonly cursor: number } {
|
|
130
|
+
const artifact = db.get<{ policy_json: string | null }>(
|
|
131
|
+
"SELECT policy_json FROM artifact WHERE id = ?",
|
|
132
|
+
artifactId,
|
|
133
|
+
);
|
|
134
|
+
const policy = storedPolicy(artifact?.policy_json ?? null);
|
|
135
|
+
if (policy.policy === "none") {
|
|
136
|
+
throw new RpcError(
|
|
137
|
+
createDiagnostic("MOSTRA_SUBMIT_POLICY_NONE", {
|
|
138
|
+
message:
|
|
139
|
+
"This artifact's submission policy is none: nothing will be submitted to wait for.",
|
|
140
|
+
}),
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
const count = until === "submitted:all" ? undefined : Number(until.slice("submitted:".length));
|
|
144
|
+
if (count !== undefined && (!Number.isSafeInteger(count) || count < 1 || count > 10_000)) {
|
|
145
|
+
throw new RpcError(
|
|
146
|
+
createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", {
|
|
147
|
+
message: "submitted:<N> takes a number of submissions from 1 to 10000.",
|
|
148
|
+
}),
|
|
149
|
+
-32602,
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
const perArtifact = policy.policy === "once" && policy.scope !== "per-viewer";
|
|
153
|
+
if (perArtifact && count !== 1) {
|
|
154
|
+
throw new RpcError(
|
|
155
|
+
createDiagnostic("MOSTRA_TEAM_ROSTER_POLICY", {
|
|
156
|
+
message: `This artifact takes one submission in all (once, per-artifact), so ${until} could never hold.`,
|
|
157
|
+
}),
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
const level = policy.policy === "once" && !explicitAfter;
|
|
161
|
+
if (count !== undefined) {
|
|
162
|
+
const from = level ? 0 : after;
|
|
163
|
+
if (!level) checkCompaction(db, { artifacts: [artifactId] }, after);
|
|
164
|
+
const row = db.get<SubmissionRow>(
|
|
165
|
+
"SELECT * FROM submission WHERE artifact_id = ? AND position > ? AND position <= ? ORDER BY position LIMIT 1 OFFSET ?",
|
|
166
|
+
artifactId,
|
|
167
|
+
from,
|
|
168
|
+
upTo,
|
|
169
|
+
count - 1,
|
|
170
|
+
);
|
|
171
|
+
if (row) return { event: submissionEvent(db, row) };
|
|
172
|
+
return { cursor: Math.max(upTo, after) };
|
|
173
|
+
}
|
|
174
|
+
if (level) {
|
|
175
|
+
const state = latestRosterState(db, artifactId, upTo);
|
|
176
|
+
if (state?.complete && state.completed) {
|
|
177
|
+
return heldHere(db, state.completed) ? { event: state.completed } : { cursor: after };
|
|
178
|
+
}
|
|
179
|
+
return { cursor: Math.max(upTo, after) };
|
|
180
|
+
}
|
|
181
|
+
checkCompaction(db, { artifacts: [artifactId] }, after);
|
|
182
|
+
const completed = db.get<EventRow>(
|
|
183
|
+
"SELECT * FROM event WHERE artifact_id = ? AND cursor > ? AND cursor <= ? AND type = 'roster.completed' ORDER BY cursor LIMIT 1",
|
|
184
|
+
artifactId,
|
|
185
|
+
after,
|
|
186
|
+
upTo,
|
|
187
|
+
);
|
|
188
|
+
if (!completed) return { cursor: Math.max(upTo, after) };
|
|
189
|
+
const event = eventRecord(completed);
|
|
190
|
+
// Not yet: the newest cursor examined stays before the completion, so the next wait finds it.
|
|
191
|
+
return heldHere(db, event) ? { event } : { cursor: Math.max(after, completed.cursor - 1) };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Whether this home holds every submission a completion names. A local home always does (they
|
|
196
|
+
* commit together); an owner instance copies a hosted `roster.completed` through its follow, while
|
|
197
|
+
* the submissions arrive by delivery, so a wait answers only once the last one is imported and
|
|
198
|
+
* `results` holds every answer the completion counts (J14). The import's commit wakes the wait.
|
|
199
|
+
*/
|
|
200
|
+
function heldHere(db: LedgerDb, completed: EventRecord): boolean {
|
|
201
|
+
const named = completed.payload["submissions"];
|
|
202
|
+
if (!Array.isArray(named)) return true;
|
|
203
|
+
for (const entry of named) {
|
|
204
|
+
const id = (entry as { submissionId?: unknown } | null)?.submissionId;
|
|
205
|
+
if (typeof id !== "string" || id === "") continue;
|
|
206
|
+
if (!db.get("SELECT 1 FROM submission WHERE id = ?", id)) return false;
|
|
207
|
+
}
|
|
208
|
+
return true;
|
|
209
|
+
}
|
|
210
|
+
|
|
64
211
|
/**
|
|
65
212
|
* Checks a condition once, inside the caller's read transaction: the event that satisfies it, or
|
|
66
213
|
* the newest cursor examined. Throws `MOSTRA_SUBMIT_POLICY_NONE` for `submitted` on an artifact
|
|
@@ -83,6 +230,9 @@ export function checkCondition(
|
|
|
83
230
|
...params,
|
|
84
231
|
);
|
|
85
232
|
let found: EventRow | undefined;
|
|
233
|
+
if (until === "submitted:all" || /^submitted:[0-9]+$/.test(until)) {
|
|
234
|
+
return checkTeamCondition(db, artifactId, until, after, upTo, explicitAfter);
|
|
235
|
+
}
|
|
86
236
|
if (until === "submitted") {
|
|
87
237
|
const artifact = db.get<{ policy_json: string | null }>(
|
|
88
238
|
"SELECT policy_json FROM artifact WHERE id = ?",
|
package/src/ledger/migrations.ts
CHANGED
|
@@ -888,4 +888,39 @@ export const MIGRATIONS: readonly Migration[] = [
|
|
|
888
888
|
`);
|
|
889
889
|
},
|
|
890
890
|
},
|
|
891
|
+
{
|
|
892
|
+
version: 16,
|
|
893
|
+
name: "expected respondents and the roster's rounds",
|
|
894
|
+
up(db) {
|
|
895
|
+
// The people an artifact expects answers from (D121, D168): one row per respondent, keyed by
|
|
896
|
+
// the host's stable key, acting as one viewer of kind `token` (D104) through a personal link.
|
|
897
|
+
// `roster_state` keeps the round and whether it is complete, so a completion is told once.
|
|
898
|
+
// Presence is never stored: no table holds it (D47, CO-04).
|
|
899
|
+
db.exec(`
|
|
900
|
+
CREATE TABLE roster_entry (
|
|
901
|
+
artifact_id TEXT NOT NULL REFERENCES artifact(id),
|
|
902
|
+
ref TEXT NOT NULL CHECK (length(ref) BETWEEN 1 AND 256),
|
|
903
|
+
name TEXT,
|
|
904
|
+
email TEXT,
|
|
905
|
+
viewer_id TEXT NOT NULL REFERENCES viewer(id),
|
|
906
|
+
token_id TEXT REFERENCES token(id),
|
|
907
|
+
position INTEGER NOT NULL,
|
|
908
|
+
added_at TEXT NOT NULL,
|
|
909
|
+
PRIMARY KEY (artifact_id, ref),
|
|
910
|
+
UNIQUE (artifact_id, viewer_id),
|
|
911
|
+
UNIQUE (artifact_id, position)
|
|
912
|
+
);
|
|
913
|
+
CREATE TABLE roster_state (
|
|
914
|
+
artifact_id TEXT PRIMARY KEY REFERENCES artifact(id),
|
|
915
|
+
round INTEGER NOT NULL CHECK (round >= 1),
|
|
916
|
+
round_cursor INTEGER NOT NULL CHECK (round_cursor >= 0),
|
|
917
|
+
round_started_at TEXT NOT NULL,
|
|
918
|
+
complete INTEGER NOT NULL CHECK (complete IN (0, 1))
|
|
919
|
+
);
|
|
920
|
+
CREATE TRIGGER roster_state_round_grows BEFORE UPDATE OF round, round_cursor ON roster_state
|
|
921
|
+
WHEN NEW.round < OLD.round OR NEW.round_cursor < OLD.round_cursor
|
|
922
|
+
BEGIN SELECT RAISE(ABORT, 'a roster round never goes back'); END;
|
|
923
|
+
`);
|
|
924
|
+
},
|
|
925
|
+
},
|
|
891
926
|
];
|
package/src/link/hosted.ts
CHANGED
|
@@ -10,6 +10,9 @@ import {
|
|
|
10
10
|
artifactPauseMethod,
|
|
11
11
|
livePushMethod,
|
|
12
12
|
MutationId,
|
|
13
|
+
rosterAddMethod,
|
|
14
|
+
rosterGetMethod,
|
|
15
|
+
rosterRemoveMethod,
|
|
13
16
|
stateGetMethod,
|
|
14
17
|
statePatchMethod,
|
|
15
18
|
} from "@mostra/protocol";
|
|
@@ -17,7 +20,15 @@ import type { HostedState } from "../actions/index.ts";
|
|
|
17
20
|
import { handler, type MethodHandler } from "../protocol-server/index.ts";
|
|
18
21
|
import type { Link } from "./manager.ts";
|
|
19
22
|
|
|
20
|
-
const FORWARDED = new Set([
|
|
23
|
+
const FORWARDED = new Set([
|
|
24
|
+
stateGetMethod.method,
|
|
25
|
+
statePatchMethod.method,
|
|
26
|
+
livePushMethod.method,
|
|
27
|
+
// The roster and its personal links are the hosted home's: its viewers answer there (D168).
|
|
28
|
+
rosterAddMethod.method,
|
|
29
|
+
rosterRemoveMethod.method,
|
|
30
|
+
rosterGetMethod.method,
|
|
31
|
+
]);
|
|
21
32
|
|
|
22
33
|
/** Server code's `state` for an artifact hosted somewhere, else `undefined`. */
|
|
23
34
|
export function hostedState(link: Link, artifactId: string): HostedState | undefined {
|
|
@@ -43,8 +54,8 @@ export function hostedState(link: Link, artifactId: string): HostedState | undef
|
|
|
43
54
|
}
|
|
44
55
|
|
|
45
56
|
/**
|
|
46
|
-
* Wraps the instance's `state/get`, `state/patch
|
|
47
|
-
* they act on its hosted home: the same params, the artifact named by its ID there.
|
|
57
|
+
* Wraps the instance's `state/get`, `state/patch`, `live/push` and `roster/*` so that, for a hosted
|
|
58
|
+
* artifact, they act on its hosted home: the same params, the artifact named by its ID there.
|
|
48
59
|
*/
|
|
49
60
|
export function forwardHosted(
|
|
50
61
|
link: Link,
|