@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
@@ -4,7 +4,7 @@ import { builtinModules, createRequire } from "node:module";
4
4
  import { accessSync, appendFileSync, chmodSync, closeSync, constants, createReadStream, createWriteStream, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync, writeSync } from "node:fs";
5
5
  import { basename, delimiter, dirname, extname, isAbsolute, join, relative, resolve, sep, win32 } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
- import { ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, ArtifactId, ArtifactManifest, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, CLI_CLIENT_NAME, CallRequest, ChooseRequest, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DeliveryId, EVENTS_NOTIFY, EnterRequest, FRAME_SESSION_HEADER, FieldsRequest, FollowRequest, HOST_PROTOCOL_REVISIONS, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, LinkId, LiveRequest, MAX_LINE_LENGTH, MutationId, PUBLIC_SHARE_DEFAULT_TTL, PUBLIC_SHARE_MAX_TTL_MS, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RpcError, RpcPeer, RunAttachRequest, RunCancelRequest, RunId, RunRequest, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SHELL_SESSION_HEADER, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, ServerEmitParams, ServerLiveValueParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, ShareId, ShellSubmitRequest, SignalRequest, StreamTicketRequest, SubmissionEnvelope, SubmissionId, SubmissionPolicy, SubmitRequest, TALLY_LIVE_PREFIX, TokenId, VERIFY_RUNNER_METHODS, VerifyVerdict, VersionId, ViewId, ViewerId, WORKER_METHODS, WorkerBatchParams, WorkerCallOutcome, WorkerPingResult, WorkerStartResult, ariaSummary, artifactCreateMethod, artifactExportMethod, artifactGetMethod, artifactImportMethod, artifactListMethod, artifactPauseMethod, artifactPublishMethod, artifactVerifyMethod, canonicalJson, checkArgumentFrames, checkRequest, createDiagnostic, depsAddMethod, devStartMethod, devStopMethod, durationMs, encodeLine, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fromBase64, gcRunMethod, hostedPushMethod, hostedSubmissionMethod, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, livePushMethod, manifestProblem, mostraInitializeMethod, mostraShutdownMethod, negotiateRevision, normalizeScopes, parseParams, portAddressingExternalBaseMethod, portDraftsMirrorMethod, portIdentityResolveMethod, portRelayAuthorMethod, portRelayCallMethod, portRelayCancelMethod, portRelayLiveMethod, portRelayReconcileMethod, portRelayRunMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, refusal, relayCallBatchMethod, relayEffectMethod, relayLiveValueMethod, relayRunUpdateMethod, remoteLinkMethod, remoteLoginMethod, remoteLoginWaitMethod, remoteLogoutMethod, remoteStatusMethod, remoteTokenMethod, resultsGetMethod, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretListMethod, secretSetMethod, serializeAll, shareListMethod, shareStartMethod, shareStopMethod, stateGetMethod, statePatchMethod, toBase64, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod } from "@mostra/protocol";
7
+ import { ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, ArtifactId, ArtifactManifest, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, CLI_CLIENT_NAME, CallRequest, ChooseRequest, DEFAULT_TEAM_VISIBILITY, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DeliveryId, EVENTS_NOTIFY, EnterRequest, FRAME_SESSION_HEADER, FieldsRequest, FollowRequest, HOST_PROTOCOL_REVISIONS, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, LinkId, LiveRequest, MAX_LINE_LENGTH, MutationId, PUBLIC_SHARE_DEFAULT_TTL, PUBLIC_SHARE_MAX_TTL_MS, PresenceRequest, RESULTS_LIST_MAX, ROSTER_MAX, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RespondentsRequest, RpcError, RpcPeer, RunAttachRequest, RunCancelRequest, RunId, RunRequest, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SHELL_SESSION_HEADER, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, ServerEmitParams, ServerLiveValueParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, ShareId, ShellSubmitRequest, SignalRequest, StreamTicketRequest, SubmissionEnvelope, SubmissionId, SubmissionPolicy, SubmitRequest, TALLY_LIVE_PREFIX, TokenId, VERIFY_RUNNER_METHODS, VerifyVerdict, VersionId, ViewId, ViewerId, WORKER_METHODS, WorkerBatchParams, WorkerCallOutcome, WorkerPingResult, WorkerStartResult, ariaSummary, artifactCreateMethod, artifactExportMethod, artifactGetMethod, artifactImportMethod, artifactListMethod, artifactPauseMethod, artifactPublishMethod, artifactVerifyMethod, canonicalJson, checkArgumentFrames, checkRequest, createDiagnostic, depsAddMethod, devStartMethod, devStopMethod, durationMs, encodeLine, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fromBase64, gcRunMethod, hostedPushMethod, hostedSubmissionMethod, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, livePushMethod, manifestProblem, mostraInitializeMethod, mostraShutdownMethod, negotiateRevision, normalizeScopes, parseParams, portAddressingExternalBaseMethod, portDraftsMirrorMethod, portIdentityResolveMethod, portRelayAuthorMethod, portRelayCallMethod, portRelayCancelMethod, portRelayLiveMethod, portRelayReconcileMethod, portRelayRunMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, refusal, relayCallBatchMethod, relayEffectMethod, relayLiveValueMethod, relayRunUpdateMethod, remoteLinkMethod, remoteLoginMethod, remoteLoginWaitMethod, remoteLogoutMethod, remoteStatusMethod, remoteTokenMethod, resultsGetMethod, resultsListMethod, rosterAddMethod, rosterGetMethod, rosterRemoveMethod, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretListMethod, secretSetMethod, serializeAll, shareListMethod, shareStartMethod, shareStopMethod, stateGetMethod, statePatchMethod, toBase64, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod } from "@mostra/protocol";
8
8
  import { createHash, createHmac, randomBytes, randomInt, randomUUID } from "node:crypto";
9
9
  import { connect, createConnection, createServer, isIP } from "node:net";
10
10
  import { execFile, execFileSync, spawn } from "node:child_process";
@@ -2896,6 +2896,37 @@ const MIGRATIONS = [
2896
2896
  SELECT artifact_id, by, reason, paused_at FROM artifact_pause;
2897
2897
  DROP TABLE artifact_pause;
2898
2898
  ALTER TABLE artifact_pause_by RENAME TO artifact_pause;
2899
+ `);
2900
+ }
2901
+ },
2902
+ {
2903
+ version: 16,
2904
+ name: "expected respondents and the roster's rounds",
2905
+ up(db) {
2906
+ db.exec(`
2907
+ CREATE TABLE roster_entry (
2908
+ artifact_id TEXT NOT NULL REFERENCES artifact(id),
2909
+ ref TEXT NOT NULL CHECK (length(ref) BETWEEN 1 AND 256),
2910
+ name TEXT,
2911
+ email TEXT,
2912
+ viewer_id TEXT NOT NULL REFERENCES viewer(id),
2913
+ token_id TEXT REFERENCES token(id),
2914
+ position INTEGER NOT NULL,
2915
+ added_at TEXT NOT NULL,
2916
+ PRIMARY KEY (artifact_id, ref),
2917
+ UNIQUE (artifact_id, viewer_id),
2918
+ UNIQUE (artifact_id, position)
2919
+ );
2920
+ CREATE TABLE roster_state (
2921
+ artifact_id TEXT PRIMARY KEY REFERENCES artifact(id),
2922
+ round INTEGER NOT NULL CHECK (round >= 1),
2923
+ round_cursor INTEGER NOT NULL CHECK (round_cursor >= 0),
2924
+ round_started_at TEXT NOT NULL,
2925
+ complete INTEGER NOT NULL CHECK (complete IN (0, 1))
2926
+ );
2927
+ CREATE TRIGGER roster_state_round_grows BEFORE UPDATE OF round, round_cursor ON roster_state
2928
+ WHEN NEW.round < OLD.round OR NEW.round_cursor < OLD.round_cursor
2929
+ BEGIN SELECT RAISE(ABORT, 'a roster round never goes back'); END;
2899
2930
  `);
2900
2931
  }
2901
2932
  }
@@ -5654,6 +5685,7 @@ function compactEvents(db, artifactId, before) {
5654
5685
  let removed = 0;
5655
5686
  let from = first.cursor;
5656
5687
  let latestVersion;
5688
+ let roster;
5657
5689
  for (const row of rows) {
5658
5690
  if (row.type === "artifact.compacted") {
5659
5691
  const earlier = JSON.parse(row.payload_json);
@@ -5661,10 +5693,22 @@ function compactEvents(db, artifactId, before) {
5661
5693
  removed += earlier.removed;
5662
5694
  for (const [type, count] of Object.entries(earlier.types)) types[type] = (types[type] ?? 0) + count;
5663
5695
  if (earlier.latestVersion) latestVersion = earlier.latestVersion;
5696
+ if (earlier.roster) roster = earlier.roster;
5664
5697
  continue;
5665
5698
  }
5666
5699
  removed += 1;
5667
5700
  types[row.type] = (types[row.type] ?? 0) + 1;
5701
+ if (row.type === "roster.completed") roster = {
5702
+ complete: true,
5703
+ completed: eventRecord(row)
5704
+ };
5705
+ else if (row.type === "roster.changed") {
5706
+ const complete = JSON.parse(row.payload_json).complete === true;
5707
+ roster = {
5708
+ complete,
5709
+ ...complete && roster?.completed ? { completed: roster.completed } : {}
5710
+ };
5711
+ }
5668
5712
  if (row.type === "version.published") {
5669
5713
  const payload = JSON.parse(row.payload_json);
5670
5714
  latestVersion = {
@@ -5679,7 +5723,8 @@ function compactEvents(db, artifactId, before) {
5679
5723
  through: last.cursor,
5680
5724
  removed,
5681
5725
  types,
5682
- ...latestVersion ? { latestVersion } : {}
5726
+ ...latestVersion ? { latestVersion } : {},
5727
+ ...roster ? { roster } : {}
5683
5728
  };
5684
5729
  db.run("DELETE FROM event WHERE artifact_id = ? AND cursor < ?", artifactId, before);
5685
5730
  db.run("INSERT INTO event (cursor, artifact_id, seq, type, actor_json, causation_json, payload_json, at) VALUES (?, ?, ?, ?, ?, NULL, ?, ?)", last.cursor, artifactId, last.seq, COMPACTED, JSON.stringify({ kind: "mostra" }), JSON.stringify(summary), (/* @__PURE__ */ new Date()).toISOString());
@@ -7236,6 +7281,355 @@ function setPause(db, artifactId, change) {
7236
7281
  };
7237
7282
  }
7238
7283
  //#endregion
7284
+ //#region src/interaction/roster.ts
7285
+ /**
7286
+ * Expected respondents and their roster (D121, D168; CO-01 to CO-03, CO-07). An artifact names the
7287
+ * people it expects answers from; each acts as one viewer of kind `token` (D104) through a personal
7288
+ * link the gateway mints. The roster has rounds: under `once` one, complete while every respondent
7289
+ * has a submission; under `epochs` a new one after each completion, complete once every respondent
7290
+ * submitted since it began. A completion is a durable `roster.completed`, appended in the same
7291
+ * transaction as the submission (or roster change) that made it, so a wait, a host and the
7292
+ * operator's events hear it exactly once per completion.
7293
+ *
7294
+ * Every function here runs inside the caller's ledger transaction.
7295
+ */
7296
+ /** The roster's state: round 1 from the start of everything until the roster first changes it. */
7297
+ function stateOf(db, artifactId) {
7298
+ return db.get("SELECT * FROM roster_state WHERE artifact_id = ?", artifactId) ?? {
7299
+ artifact_id: artifactId,
7300
+ round: 1,
7301
+ round_cursor: 0,
7302
+ round_started_at: "",
7303
+ complete: 0
7304
+ };
7305
+ }
7306
+ function entries(db, artifactId) {
7307
+ return db.all("SELECT * FROM roster_entry WHERE artifact_id = ? ORDER BY position", artifactId);
7308
+ }
7309
+ function policyOf(db, artifactId) {
7310
+ return storedPolicy(db.get("SELECT policy_json FROM artifact WHERE id = ?", artifactId)?.policy_json ?? null);
7311
+ }
7312
+ function submissionStanding(db, artifactId, owner) {
7313
+ const policy = policyOf(db, artifactId);
7314
+ return {
7315
+ closesAll: policy.policy === "once" && policy.scope !== "per-viewer",
7316
+ visibility: owner ? "names" : teamVisibility(db, artifactId)
7317
+ };
7318
+ }
7319
+ /**
7320
+ * What viewers see of each other on an artifact (CO-07): its latest version's `team.visibility`,
7321
+ * else `private` (D168). The latest version decides for every view, so a version that narrows it
7322
+ * narrows it for pages of older versions too.
7323
+ */
7324
+ function teamVisibility(db, artifactId) {
7325
+ const row = db.get(`SELECT version.manifest_json FROM artifact JOIN version ON version.id = artifact.latest_version_id
7326
+ WHERE artifact.id = ?`, artifactId);
7327
+ if (!row) return DEFAULT_TEAM_VISIBILITY;
7328
+ try {
7329
+ const value = JSON.parse(row.manifest_json).team?.visibility;
7330
+ return value === "counts" || value === "names" || value === "private" ? value : DEFAULT_TEAM_VISIBILITY;
7331
+ } catch {
7332
+ return DEFAULT_TEAM_VISIBILITY;
7333
+ }
7334
+ }
7335
+ /**
7336
+ * A viewer's key as pages see it (D168): stable for one viewer of one artifact, different across
7337
+ * artifacts, and no viewer ID, which pages never learn of others (D104).
7338
+ */
7339
+ function peerKey(artifactId, viewerId) {
7340
+ return `vk_${createHash("sha256").update(`mostra/viewer-key\u0000${artifactId}\u0000${viewerId}`).digest("hex").slice(0, 24)}`;
7341
+ }
7342
+ /**
7343
+ * Where each respondent stands in the round (CO-03): `submitted` with a submission in it (under
7344
+ * `once`, their one submission; under `epochs`, their latest after the round began), else
7345
+ * `drafting` when they opened the artifact or wrote their draft in it, else `not-opened`.
7346
+ */
7347
+ function standings(db, artifactId, state) {
7348
+ const list = entries(db, artifactId);
7349
+ if (list.length === 0) return [];
7350
+ const inRound = new Map(db.all("SELECT s.viewer_id, s.id, s.created_at, s.position FROM submission s JOIN roster_entry r ON r.artifact_id = s.artifact_id AND r.viewer_id = s.viewer_id WHERE s.artifact_id = ? AND s.position > ? AND s.position = (SELECT MAX(t.position) FROM submission t WHERE t.artifact_id = s.artifact_id AND t.viewer_id = s.viewer_id)", artifactId, state.round_cursor).map((row) => [row.viewer_id, row]));
7351
+ const totals = new Map(db.all("SELECT s.viewer_id, COUNT(*) AS n FROM submission s JOIN roster_entry r ON r.artifact_id = s.artifact_id AND r.viewer_id = s.viewer_id WHERE s.artifact_id = ? GROUP BY s.viewer_id", artifactId).map((row) => [row.viewer_id, row.n]));
7352
+ const views = new Map(db.all("SELECT v.viewer_id, MIN(v.opened_at) AS first, MAX(v.opened_at) AS last FROM view v JOIN roster_entry r ON r.artifact_id = v.artifact_id AND r.viewer_id = v.viewer_id WHERE v.artifact_id = ? GROUP BY v.viewer_id", artifactId).map((row) => [row.viewer_id, row]));
7353
+ const wrote = new Map(db.all("SELECT d.viewer_id, MAX(f.updated_at) AS last FROM field f JOIN document d ON d.id = f.document_id JOIN roster_entry r ON r.artifact_id = d.artifact_id AND r.viewer_id = d.viewer_id WHERE d.artifact_id = ? AND d.scope = 'viewer' GROUP BY d.viewer_id", artifactId).map((row) => [row.viewer_id, row.last]));
7354
+ return list.map((entry) => {
7355
+ const submission = inRound.get(entry.viewer_id);
7356
+ const opened = views.get(entry.viewer_id);
7357
+ const activeAt = [opened?.last, wrote.get(entry.viewer_id)].filter((at) => typeof at === "string").sort().at(-1) ?? void 0;
7358
+ return {
7359
+ entry,
7360
+ status: submission ? "submitted" : activeAt !== void 0 && activeAt >= state.round_started_at ? "drafting" : "not-opened",
7361
+ ...opened ? { openedAt: opened.first } : {},
7362
+ ...activeAt !== void 0 ? { activeAt } : {},
7363
+ ...submission ? { submission: {
7364
+ id: submission.id,
7365
+ at: submission.created_at,
7366
+ position: submission.position
7367
+ } } : {},
7368
+ submissions: totals.get(entry.viewer_id) ?? 0
7369
+ };
7370
+ });
7371
+ }
7372
+ function countsOf(list) {
7373
+ return {
7374
+ total: list.length,
7375
+ notOpened: list.filter((one) => one.status === "not-opened").length,
7376
+ drafting: list.filter((one) => one.status === "drafting").length,
7377
+ submitted: list.filter((one) => one.status === "submitted").length
7378
+ };
7379
+ }
7380
+ /** Whether every respondent submitted in the round; an empty roster never has. */
7381
+ function completeOf(list) {
7382
+ return list.length > 0 && list.every((one) => one.status === "submitted");
7383
+ }
7384
+ /** The whole roster, as agents and hosts read it (`roster/get`, CO-03, CO-07). */
7385
+ function readRoster(db, artifactId, live = () => true) {
7386
+ const state = stateOf(db, artifactId);
7387
+ const list = standings(db, artifactId, state);
7388
+ return {
7389
+ round: state.round,
7390
+ complete: completeOf(list),
7391
+ visibility: teamVisibility(db, artifactId),
7392
+ counts: countsOf(list),
7393
+ respondents: list.map((one) => {
7394
+ const { entry } = one;
7395
+ return {
7396
+ ref: entry.ref,
7397
+ ...entry.name !== null ? { name: entry.name } : {},
7398
+ ...entry.email !== null ? { email: entry.email } : {},
7399
+ viewerId: entry.viewer_id,
7400
+ status: one.status,
7401
+ ...one.openedAt !== void 0 ? { openedAt: one.openedAt } : {},
7402
+ ...one.activeAt !== void 0 ? { activeAt: one.activeAt } : {},
7403
+ ...one.submission ? { submission: {
7404
+ id: one.submission.id,
7405
+ at: one.submission.at
7406
+ } } : {},
7407
+ submissions: one.submissions,
7408
+ ...entry.token_id !== null && live(entry.token_id) ? { tokenId: entry.token_id } : {},
7409
+ addedAt: entry.added_at
7410
+ };
7411
+ })
7412
+ };
7413
+ }
7414
+ /** Whether the artifact has any expected respondent. */
7415
+ function hasRoster(db, artifactId) {
7416
+ return db.get("SELECT 1 FROM roster_entry WHERE artifact_id = ? LIMIT 1", artifactId) !== void 0;
7417
+ }
7418
+ /**
7419
+ * Settles the roster after a change inside its transaction (a submission, an import, a roster
7420
+ * change): when the round became complete, appends `roster.completed` with each respondent's
7421
+ * submission in the round and, under `epochs`, begins the next round; when a roster change made a
7422
+ * complete round incomplete again (someone joined), says so. Returns whether it is complete now.
7423
+ */
7424
+ function settleRoster(db, artifactId, now) {
7425
+ if (!hasRoster(db, artifactId) && !db.get("SELECT 1 FROM roster_state WHERE artifact_id = ?", artifactId)) return false;
7426
+ const state = stateOf(db, artifactId);
7427
+ const list = standings(db, artifactId, state);
7428
+ const complete = completeOf(list);
7429
+ const ensure = () => {
7430
+ db.run("INSERT OR IGNORE INTO roster_state (artifact_id, round, round_cursor, round_started_at, complete) VALUES (?, 1, 0, '', 0)", artifactId);
7431
+ };
7432
+ if (complete && state.complete === 0) {
7433
+ ensure();
7434
+ const cursor = Number(appendEvent(db, {
7435
+ artifactId,
7436
+ type: "roster.completed",
7437
+ actor: { kind: "mostra" },
7438
+ payload: {
7439
+ round: state.round,
7440
+ respondents: list.length,
7441
+ submissions: list.map((one) => ({
7442
+ ref: one.entry.ref,
7443
+ submissionId: one.submission?.id ?? ""
7444
+ }))
7445
+ }
7446
+ }));
7447
+ if (policyOf(db, artifactId).policy === "epochs") {
7448
+ db.run("UPDATE roster_state SET round = round + 1, round_cursor = ?, round_started_at = ?, complete = 0 WHERE artifact_id = ?", cursor, now, artifactId);
7449
+ return false;
7450
+ }
7451
+ db.run("UPDATE roster_state SET complete = 1 WHERE artifact_id = ?", artifactId);
7452
+ return true;
7453
+ }
7454
+ if (!complete && state.complete === 1) db.run("UPDATE roster_state SET complete = 0 WHERE artifact_id = ?", artifactId);
7455
+ return complete;
7456
+ }
7457
+ function rosterTooLarge(count) {
7458
+ return new RpcError(createDiagnostic("MOSTRA_TEAM_ROSTER_TOO_LARGE", { message: `This change would give the roster ${count} expected respondents, more than ${ROSTER_MAX}.` }));
7459
+ }
7460
+ /**
7461
+ * Adds expected respondents (CO-01), idempotently by `ref`: one already there keeps their row and
7462
+ * link, and a name or email given again replaces theirs. `link` gives each respondent's personal
7463
+ * link's token (`current` is the one their row names, which the caller keeps while it works) and
7464
+ * runs in this transaction. Appends `roster.changed` when anything changed.
7465
+ */
7466
+ function addRespondents(db, input) {
7467
+ const seen = /* @__PURE__ */ new Set();
7468
+ const specs = input.respondents.filter((spec) => {
7469
+ if (seen.has(spec.ref)) return false;
7470
+ seen.add(spec.ref);
7471
+ return true;
7472
+ });
7473
+ const existing = new Map(entries(db, input.artifactId).map((entry) => [entry.ref, entry]));
7474
+ const fresh = specs.filter((spec) => !existing.has(spec.ref)).length;
7475
+ if (existing.size + fresh > ROSTER_MAX) throw rosterTooLarge(existing.size + fresh);
7476
+ let position = db.get("SELECT MAX(position) AS last FROM roster_entry WHERE artifact_id = ?", input.artifactId)?.last ?? 0;
7477
+ const added = [];
7478
+ const renamed = [];
7479
+ const relinked = [];
7480
+ const tokens = [];
7481
+ for (const spec of specs) {
7482
+ const viewerId = viewerForSpec(db, {
7483
+ ref: spec.ref,
7484
+ ...spec.name !== void 0 ? { name: spec.name } : {}
7485
+ });
7486
+ const entry = existing.get(spec.ref);
7487
+ const tokenId = input.link(viewerId, entry?.token_id ?? void 0);
7488
+ tokens.push({
7489
+ ref: spec.ref,
7490
+ tokenId
7491
+ });
7492
+ if (!entry) {
7493
+ position += 1;
7494
+ db.run("INSERT INTO roster_entry (artifact_id, ref, name, email, viewer_id, token_id, position, added_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", input.artifactId, spec.ref, spec.name ?? null, spec.email ?? null, viewerId, tokenId, position, input.now);
7495
+ added.push({
7496
+ ref: spec.ref,
7497
+ ...spec.name !== void 0 ? { name: spec.name } : {}
7498
+ });
7499
+ continue;
7500
+ }
7501
+ const name = spec.name ?? entry.name;
7502
+ const email = spec.email ?? entry.email;
7503
+ if (name !== entry.name || email !== entry.email || tokenId !== entry.token_id) {
7504
+ db.run("UPDATE roster_entry SET name = ?, email = ?, token_id = ? WHERE artifact_id = ? AND ref = ?", name, email, tokenId, input.artifactId, spec.ref);
7505
+ if (name !== entry.name) renamed.push({
7506
+ ref: spec.ref,
7507
+ ...name !== null ? { name } : {}
7508
+ });
7509
+ if (tokenId !== entry.token_id) relinked.push(spec.ref);
7510
+ }
7511
+ }
7512
+ if (added.length > 0 || renamed.length > 0 || relinked.length > 0) changed(db, input, {
7513
+ added,
7514
+ renamed,
7515
+ relinked,
7516
+ removed: []
7517
+ });
7518
+ return { tokens };
7519
+ }
7520
+ /**
7521
+ * Removes expected respondents by `ref` (D168); unknown ones are ignored. Their links, drafts and
7522
+ * submissions stay. Appends `roster.changed` and, when everyone still expected has answered,
7523
+ * `roster.completed`.
7524
+ */
7525
+ function removeRespondents(db, input) {
7526
+ const removed = [];
7527
+ for (const ref of new Set(input.refs)) if (db.run("DELETE FROM roster_entry WHERE artifact_id = ? AND ref = ?", input.artifactId, ref).changes > 0) removed.push(ref);
7528
+ if (removed.length > 0) changed(db, input, {
7529
+ added: [],
7530
+ renamed: [],
7531
+ relinked: [],
7532
+ removed
7533
+ });
7534
+ return { removed };
7535
+ }
7536
+ /** Appends `roster.changed` after settling the roster, so the event says where it stands. */
7537
+ function changed(db, input, change) {
7538
+ db.run("INSERT OR IGNORE INTO roster_state (artifact_id, round, round_cursor, round_started_at, complete) VALUES (?, 1, 0, '', 0)", input.artifactId);
7539
+ const before = stateOf(db, input.artifactId);
7540
+ const list = standings(db, input.artifactId, before);
7541
+ appendEvent(db, {
7542
+ artifactId: input.artifactId,
7543
+ type: "roster.changed",
7544
+ actor: input.actor,
7545
+ payload: {
7546
+ round: before.round,
7547
+ respondents: list.length,
7548
+ complete: completeOf(list),
7549
+ ...change.added.length > 0 ? { added: change.added } : {},
7550
+ ...change.renamed.length > 0 ? { renamed: change.renamed } : {},
7551
+ ...change.relinked.length > 0 ? { relinked: change.relinked } : {},
7552
+ ...change.removed.length > 0 ? { removed: change.removed } : {}
7553
+ }
7554
+ });
7555
+ settleRoster(db, input.artifactId, input.now);
7556
+ }
7557
+ function peerOf(artifactId, viewer, self) {
7558
+ return {
7559
+ key: peerKey(artifactId, viewer.id),
7560
+ self,
7561
+ kind: viewer.kind,
7562
+ ...viewer.name !== void 0 ? { name: viewer.name } : {},
7563
+ ...viewer.verified !== void 0 ? { verified: viewer.verified } : {}
7564
+ };
7565
+ }
7566
+ /**
7567
+ * The roster as one page may see it (CO-03, CO-07): the viewer's own entry always (when they are
7568
+ * expected), the counts under `counts` and `names`, every respondent under `names`, and everything
7569
+ * for the artifact's owner. Never another viewer's `ref`, email or viewer ID.
7570
+ */
7571
+ function rosterForPage(db, input) {
7572
+ const [one] = rosterForPages(db, {
7573
+ artifactId: input.artifactId,
7574
+ pages: [{
7575
+ viewerId: input.viewerId,
7576
+ owner: input.owner
7577
+ }],
7578
+ viewerOf: input.viewerOf
7579
+ });
7580
+ return one;
7581
+ }
7582
+ /**
7583
+ * The roster as each of several pages may see it, from one read of the standings (Opus review 9):
7584
+ * a change heard by many following pages costs one roster read, not one per page.
7585
+ */
7586
+ function rosterForPages(db, input) {
7587
+ const state = stateOf(db, input.artifactId);
7588
+ const list = standings(db, input.artifactId, state);
7589
+ const visibility = teamVisibility(db, input.artifactId);
7590
+ const viewers = /* @__PURE__ */ new Map();
7591
+ const viewerOf = (viewerId) => {
7592
+ let viewer = viewers.get(viewerId);
7593
+ if (!viewer) {
7594
+ viewer = input.viewerOf(viewerId);
7595
+ viewers.set(viewerId, viewer);
7596
+ }
7597
+ return viewer;
7598
+ };
7599
+ const counts = countsOf(list);
7600
+ const complete = completeOf(list);
7601
+ const byViewer = new Map(list.map((one) => [one.entry.viewer_id, one]));
7602
+ return input.pages.map((page) => {
7603
+ const project = (one) => {
7604
+ const viewer = viewerOf(one.entry.viewer_id);
7605
+ return {
7606
+ ...peerOf(input.artifactId, {
7607
+ ...viewer,
7608
+ ...one.entry.name !== null ? { name: one.entry.name } : {}
7609
+ }, one.entry.viewer_id === page.viewerId),
7610
+ status: one.status,
7611
+ ...one.openedAt !== void 0 ? { openedAt: one.openedAt } : {},
7612
+ ...one.submission ? { submittedAt: one.submission.at } : {}
7613
+ };
7614
+ };
7615
+ const own = byViewer.get(page.viewerId);
7616
+ const sees = page.owner ? "names" : visibility;
7617
+ return {
7618
+ visibility,
7619
+ owner: page.owner,
7620
+ round: state.round,
7621
+ ...own ? { self: project(own) } : {},
7622
+ ...sees !== "private" ? {
7623
+ counts,
7624
+ complete
7625
+ } : {},
7626
+ ...sees === "names" ? { respondents: list.map(project) } : {}
7627
+ };
7628
+ });
7629
+ }
7630
+ /** The roster's events' types: pages never see them (they name refs and emails, D168). */
7631
+ const ROSTER_EVENTS = /* @__PURE__ */ new Set(["roster.changed", "roster.completed"]);
7632
+ //#endregion
7239
7633
  //#region src/interaction/runs.ts
7240
7634
  /**
7241
7635
  * Action runs in the ledger (D24, D54, AC-02, AC-03; ARCHITECTURE §7): each invocation through
@@ -7635,6 +8029,87 @@ function submissionEvent(db, row) {
7635
8029
  };
7636
8030
  }
7637
8031
  /**
8032
+ * The latest roster event at or before `upTo` (`roster.changed` or `roster.completed`), or the
8033
+ * roster's state a compaction summary kept for the events it replaced (DATA_MODEL §4).
8034
+ */
8035
+ function latestRosterState(db, artifactId, upTo) {
8036
+ const row = db.get("SELECT * FROM event WHERE artifact_id = ? AND cursor <= ? AND type IN ('roster.changed', 'roster.completed', ?) ORDER BY cursor DESC LIMIT 1", artifactId, upTo, COMPACTED);
8037
+ if (!row) return void 0;
8038
+ const payload = JSON.parse(row.payload_json);
8039
+ if (row.type === "artifact.compacted") return payload["roster"];
8040
+ const lastCompleted = () => {
8041
+ const completed = db.get("SELECT * FROM event WHERE artifact_id = ? AND cursor <= ? AND type = 'roster.completed' ORDER BY cursor DESC LIMIT 1", artifactId, upTo);
8042
+ if (completed) return eventRecord(completed);
8043
+ const summary = db.get(`SELECT * FROM event WHERE artifact_id = ? AND cursor <= ? AND type = '${COMPACTED}' ORDER BY cursor DESC LIMIT 1`, artifactId, upTo);
8044
+ if (!summary) return void 0;
8045
+ return JSON.parse(summary.payload_json).roster?.completed;
8046
+ };
8047
+ if (row.type === "roster.completed") return {
8048
+ complete: true,
8049
+ completed: eventRecord(row)
8050
+ };
8051
+ if (payload["complete"] !== true) return { complete: false };
8052
+ const completed = lastCompleted();
8053
+ return completed ? {
8054
+ complete: true,
8055
+ completed
8056
+ } : { complete: true };
8057
+ }
8058
+ /**
8059
+ * `submitted:all` and `submitted:<N>` (D168, CO-02), under `once` per-viewer and `epochs`:
8060
+ * - `submitted:all` is the roster's completion. Under `once` per-viewer without an explicit
8061
+ * cursor it is level-triggered: the roster is complete now (its latest event says so), and the
8062
+ * latest `roster.completed` answers. Otherwise it is the first `roster.completed` after the
8063
+ * cursor, so an agent waits for each next completion (a roster that grew, an `epochs` round).
8064
+ * It is read from durable events only, so an owner instance answers it for a hosted artifact
8065
+ * from the events it follows.
8066
+ * - `submitted:<N>` counts submissions: under `once` per-viewer without an explicit cursor all of
8067
+ * them, otherwise those after the cursor; the N-th one's `submission.created` answers.
8068
+ * Under `once` per-artifact (one submission in all) only `submitted:1` can ever hold:
8069
+ * `MOSTRA_TEAM_ROSTER_POLICY` for the rest; under `none`, `MOSTRA_SUBMIT_POLICY_NONE`.
8070
+ */
8071
+ function checkTeamCondition(db, artifactId, until, after, upTo, explicitAfter) {
8072
+ const policy = storedPolicy(db.get("SELECT policy_json FROM artifact WHERE id = ?", artifactId)?.policy_json ?? null);
8073
+ if (policy.policy === "none") throw new RpcError(createDiagnostic("MOSTRA_SUBMIT_POLICY_NONE", { message: "This artifact's submission policy is none: nothing will be submitted to wait for." }));
8074
+ const count = until === "submitted:all" ? void 0 : Number(until.slice(10));
8075
+ if (count !== void 0 && (!Number.isSafeInteger(count) || count < 1 || count > 1e4)) throw new RpcError(createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", { message: "submitted:<N> takes a number of submissions from 1 to 10000." }), -32602);
8076
+ if (policy.policy === "once" && policy.scope !== "per-viewer" && count !== 1) throw new RpcError(createDiagnostic("MOSTRA_TEAM_ROSTER_POLICY", { message: `This artifact takes one submission in all (once, per-artifact), so ${until} could never hold.` }));
8077
+ const level = policy.policy === "once" && !explicitAfter;
8078
+ if (count !== void 0) {
8079
+ const from = level ? 0 : after;
8080
+ if (!level) checkCompaction(db, { artifacts: [artifactId] }, after);
8081
+ const row = db.get("SELECT * FROM submission WHERE artifact_id = ? AND position > ? AND position <= ? ORDER BY position LIMIT 1 OFFSET ?", artifactId, from, upTo, count - 1);
8082
+ if (row) return { event: submissionEvent(db, row) };
8083
+ return { cursor: Math.max(upTo, after) };
8084
+ }
8085
+ if (level) {
8086
+ const state = latestRosterState(db, artifactId, upTo);
8087
+ if (state?.complete && state.completed) return heldHere(db, state.completed) ? { event: state.completed } : { cursor: after };
8088
+ return { cursor: Math.max(upTo, after) };
8089
+ }
8090
+ checkCompaction(db, { artifacts: [artifactId] }, after);
8091
+ const completed = db.get("SELECT * FROM event WHERE artifact_id = ? AND cursor > ? AND cursor <= ? AND type = 'roster.completed' ORDER BY cursor LIMIT 1", artifactId, after, upTo);
8092
+ if (!completed) return { cursor: Math.max(upTo, after) };
8093
+ const event = eventRecord(completed);
8094
+ return heldHere(db, event) ? { event } : { cursor: Math.max(after, completed.cursor - 1) };
8095
+ }
8096
+ /**
8097
+ * Whether this home holds every submission a completion names. A local home always does (they
8098
+ * commit together); an owner instance copies a hosted `roster.completed` through its follow, while
8099
+ * the submissions arrive by delivery, so a wait answers only once the last one is imported and
8100
+ * `results` holds every answer the completion counts (J14). The import's commit wakes the wait.
8101
+ */
8102
+ function heldHere(db, completed) {
8103
+ const named = completed.payload["submissions"];
8104
+ if (!Array.isArray(named)) return true;
8105
+ for (const entry of named) {
8106
+ const id = entry?.submissionId;
8107
+ if (typeof id !== "string" || id === "") continue;
8108
+ if (!db.get("SELECT 1 FROM submission WHERE id = ?", id)) return false;
8109
+ }
8110
+ return true;
8111
+ }
8112
+ /**
7638
8113
  * Checks a condition once, inside the caller's read transaction: the event that satisfies it, or
7639
8114
  * the newest cursor examined. Throws `MOSTRA_SUBMIT_POLICY_NONE` for `submitted` on an artifact
7640
8115
  * without submissions, and `MOSTRA_HOST_CURSOR_COMPACTED` for a cursor inside a compacted range.
@@ -7643,6 +8118,7 @@ function checkCondition(db, artifactId, until, after, explicitAfter = true) {
7643
8118
  const upTo = latestCursor(db);
7644
8119
  const first = (sql, ...params) => db.get(`SELECT * FROM event WHERE artifact_id = ? AND cursor > ? AND cursor <= ? AND ${sql} ORDER BY cursor LIMIT 1`, artifactId, after, upTo, ...params);
7645
8120
  let found;
8121
+ if (until === "submitted:all" || /^submitted:[0-9]+$/.test(until)) return checkTeamCondition(db, artifactId, until, after, upTo, explicitAfter);
7646
8122
  if (until === "submitted") {
7647
8123
  const policy = storedPolicy(db.get("SELECT policy_json FROM artifact WHERE id = ?", artifactId)?.policy_json ?? null);
7648
8124
  if (policy.policy === "none") throw new RpcError(createDiagnostic("MOSTRA_SUBMIT_POLICY_NONE", { message: "This artifact's submission policy is none: nothing will be submitted to wait for." }));
@@ -7724,6 +8200,11 @@ const POLL_QUEUE_MAX = 1e3;
7724
8200
  * - a run's delta that continues the one queued for the run merges into it, losing nothing.
7725
8201
  */
7726
8202
  function coalesceInto(view, queue, message) {
8203
+ if (message.kind === "respondents" || message.kind === "presence") {
8204
+ for (let index = queue.length - 1; index >= 0; index--) if (queue[index].kind === message.kind) queue.splice(index, 1);
8205
+ queue.push(message);
8206
+ return;
8207
+ }
7727
8208
  if (message.kind === "live") {
7728
8209
  if (view.live.get(message.live.key)?.window === void 0 && message.live.value !== void 0) for (let index = queue.length - 1; index >= 0; index--) {
7729
8210
  const queued = queue[index];
@@ -7844,6 +8325,10 @@ function createEphemeralBus(options = {}) {
7844
8325
  if ((view.live.get(message.live.key)?.until ?? 0) > at) deliver(view, message);
7845
8326
  }
7846
8327
  },
8328
+ send(artifactId, viewId, message) {
8329
+ const view = views.get(viewId);
8330
+ if (view && view.artifactId === artifactId) deliver(view, message);
8331
+ },
7847
8332
  listen(artifactId, viewId, listener) {
7848
8333
  const view = viewOf(artifactId, viewId);
7849
8334
  view.listeners.add(listener);
@@ -7902,6 +8387,296 @@ function createEphemeralBus(options = {}) {
7902
8387
  };
7903
8388
  }
7904
8389
  //#endregion
8390
+ //#region src/interaction/team.ts
8391
+ /** How long a page stays present without posting again; pages post every 10 s. */
8392
+ const PRESENCE_LEASE_MS = 3e4;
8393
+ /** How long a view follows its roster after it read it; pages read again every 20 s. */
8394
+ const RESPONDENTS_LEASE_MS = 6e4;
8395
+ /** Creates team traffic over a bus. */
8396
+ function createTeamTraffic(options) {
8397
+ const { bus, source } = options;
8398
+ const now = options.now ?? Date.now;
8399
+ const present = /* @__PURE__ */ new Map();
8400
+ /** Each artifact's present views, so a fan-out reads only its own artifact's (Opus review 9). */
8401
+ const presentOn = /* @__PURE__ */ new Map();
8402
+ const put = (entry) => {
8403
+ present.set(entry.viewId, entry);
8404
+ let views = presentOn.get(entry.artifactId);
8405
+ if (!views) {
8406
+ views = /* @__PURE__ */ new Set();
8407
+ presentOn.set(entry.artifactId, views);
8408
+ }
8409
+ views.add(entry.viewId);
8410
+ };
8411
+ const drop = (viewId) => {
8412
+ const entry = present.get(viewId);
8413
+ if (!entry) return;
8414
+ present.delete(viewId);
8415
+ const views = presentOn.get(entry.artifactId);
8416
+ views?.delete(viewId);
8417
+ if (views?.size === 0) presentOn.delete(entry.artifactId);
8418
+ };
8419
+ const presentFor = function* (artifactId) {
8420
+ for (const viewId of presentOn.get(artifactId) ?? []) {
8421
+ const entry = present.get(viewId);
8422
+ if (entry) yield entry;
8423
+ }
8424
+ };
8425
+ const buckets = /* @__PURE__ */ new Map();
8426
+ const following = /* @__PURE__ */ new Map();
8427
+ const fanout = /* @__PURE__ */ new Map();
8428
+ const settle = /* @__PURE__ */ new Map();
8429
+ /** Lookups for one fan-out: each viewer's peer, the owner check and the visibility, read once. */
8430
+ const memo = (artifactId) => {
8431
+ const peers = /* @__PURE__ */ new Map();
8432
+ const owners = /* @__PURE__ */ new Map();
8433
+ let visibility;
8434
+ return {
8435
+ visibility: () => visibility ??= source.visibility(artifactId),
8436
+ isOwner: (viewerId) => {
8437
+ let owner = owners.get(viewerId);
8438
+ if (owner === void 0) {
8439
+ owner = source.isOwner(viewerId);
8440
+ owners.set(viewerId, owner);
8441
+ }
8442
+ return owner;
8443
+ },
8444
+ peer: (viewerId) => {
8445
+ let peer = peers.get(viewerId);
8446
+ if (!peer) {
8447
+ peer = source.peer(artifactId, viewerId);
8448
+ peers.set(viewerId, peer);
8449
+ }
8450
+ return peer;
8451
+ }
8452
+ };
8453
+ };
8454
+ /** Who is present on an artifact, as one viewer may see it. */
8455
+ const stateFor = (artifactId, viewerId, lookups = memo(artifactId)) => {
8456
+ const visibility = lookups.visibility();
8457
+ const sees = lookups.isOwner(viewerId) ? "names" : visibility;
8458
+ const at = now();
8459
+ const byViewer = /* @__PURE__ */ new Map();
8460
+ for (const entry of presentFor(artifactId)) {
8461
+ if (entry.until <= at) continue;
8462
+ const kept = byViewer.get(entry.viewerId);
8463
+ if (!kept || kept.at < entry.at) byViewer.set(entry.viewerId, entry);
8464
+ }
8465
+ const peerOf = (entry) => {
8466
+ const peer = lookups.peer(entry.viewerId);
8467
+ return {
8468
+ key: peer.key,
8469
+ self: entry.viewerId === viewerId,
8470
+ kind: peer.kind,
8471
+ ...peer.name !== void 0 ? { name: peer.name } : {},
8472
+ ...peer.verified !== void 0 ? { verified: peer.verified } : {},
8473
+ ...entry.cursor ? { cursor: entry.cursor } : {},
8474
+ ...entry.selection ? { selection: entry.selection } : {},
8475
+ at: new Date(entry.at).toISOString()
8476
+ };
8477
+ };
8478
+ const own = byViewer.get(viewerId);
8479
+ const others = [...byViewer.values()].filter((entry) => entry.viewerId !== viewerId);
8480
+ const peers = own ? [peerOf(own)] : [];
8481
+ if (sees === "names") {
8482
+ others.sort((a, b) => b.at - a.at);
8483
+ for (const entry of others.slice(0, 200)) peers.push(peerOf(entry));
8484
+ }
8485
+ return {
8486
+ visibility,
8487
+ peers,
8488
+ ...sees !== "private" ? { others: others.length } : {}
8489
+ };
8490
+ };
8491
+ /**
8492
+ * Sends each present view of an artifact what it may see now, when that differs from what it
8493
+ * last got: a view under `private` sees only itself, so others coming, moving and going send it
8494
+ * nothing (Opus review 2), and under `counts` only a change of the count does.
8495
+ */
8496
+ const fanOut = (artifactId) => {
8497
+ fanout.delete(artifactId);
8498
+ const at = now();
8499
+ const lookups = memo(artifactId);
8500
+ for (const entry of presentFor(artifactId)) {
8501
+ if (entry.until <= at) continue;
8502
+ try {
8503
+ const presence = stateFor(artifactId, entry.viewerId, lookups);
8504
+ const text = JSON.stringify(presence);
8505
+ if (text === entry.last) continue;
8506
+ entry.last = text;
8507
+ bus.send(artifactId, entry.viewId, {
8508
+ kind: "presence",
8509
+ presence
8510
+ });
8511
+ } catch (error) {
8512
+ options.log?.error("team.presence_failed", { error });
8513
+ }
8514
+ }
8515
+ };
8516
+ /** Schedules the artifact's next presence message, at most every {@link PRESENCE_FANOUT_MS}. */
8517
+ const changedPresence = (artifactId) => {
8518
+ if (fanout.has(artifactId)) return;
8519
+ const timer = setTimeout(() => fanOut(artifactId), 50);
8520
+ timer.unref?.();
8521
+ fanout.set(artifactId, timer);
8522
+ };
8523
+ /** Sends each following view its roster when it changed, from one read for all of them. */
8524
+ const sendRosters = (artifactId) => {
8525
+ settle.delete(artifactId);
8526
+ const at = now();
8527
+ const views = [];
8528
+ for (const [viewId, entry] of following) {
8529
+ if (entry.artifactId !== artifactId) continue;
8530
+ if (entry.until <= at) following.delete(viewId);
8531
+ else views.push([viewId, entry]);
8532
+ }
8533
+ if (views.length === 0) return;
8534
+ let rosters;
8535
+ try {
8536
+ rosters = source.rostersForPages(artifactId, views.map(([, entry]) => entry.viewerId));
8537
+ } catch (error) {
8538
+ options.log?.error("team.respondents_failed", { error });
8539
+ return;
8540
+ }
8541
+ views.forEach(([viewId, entry], index) => {
8542
+ const roster = rosters[index];
8543
+ if (!roster) return;
8544
+ const text = JSON.stringify(roster);
8545
+ if (text === entry.last) return;
8546
+ entry.last = text;
8547
+ try {
8548
+ bus.send(artifactId, viewId, {
8549
+ kind: "respondents",
8550
+ respondents: roster
8551
+ });
8552
+ } catch (error) {
8553
+ options.log?.error("team.respondents_failed", { error });
8554
+ }
8555
+ });
8556
+ };
8557
+ const stopTeam = source.onTeam((artifactId) => {
8558
+ let any = false;
8559
+ for (const entry of following.values()) if (entry.artifactId === artifactId) {
8560
+ any = true;
8561
+ break;
8562
+ }
8563
+ if (!any || settle.has(artifactId)) return;
8564
+ const timer = setTimeout(() => sendRosters(artifactId), 100);
8565
+ timer.unref?.();
8566
+ settle.set(artifactId, timer);
8567
+ });
8568
+ const sweep = setInterval(() => {
8569
+ const at = now();
8570
+ const left = /* @__PURE__ */ new Set();
8571
+ for (const [viewId, entry] of present) if (entry.until <= at) {
8572
+ drop(viewId);
8573
+ left.add(entry.artifactId);
8574
+ }
8575
+ for (const [viewId, entry] of following) if (entry.until <= at) following.delete(viewId);
8576
+ for (const [viewId, bucket] of buckets) if (bucket.refilled + 3e4 <= at) buckets.delete(viewId);
8577
+ for (const artifactId of left) changedPresence(artifactId);
8578
+ }, 1e3);
8579
+ sweep.unref?.();
8580
+ return {
8581
+ presence(page, request) {
8582
+ const at = now();
8583
+ const viewId = request.viewId;
8584
+ let entry = present.get(viewId);
8585
+ if (entry && (entry.artifactId !== page.artifactId || entry.viewerId !== page.viewerId)) {
8586
+ drop(viewId);
8587
+ entry = void 0;
8588
+ }
8589
+ const known = buckets.get(viewId);
8590
+ const stale = request.seq !== void 0 && known?.seq !== void 0 && request.seq <= known.seq;
8591
+ if (request.seq !== void 0 && !stale) {
8592
+ const remembered = known ?? {
8593
+ tokens: 20,
8594
+ refilled: at
8595
+ };
8596
+ remembered.seq = request.seq;
8597
+ buckets.set(viewId, remembered);
8598
+ }
8599
+ if (request.leave === true && entry && !stale) {
8600
+ drop(viewId);
8601
+ changedPresence(page.artifactId);
8602
+ return { state: stateFor(page.artifactId, page.viewerId) };
8603
+ }
8604
+ const bucket = buckets.get(viewId) ?? {
8605
+ tokens: 20,
8606
+ refilled: at
8607
+ };
8608
+ bucket.tokens = Math.min(20, bucket.tokens + (at - bucket.refilled) / 1e3 * 20);
8609
+ bucket.refilled = at;
8610
+ buckets.set(viewId, bucket);
8611
+ if (bucket.tokens < 1) return {
8612
+ limited: true,
8613
+ retryAfterMs: Math.ceil((1 - bucket.tokens) / 20 * 1e3)
8614
+ };
8615
+ bucket.tokens -= 1;
8616
+ if (stale || request.leave === true) return { state: stateFor(page.artifactId, page.viewerId) };
8617
+ if (!entry) {
8618
+ entry = {
8619
+ artifactId: page.artifactId,
8620
+ viewId,
8621
+ viewerId: page.viewerId,
8622
+ at,
8623
+ until: at + PRESENCE_LEASE_MS
8624
+ };
8625
+ put(entry);
8626
+ }
8627
+ if (request.cursor !== void 0) {
8628
+ if (request.cursor === null) delete entry.cursor;
8629
+ else entry.cursor = {
8630
+ x: request.cursor.x,
8631
+ y: request.cursor.y
8632
+ };
8633
+ }
8634
+ if (request.selection !== void 0) {
8635
+ if (request.selection === null) delete entry.selection;
8636
+ else entry.selection = {
8637
+ ...request.selection.element !== void 0 ? { element: request.selection.element } : {},
8638
+ ...request.selection.start !== void 0 ? { start: request.selection.start } : {},
8639
+ ...request.selection.end !== void 0 ? { end: request.selection.end } : {}
8640
+ };
8641
+ }
8642
+ entry.at = at;
8643
+ entry.until = at + PRESENCE_LEASE_MS;
8644
+ changedPresence(page.artifactId);
8645
+ const state = stateFor(page.artifactId, page.viewerId);
8646
+ entry.last = JSON.stringify(state);
8647
+ return { state };
8648
+ },
8649
+ respondents(page, viewId) {
8650
+ const roster = source.rosterForPage(page);
8651
+ following.set(viewId, {
8652
+ artifactId: page.artifactId,
8653
+ viewerId: page.viewerId,
8654
+ until: now() + RESPONDENTS_LEASE_MS,
8655
+ last: JSON.stringify(roster)
8656
+ });
8657
+ return roster;
8658
+ },
8659
+ presentCount() {
8660
+ const at = now();
8661
+ let count = 0;
8662
+ for (const entry of present.values()) if (entry.until > at) count += 1;
8663
+ return count;
8664
+ },
8665
+ close() {
8666
+ clearInterval(sweep);
8667
+ present.clear();
8668
+ presentOn.clear();
8669
+ buckets.clear();
8670
+ following.clear();
8671
+ stopTeam();
8672
+ for (const timer of fanout.values()) clearTimeout(timer);
8673
+ for (const timer of settle.values()) clearTimeout(timer);
8674
+ fanout.clear();
8675
+ settle.clear();
8676
+ }
8677
+ };
8678
+ }
8679
+ //#endregion
7905
8680
  //#region src/interaction/index.ts
7906
8681
  /**
7907
8682
  * The interaction core (ARCHITECTURE §6; IN-01 to IN-12, LL-01, LL-02): drafts and artifact
@@ -7939,6 +8714,7 @@ function versionNumber(db, versionId) {
7939
8714
  */
7940
8715
  function visibleTo(event, page, run) {
7941
8716
  const viewerId = page.viewerId;
8717
+ if (ROSTER_EVENTS.has(event.type)) return false;
7942
8718
  if (event.type.startsWith("draft.")) return event.payload["viewerId"] === viewerId;
7943
8719
  if (event.type.startsWith("host.")) return false;
7944
8720
  if (event.type.startsWith("action.")) {
@@ -7950,16 +8726,36 @@ function visibleTo(event, page, run) {
7950
8726
  return true;
7951
8727
  }
7952
8728
  /**
7953
- * Another viewer as a page sees them: kind and display name, never their viewer or view IDs
7954
- * (D104; Claude review finding 12). The name stays, so a conflict can say who changed a field.
8729
+ * Another viewer as a page sees them: kind, display name and their key on this artifact, never
8730
+ * their viewer or view IDs (D104; Claude review finding 12). The name stays, so a conflict can say
8731
+ * who changed a field, and the key lets a page tell two people of one name apart and match the
8732
+ * writer of a shared field to a respondent or a present viewer (D168, CO-05).
7955
8733
  */
7956
- function actorForPage(actor, viewerId) {
7957
- if (actor.kind !== "viewer" || actor.id === viewerId) return actor;
8734
+ function actorForPage(actor, viewerId, artifactId) {
8735
+ if (actor.kind !== "viewer" || actor.id === void 0) return actor;
8736
+ const key = peerKey(artifactId, actor.id);
8737
+ if (actor.id === viewerId) return {
8738
+ ...actor,
8739
+ key
8740
+ };
7958
8741
  return {
7959
8742
  kind: "viewer",
7960
- ...actor.name !== void 0 ? { name: actor.name } : {}
8743
+ ...actor.name !== void 0 ? { name: actor.name } : {},
8744
+ key
7961
8745
  };
7962
8746
  }
8747
+ /**
8748
+ * How a page sees an event of a submission (CO-07, D168): its own as it is; another viewer's
8749
+ * under `once` for the whole artifact as it is, since it closes every draft; otherwise only its
8750
+ * `submission.created`, and only as the visibility allows: none under `private`, without a name
8751
+ * or key under `counts`, named under `names`. Another viewer's deliveries tell a page nothing it
8752
+ * needs, so they never reach it there.
8753
+ */
8754
+ function submissionShown(event, viewerId, standing, submitterOf) {
8755
+ if ((event.type === "submission.created" ? String(event.payload["viewerId"] ?? "") : submitterOf(String(event.payload["submissionId"] ?? ""))) === viewerId || standing.closesAll) return "as-is";
8756
+ if (event.type !== "submission.created" || standing.visibility === "private") return "hidden";
8757
+ return standing.visibility === "counts" ? "anonymous" : "as-is";
8758
+ }
7963
8759
  /** An event as a page sees it: other viewers' identities left out. */
7964
8760
  function eventForPage(event, viewerId) {
7965
8761
  if (event.type === "worker.crashed") {
@@ -7976,21 +8772,24 @@ function eventForPage(event, viewerId) {
7976
8772
  payload
7977
8773
  };
7978
8774
  }
7979
- if (event.actor.kind !== "viewer" || event.actor.id === viewerId) return event;
8775
+ if (event.actor.kind !== "viewer" || event.actor.id === viewerId) return event.actor.kind === "viewer" ? {
8776
+ ...event,
8777
+ actor: actorForPage(event.actor, viewerId, event.artifactId ?? "")
8778
+ } : event;
7980
8779
  const { viewerId: _viewer, viewId: _view, ...payload } = event.payload;
7981
8780
  const causation = event.causation ? Object.fromEntries(Object.entries(event.causation).filter(([key]) => key !== "viewId")) : void 0;
7982
8781
  return {
7983
8782
  ...event,
7984
- actor: actorForPage(event.actor, viewerId),
8783
+ actor: actorForPage(event.actor, viewerId, event.artifactId ?? ""),
7985
8784
  ...causation ? { causation } : {},
7986
8785
  payload
7987
8786
  };
7988
8787
  }
7989
8788
  /** Fields as a page sees them: who last wrote each, without another viewer's ID. */
7990
- function fieldsForPage(fields, viewerId) {
8789
+ function fieldsForPage(fields, viewerId, artifactId) {
7991
8790
  return Object.fromEntries(Object.entries(fields).map(([id, field]) => [id, field.updatedBy ? {
7992
8791
  ...field,
7993
- updatedBy: actorForPage(field.updatedBy, viewerId)
8792
+ updatedBy: actorForPage(field.updatedBy, viewerId, artifactId)
7994
8793
  } : field]));
7995
8794
  }
7996
8795
  /**
@@ -8023,6 +8822,15 @@ function createInteraction(options) {
8023
8822
  }
8024
8823
  };
8025
8824
  const tallyListeners = /* @__PURE__ */ new Set();
8825
+ const teamListeners = /* @__PURE__ */ new Set();
8826
+ /** Tells the team routes an artifact's respondents' status may have changed (D168). */
8827
+ const touched = (artifactId) => {
8828
+ for (const listener of teamListeners) try {
8829
+ listener(artifactId);
8830
+ } catch (error) {
8831
+ log.error("interaction.team_listener_failed", { error });
8832
+ }
8833
+ };
8026
8834
  const { ledger, log, hosts } = options;
8027
8835
  const outbox = new Outbox({
8028
8836
  ledger,
@@ -8059,6 +8867,15 @@ function createInteraction(options) {
8059
8867
  kind: as,
8060
8868
  ...session.client ? { id: session.client.name } : {}
8061
8869
  });
8870
+ /** Whether a viewer is the artifact's owner (CO-07): the local user, or a hosted home's account. */
8871
+ const ownerOf = (db, viewerId) => {
8872
+ const row = db.get("SELECT kind, external_ref FROM viewer WHERE id = ?", viewerId);
8873
+ if (!row) return false;
8874
+ return options.isOwner ? options.isOwner({
8875
+ kind: row.kind,
8876
+ ref: row.external_ref
8877
+ }) : row.kind === "local";
8878
+ };
8062
8879
  return {
8063
8880
  start() {
8064
8881
  outbox.start();
@@ -8083,7 +8900,9 @@ function createInteraction(options) {
8083
8900
  pause: (artifactId, change) => ledger.write((db) => setPause(db, artifactId, change)),
8084
8901
  pauseOf: (artifactId) => ledger.read((db) => pauseOf(db, artifactId)),
8085
8902
  openView(input) {
8086
- return ledger.write((db) => openView(db, input));
8903
+ const viewId = ledger.write((db) => openView(db, input));
8904
+ touched(input.artifactId);
8905
+ return viewId;
8087
8906
  },
8088
8907
  viewControls(page, viewId) {
8089
8908
  return ledger.read((db) => viewControls(viewFor(db, viewId, page.artifactId, page.viewerId, page.tokenId)));
@@ -8122,20 +8941,31 @@ function createInteraction(options) {
8122
8941
  ...outcome.result,
8123
8942
  conflicts: outcome.result.conflicts.map((conflict) => conflict.updatedBy ? {
8124
8943
  ...conflict,
8125
- updatedBy: actorForPage(conflict.updatedBy, page.viewerId)
8944
+ updatedBy: actorForPage(conflict.updatedBy, page.viewerId, page.artifactId)
8126
8945
  } : conflict)
8127
8946
  };
8128
- if (outcome.changed && input.scope === "viewer") outbox.mirror(page.artifactId, page.viewerId);
8947
+ if (outcome.changed && input.scope === "viewer") {
8948
+ outbox.mirror(page.artifactId, page.viewerId);
8949
+ touched(page.artifactId);
8950
+ }
8129
8951
  return result;
8130
8952
  },
8131
8953
  importSubmission(envelope, source) {
8132
8954
  const owners = options.deliveryOwners?.(envelope.artifactId) ?? outbox.owners();
8133
- const answer = ledger.write((db) => importSubmission(db, {
8134
- envelope,
8135
- source,
8136
- owners,
8137
- owned: (inner, artifactId) => inner.get("SELECT 1 FROM hosted_artifact WHERE artifact_id = ? AND server = ?", artifactId, source.server) !== void 0
8138
- }));
8955
+ let created = false;
8956
+ const answer = ledger.write((db) => {
8957
+ const held = db.get("SELECT 1 FROM submission WHERE id = ?", envelope.submissionId);
8958
+ const result = importSubmission(db, {
8959
+ envelope,
8960
+ source,
8961
+ owners,
8962
+ owned: (inner, artifactId) => inner.get("SELECT 1 FROM hosted_artifact WHERE artifact_id = ? AND server = ?", artifactId, source.server) !== void 0
8963
+ });
8964
+ created = held === void 0 && db.get("SELECT 1 FROM submission WHERE id = ?", envelope.submissionId) !== void 0;
8965
+ if (created) settleRoster(db, envelope.artifactId, (/* @__PURE__ */ new Date()).toISOString());
8966
+ return result;
8967
+ });
8968
+ if (created) touched(envelope.artifactId);
8139
8969
  log.info("interaction.imported", {
8140
8970
  artifactId: envelope.artifactId,
8141
8971
  submissionId: envelope.submissionId,
@@ -8177,16 +9007,21 @@ function createInteraction(options) {
8177
9007
  },
8178
9008
  submit(page, input) {
8179
9009
  const owners = options.deliveryOwners?.(page.artifactId) ?? outbox.owners();
8180
- const outcome = asPage(() => ledger.write((db) => submit(db, {
8181
- artifactId: page.artifactId,
8182
- viewerId: page.viewerId,
8183
- ...page.tokenId !== void 0 ? { tokenId: page.tokenId } : {},
8184
- viewId: input.viewId,
8185
- expectedRevision: input.expectedRevision,
8186
- channel: input.channel,
8187
- owners,
8188
- covers: options.coverage
8189
- })));
9010
+ const outcome = asPage(() => ledger.write((db) => {
9011
+ const made = submit(db, {
9012
+ artifactId: page.artifactId,
9013
+ viewerId: page.viewerId,
9014
+ ...page.tokenId !== void 0 ? { tokenId: page.tokenId } : {},
9015
+ viewId: input.viewId,
9016
+ expectedRevision: input.expectedRevision,
9017
+ channel: input.channel,
9018
+ owners,
9019
+ covers: options.coverage
9020
+ });
9021
+ if (made.created) settleRoster(db, page.artifactId, (/* @__PURE__ */ new Date()).toISOString());
9022
+ return made;
9023
+ }));
9024
+ if (outcome.created) touched(page.artifactId);
8190
9025
  if (outcome.tallied) for (const listener of tallyListeners) try {
8191
9026
  listener(page.artifactId, outcome.tallied);
8192
9027
  } catch (error) {
@@ -8287,7 +9122,7 @@ function createInteraction(options) {
8287
9122
  const state = documentSnapshot(db, page.artifactId, null);
8288
9123
  return {
8289
9124
  ...state,
8290
- fields: fieldsForPage(state.fields, page.viewerId)
9125
+ fields: fieldsForPage(state.fields, page.viewerId, page.artifactId)
8291
9126
  };
8292
9127
  })(),
8293
9128
  ...latestOwn ? { submission: forPage(submissionSummary(db, latestOwn)) } : {},
@@ -8312,6 +9147,12 @@ function createInteraction(options) {
8312
9147
  if (!runs.has(runId)) runs.set(runId, runById(db, page.artifactId, runId));
8313
9148
  return runs.get(runId);
8314
9149
  };
9150
+ const standing = submissionStanding(db, page.artifactId, ownerOf(db, page.viewerId));
9151
+ const submitters = /* @__PURE__ */ new Map();
9152
+ const submitterOf = (submissionId) => {
9153
+ if (!submitters.has(submissionId)) submitters.set(submissionId, db.get("SELECT viewer_id FROM submission WHERE id = ?", submissionId)?.viewer_id);
9154
+ return submitters.get(submissionId);
9155
+ };
8315
9156
  for (;;) {
8316
9157
  const read = readEvents(db, {
8317
9158
  filter: { artifacts: [page.artifactId] },
@@ -8325,6 +9166,16 @@ function createInteraction(options) {
8325
9166
  };
8326
9167
  cursor = Number(event.cursor);
8327
9168
  if (options.sentOnly && DELIVERY_EVENTS.has(event.type)) continue;
9169
+ if (event.type.startsWith("submission.")) {
9170
+ const shown = submissionShown(event, page.viewerId, standing, submitterOf);
9171
+ if (shown === "hidden") continue;
9172
+ const seen = eventForPage(event, page.viewerId);
9173
+ events.push(shown === "anonymous" ? {
9174
+ ...seen,
9175
+ actor: { kind: seen.actor.kind }
9176
+ } : seen);
9177
+ continue;
9178
+ }
8328
9179
  if (visibleTo(event, page, runOf)) events.push(eventForPage(event, page.viewerId));
8329
9180
  }
8330
9181
  cursor = Math.max(cursor, Number(read.cursor));
@@ -8374,6 +9225,26 @@ function createInteraction(options) {
8374
9225
  };
8375
9226
  });
8376
9227
  }),
9228
+ handler(resultsListMethod, (params) => {
9229
+ const artifactId = options.artifacts.resolve(params.artifact);
9230
+ const after = params.after === void 0 ? 0 : Number(params.after);
9231
+ const limit = params.limit ?? RESULTS_LIST_MAX;
9232
+ return ledger.read((db) => {
9233
+ const rows = db.all("SELECT * FROM submission WHERE artifact_id = ? AND position > ? ORDER BY position LIMIT ?", artifactId, after, limit + 1);
9234
+ const page = rows.slice(0, limit);
9235
+ return {
9236
+ results: page.map((row) => {
9237
+ const results = buildResults(db, row);
9238
+ return params.format === "md" ? {
9239
+ submissionId: row.id,
9240
+ markdown: resultsMarkdown(results, JSON.parse(row.snapshot_json))
9241
+ } : results;
9242
+ }),
9243
+ cursor: String(page.at(-1)?.position ?? after),
9244
+ more: rows.length > limit
9245
+ };
9246
+ });
9247
+ }),
8377
9248
  handler(waitMethod, (params, session) => waitFor({
8378
9249
  ledger,
8379
9250
  artifactId: options.artifacts.resolve(params.artifact),
@@ -8568,7 +9439,58 @@ function createInteraction(options) {
8568
9439
  tallyListeners.add(listener);
8569
9440
  return () => tallyListeners.delete(listener);
8570
9441
  },
8571
- subscriptionCount: () => subscriptions.size
9442
+ subscriptionCount: () => subscriptions.size,
9443
+ addRespondents(db, input) {
9444
+ const added = addRespondents(db, {
9445
+ ...input,
9446
+ now: (/* @__PURE__ */ new Date()).toISOString()
9447
+ });
9448
+ queueMicrotask(() => touched(input.artifactId));
9449
+ return added;
9450
+ },
9451
+ removeRespondents(db, input) {
9452
+ const removed = removeRespondents(db, {
9453
+ ...input,
9454
+ now: (/* @__PURE__ */ new Date()).toISOString()
9455
+ });
9456
+ queueMicrotask(() => touched(input.artifactId));
9457
+ return removed;
9458
+ },
9459
+ roster: (artifactId, live) => ledger.read((db) => readRoster(db, artifactId, live)),
9460
+ rosterForPage(page) {
9461
+ return ledger.read((db) => rosterForPage(db, {
9462
+ artifactId: page.artifactId,
9463
+ viewerId: page.viewerId,
9464
+ owner: ownerOf(db, page.viewerId),
9465
+ viewerOf: (viewerId) => viewer(db, viewerId)
9466
+ }));
9467
+ },
9468
+ rostersForPages(artifactId, viewerIds) {
9469
+ return ledger.read((db) => rosterForPages(db, {
9470
+ artifactId,
9471
+ pages: viewerIds.map((viewerId) => ({
9472
+ viewerId,
9473
+ owner: ownerOf(db, viewerId)
9474
+ })),
9475
+ viewerOf: (viewerId) => viewer(db, viewerId)
9476
+ }));
9477
+ },
9478
+ visibility: (artifactId) => ledger.read((db) => teamVisibility(db, artifactId)),
9479
+ isOwner: (viewerId) => ledger.read((db) => ownerOf(db, viewerId)),
9480
+ peer(artifactId, viewerId) {
9481
+ const record = ledger.read((db) => viewer(db, viewerId));
9482
+ return {
9483
+ key: peerKey(artifactId, viewerId),
9484
+ id: record.id,
9485
+ kind: record.kind,
9486
+ ...record.name !== void 0 ? { name: record.name } : {},
9487
+ ...record.verified !== void 0 ? { verified: record.verified } : {}
9488
+ };
9489
+ },
9490
+ onTeam(listener) {
9491
+ teamListeners.add(listener);
9492
+ return () => teamListeners.delete(listener);
9493
+ }
8572
9494
  };
8573
9495
  }
8574
9496
  //#endregion
@@ -9413,7 +10335,8 @@ const STATUS = {
9413
10335
  MOSTRA_HOME_DISK_FULL: 507,
9414
10336
  MOSTRA_HOME_GONE: 503,
9415
10337
  MOSTRA_HYGIENE_SCOPE_DENIED: 403,
9416
- MOSTRA_SUBMIT_PAUSED: 423
10338
+ MOSTRA_SUBMIT_PAUSED: 423,
10339
+ MOSTRA_TEAM_PRESENCE_RATE_LIMITED: 429
9417
10340
  };
9418
10341
  /** A refusal or a diagnostic as the browser gets it. */
9419
10342
  function answer(diagnostic, status, extra = {}) {
@@ -9425,6 +10348,15 @@ function answer(diagnostic, status, extra = {}) {
9425
10348
  function malformed(message) {
9426
10349
  return answer(refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", message).diagnostic, 400);
9427
10350
  }
10351
+ /** What an ephemeral message's SSE `data` carries: the message's own payload, by its kind. */
10352
+ function ephemeralData(message) {
10353
+ switch (message.kind) {
10354
+ case "run": return message.run;
10355
+ case "live": return message.live;
10356
+ case "respondents": return message.respondents;
10357
+ case "presence": return message.presence;
10358
+ }
10359
+ }
9428
10360
  /** Turns an interaction refusal into its response; anything else is a defect for `onError`. */
9429
10361
  function failure(error) {
9430
10362
  if (error instanceof SubmitConflict) return answer(error.diagnostic, 409, { submission: error.submission });
@@ -9592,7 +10524,7 @@ function browserRoutes(options) {
9592
10524
  wake?.();
9593
10525
  });
9594
10526
  const held = [];
9595
- const heldText = () => held.splice(0).map((message) => `event: ${message.kind}\ndata: ${JSON.stringify(message.kind === "run" ? message.run : message.live)}\n\n`).join("");
10527
+ const heldText = () => held.splice(0).map((message) => `event: ${message.kind}\ndata: ${JSON.stringify(ephemeralData(message))}\n\n`).join("");
9596
10528
  const unlisten = options.bus?.listen(page.artifactId, viewIdOf(context), (message) => {
9597
10529
  options.bus?.coalesce(page.artifactId, viewIdOf(context), held, message);
9598
10530
  if (held.length > EPHEMERAL_HELD) held.splice(0, held.length - EPHEMERAL_HELD);
@@ -9859,6 +10791,43 @@ function browserRoutes(options) {
9859
10791
  return failure(error);
9860
10792
  }
9861
10793
  };
10794
+ /** A handler of a team route without team traffic: this gateway serves neither (verify's). */
10795
+ const noTeam = () => answer(refusal("MOSTRA_HYGIENE_NOT_SERVED", "This gateway serves no respondents or presence.", 404).diagnostic, 404);
10796
+ /** `respondents` (D168): the roster as the page may see it, followed for a minute. */
10797
+ const respondents = async (context) => {
10798
+ const refused = knownRevision(context);
10799
+ if (refused) return refused;
10800
+ if (!options.team) return noTeam();
10801
+ const request = await body(context, RespondentsRequest);
10802
+ if (request instanceof Response) return request;
10803
+ const page = pageOf(context);
10804
+ try {
10805
+ interaction.checkView(page, request.viewId);
10806
+ return jsonResponse(options.team.respondents(page, request.viewId));
10807
+ } catch (error) {
10808
+ return failure(error);
10809
+ }
10810
+ };
10811
+ /** `presence` (D168, CO-04): joins, shares or leaves; never stored. */
10812
+ const presence = async (context) => {
10813
+ const refused = knownRevision(context);
10814
+ if (refused) return refused;
10815
+ if (!options.team) return noTeam();
10816
+ const request = await body(context, PresenceRequest);
10817
+ if (request instanceof Response) return request;
10818
+ const page = pageOf(context);
10819
+ try {
10820
+ interaction.checkView(page, request.viewId);
10821
+ } catch (error) {
10822
+ return failure(error);
10823
+ }
10824
+ const outcome = options.team.presence(page, request);
10825
+ if ("limited" in outcome) return jsonResponse(createDiagnostic("MOSTRA_TEAM_PRESENCE_RATE_LIMITED", { message: "This page sends presence faster than 20 updates a second." }), {
10826
+ status: 429,
10827
+ headers: { "retry-after": String(Math.max(1, Math.ceil(outcome.retryAfterMs / 1e3))) }
10828
+ });
10829
+ return jsonResponse(outcome.state);
10830
+ };
9862
10831
  return {
9863
10832
  fields,
9864
10833
  submit,
@@ -9866,6 +10835,8 @@ function browserRoutes(options) {
9866
10835
  stream,
9867
10836
  poll: pollFor(true),
9868
10837
  shellPoll: pollFor(false),
10838
+ respondents,
10839
+ presence,
9869
10840
  shellSubmit,
9870
10841
  choose,
9871
10842
  follow,
@@ -11263,6 +12234,124 @@ function fileResponse(file, request, headers) {
11263
12234
  });
11264
12235
  }
11265
12236
  //#endregion
12237
+ //#region src/gateway/team.ts
12238
+ /**
12239
+ * The roster's host methods (D121, D168; CO-01, CO-03, CO-07): `roster/add` names expected
12240
+ * respondents and gives each a personal link, `roster/remove` stops expecting them, `roster/get`
12241
+ * reads everyone's status. They live with the gateway because a personal link is a capability
12242
+ * link (D97): minted here, with the respondent's viewer (D104), in the same transaction as the
12243
+ * roster's change. The roster itself, its rounds and its completion are the interaction core's.
12244
+ */
12245
+ /** Who changed the roster: the client that called. */
12246
+ function actorOf(session) {
12247
+ return {
12248
+ kind: "agent",
12249
+ ...session.client ? { id: session.client.name } : {}
12250
+ };
12251
+ }
12252
+ /** The roster's host methods. */
12253
+ function rosterMethods(options) {
12254
+ const { ledger, interaction, capabilities } = options;
12255
+ const live = (tokenId) => capabilities.grant(tokenId)?.live === true;
12256
+ const roster = (artifactId) => interaction.roster(artifactId, live);
12257
+ return [
12258
+ handler(rosterAddMethod, async (params, session) => {
12259
+ const detail = options.artifacts.get(params.artifact);
12260
+ const version = options.versionOf(detail, params.version);
12261
+ if (!version) throw new RpcError(createDiagnostic("MOSTRA_ARTIFACT_VERSION_NOT_FOUND", { message: params.version === void 0 ? `The artifact ${detail.id} has no published version.` : `The artifact ${detail.id} has no version ${params.version}.` }));
12262
+ if (version.collected !== void 0) throw options.collected(version.number);
12263
+ const base = await options.linkBase(detail.id);
12264
+ const scopes = normalizeScopes(params.scopes ?? ALL_SCOPES).join(" ");
12265
+ const pinned = params.version === void 0 ? void 0 : version.number;
12266
+ /**
12267
+ * Whether a respondent's link is the one this request would mint: it works here (D97 items
12268
+ * 5, 10) with the same scopes, the same pinned version, and an expiry exactly when a `ttl` is
12269
+ * asked for (Opus review 6). Otherwise the respondent gets a new link; the old one isn't
12270
+ * revoked, since they may hold it already.
12271
+ */
12272
+ const reusable = (tokenId) => {
12273
+ const grant = capabilities.grant(tokenId);
12274
+ return grant?.live === true && grant.shellOrigin === base && normalizeScopes(grant.scopes).join(" ") === scopes && grant.pinnedVersion === pinned && grant.expiresAt !== void 0 === (params.ttl !== void 0);
12275
+ };
12276
+ const key = requestKey("roster/add", params);
12277
+ if (options.linkLimit) {
12278
+ if (!(key !== void 0 && ledger.read((db) => recordedResult(db, key)) !== void 0)) {
12279
+ const current = new Map(interaction.roster(detail.id, live).respondents.map((one) => [one.ref, one.tokenId]));
12280
+ let fresh = 0;
12281
+ for (const ref of new Set(params.respondents.map((one) => one.ref))) {
12282
+ const tokenId = current.get(ref);
12283
+ if (tokenId === void 0 || !reusable(tokenId)) fresh += 1;
12284
+ }
12285
+ if (fresh > 0) await options.linkLimit(detail.id, fresh);
12286
+ }
12287
+ }
12288
+ const minted = /* @__PURE__ */ new Map();
12289
+ const links = ledger.write((db) => {
12290
+ if (key !== void 0) {
12291
+ const row = recordedResult(db, key);
12292
+ if (row) return row.tokens;
12293
+ }
12294
+ const recorded = interaction.addRespondents(db, {
12295
+ artifactId: detail.id,
12296
+ respondents: params.respondents,
12297
+ actor: actorOf(session),
12298
+ link: (viewerId, current) => {
12299
+ if (current !== void 0 && reusable(current)) return current;
12300
+ const token = capabilities.mint({
12301
+ artifactId: detail.id,
12302
+ scopes: params.scopes,
12303
+ ttlMs: params.ttl === void 0 ? void 0 : durationMs(params.ttl),
12304
+ pinnedVersion: pinned,
12305
+ viewerId,
12306
+ shellOrigin: base
12307
+ }, db);
12308
+ minted.set(token.tokenId, token);
12309
+ return token.tokenId;
12310
+ }
12311
+ }).tokens.map((token) => ({
12312
+ ref: token.ref,
12313
+ tokenId: token.tokenId
12314
+ }));
12315
+ if (key !== void 0) recordResult(db, key, { tokens: recorded });
12316
+ return recorded;
12317
+ }).map(({ ref, tokenId }) => {
12318
+ const token = minted.get(tokenId) ?? capabilities.reveal(tokenId);
12319
+ if (!token) throw new RpcError(createDiagnostic("MOSTRA_HYGIENE_TOKEN_REVOKED", { message: `The personal link of ${ref} can't be shown again: the home's capability key changed. Add them again to give them a new one.` }));
12320
+ return {
12321
+ ref,
12322
+ link: options.link(token)
12323
+ };
12324
+ });
12325
+ return {
12326
+ roster: roster(detail.id),
12327
+ links
12328
+ };
12329
+ }),
12330
+ handler(rosterRemoveMethod, (params, session) => {
12331
+ const detail = options.artifacts.get(params.artifact);
12332
+ const key = requestKey("roster/remove", params);
12333
+ const removed = ledger.write((db) => {
12334
+ if (key !== void 0) {
12335
+ const row = recordedResult(db, key);
12336
+ if (row) return row.removed;
12337
+ }
12338
+ const outcome = interaction.removeRespondents(db, {
12339
+ artifactId: detail.id,
12340
+ refs: params.refs,
12341
+ actor: actorOf(session)
12342
+ });
12343
+ if (key !== void 0) recordResult(db, key, { removed: outcome.removed });
12344
+ return [...outcome.removed];
12345
+ });
12346
+ return {
12347
+ roster: roster(detail.id),
12348
+ removed
12349
+ };
12350
+ }),
12351
+ handler(rosterGetMethod, (params) => roster(options.artifacts.get(params.artifact).id))
12352
+ ];
12353
+ }
12354
+ //#endregion
11266
12355
  //#region src/gateway/worker.ts
11267
12356
  /**
11268
12357
  * Worker-mode frame sessions (D70, D158 item 5): where the shell and the artifact are two sites,
@@ -11635,6 +12724,20 @@ function laterArtifactRoutes(served, acting, ticket) {
11635
12724
  auth: "session",
11636
12725
  ...acting ? { handler: acting.live } : {}
11637
12726
  },
12727
+ {
12728
+ method: "POST",
12729
+ path: "/_mostra/v/:rev/respondents",
12730
+ intent: "mutation",
12731
+ auth: "session",
12732
+ handler: served.respondents
12733
+ },
12734
+ {
12735
+ method: "POST",
12736
+ path: "/_mostra/v/:rev/presence",
12737
+ intent: "mutation",
12738
+ auth: "session",
12739
+ handler: served.presence
12740
+ },
11638
12741
  {
11639
12742
  method: "POST",
11640
12743
  path: "/_mostra/v/:rev/ticket",
@@ -11662,7 +12765,13 @@ function laterArtifactRoutes(served, acting, ticket) {
11662
12765
  /** Creates the gateway; nothing is bound until {@link Gateway.start}. */
11663
12766
  function createGateway(options) {
11664
12767
  const { addressing, capabilities, artifacts, log, interaction } = options;
12768
+ const team = options.bus ? createTeamTraffic({
12769
+ bus: options.bus,
12770
+ source: interaction,
12771
+ log
12772
+ }) : void 0;
11665
12773
  const served = browserRoutes({
12774
+ ...team ? { team } : {},
11666
12775
  interaction,
11667
12776
  capabilities,
11668
12777
  log,
@@ -12902,6 +14011,17 @@ function createGateway(options) {
12902
14011
  by: entry.spec.by
12903
14012
  })),
12904
14013
  methods: () => [
14014
+ ...rosterMethods({
14015
+ ledger: options.ledger,
14016
+ interaction,
14017
+ capabilities,
14018
+ artifacts,
14019
+ versionOf,
14020
+ linkBase,
14021
+ link,
14022
+ collected: (number) => new RpcError(collectedDiagnostic(number)),
14023
+ ...options.linkLimit ? { linkLimit: options.linkLimit } : {}
14024
+ }),
12905
14025
  handler(viewUrlMethod, async (params) => {
12906
14026
  const detail = artifacts.get(params.artifact);
12907
14027
  const version = versionOf(detail, params.version);
@@ -12946,6 +14066,7 @@ function createGateway(options) {
12946
14066
  ],
12947
14067
  artifactOrigins: () => new Map([...artifactListeners].map(([artifactId, entry]) => [artifactId, addressing.origin(entry.port)])),
12948
14068
  async close() {
14069
+ team?.close();
12949
14070
  await Promise.allSettled([...opening.values(), ...openingFaces.values()]);
12950
14071
  await Promise.all([
12951
14072
  shellListener?.close(),
@@ -14667,7 +15788,11 @@ function runnerEnvironment(env, browsers) {
14667
15788
  if (browsers !== void 0) out["PLAYWRIGHT_BROWSERS_PATH"] = browsers;
14668
15789
  const idle = env["MOSTRA_TEST_VERIFY_IDLE_MS"];
14669
15790
  if (idle) out["MOSTRA_TEST_VERIFY_IDLE_MS"] = idle;
14670
- for (const name of ["MOSTRA_TEST_VERIFY_LOSE_BROWSER", "MOSTRA_TEST_VERIFY_FAIL_ONCE"]) {
15791
+ for (const name of [
15792
+ "MOSTRA_TEST_VERIFY_LOSE_BROWSER",
15793
+ "MOSTRA_TEST_VERIFY_FAIL_ONCE",
15794
+ "MOSTRA_TEST_VERIFY_COLLIDE_ONCE"
15795
+ ]) {
14671
15796
  const value = env[name];
14672
15797
  if (value) out[name] = value;
14673
15798
  }
@@ -15070,6 +16195,10 @@ function createVerifier(options) {
15070
16195
  if (error instanceof RpcError && error.diagnostic.code === "MOSTRA_VERIFY_TIMEOUT") return { timedOut: true };
15071
16196
  throw error;
15072
16197
  });
16198
+ if (result.renderedAgain !== void 0) options.log.info("verify.rendered_again", {
16199
+ name,
16200
+ why: options.redactor.redact(result.renderedAgain)
16201
+ });
15073
16202
  if (result.aria) {
15074
16203
  const text = options.redactor.redact(result.aria.text);
15075
16204
  await writeFile(result.aria.path, text);
@@ -18611,7 +19740,10 @@ function ownerInitialize(input) {
18611
19740
  const FORWARDED = /* @__PURE__ */ new Set([
18612
19741
  stateGetMethod.method,
18613
19742
  statePatchMethod.method,
18614
- livePushMethod.method
19743
+ livePushMethod.method,
19744
+ rosterAddMethod.method,
19745
+ rosterRemoveMethod.method,
19746
+ rosterGetMethod.method
18615
19747
  ]);
18616
19748
  /** Server code's `state` for an artifact hosted somewhere, else `undefined`. */
18617
19749
  function hostedState(link, artifactId) {
@@ -18634,8 +19766,8 @@ function hostedState(link, artifactId) {
18634
19766
  };
18635
19767
  }
18636
19768
  /**
18637
- * Wraps the instance's `state/get`, `state/patch` and `live/push` so that, for a hosted artifact,
18638
- * they act on its hosted home: the same params, the artifact named by its ID there.
19769
+ * Wraps the instance's `state/get`, `state/patch`, `live/push` and `roster/*` so that, for a hosted
19770
+ * artifact, they act on its hosted home: the same params, the artifact named by its ID there.
18639
19771
  */
18640
19772
  function forwardHosted(link, resolve, handlers) {
18641
19773
  return handlers.map((entry) => {
@@ -19196,6 +20328,14 @@ function createLink(options) {
19196
20328
  const secret = /#t=([^&]+)/.exec(url)?.[1];
19197
20329
  if (secret !== void 0) options.protect(secret);
19198
20330
  };
20331
+ /** Protects every capability link a value holds, at any depth. */
20332
+ const protectLinksIn = (value, depth = 0) => {
20333
+ if (depth > 16) return;
20334
+ if (typeof value === "string") {
20335
+ if (value.includes("#t=")) protectLink(value);
20336
+ } else if (Array.isArray(value)) for (const item of value) protectLinksIn(item, depth + 1);
20337
+ else if (value !== null && typeof value === "object") for (const item of Object.values(value)) protectLinksIn(item, depth + 1);
20338
+ };
19199
20339
  const linkRow = (db, server) => db.get("SELECT * FROM remote_link WHERE server = ?", server);
19200
20340
  const owned = (server) => (db, artifactId) => db.get("SELECT 1 FROM hosted_artifact WHERE artifact_id = ? AND server = ?", artifactId, server) !== void 0;
19201
20341
  /** A fresh access token, refreshing (and rotating the refresh token) when it's due. */
@@ -19998,7 +21138,9 @@ function createLink(options) {
19998
21138
  if (error instanceof RpcError) throw error;
19999
21139
  throw new RpcError(createDiagnostic("MOSTRA_REMOTE_UNREACHABLE", { message: `${server} can't be reached now; the hosted artifact's state lives there, so nothing was written.` }));
20000
21140
  }
20001
- return session.call(definition, params, { timeoutMs: 3e4 });
21141
+ const answer = await session.call(definition, params, { timeoutMs: 3e4 });
21142
+ protectLinksIn(answer);
21143
+ return answer;
20002
21144
  },
20003
21145
  shares: () => ({
20004
21146
  mint: async (input) => {
@@ -20023,6 +21165,16 @@ function createLink(options) {
20023
21165
  ...minted.expiresAt !== void 0 ? { expiresAt: minted.expiresAt } : {}
20024
21166
  };
20025
21167
  },
21168
+ respondents: async (input) => {
21169
+ const added = await (await self.session(input.server)).call(rosterAddMethod, {
21170
+ artifact: { artifactId: input.artifactId },
21171
+ respondents: [...input.respondents],
21172
+ ...input.scopes !== void 0 ? { scopes: input.scopes } : {},
21173
+ ...input.ttl !== void 0 ? { ttl: input.ttl } : {}
21174
+ });
21175
+ for (const entry of added.links) protectLink(entry.link.url);
21176
+ return added.links;
21177
+ },
20026
21178
  url: (server, tokenId) => readLinks(server)[tokenId],
20027
21179
  revoke: async (server, tokenId) => {
20028
21180
  await (await self.session(server)).call(viewRevokeMethod, { tokenId });
@@ -21447,13 +22599,33 @@ function createShares(options) {
21447
22599
  const start = async (params) => {
21448
22600
  const detail = options.artifacts.get(params.artifact);
21449
22601
  if (!detail.latestVersion && detail.versions.length === 0) throw new RpcError(createDiagnostic("MOSTRA_ARTIFACT_VERSION_NOT_FOUND", { message: `The artifact ${detail.id} has no published version to share.` }));
22602
+ if (params.respondents !== void 0 && params.respondents.length > 0) {
22603
+ if (params.via !== "remote") throw new RpcError(createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", { message: "Expected respondents are named on a share to a remote server (via remote); for local links use roster/add." }), -32602);
22604
+ if (params.viewer !== void 0) throw new RpcError(createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", { message: "A share names either one viewer for its link or expected respondents, each with a link of their own: not both." }), -32602);
22605
+ }
22606
+ const withRespondents = async (share) => {
22607
+ const respondents = params.respondents;
22608
+ if (respondents === void 0 || respondents.length === 0 || !options.remote) return share;
22609
+ const plan = JSON.parse(row(share.shareId).plan_json);
22610
+ const links = await options.remote.respondents({
22611
+ server: plan.server,
22612
+ artifactId: detail.id,
22613
+ respondents,
22614
+ scopes: params.scopes,
22615
+ ttl: params.ttl
22616
+ });
22617
+ return {
22618
+ ...share,
22619
+ respondents: [...links]
22620
+ };
22621
+ };
21450
22622
  const key = requestKey("share/start", params);
21451
22623
  if (key !== void 0) {
21452
22624
  const replay = ledger.read((db) => recordedResult(db, key));
21453
22625
  const found = replay ? row(replay.shareId) : void 0;
21454
- if (found) return withUrl(toShare(found));
22626
+ if (found) return withRespondents(withUrl(toShare(found)));
21455
22627
  }
21456
- if (params.via === "remote") return startRemote(params, detail, key);
22628
+ if (params.via === "remote") return withRespondents(await startRemote(params, detail, key));
21457
22629
  const ttlMs = lifetime(params.via, params.ttl);
21458
22630
  const shareId = ShareId.create();
21459
22631
  const { shell, artifact, plan, hostname } = await setUp(shareId, detail.id, params.via, void 0);
@@ -22289,7 +23461,7 @@ async function assemble(home, options) {
22289
23461
  dependenciesAdded: (artifact) => dev.dependenciesChanged(artifact)
22290
23462
  }),
22291
23463
  ...dev.methods(),
22292
- ...gateway.methods(),
23464
+ ...forwardHosted(link, (ref) => registry.get(canonicalRef(ref)).id, gateway.methods()),
22293
23465
  ...shares.methods(),
22294
23466
  ...link.methods(),
22295
23467
  ...forwardHosted(link, (ref) => registry.get(canonicalRef(ref)).id, interaction.methods()),
@@ -22519,4 +23691,4 @@ function sourceDirectory(path) {
22519
23691
  //#endregion
22520
23692
  export { markRunning as A, handler as B, jsonResponse as C, createEphemeralBus as D, createInteraction as E, BINDING_SUBPROTOCOL as F, readFieldCoverage as G, openLedger as H, MAX_FRAME_BYTES as I, coverageMatcher as J, readServerFunctions as K, serveWebSocket as L, markWaiting as M, runState as N, appendRunOutput as O, appendEvent as P, attachInProcess as R, isRefusal as S, openRegistry as T, faultsFrom as U, holdLock as V, noFaults as W, openFileLog as Y, resetOnClose as _, uninstallService as a, BASE_HEADERS as b, resolveHomePath as c, versionIdFor as d, createLive as f, shellAssetResponse as g, locateShell as h, serviceStatus as i, markUnknown as j, finishRun as k, canonicalRef as l, createGateway as m, startInstance as n, checkPlatform as o, liveMethods as p, readProcess as q, installService as r, platformName as s, runtimeVersion as t, listingDigest as u, Capabilities as v, readJsonObject as w, documentHeaders as x, capabilityKey as y, ProtocolServer as z };
22521
23693
 
22522
- //# sourceMappingURL=instance-DCiUHvgZ.js.map
23694
+ //# sourceMappingURL=instance-CBUlOmzG.js.map