@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.
Files changed (37) hide show
  1. package/dist/bin.js +152 -32
  2. package/dist/bin.js.map +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/{instance-DCiUHvgZ.js → instance-CBUlOmzG.js} +1215 -43
  5. package/dist/instance-CBUlOmzG.js.map +1 -0
  6. package/dist/reference/cli.md +112 -2
  7. package/dist/reference/diagnostics.json +27 -0
  8. package/dist/reference/errors/MOSTRA_TEAM_PRESENCE_RATE_LIMITED.md +23 -0
  9. package/dist/reference/errors/MOSTRA_TEAM_ROSTER_POLICY.md +23 -0
  10. package/dist/reference/errors/MOSTRA_TEAM_ROSTER_TOO_LARGE.md +23 -0
  11. package/dist/skill/SKILL.md +5 -3
  12. package/dist/skill/references/answers.md +3 -1
  13. package/dist/skill/references/mcp.md +2 -2
  14. package/dist/skill/references/teams.md +78 -0
  15. package/package.json +6 -6
  16. package/src/gateway/browser.ts +84 -1
  17. package/src/gateway/index.ts +40 -1
  18. package/src/gateway/team.ts +181 -0
  19. package/src/instance/index.ts +2 -1
  20. package/src/interaction/ephemeral.ts +21 -0
  21. package/src/interaction/events.ts +17 -0
  22. package/src/interaction/index.ts +265 -20
  23. package/src/interaction/roster.ts +585 -0
  24. package/src/interaction/team.ts +426 -0
  25. package/src/interaction/wait.ts +150 -0
  26. package/src/ledger/migrations.ts +35 -0
  27. package/src/link/hosted.ts +14 -3
  28. package/src/link/manager.ts +31 -1
  29. package/src/server/directory.ts +22 -0
  30. package/src/server/feed.ts +89 -3
  31. package/src/server/hosted.ts +54 -22
  32. package/src/server/index.ts +10 -0
  33. package/src/server/operator.ts +87 -28
  34. package/src/share/index.ts +50 -2
  35. package/src/verify/index.ts +7 -0
  36. package/src/verify/runner.ts +5 -1
  37. package/dist/instance-DCiUHvgZ.js.map +0 -1
@@ -41,6 +41,7 @@ import {
41
41
  remoteLogoutMethod,
42
42
  remoteStatusMethod,
43
43
  remoteTokenMethod,
44
+ rosterAddMethod,
44
45
  type ServerLiveValueParams,
45
46
  SubmissionEnvelope,
46
47
  type SubmissionPolicy,
@@ -335,6 +336,17 @@ export function createLink(options: LinkOptions): Link {
335
336
  const secret = /#t=([^&]+)/.exec(url)?.[1];
336
337
  if (secret !== undefined) options.protect(secret);
337
338
  };
339
+ /** Protects every capability link a value holds, at any depth. */
340
+ const protectLinksIn = (value: unknown, depth = 0): void => {
341
+ if (depth > 16) return;
342
+ if (typeof value === "string") {
343
+ if (value.includes("#t=")) protectLink(value);
344
+ } else if (Array.isArray(value)) {
345
+ for (const item of value) protectLinksIn(item, depth + 1);
346
+ } else if (value !== null && typeof value === "object") {
347
+ for (const item of Object.values(value)) protectLinksIn(item, depth + 1);
348
+ }
349
+ };
338
350
 
339
351
  const linkRow = (db: LedgerDb, server: string): LinkRow | undefined =>
340
352
  db.get<LinkRow>("SELECT * FROM remote_link WHERE server = ?", server);
@@ -1452,7 +1464,12 @@ export function createLink(options: LinkOptions): Link {
1452
1464
  }),
1453
1465
  );
1454
1466
  }
1455
- return session.call(definition, params, { timeoutMs: 30_000 });
1467
+ const answer = await session.call(definition, params, { timeoutMs: 30_000 });
1468
+ // A forwarded answer may carry the hosted home's capability links (`roster/add`'s personal
1469
+ // links, D168): whatever it carries is protected from the logs here, as the share's own link
1470
+ // is (Opus review 3).
1471
+ protectLinksIn(answer);
1472
+ return answer;
1456
1473
  },
1457
1474
  shares: () => ({
1458
1475
  mint: async (input) => {
@@ -1475,6 +1492,19 @@ export function createLink(options: LinkOptions): Link {
1475
1492
  ...(minted.expiresAt !== undefined ? { expiresAt: minted.expiresAt } : {}),
1476
1493
  };
1477
1494
  },
1495
+ respondents: async (input) => {
1496
+ // The roster is the hosted home's, its personal links hosted links (D168): each is
1497
+ // protected from the logs here as the share's own link is.
1498
+ const session = await self.session(input.server);
1499
+ const added = await session.call(rosterAddMethod, {
1500
+ artifact: { artifactId: input.artifactId },
1501
+ respondents: [...input.respondents],
1502
+ ...(input.scopes !== undefined ? { scopes: input.scopes } : {}),
1503
+ ...(input.ttl !== undefined ? { ttl: input.ttl } : {}),
1504
+ });
1505
+ for (const entry of added.links) protectLink(entry.link.url);
1506
+ return added.links;
1507
+ },
1478
1508
  url: (server, tokenId) => readLinks(server)[tokenId],
1479
1509
  revoke: async (server, tokenId) => {
1480
1510
  const session = await self.session(server);
@@ -207,4 +207,26 @@ export const SERVER_MIGRATIONS: readonly Migration[] = [
207
207
  db.exec("ALTER TABLE artifact_route ADD COLUMN removing_json TEXT");
208
208
  },
209
209
  },
210
+ {
211
+ version: 4,
212
+ name: "invitations in the outbound queue",
213
+ up(db) {
214
+ // WP-31 (D168): the operator's `invitations` port is delivered like `events` and `metering`,
215
+ // at least once from the same queue; a row keeps the link's token, never its URL. SQLite
216
+ // can't widen a CHECK in place, so the table is rebuilt with every row it holds.
217
+ db.exec(`
218
+ CREATE TABLE outbound_next (
219
+ id TEXT PRIMARY KEY,
220
+ port TEXT NOT NULL CHECK (port IN ('metering', 'events', 'invitations')),
221
+ payload_json TEXT NOT NULL,
222
+ attempts INTEGER NOT NULL DEFAULT 0,
223
+ next_attempt_at TEXT NOT NULL
224
+ );
225
+ INSERT INTO outbound_next (rowid, id, port, payload_json, attempts, next_attempt_at)
226
+ SELECT rowid, id, port, payload_json, attempts, next_attempt_at FROM outbound;
227
+ DROP TABLE outbound;
228
+ ALTER TABLE outbound_next RENAME TO outbound;
229
+ `);
230
+ },
231
+ },
210
232
  ];
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * A hosted home's events for its operator (INTERFACES §18.6, D165 item 9): `submission.accepted`
3
- * (with the submission's Results), `version.pushed` and `run.ended`, read from the home's own
3
+ * (with the submission's Results), `version.pushed`, `run.ended` and `roster.completed` (D168), and
4
+ * an invitation for each expected respondent with an email whom the roster added or gave a new
5
+ * personal link (`roster.changed`'s `added` and `relinked`), read from the home's own
4
6
  * event log after `operator_cursor` and handed to the server's durable outbound queue, so each is
5
7
  * delivered at least once with a stable ID (`<home>:<incarnation>:<cursor>`). The cursor moves
6
8
  * only after the queue holds what was read; a crash between them hands the same events again,
@@ -28,6 +30,8 @@ export interface OperatorFeedOptions {
28
30
  readonly operator: Operator;
29
31
  readonly meter: Meter;
30
32
  readonly account: () => string;
33
+ /** Who sends the home's invitations: its owner's name and how it was verified. */
34
+ readonly sender?: () => { readonly name?: string; readonly verifiedBy?: string };
31
35
  readonly routeOf: (
32
36
  artifactId: string,
33
37
  ) => { readonly id: string; readonly label: string } | undefined;
@@ -60,7 +64,7 @@ const RUN_ENDS = new Map([
60
64
  /** Starts the feed of a home. */
61
65
  export function createOperatorFeed(options: OperatorFeedOptions): OperatorFeed {
62
66
  const { ledger, operator, meter, log } = options;
63
- const wanted = operator.has.events || meter.on;
67
+ const wanted = operator.has.events || meter.on || operator.has.invitations;
64
68
  let stopped = false;
65
69
  let scheduled = false;
66
70
 
@@ -113,6 +117,17 @@ export function createOperatorFeed(options: OperatorFeedOptions): OperatorFeed {
113
117
  payload: { versionId: payload["versionId"], number: payload["number"] },
114
118
  };
115
119
  }
120
+ if (row.type === "roster.completed") {
121
+ return {
122
+ ...base,
123
+ kind: "roster.completed",
124
+ payload: {
125
+ round: payload["round"],
126
+ respondents: payload["respondents"],
127
+ submissions: payload["submissions"],
128
+ },
129
+ };
130
+ }
116
131
  const status = RUN_ENDS.get(row.type);
117
132
  if (status !== undefined) {
118
133
  return {
@@ -124,6 +139,72 @@ export function createOperatorFeed(options: OperatorFeedOptions): OperatorFeed {
124
139
  return undefined;
125
140
  };
126
141
 
142
+ /**
143
+ * The invitations a roster change calls for (D168): one per respondent it added or gave a new
144
+ * link, who has an email and is still expected, keyed by their link's token, so a repeated read
145
+ * enqueues nothing new and a later link gets an invitation of its own.
146
+ */
147
+ const invite = (row: EventRow): void => {
148
+ if (row.artifact_id === null) return;
149
+ const route = options.routeOf(row.artifact_id);
150
+ if (!route) return;
151
+ const payload = JSON.parse(row.payload_json) as {
152
+ added?: readonly { ref?: unknown }[];
153
+ relinked?: readonly unknown[];
154
+ };
155
+ const refs = new Set<string>([
156
+ ...(payload.added ?? []).flatMap((entry) =>
157
+ typeof entry.ref === "string" ? [entry.ref] : [],
158
+ ),
159
+ ...(payload.relinked ?? []).filter((ref): ref is string => typeof ref === "string"),
160
+ ]);
161
+ if (refs.size === 0) return;
162
+ const artifactId = row.artifact_id;
163
+ const found = ledger.read((db) => ({
164
+ title: db.get<{ title: string }>("SELECT title FROM artifact WHERE id = ?", artifactId)
165
+ ?.title,
166
+ entries: [...refs].flatMap((ref) => {
167
+ const entry = db.get<{
168
+ ref: string;
169
+ name: string | null;
170
+ email: string | null;
171
+ token_id: string | null;
172
+ }>(
173
+ "SELECT ref, name, email, token_id FROM roster_entry WHERE artifact_id = ? AND ref = ?",
174
+ artifactId,
175
+ ref,
176
+ );
177
+ return entry && entry.email !== null && entry.token_id !== null ? [entry] : [];
178
+ }),
179
+ }));
180
+ const sender = options.sender?.() ?? {};
181
+ for (const entry of found.entries) {
182
+ operator.enqueue({
183
+ port: "invitations",
184
+ invitation: {
185
+ invitationId: `${options.homeId}:${entry.token_id}`,
186
+ account: options.account(),
187
+ home: options.homeId,
188
+ routeId: route.id,
189
+ label: route.label,
190
+ artifactId,
191
+ title: found.title ?? "",
192
+ respondent: {
193
+ ref: entry.ref,
194
+ ...(entry.name !== null ? { name: entry.name } : {}),
195
+ email: entry.email as string,
196
+ },
197
+ sender: {
198
+ ...(sender.name !== undefined ? { name: sender.name } : {}),
199
+ ...(sender.verifiedBy !== undefined ? { verifiedBy: sender.verifiedBy } : {}),
200
+ },
201
+ tokenId: entry.token_id as string,
202
+ at: row.at,
203
+ },
204
+ });
205
+ }
206
+ };
207
+
127
208
  const scan = (): void => {
128
209
  scheduled = false;
129
210
  if (stopped) return;
@@ -140,13 +221,18 @@ export function createOperatorFeed(options: OperatorFeedOptions): OperatorFeed {
140
221
  db.all<EventRow>(
141
222
  `SELECT cursor, artifact_id, type, payload_json, at FROM event WHERE cursor > ?
142
223
  AND type IN ('submission.created', 'version.published', 'action.succeeded',
143
- 'action.failed', 'action.cancelled', 'action.unknown')
224
+ 'action.failed', 'action.cancelled', 'action.unknown',
225
+ 'roster.changed', 'roster.completed')
144
226
  ORDER BY cursor LIMIT ?`,
145
227
  cursor,
146
228
  PAGE,
147
229
  ),
148
230
  );
149
231
  for (const row of rows) {
232
+ if (row.type === "roster.changed") {
233
+ if (operator.has.invitations) invite(row);
234
+ continue;
235
+ }
150
236
  const event = toEvent(row);
151
237
  if (!event) continue;
152
238
  if (event.kind === "submission.accepted") {
@@ -128,6 +128,13 @@ export interface HostedHome {
128
128
  revokeLinks(artifactId: string): number;
129
129
  /** Revokes one link; `false` when this home has no such link. */
130
130
  revokeLink(tokenId: string): boolean;
131
+ /**
132
+ * A personal link's URL and expiry, built from its token now (an invitation's, D168), or
133
+ * `undefined` when it no longer works: revoked, expired, or made where it can't be shown again.
134
+ */
135
+ invitationLink(
136
+ tokenId: string,
137
+ ): { readonly url: string; readonly expiresAt?: string } | undefined;
131
138
  /**
132
139
  * Removes an artifact and everything of it from this home (`ServerHandle.remove`): its rows, its
133
140
  * version files no other version of the home names, and its route; its label is kept issued
@@ -248,6 +255,12 @@ export async function openHostedHome(options: HostedHomeOptions): Promise<Hosted
248
255
  const interaction = createInteraction({
249
256
  // A respondent on a hosted link learns only that the answer was sent (D165 item 1a).
250
257
  sentOnly: true,
258
+ // The owner is the account the home belongs to, signed in on its page (CO-07): it sees every
259
+ // respondent and every present viewer, whatever the artifact's visibility.
260
+ isOwner: (viewer) =>
261
+ options.services !== undefined &&
262
+ viewer.kind === "account" &&
263
+ viewer.ref === options.services.owner(id).account,
251
264
  ledger,
252
265
  log,
253
266
  faults: noFaults,
@@ -477,6 +490,8 @@ export async function openHostedHome(options: HostedHomeOptions): Promise<Hosted
477
490
  shellDir: options.shellDir,
478
491
  interaction,
479
492
  bus,
493
+ // `roster/add` asks the operator's `limits` for the personal links it mints (D168).
494
+ linkLimit: (artifactId, count) => linkLimit(artifactId, count),
480
495
  actions: relay,
481
496
  live: hostedLive,
482
497
  // Both channels: a hosted home has no host to narrow them (its owner is a host of it, D165).
@@ -646,32 +661,35 @@ export async function openHostedHome(options: HostedHomeOptions): Promise<Hosted
646
661
  };
647
662
 
648
663
  /**
649
- * `view/url` on a hosted home under the operator's `limits` (`link`): refused with its words, and
650
- * refused for now when the operator doesn't answer, since a link creates something (D165 item 9).
664
+ * New links on a hosted home under the operator's `limits` (`link`): `view/url`'s one, and the
665
+ * personal links `roster/add` mints (D168); refused with the operator's words, and refused for now
666
+ * when it doesn't answer, since a link creates something (D165 item 9).
651
667
  */
668
+ const linkLimit = async (artifactId: string, quantity?: number): Promise<void> => {
669
+ const services = options.services;
670
+ if (!services) return;
671
+ const route = routeOf(artifactId);
672
+ const verdict = await services.operator.limit({
673
+ account: services.owner(id).account,
674
+ home: id,
675
+ artifact: artifactId,
676
+ ...(route ? { routeId: route.id } : {}),
677
+ operation: "link",
678
+ ...(quantity !== undefined ? { quantity } : {}),
679
+ });
680
+ if (verdict.allowed === "unavailable") {
681
+ throw refuse(
682
+ "MOSTRA_REMOTE_OPERATOR_UNAVAILABLE",
683
+ "The server's operator didn't answer in time; try minting the link again.",
684
+ );
685
+ }
686
+ if (verdict.allowed === false) throw refuse("MOSTRA_REMOTE_LIMIT_REACHED", verdict.message);
687
+ };
652
688
  const limitedLinks = (method: MethodHandler): MethodHandler => ({
653
689
  definition: method.definition,
654
690
  async handle(params, session) {
655
- const services = options.services;
656
- if (services) {
657
- const ref = (params as { artifact?: unknown }).artifact;
658
- const artifactId = registry.get(canonicalRef(ref as never)).id;
659
- const route = routeOf(artifactId);
660
- const verdict = await services.operator.limit({
661
- account: services.owner(id).account,
662
- home: id,
663
- artifact: artifactId,
664
- ...(route ? { routeId: route.id } : {}),
665
- operation: "link",
666
- });
667
- if (verdict.allowed === "unavailable") {
668
- throw refuse(
669
- "MOSTRA_REMOTE_OPERATOR_UNAVAILABLE",
670
- "The server's operator didn't answer in time; try minting the link again.",
671
- );
672
- }
673
- if (verdict.allowed === false) throw refuse("MOSTRA_REMOTE_LIMIT_REACHED", verdict.message);
674
- }
691
+ const ref = (params as { artifact?: unknown }).artifact;
692
+ await linkLimit(registry.get(canonicalRef(ref as never)).id);
675
693
  return method.handle(params, session);
676
694
  },
677
695
  });
@@ -1119,6 +1137,13 @@ export async function openHostedHome(options: HostedHomeOptions): Promise<Hosted
1119
1137
  operator: options.services.operator,
1120
1138
  meter: options.services.meter,
1121
1139
  account: () => (options.services as HostedServices).owner(id).account,
1140
+ sender: () => {
1141
+ const owner = (options.services as HostedServices).owner(id);
1142
+ return {
1143
+ ...(owner.name !== undefined ? { name: owner.name } : {}),
1144
+ ...(owner.verifiedBy !== undefined ? { verifiedBy: owner.verifiedBy } : {}),
1145
+ };
1146
+ },
1122
1147
  routeOf,
1123
1148
  incarnation: () => incarnation,
1124
1149
  log,
@@ -1170,6 +1195,13 @@ export async function openHostedHome(options: HostedHomeOptions): Promise<Hosted
1170
1195
  },
1171
1196
  revokeLinks,
1172
1197
  revokeLink: (tokenId) => capabilities.revoke(tokenId) !== "unknown",
1198
+ invitationLink(tokenId) {
1199
+ const grant = capabilities.grant(tokenId);
1200
+ if (!grant?.live) return undefined;
1201
+ const url = gateway.reveal(tokenId);
1202
+ if (url === undefined) return undefined;
1203
+ return { url, ...(grant.expiresAt !== undefined ? { expiresAt: grant.expiresAt } : {}) };
1204
+ },
1173
1205
  async remove(artifactId) {
1174
1206
  /** The client files a version's listing names. */
1175
1207
  const clientFilesOf = async (versionId: string): Promise<string[]> => {
@@ -245,6 +245,16 @@ export async function startServer(options: ServerOptions): Promise<RemoteServer>
245
245
  handle,
246
246
  directory: data.directory,
247
247
  log,
248
+ // An invitation's link is built when it is handed over, never kept in the queue (D168).
249
+ invitationLink: async (homeId, tokenId) => {
250
+ // A home the directory no longer has can't build a link: its invitations go, while one
251
+ // that is only closed, drained or failing to open is tried again later.
252
+ const known = data.directory.read((db) =>
253
+ db.get("SELECT 1 FROM home WHERE id = ?", homeId),
254
+ );
255
+ if (known === undefined) return undefined;
256
+ return (await data.home(homeId)).assembled.invitationLink(tokenId);
257
+ },
248
258
  ...(Number(options.env["MOSTRA_TEST_OPERATOR_DISPATCH_MS"]) > 0
249
259
  ? { dispatchMs: Number(options.env["MOSTRA_TEST_OPERATOR_DISPATCH_MS"]) }
250
260
  : {}),
@@ -5,9 +5,10 @@
5
5
  * schemas; a call that throws, times out or answers what the schema refuses counts as no answer,
6
6
  * and each port's caller says what no answer means (`limits`: operations that create fail closed,
7
7
  * viewer input proceeds; `routing`: nothing is served; `policy`: nothing is added). Outbound
8
- * deliveries (`metering`, `events`) are kept in the directory's `outbound` table and retried with
9
- * backoff until the operator takes them, at least once and idempotent by their IDs, across
10
- * restarts.
8
+ * deliveries (`metering`, `events`, `invitations`) are kept in the directory's `outbound` table and
9
+ * retried with backoff until the operator takes them, at least once and idempotent by their IDs,
10
+ * across restarts. An invitation is kept by its link's token and handed over with the link built
11
+ * then, so the queue never holds a capability secret (D168).
11
12
  *
12
13
  * Without an operator module every port is its no-op default, and this module does nothing but
13
14
  * answer "allowed".
@@ -21,6 +22,7 @@ import {
21
22
  ChatHostPolicy as ChatHostPolicySchema,
22
23
  type CredentialResource,
23
24
  type IdentityProvider,
25
+ type Invitation,
24
26
  LimitAnswer,
25
27
  type LimitQuery,
26
28
  LinkHost,
@@ -70,6 +72,7 @@ export interface Operator {
70
72
  readonly linkHost: boolean;
71
73
  readonly events: boolean;
72
74
  readonly identity: boolean;
75
+ readonly invitations: boolean;
73
76
  };
74
77
  limit(q: LimitQuery): Promise<LimitVerdict>;
75
78
  linkPolicy(q: LinkQuery): Promise<LinkPolicy>;
@@ -95,7 +98,8 @@ export interface Operator {
95
98
  enqueue(
96
99
  item:
97
100
  | { readonly port: "events"; readonly event: OperatorEvent }
98
- | { readonly port: "metering"; readonly batch: MeterBatch },
101
+ | { readonly port: "metering"; readonly batch: MeterBatch }
102
+ | { readonly port: "invitations"; readonly invitation: QueuedInvitation },
99
103
  ): void;
100
104
  /** Delivers what waits now (tests; the dispatcher does it on its own). */
101
105
  flush(): Promise<void>;
@@ -112,8 +116,20 @@ export interface OperatorOptions {
112
116
  readonly now?: () => number;
113
117
  /** How often the outbound dispatcher looks for work; tests shorten it. */
114
118
  readonly dispatchMs?: number;
119
+ /**
120
+ * A personal link's URL, built from its token when an invitation is handed over (D168), or
121
+ * `undefined` when the link no longer works (revoked, expired, replaced): the queue never holds
122
+ * the URL, whose fragment is the link's secret.
123
+ */
124
+ readonly invitationLink?: (
125
+ home: string,
126
+ tokenId: string,
127
+ ) => Promise<{ readonly url: string; readonly expiresAt?: string } | undefined>;
115
128
  }
116
129
 
130
+ /** An invitation as the outbound queue keeps it: its link's token, never the link (D168). */
131
+ export type QueuedInvitation = Omit<Invitation, "url" | "expiresAt"> & { readonly tokenId: string };
132
+
117
133
  function configInvalid(message: string): RpcError {
118
134
  return new RpcError(createDiagnostic("MOSTRA_REMOTE_CONFIG_INVALID", { message }));
119
135
  }
@@ -234,11 +250,34 @@ export async function loadOperator(options: OperatorOptions): Promise<Operator>
234
250
  }): Promise<void> => {
235
251
  const payload = JSON.parse(row.payload_json) as unknown;
236
252
  try {
237
- await within(OPERATOR_TIME_LIMITS.outbound, () =>
238
- row.port === "events"
239
- ? ports.events?.deliver(payload as OperatorEvent)
240
- : ports.metering?.record(payload as MeterBatch),
241
- );
253
+ if (row.port === "invitations") {
254
+ const { tokenId, ...invitation } = payload as QueuedInvitation;
255
+ // Building the link opens its home: bounded like the hand-over, so a home that hangs
256
+ // can't stall the dispatcher (Opus review 4).
257
+ const link = await within(OPERATOR_TIME_LIMITS.outbound, () =>
258
+ options.invitationLink?.(invitation.home, tokenId),
259
+ );
260
+ if (link === undefined) {
261
+ // The link stopped working before it was handed over: inviting with it would mail a
262
+ // dead link, and a later one gets an invitation of its own.
263
+ directory.write((db) => db.run("DELETE FROM outbound WHERE id = ?", row.id));
264
+ log.info("operator.invitation_dropped", { invitationId: invitation.invitationId });
265
+ return;
266
+ }
267
+ await within(OPERATOR_TIME_LIMITS.outbound, () =>
268
+ ports.invitations?.send({
269
+ ...invitation,
270
+ url: link.url,
271
+ ...(link.expiresAt !== undefined ? { expiresAt: link.expiresAt } : {}),
272
+ }),
273
+ );
274
+ } else {
275
+ await within(OPERATOR_TIME_LIMITS.outbound, () =>
276
+ row.port === "events"
277
+ ? ports.events?.deliver(payload as OperatorEvent)
278
+ : ports.metering?.record(payload as MeterBatch),
279
+ );
280
+ }
242
281
  directory.write((db) => db.run("DELETE FROM outbound WHERE id = ?", row.id));
243
282
  } catch (error) {
244
283
  const delay = Math.min(OUTBOUND_MAX_BACKOFF_MS, 1_000 * 2 ** Math.min(row.attempts, 20));
@@ -263,23 +302,31 @@ export async function loadOperator(options: OperatorOptions): Promise<Operator>
263
302
  await Promise.resolve();
264
303
  try {
265
304
  for (;;) {
266
- // The oldest rows of each port, due or not: a port whose oldest delivery waits for its
267
- // retry waits whole, so an operator sees a home's events in the order they happened.
268
- const rows = directory.read((db) =>
269
- (["events", "metering"] as const).flatMap((port) =>
270
- db.all<{
271
- id: string;
272
- port: string;
273
- payload_json: string;
274
- attempts: number;
275
- next_attempt_at: string;
276
- }>(
305
+ // The oldest rows of each ordered port, due or not: a port whose oldest delivery waits
306
+ // for its retry waits whole, so an operator sees a home's events in the order they
307
+ // happened. Invitations have no order: each waits for its own retry and none holds
308
+ // another back, so one home that can't build its links never stops the server's
309
+ // other invitations (Opus review 4).
310
+ const due = new Date(now()).toISOString();
311
+ type Row = {
312
+ id: string;
313
+ port: string;
314
+ payload_json: string;
315
+ attempts: number;
316
+ next_attempt_at: string;
317
+ };
318
+ const rows = directory.read((db) => [
319
+ ...(["events", "metering"] as const).flatMap((port) =>
320
+ db.all<Row>(
277
321
  "SELECT id, port, payload_json, attempts, next_attempt_at FROM outbound WHERE port = ? ORDER BY rowid LIMIT 50",
278
322
  port,
279
323
  ),
280
324
  ),
281
- );
282
- const due = new Date(now()).toISOString();
325
+ ...db.all<Row>(
326
+ "SELECT id, port, payload_json, attempts, next_attempt_at FROM outbound WHERE port = 'invitations' AND next_attempt_at <= ? ORDER BY rowid LIMIT 50",
327
+ due,
328
+ ),
329
+ ]);
283
330
  if (rows.every((row) => row.next_attempt_at > due)) return;
284
331
  const blocked = new Set<string>();
285
332
  let delivered = 0;
@@ -294,8 +341,9 @@ export async function loadOperator(options: OperatorOptions): Promise<Operator>
294
341
  const still = directory.read((db) =>
295
342
  db.get<{ attempts: number }>("SELECT attempts FROM outbound WHERE id = ?", row.id),
296
343
  );
297
- if (still && still.attempts > before) blocked.add(row.port);
298
- else delivered += 1;
344
+ if (still && still.attempts > before) {
345
+ if (row.port !== "invitations") blocked.add(row.port);
346
+ } else delivered += 1;
299
347
  }
300
348
  if (delivered === 0) return;
301
349
  }
@@ -306,7 +354,7 @@ export async function loadOperator(options: OperatorOptions): Promise<Operator>
306
354
  return dispatching;
307
355
  };
308
356
  const timer =
309
- ports.events || ports.metering
357
+ ports.events || ports.metering || ports.invitations
310
358
  ? setInterval(() => void dispatch(), options.dispatchMs ?? 1_000)
311
359
  : undefined;
312
360
  timer?.unref();
@@ -324,6 +372,7 @@ export async function loadOperator(options: OperatorOptions): Promise<Operator>
324
372
  linkHost: typeof ports.routing?.linkHost === "function",
325
373
  events: typeof ports.events?.deliver === "function",
326
374
  identity: typeof ports.identity?.providers === "function",
375
+ invitations: typeof ports.invitations?.send === "function",
327
376
  };
328
377
 
329
378
  return {
@@ -474,9 +523,19 @@ export async function loadOperator(options: OperatorOptions): Promise<Operator>
474
523
  },
475
524
 
476
525
  enqueue(item) {
477
- if (item.port === "events" ? !has.events : !has.metering) return;
478
- const id = item.port === "events" ? item.event.eventId : item.batch.batchId;
479
- const payload = item.port === "events" ? item.event : item.batch;
526
+ if (!has[item.port]) return;
527
+ const id =
528
+ item.port === "events"
529
+ ? item.event.eventId
530
+ : item.port === "metering"
531
+ ? item.batch.batchId
532
+ : item.invitation.invitationId;
533
+ const payload =
534
+ item.port === "events"
535
+ ? item.event
536
+ : item.port === "metering"
537
+ ? item.batch
538
+ : item.invitation;
480
539
  directory.write((db) =>
481
540
  db.run(
482
541
  "INSERT OR IGNORE INTO outbound (id, port, payload_json, attempts, next_attempt_at) VALUES (?, ?, ?, 0, ?)",
@@ -27,6 +27,7 @@ import {
27
27
  durationMs,
28
28
  PUBLIC_SHARE_DEFAULT_TTL,
29
29
  PUBLIC_SHARE_MAX_TTL_MS,
30
+ type RespondentLink,
30
31
  RpcError,
31
32
  type Share,
32
33
  ShareId,
@@ -122,6 +123,17 @@ export interface RemoteShares {
122
123
  readonly hostname: string;
123
124
  readonly expiresAt?: string | undefined;
124
125
  }>;
126
+ /**
127
+ * Names expected respondents on the server's hosted home (`roster/add`, D168), each with a
128
+ * personal link there; idempotent by `ref`, so a retried share returns the same links.
129
+ */
130
+ respondents(input: {
131
+ readonly server: string;
132
+ readonly artifactId: string;
133
+ readonly respondents: NonNullable<ShareStartParams["respondents"]>;
134
+ readonly scopes?: ShareStartParams["scopes"];
135
+ readonly ttl?: ShareStartParams["ttl"];
136
+ }): Promise<readonly RespondentLink[]>;
125
137
  /** A minted link again, from what this home kept; `undefined` once it can't be. */
126
138
  url(server: string, tokenId: string): string | undefined;
127
139
  /** Revokes a link on the server's hosted home; fails with `MOSTRA_REMOTE_UNREACHABLE`. */
@@ -615,13 +627,49 @@ export function createShares(options: SharesOptions): Shares {
615
627
  }),
616
628
  );
617
629
  }
630
+ if (params.respondents !== undefined && params.respondents.length > 0) {
631
+ // Expected respondents are named on a hosted share (D168): their links are the hosted
632
+ // home's. Over a tunnel each viewer is already their own (a tailnet person, a link's own
633
+ // viewer), and `mostra roster add` names respondents with local personal links.
634
+ if (params.via !== "remote") {
635
+ throw new RpcError(
636
+ createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", {
637
+ message:
638
+ "Expected respondents are named on a share to a remote server (via remote); for local links use roster/add.",
639
+ }),
640
+ -32602,
641
+ );
642
+ }
643
+ if (params.viewer !== undefined) {
644
+ throw new RpcError(
645
+ createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", {
646
+ message:
647
+ "A share names either one viewer for its link or expected respondents, each with a link of their own: not both.",
648
+ }),
649
+ -32602,
650
+ );
651
+ }
652
+ }
653
+ const withRespondents = async (share: ShareStartResult): Promise<ShareStartResult> => {
654
+ const respondents = params.respondents;
655
+ if (respondents === undefined || respondents.length === 0 || !options.remote) return share;
656
+ const plan = JSON.parse((row(share.shareId) as ShareRow).plan_json) as Plan;
657
+ const links = await options.remote.respondents({
658
+ server: plan.server as string,
659
+ artifactId: detail.id,
660
+ respondents,
661
+ scopes: params.scopes,
662
+ ttl: params.ttl,
663
+ });
664
+ return { ...share, respondents: [...links] };
665
+ };
618
666
  const key = requestKey("share/start", params);
619
667
  if (key !== undefined) {
620
668
  const replay = ledger.read((db) => recordedResult<{ shareId: string }>(db, key));
621
669
  const found = replay ? row(replay.shareId) : undefined;
622
- if (found) return withUrl(toShare(found));
670
+ if (found) return withRespondents(withUrl(toShare(found)));
623
671
  }
624
- if (params.via === "remote") return startRemote(params, detail, key);
672
+ if (params.via === "remote") return withRespondents(await startRemote(params, detail, key));
625
673
  const ttlMs = lifetime(params.via, params.ttl);
626
674
  const shareId = ShareId.create();
627
675
  const { shell, artifact, plan, hostname } = await setUp(
@@ -492,6 +492,13 @@ export function createVerifier(options: VerifierOptions): Verifier {
492
492
  return { timedOut: true } as RenderResult;
493
493
  throw error;
494
494
  });
495
+ // A render the browser's own connection failure spoiled was rendered again (#132): said
496
+ // in the log, never in the verdict, since it says nothing of the artifact.
497
+ if (result.renderedAgain !== undefined)
498
+ options.log.info("verify.rendered_again", {
499
+ name,
500
+ why: options.redactor.redact(result.renderedAgain),
501
+ });
495
502
  // Every ARIA snapshot verify keeps is written through the redactor, the baseline's too
496
503
  // (D138 item 1, Opus review finding 8); the runner only reads it.
497
504
  if (result.aria) {
@@ -100,7 +100,11 @@ export function runnerEnvironment(env: Environment, browsers?: string): Environm
100
100
  if (browsers !== undefined) out["PLAYWRIGHT_BROWSERS_PATH"] = browsers;
101
101
  const idle = env["MOSTRA_TEST_VERIFY_IDLE_MS"];
102
102
  if (idle) out["MOSTRA_TEST_VERIFY_IDLE_MS"] = idle;
103
- for (const name of ["MOSTRA_TEST_VERIFY_LOSE_BROWSER", "MOSTRA_TEST_VERIFY_FAIL_ONCE"]) {
103
+ for (const name of [
104
+ "MOSTRA_TEST_VERIFY_LOSE_BROWSER",
105
+ "MOSTRA_TEST_VERIFY_FAIL_ONCE",
106
+ "MOSTRA_TEST_VERIFY_COLLIDE_ONCE",
107
+ ]) {
104
108
  const value = env[name];
105
109
  if (value) out[name] = value;
106
110
  }