@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
package/dist/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { A as markRunning, B as handler, C as jsonResponse, D as createEphemeralBus, E as createInteraction, F as BINDING_SUBPROTOCOL, G as readFieldCoverage, H as openLedger, I as MAX_FRAME_BYTES, J as coverageMatcher, K as readServerFunctions, L as serveWebSocket, M as markWaiting, N as runState, O as appendRunOutput, P as appendEvent, R as attachInProcess, S as isRefusal, T as openRegistry, U as faultsFrom, V as holdLock, W as noFaults, Y as openFileLog, _ as resetOnClose, a as uninstallService, b as BASE_HEADERS$1, c as resolveHomePath, d as versionIdFor, f as createLive, g as shellAssetResponse, h as locateShell, i as serviceStatus, j as markUnknown, k as finishRun, l as canonicalRef, m as createGateway, n as startInstance, o as checkPlatform, p as liveMethods, q as readProcess, r as installService, s as platformName, t as runtimeVersion, u as listingDigest, v as Capabilities, w as readJsonObject, x as documentHeaders, y as capabilityKey, z as ProtocolServer } from "./instance-DCiUHvgZ.js";
2
+ import { A as markRunning, B as handler, C as jsonResponse, D as createEphemeralBus, E as createInteraction, F as BINDING_SUBPROTOCOL, G as readFieldCoverage, H as openLedger, I as MAX_FRAME_BYTES, J as coverageMatcher, K as readServerFunctions, L as serveWebSocket, M as markWaiting, N as runState, O as appendRunOutput, P as appendEvent, R as attachInProcess, S as isRefusal, T as openRegistry, U as faultsFrom, V as holdLock, W as noFaults, Y as openFileLog, _ as resetOnClose, a as uninstallService, b as BASE_HEADERS$1, c as resolveHomePath, d as versionIdFor, f as createLive, g as shellAssetResponse, h as locateShell, i as serviceStatus, j as markUnknown, k as finishRun, l as canonicalRef, m as createGateway, n as startInstance, o as checkPlatform, p as liveMethods, q as readProcess, r as installService, s as platformName, t as runtimeVersion, u as listingDigest, v as Capabilities, w as readJsonObject, x as documentHeaders, y as capabilityKey, z as ProtocolServer } from "./instance-CBUlOmzG.js";
3
3
  import { c as removeTree, s as realPath } from "./files-DGeWuE4I.js";
4
4
  import { d as runtimeRoot, i as ownedDirectory } from "./directories-BLJjeSPD.js";
5
5
  import { createWriteStream, existsSync, linkSync, mkdirSync, readFileSync, renameSync, statfsSync, writeFileSync } from "node:fs";
@@ -2521,6 +2521,25 @@ const SERVER_MIGRATIONS = [
2521
2521
  up(db) {
2522
2522
  db.exec("ALTER TABLE artifact_route ADD COLUMN removing_json TEXT");
2523
2523
  }
2524
+ },
2525
+ {
2526
+ version: 4,
2527
+ name: "invitations in the outbound queue",
2528
+ up(db) {
2529
+ db.exec(`
2530
+ CREATE TABLE outbound_next (
2531
+ id TEXT PRIMARY KEY,
2532
+ port TEXT NOT NULL CHECK (port IN ('metering', 'events', 'invitations')),
2533
+ payload_json TEXT NOT NULL,
2534
+ attempts INTEGER NOT NULL DEFAULT 0,
2535
+ next_attempt_at TEXT NOT NULL
2536
+ );
2537
+ INSERT INTO outbound_next (rowid, id, port, payload_json, attempts, next_attempt_at)
2538
+ SELECT rowid, id, port, payload_json, attempts, next_attempt_at FROM outbound;
2539
+ DROP TABLE outbound;
2540
+ ALTER TABLE outbound_next RENAME TO outbound;
2541
+ `);
2542
+ }
2524
2543
  }
2525
2544
  ];
2526
2545
  //#endregion
@@ -2930,7 +2949,7 @@ const RUN_ENDS = /* @__PURE__ */ new Map([
2930
2949
  /** Starts the feed of a home. */
2931
2950
  function createOperatorFeed(options) {
2932
2951
  const { ledger, operator, meter, log } = options;
2933
- const wanted = operator.has.events || meter.on;
2952
+ const wanted = operator.has.events || meter.on || operator.has.invitations;
2934
2953
  let stopped = false;
2935
2954
  let scheduled = false;
2936
2955
  const cursorOf = () => ledger.read((db) => db.get("SELECT cursor FROM operator_cursor WHERE id = 1")?.cursor ?? -1);
@@ -2974,6 +2993,15 @@ function createOperatorFeed(options) {
2974
2993
  number: payload["number"]
2975
2994
  }
2976
2995
  };
2996
+ if (row.type === "roster.completed") return {
2997
+ ...base,
2998
+ kind: "roster.completed",
2999
+ payload: {
3000
+ round: payload["round"],
3001
+ respondents: payload["respondents"],
3002
+ submissions: payload["submissions"]
3003
+ }
3004
+ };
2977
3005
  const status = RUN_ENDS.get(row.type);
2978
3006
  if (status !== void 0) return {
2979
3007
  ...base,
@@ -2985,6 +3013,51 @@ function createOperatorFeed(options) {
2985
3013
  }
2986
3014
  };
2987
3015
  };
3016
+ /**
3017
+ * The invitations a roster change calls for (D168): one per respondent it added or gave a new
3018
+ * link, who has an email and is still expected, keyed by their link's token, so a repeated read
3019
+ * enqueues nothing new and a later link gets an invitation of its own.
3020
+ */
3021
+ const invite = (row) => {
3022
+ if (row.artifact_id === null) return;
3023
+ const route = options.routeOf(row.artifact_id);
3024
+ if (!route) return;
3025
+ const payload = JSON.parse(row.payload_json);
3026
+ const refs = /* @__PURE__ */ new Set([...(payload.added ?? []).flatMap((entry) => typeof entry.ref === "string" ? [entry.ref] : []), ...(payload.relinked ?? []).filter((ref) => typeof ref === "string")]);
3027
+ if (refs.size === 0) return;
3028
+ const artifactId = row.artifact_id;
3029
+ const found = ledger.read((db) => ({
3030
+ title: db.get("SELECT title FROM artifact WHERE id = ?", artifactId)?.title,
3031
+ entries: [...refs].flatMap((ref) => {
3032
+ const entry = db.get("SELECT ref, name, email, token_id FROM roster_entry WHERE artifact_id = ? AND ref = ?", artifactId, ref);
3033
+ return entry && entry.email !== null && entry.token_id !== null ? [entry] : [];
3034
+ })
3035
+ }));
3036
+ const sender = options.sender?.() ?? {};
3037
+ for (const entry of found.entries) operator.enqueue({
3038
+ port: "invitations",
3039
+ invitation: {
3040
+ invitationId: `${options.homeId}:${entry.token_id}`,
3041
+ account: options.account(),
3042
+ home: options.homeId,
3043
+ routeId: route.id,
3044
+ label: route.label,
3045
+ artifactId,
3046
+ title: found.title ?? "",
3047
+ respondent: {
3048
+ ref: entry.ref,
3049
+ ...entry.name !== null ? { name: entry.name } : {},
3050
+ email: entry.email
3051
+ },
3052
+ sender: {
3053
+ ...sender.name !== void 0 ? { name: sender.name } : {},
3054
+ ...sender.verifiedBy !== void 0 ? { verifiedBy: sender.verifiedBy } : {}
3055
+ },
3056
+ tokenId: entry.token_id,
3057
+ at: row.at
3058
+ }
3059
+ });
3060
+ };
2988
3061
  const scan = () => {
2989
3062
  scheduled = false;
2990
3063
  if (stopped) return;
@@ -2998,9 +3071,14 @@ function createOperatorFeed(options) {
2998
3071
  for (;;) {
2999
3072
  const rows = ledger.read((db) => db.all(`SELECT cursor, artifact_id, type, payload_json, at FROM event WHERE cursor > ?
3000
3073
  AND type IN ('submission.created', 'version.published', 'action.succeeded',
3001
- 'action.failed', 'action.cancelled', 'action.unknown')
3074
+ 'action.failed', 'action.cancelled', 'action.unknown',
3075
+ 'roster.changed', 'roster.completed')
3002
3076
  ORDER BY cursor LIMIT ?`, cursor, PAGE));
3003
3077
  for (const row of rows) {
3078
+ if (row.type === "roster.changed") {
3079
+ if (operator.has.invitations) invite(row);
3080
+ continue;
3081
+ }
3004
3082
  const event = toEvent(row);
3005
3083
  if (!event) continue;
3006
3084
  if (event.kind === "submission.accepted") meter.add("submissions", {
@@ -4241,6 +4319,7 @@ async function openHostedHome(options) {
4241
4319
  let protocol;
4242
4320
  const interaction = createInteraction({
4243
4321
  sentOnly: true,
4322
+ isOwner: (viewer) => options.services !== void 0 && viewer.kind === "account" && viewer.ref === options.services.owner(id).account,
4244
4323
  ledger,
4245
4324
  log,
4246
4325
  faults: noFaults,
@@ -4368,6 +4447,7 @@ async function openHostedHome(options) {
4368
4447
  shellDir: options.shellDir,
4369
4448
  interaction,
4370
4449
  bus,
4450
+ linkLimit: (artifactId, count) => linkLimit(artifactId, count),
4371
4451
  actions: relay,
4372
4452
  live: { read(page, input) {
4373
4453
  const states = live.read(page, input);
@@ -4507,27 +4587,30 @@ async function openHostedHome(options) {
4507
4587
  });
4508
4588
  };
4509
4589
  /**
4510
- * `view/url` on a hosted home under the operator's `limits` (`link`): refused with its words, and
4511
- * refused for now when the operator doesn't answer, since a link creates something (D165 item 9).
4590
+ * New links on a hosted home under the operator's `limits` (`link`): `view/url`'s one, and the
4591
+ * personal links `roster/add` mints (D168); refused with the operator's words, and refused for now
4592
+ * when it doesn't answer, since a link creates something (D165 item 9).
4512
4593
  */
4594
+ const linkLimit = async (artifactId, quantity) => {
4595
+ const services = options.services;
4596
+ if (!services) return;
4597
+ const route = routeOf(artifactId);
4598
+ const verdict = await services.operator.limit({
4599
+ account: services.owner(id).account,
4600
+ home: id,
4601
+ artifact: artifactId,
4602
+ ...route ? { routeId: route.id } : {},
4603
+ operation: "link",
4604
+ ...quantity !== void 0 ? { quantity } : {}
4605
+ });
4606
+ if (verdict.allowed === "unavailable") throw refuse("MOSTRA_REMOTE_OPERATOR_UNAVAILABLE", "The server's operator didn't answer in time; try minting the link again.");
4607
+ if (verdict.allowed === false) throw refuse("MOSTRA_REMOTE_LIMIT_REACHED", verdict.message);
4608
+ };
4513
4609
  const limitedLinks = (method) => ({
4514
4610
  definition: method.definition,
4515
4611
  async handle(params, session) {
4516
- const services = options.services;
4517
- if (services) {
4518
- const ref = params.artifact;
4519
- const artifactId = registry.get(canonicalRef(ref)).id;
4520
- const route = routeOf(artifactId);
4521
- const verdict = await services.operator.limit({
4522
- account: services.owner(id).account,
4523
- home: id,
4524
- artifact: artifactId,
4525
- ...route ? { routeId: route.id } : {},
4526
- operation: "link"
4527
- });
4528
- if (verdict.allowed === "unavailable") throw refuse("MOSTRA_REMOTE_OPERATOR_UNAVAILABLE", "The server's operator didn't answer in time; try minting the link again.");
4529
- if (verdict.allowed === false) throw refuse("MOSTRA_REMOTE_LIMIT_REACHED", verdict.message);
4530
- }
4612
+ const ref = params.artifact;
4613
+ await linkLimit(registry.get(canonicalRef(ref)).id);
4531
4614
  return method.handle(params, session);
4532
4615
  }
4533
4616
  });
@@ -4812,6 +4895,13 @@ async function openHostedHome(options) {
4812
4895
  operator: options.services.operator,
4813
4896
  meter: options.services.meter,
4814
4897
  account: () => options.services.owner(id).account,
4898
+ sender: () => {
4899
+ const owner = options.services.owner(id);
4900
+ return {
4901
+ ...owner.name !== void 0 ? { name: owner.name } : {},
4902
+ ...owner.verifiedBy !== void 0 ? { verifiedBy: owner.verifiedBy } : {}
4903
+ };
4904
+ },
4815
4905
  routeOf,
4816
4906
  incarnation: () => incarnation,
4817
4907
  log
@@ -4843,6 +4933,16 @@ async function openHostedHome(options) {
4843
4933
  },
4844
4934
  revokeLinks,
4845
4935
  revokeLink: (tokenId) => capabilities.revoke(tokenId) !== "unknown",
4936
+ invitationLink(tokenId) {
4937
+ const grant = capabilities.grant(tokenId);
4938
+ if (!grant?.live) return void 0;
4939
+ const url = gateway.reveal(tokenId);
4940
+ if (url === void 0) return void 0;
4941
+ return {
4942
+ url,
4943
+ ...grant.expiresAt !== void 0 ? { expiresAt: grant.expiresAt } : {}
4944
+ };
4945
+ },
4846
4946
  async remove(artifactId) {
4847
4947
  /** The client files a version's listing names. */
4848
4948
  const clientFilesOf = async (versionId) => {
@@ -5300,9 +5400,10 @@ function createMeter(options) {
5300
5400
  * schemas; a call that throws, times out or answers what the schema refuses counts as no answer,
5301
5401
  * and each port's caller says what no answer means (`limits`: operations that create fail closed,
5302
5402
  * viewer input proceeds; `routing`: nothing is served; `policy`: nothing is added). Outbound
5303
- * deliveries (`metering`, `events`) are kept in the directory's `outbound` table and retried with
5304
- * backoff until the operator takes them, at least once and idempotent by their IDs, across
5305
- * restarts.
5403
+ * deliveries (`metering`, `events`, `invitations`) are kept in the directory's `outbound` table and
5404
+ * retried with backoff until the operator takes them, at least once and idempotent by their IDs,
5405
+ * across restarts. An invitation is kept by its link's token and handed over with the link built
5406
+ * then, so the queue never holds a capability secret (D168).
5306
5407
  *
5307
5408
  * Without an operator module every port is its no-op default, and this module does nothing but
5308
5409
  * answer "allowed".
@@ -5395,7 +5496,20 @@ async function loadOperator(options) {
5395
5496
  const deliverOne = async (row) => {
5396
5497
  const payload = JSON.parse(row.payload_json);
5397
5498
  try {
5398
- await within(OPERATOR_TIME_LIMITS.outbound, () => row.port === "events" ? ports.events?.deliver(payload) : ports.metering?.record(payload));
5499
+ if (row.port === "invitations") {
5500
+ const { tokenId, ...invitation } = payload;
5501
+ const link = await within(OPERATOR_TIME_LIMITS.outbound, () => options.invitationLink?.(invitation.home, tokenId));
5502
+ if (link === void 0) {
5503
+ directory.write((db) => db.run("DELETE FROM outbound WHERE id = ?", row.id));
5504
+ log.info("operator.invitation_dropped", { invitationId: invitation.invitationId });
5505
+ return;
5506
+ }
5507
+ await within(OPERATOR_TIME_LIMITS.outbound, () => ports.invitations?.send({
5508
+ ...invitation,
5509
+ url: link.url,
5510
+ ...link.expiresAt !== void 0 ? { expiresAt: link.expiresAt } : {}
5511
+ }));
5512
+ } else await within(OPERATOR_TIME_LIMITS.outbound, () => row.port === "events" ? ports.events?.deliver(payload) : ports.metering?.record(payload));
5399
5513
  directory.write((db) => db.run("DELETE FROM outbound WHERE id = ?", row.id));
5400
5514
  } catch (error) {
5401
5515
  const delay = Math.min(OUTBOUND_MAX_BACKOFF_MS, 1e3 * 2 ** Math.min(row.attempts, 20));
@@ -5412,8 +5526,8 @@ async function loadOperator(options) {
5412
5526
  await Promise.resolve();
5413
5527
  try {
5414
5528
  for (;;) {
5415
- const rows = directory.read((db) => ["events", "metering"].flatMap((port) => db.all("SELECT id, port, payload_json, attempts, next_attempt_at FROM outbound WHERE port = ? ORDER BY rowid LIMIT 50", port)));
5416
5529
  const due = new Date(now()).toISOString();
5530
+ const rows = directory.read((db) => [...["events", "metering"].flatMap((port) => db.all("SELECT id, port, payload_json, attempts, next_attempt_at FROM outbound WHERE port = ? ORDER BY rowid LIMIT 50", port)), ...db.all("SELECT id, port, payload_json, attempts, next_attempt_at FROM outbound WHERE port = 'invitations' AND next_attempt_at <= ? ORDER BY rowid LIMIT 50", due)]);
5417
5531
  if (rows.every((row) => row.next_attempt_at > due)) return;
5418
5532
  const blocked = /* @__PURE__ */ new Set();
5419
5533
  let delivered = 0;
@@ -5426,8 +5540,9 @@ async function loadOperator(options) {
5426
5540
  const before = row.attempts;
5427
5541
  await deliverOne(row);
5428
5542
  const still = directory.read((db) => db.get("SELECT attempts FROM outbound WHERE id = ?", row.id));
5429
- if (still && still.attempts > before) blocked.add(row.port);
5430
- else delivered += 1;
5543
+ if (still && still.attempts > before) {
5544
+ if (row.port !== "invitations") blocked.add(row.port);
5545
+ } else delivered += 1;
5431
5546
  }
5432
5547
  if (delivered === 0) return;
5433
5548
  }
@@ -5437,7 +5552,7 @@ async function loadOperator(options) {
5437
5552
  })();
5438
5553
  return dispatching;
5439
5554
  };
5440
- const timer = ports.events || ports.metering ? setInterval(() => void dispatch(), options.dispatchMs ?? 1e3) : void 0;
5555
+ const timer = ports.events || ports.metering || ports.invitations ? setInterval(() => void dispatch(), options.dispatchMs ?? 1e3) : void 0;
5441
5556
  timer?.unref();
5442
5557
  const has = {
5443
5558
  limits: typeof ports.limits?.check === "function",
@@ -5451,7 +5566,8 @@ async function loadOperator(options) {
5451
5566
  routing: typeof ports.routing?.resolve === "function",
5452
5567
  linkHost: typeof ports.routing?.linkHost === "function",
5453
5568
  events: typeof ports.events?.deliver === "function",
5454
- identity: typeof ports.identity?.providers === "function"
5569
+ identity: typeof ports.identity?.providers === "function",
5570
+ invitations: typeof ports.invitations?.send === "function"
5455
5571
  };
5456
5572
  return {
5457
5573
  has,
@@ -5549,9 +5665,9 @@ async function loadOperator(options) {
5549
5665
  });
5550
5666
  },
5551
5667
  enqueue(item) {
5552
- if (item.port === "events" ? !has.events : !has.metering) return;
5553
- const id = item.port === "events" ? item.event.eventId : item.batch.batchId;
5554
- const payload = item.port === "events" ? item.event : item.batch;
5668
+ if (!has[item.port]) return;
5669
+ const id = item.port === "events" ? item.event.eventId : item.port === "metering" ? item.batch.batchId : item.invitation.invitationId;
5670
+ const payload = item.port === "events" ? item.event : item.port === "metering" ? item.batch : item.invitation;
5555
5671
  directory.write((db) => db.run("INSERT OR IGNORE INTO outbound (id, port, payload_json, attempts, next_attempt_at) VALUES (?, ?, ?, 0, ?)", `${item.port}:${id}`, item.port, JSON.stringify(payload), new Date(now()).toISOString()));
5556
5672
  dispatch();
5557
5673
  },
@@ -6210,6 +6326,10 @@ async function startServer(options) {
6210
6326
  handle,
6211
6327
  directory: data.directory,
6212
6328
  log,
6329
+ invitationLink: async (homeId, tokenId) => {
6330
+ if (data.directory.read((db) => db.get("SELECT 1 FROM home WHERE id = ?", homeId)) === void 0) return void 0;
6331
+ return (await data.home(homeId)).assembled.invitationLink(tokenId);
6332
+ },
6213
6333
  ...Number(options.env["MOSTRA_TEST_OPERATOR_DISPATCH_MS"]) > 0 ? { dispatchMs: Number(options.env["MOSTRA_TEST_OPERATOR_DISPATCH_MS"]) } : {}
6214
6334
  });
6215
6335
  } catch (error) {