@mostra/runtime 0.10.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 (257) hide show
  1. package/dist/bin.js +4178 -310
  2. package/dist/bin.js.map +1 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/{instance-FExcyENK.js → instance-CBUlOmzG.js} +1892 -85
  6. package/dist/instance-CBUlOmzG.js.map +1 -0
  7. package/dist/reference/cli.md +1432 -0
  8. package/dist/reference/diagnostics.json +1579 -0
  9. package/dist/reference/errors/MOSTRA_A11Y_MINOR.md +23 -0
  10. package/dist/reference/errors/MOSTRA_A11Y_SERIOUS.md +23 -0
  11. package/dist/reference/errors/MOSTRA_ACTION_CANCELLED.md +23 -0
  12. package/dist/reference/errors/MOSTRA_ACTION_EVENT_INVALID.md +23 -0
  13. package/dist/reference/errors/MOSTRA_ACTION_EXPORT_INVALID.md +23 -0
  14. package/dist/reference/errors/MOSTRA_ACTION_INTERRUPTED.md +23 -0
  15. package/dist/reference/errors/MOSTRA_ACTION_PAUSED.md +23 -0
  16. package/dist/reference/errors/MOSTRA_ACTION_RUN_NOT_FOUND.md +23 -0
  17. package/dist/reference/errors/MOSTRA_ACTION_THREW.md +23 -0
  18. package/dist/reference/errors/MOSTRA_ACTION_TOO_LARGE.md +23 -0
  19. package/dist/reference/errors/MOSTRA_ACTION_UNKNOWN_FUNCTION.md +23 -0
  20. package/dist/reference/errors/MOSTRA_ACTION_UNSERIALIZABLE.md +23 -0
  21. package/dist/reference/errors/MOSTRA_ARTIFACT_BUNDLE_INVALID.md +23 -0
  22. package/dist/reference/errors/MOSTRA_ARTIFACT_DIR_NOT_EMPTY.md +23 -0
  23. package/dist/reference/errors/MOSTRA_ARTIFACT_ENTRY_AMBIGUOUS.md +23 -0
  24. package/dist/reference/errors/MOSTRA_ARTIFACT_ID_DROPPED.md +23 -0
  25. package/dist/reference/errors/MOSTRA_ARTIFACT_NOT_FOUND.md +23 -0
  26. package/dist/reference/errors/MOSTRA_ARTIFACT_NO_ENTRY.md +23 -0
  27. package/dist/reference/errors/MOSTRA_ARTIFACT_NO_PAGE.md +23 -0
  28. package/dist/reference/errors/MOSTRA_ARTIFACT_PATCH_REJECTED.md +23 -0
  29. package/dist/reference/errors/MOSTRA_ARTIFACT_PATH_INVALID.md +23 -0
  30. package/dist/reference/errors/MOSTRA_ARTIFACT_SOURCE_MISSING.md +23 -0
  31. package/dist/reference/errors/MOSTRA_ARTIFACT_SOURCE_UNREADABLE.md +23 -0
  32. package/dist/reference/errors/MOSTRA_ARTIFACT_TEMPLATE_UNKNOWN.md +23 -0
  33. package/dist/reference/errors/MOSTRA_ARTIFACT_VERSION_COLLECTED.md +23 -0
  34. package/dist/reference/errors/MOSTRA_ARTIFACT_VERSION_NOT_FOUND.md +23 -0
  35. package/dist/reference/errors/MOSTRA_BUILD_CRASHED.md +23 -0
  36. package/dist/reference/errors/MOSTRA_BUILD_FAILED.md +23 -0
  37. package/dist/reference/errors/MOSTRA_BUILD_TIMEOUT.md +23 -0
  38. package/dist/reference/errors/MOSTRA_BUILD_UNRESOLVED.md +23 -0
  39. package/dist/reference/errors/MOSTRA_CLI_CONFIG_UNWRITABLE.md +23 -0
  40. package/dist/reference/errors/MOSTRA_CLI_UNKNOWN_COMMAND.md +23 -0
  41. package/dist/reference/errors/MOSTRA_CLI_USAGE.md +23 -0
  42. package/dist/reference/errors/MOSTRA_CONSOLE_ERROR.md +23 -0
  43. package/dist/reference/errors/MOSTRA_CONSOLE_WARNING.md +23 -0
  44. package/dist/reference/errors/MOSTRA_DEP_INSTALL_FAILED.md +23 -0
  45. package/dist/reference/errors/MOSTRA_DEP_MISSING.md +23 -0
  46. package/dist/reference/errors/MOSTRA_DEP_NOT_FOUND.md +23 -0
  47. package/dist/reference/errors/MOSTRA_DEP_OFFLINE.md +23 -0
  48. package/dist/reference/errors/MOSTRA_DEP_SPEC_INVALID.md +23 -0
  49. package/dist/reference/errors/MOSTRA_DEP_TIMEOUT.md +23 -0
  50. package/dist/reference/errors/MOSTRA_DEP_WARM_CONFLICT.md +23 -0
  51. package/dist/reference/errors/MOSTRA_ENV_BIND_FAILED.md +23 -0
  52. package/dist/reference/errors/MOSTRA_ENV_BROWSER_MISSING.md +23 -0
  53. package/dist/reference/errors/MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED.md +23 -0
  54. package/dist/reference/errors/MOSTRA_ENV_BUNDLE_INVALID.md +23 -0
  55. package/dist/reference/errors/MOSTRA_ENV_BUNDLE_UNAVAILABLE.md +23 -0
  56. package/dist/reference/errors/MOSTRA_ENV_HELPER_MISSING.md +23 -0
  57. package/dist/reference/errors/MOSTRA_ENV_NODE_UNSUPPORTED.md +23 -0
  58. package/dist/reference/errors/MOSTRA_ENV_PORT_TAKEN.md +23 -0
  59. package/dist/reference/errors/MOSTRA_ENV_RUNTIME_INSTALLING.md +23 -0
  60. package/dist/reference/errors/MOSTRA_ENV_RUNTIME_MISSING.md +23 -0
  61. package/dist/reference/errors/MOSTRA_ENV_SERVICE_FAILED.md +23 -0
  62. package/dist/reference/errors/MOSTRA_ENV_SHELL_MISSING.md +23 -0
  63. package/dist/reference/errors/MOSTRA_ENV_WARM_MISSING.md +23 -0
  64. package/dist/reference/errors/MOSTRA_FIELD_CONFLICT.md +23 -0
  65. package/dist/reference/errors/MOSTRA_FIELD_DUPLICATE_ID.md +23 -0
  66. package/dist/reference/errors/MOSTRA_FIELD_ID_INVALID.md +23 -0
  67. package/dist/reference/errors/MOSTRA_FIELD_ID_UNSTABLE.md +23 -0
  68. package/dist/reference/errors/MOSTRA_FIELD_MUTATION_ID_REUSED.md +23 -0
  69. package/dist/reference/errors/MOSTRA_FIELD_SHARED.md +23 -0
  70. package/dist/reference/errors/MOSTRA_FIELD_TOO_LARGE.md +23 -0
  71. package/dist/reference/errors/MOSTRA_FIELD_UNBOUND.md +23 -0
  72. package/dist/reference/errors/MOSTRA_HOME_DISK_FULL.md +23 -0
  73. package/dist/reference/errors/MOSTRA_HOME_GC_INCOMPLETE.md +23 -0
  74. package/dist/reference/errors/MOSTRA_HOME_GONE.md +23 -0
  75. package/dist/reference/errors/MOSTRA_HOME_INTEGRITY.md +23 -0
  76. package/dist/reference/errors/MOSTRA_HOME_LEDGER_UNREADABLE.md +23 -0
  77. package/dist/reference/errors/MOSTRA_HOME_LOCKED.md +23 -0
  78. package/dist/reference/errors/MOSTRA_HOME_MISMATCH.md +23 -0
  79. package/dist/reference/errors/MOSTRA_HOME_NETWORK_FILESYSTEM.md +23 -0
  80. package/dist/reference/errors/MOSTRA_HOME_NOT_ALWAYS_ON.md +23 -0
  81. package/dist/reference/errors/MOSTRA_HOME_NOT_OWNED.md +23 -0
  82. package/dist/reference/errors/MOSTRA_HOME_SOCKET_TOO_LONG.md +23 -0
  83. package/dist/reference/errors/MOSTRA_HOME_TOO_NEW.md +23 -0
  84. package/dist/reference/errors/MOSTRA_HOST_CONNECTION_CLOSED.md +23 -0
  85. package/dist/reference/errors/MOSTRA_HOST_CURSOR_COMPACTED.md +23 -0
  86. package/dist/reference/errors/MOSTRA_HOST_IDENTITY_UNAVAILABLE.md +23 -0
  87. package/dist/reference/errors/MOSTRA_HOST_INITIALIZE_ORDER.md +23 -0
  88. package/dist/reference/errors/MOSTRA_HOST_INTERNAL_ERROR.md +23 -0
  89. package/dist/reference/errors/MOSTRA_HOST_INVALID_PARAMS.md +23 -0
  90. package/dist/reference/errors/MOSTRA_HOST_MALFORMED.md +23 -0
  91. package/dist/reference/errors/MOSTRA_HOST_MESSAGE_TOO_LARGE.md +23 -0
  92. package/dist/reference/errors/MOSTRA_HOST_METHOD_UNKNOWN.md +23 -0
  93. package/dist/reference/errors/MOSTRA_HOST_NOTIFICATION_UNSUPPORTED.md +23 -0
  94. package/dist/reference/errors/MOSTRA_HOST_PORT_UNSUPPORTED.md +23 -0
  95. package/dist/reference/errors/MOSTRA_HOST_REQUEST_ID_REUSED.md +23 -0
  96. package/dist/reference/errors/MOSTRA_HOST_REVISION_UNSUPPORTED.md +23 -0
  97. package/dist/reference/errors/MOSTRA_HOST_SHUTDOWN_REFUSED.md +23 -0
  98. package/dist/reference/errors/MOSTRA_HOST_SUBSCRIPTION_UNKNOWN.md +23 -0
  99. package/dist/reference/errors/MOSTRA_HOST_TIMEOUT.md +23 -0
  100. package/dist/reference/errors/MOSTRA_HYGIENE_CONTENT_TYPE.md +23 -0
  101. package/dist/reference/errors/MOSTRA_HYGIENE_CSRF_MISSING.md +23 -0
  102. package/dist/reference/errors/MOSTRA_HYGIENE_FRAME_SESSION.md +23 -0
  103. package/dist/reference/errors/MOSTRA_HYGIENE_HEADERS_TOO_LARGE.md +23 -0
  104. package/dist/reference/errors/MOSTRA_HYGIENE_HOST_REFUSED.md +23 -0
  105. package/dist/reference/errors/MOSTRA_HYGIENE_NOT_SERVED.md +23 -0
  106. package/dist/reference/errors/MOSTRA_HYGIENE_ORIGIN_REFUSED.md +23 -0
  107. package/dist/reference/errors/MOSTRA_HYGIENE_RATE_LIMITED.md +23 -0
  108. package/dist/reference/errors/MOSTRA_HYGIENE_REQUEST_MALFORMED.md +23 -0
  109. package/dist/reference/errors/MOSTRA_HYGIENE_SCOPE_DENIED.md +23 -0
  110. package/dist/reference/errors/MOSTRA_HYGIENE_SESSION_CONFLICT.md +23 -0
  111. package/dist/reference/errors/MOSTRA_HYGIENE_SESSION_MISSING.md +23 -0
  112. package/dist/reference/errors/MOSTRA_HYGIENE_TOKEN_INVALID.md +23 -0
  113. package/dist/reference/errors/MOSTRA_HYGIENE_TOKEN_REVOKED.md +23 -0
  114. package/dist/reference/errors/MOSTRA_LIVE_SOURCE_FAILED.md +23 -0
  115. package/dist/reference/errors/MOSTRA_LIVE_TOO_LARGE.md +23 -0
  116. package/dist/reference/errors/MOSTRA_MANIFEST_INVALID.md +23 -0
  117. package/dist/reference/errors/MOSTRA_MANIFEST_NOT_LITERAL.md +23 -0
  118. package/dist/reference/errors/MOSTRA_MANIFEST_UNKNOWN_KEY.md +23 -0
  119. package/dist/reference/errors/MOSTRA_NETWORK_EXTERNAL_FAILED.md +23 -0
  120. package/dist/reference/errors/MOSTRA_NETWORK_REQUEST_FAILED.md +23 -0
  121. package/dist/reference/errors/MOSTRA_PLATFORM_UNSUPPORTED.md +23 -0
  122. package/dist/reference/errors/MOSTRA_PUBLISH_ID_CONFLICT.md +23 -0
  123. package/dist/reference/errors/MOSTRA_PUBLISH_SOURCE_CHANGED.md +23 -0
  124. package/dist/reference/errors/MOSTRA_PUBLISH_VERIFY_FAILED.md +23 -0
  125. package/dist/reference/errors/MOSTRA_REGRESSION_ACTION_REMOVED.md +23 -0
  126. package/dist/reference/errors/MOSTRA_REGRESSION_ARIA.md +23 -0
  127. package/dist/reference/errors/MOSTRA_REGRESSION_FIELD_REMOVED.md +23 -0
  128. package/dist/reference/errors/MOSTRA_REGRESSION_LIVE_REMOVED.md +23 -0
  129. package/dist/reference/errors/MOSTRA_REGRESSION_PAGE_REMOVED.md +23 -0
  130. package/dist/reference/errors/MOSTRA_REGRESSION_PIXELS.md +23 -0
  131. package/dist/reference/errors/MOSTRA_REMOTE_CONFIG_INVALID.md +23 -0
  132. package/dist/reference/errors/MOSTRA_REMOTE_HOME_MOVING.md +23 -0
  133. package/dist/reference/errors/MOSTRA_REMOTE_HOME_SUSPENDED.md +23 -0
  134. package/dist/reference/errors/MOSTRA_REMOTE_LIMIT_REACHED.md +23 -0
  135. package/dist/reference/errors/MOSTRA_REMOTE_LOGIN_FAILED.md +23 -0
  136. package/dist/reference/errors/MOSTRA_REMOTE_NOT_OWNER_INSTANCE.md +23 -0
  137. package/dist/reference/errors/MOSTRA_REMOTE_NO_INSTANCE.md +23 -0
  138. package/dist/reference/errors/MOSTRA_REMOTE_OPERATOR_UNAVAILABLE.md +23 -0
  139. package/dist/reference/errors/MOSTRA_REMOTE_OWNER_OFFLINE.md +23 -0
  140. package/dist/reference/errors/MOSTRA_REMOTE_PAUSED_BY_OPERATOR.md +23 -0
  141. package/dist/reference/errors/MOSTRA_REMOTE_QUEUE_FULL.md +23 -0
  142. package/dist/reference/errors/MOSTRA_REMOTE_RATE_LIMITED.md +23 -0
  143. package/dist/reference/errors/MOSTRA_REMOTE_SIGN_IN_REQUIRED.md +23 -0
  144. package/dist/reference/errors/MOSTRA_REMOTE_UNDER_REVIEW.md +23 -0
  145. package/dist/reference/errors/MOSTRA_REMOTE_UNREACHABLE.md +23 -0
  146. package/dist/reference/errors/MOSTRA_RUNTIME_BLANK.md +23 -0
  147. package/dist/reference/errors/MOSTRA_RUNTIME_NOT_READY.md +23 -0
  148. package/dist/reference/errors/MOSTRA_RUNTIME_PAGE_ERROR.md +23 -0
  149. package/dist/reference/errors/MOSTRA_RUNTIME_WORKER_CRASHED.md +23 -0
  150. package/dist/reference/errors/MOSTRA_RUNTIME_WORKER_PARKED.md +23 -0
  151. package/dist/reference/errors/MOSTRA_SECRET_MISSING.md +23 -0
  152. package/dist/reference/errors/MOSTRA_SHARE_NOT_ENABLED.md +23 -0
  153. package/dist/reference/errors/MOSTRA_SHARE_NOT_FOUND.md +23 -0
  154. package/dist/reference/errors/MOSTRA_SHARE_PORTS_EXHAUSTED.md +23 -0
  155. package/dist/reference/errors/MOSTRA_SHARE_TOOL_MISSING.md +23 -0
  156. package/dist/reference/errors/MOSTRA_SHARE_TOOL_NOT_READY.md +23 -0
  157. package/dist/reference/errors/MOSTRA_SHARE_TTL_INVALID.md +23 -0
  158. package/dist/reference/errors/MOSTRA_SHARE_TUNNEL_FAILED.md +23 -0
  159. package/dist/reference/errors/MOSTRA_SMOKE_BUDGET.md +23 -0
  160. package/dist/reference/errors/MOSTRA_SMOKE_NO_EFFECT.md +23 -0
  161. package/dist/reference/errors/MOSTRA_SUBMIT_ALREADY.md +23 -0
  162. package/dist/reference/errors/MOSTRA_SUBMIT_BLOCKED.md +23 -0
  163. package/dist/reference/errors/MOSTRA_SUBMIT_CHANNEL_DENIED.md +23 -0
  164. package/dist/reference/errors/MOSTRA_SUBMIT_NOT_FOUND.md +23 -0
  165. package/dist/reference/errors/MOSTRA_SUBMIT_PAUSED.md +23 -0
  166. package/dist/reference/errors/MOSTRA_SUBMIT_POLICY_NONE.md +23 -0
  167. package/dist/reference/errors/MOSTRA_SUBMIT_REVISION_MOVED.md +23 -0
  168. package/dist/reference/errors/MOSTRA_SUBMIT_SIGNAL_INVALID.md +23 -0
  169. package/dist/reference/errors/MOSTRA_SUBMIT_VIEW_INVALID.md +23 -0
  170. package/dist/reference/errors/MOSTRA_TARGET_UNAVAILABLE.md +23 -0
  171. package/dist/reference/errors/MOSTRA_TEAM_PRESENCE_RATE_LIMITED.md +23 -0
  172. package/dist/reference/errors/MOSTRA_TEAM_ROSTER_POLICY.md +23 -0
  173. package/dist/reference/errors/MOSTRA_TEAM_ROSTER_TOO_LARGE.md +23 -0
  174. package/dist/reference/errors/MOSTRA_TYPE_ERROR.md +23 -0
  175. package/dist/reference/errors/MOSTRA_TYPE_UNTYPED_PACKAGE.md +23 -0
  176. package/dist/reference/errors/MOSTRA_VERIFY_ACTION_SKIPPED.md +23 -0
  177. package/dist/reference/errors/MOSTRA_VERIFY_BASELINE_MISSING.md +23 -0
  178. package/dist/reference/errors/MOSTRA_VERIFY_CRASHED.md +23 -0
  179. package/dist/reference/errors/MOSTRA_VERIFY_LIVE_FAILED.md +23 -0
  180. package/dist/reference/errors/MOSTRA_VERIFY_NO_BASELINE.md +23 -0
  181. package/dist/reference/errors/MOSTRA_VERIFY_SECRET_MISSING.md +23 -0
  182. package/dist/reference/errors/MOSTRA_VERIFY_SKIP_CONSEQUENCE.md +23 -0
  183. package/dist/reference/errors/MOSTRA_VERIFY_TIMEOUT.md +23 -0
  184. package/dist/reference/self-hosting.md +130 -0
  185. package/dist/reference/telemetry.md +84 -0
  186. package/dist/skill/SKILL.md +124 -0
  187. package/dist/skill/assets/examples/dashboard/index.tsx +161 -0
  188. package/dist/skill/assets/examples/dashboard/live.ts +25 -0
  189. package/dist/skill/assets/examples/dashboard/styles.css +125 -0
  190. package/dist/skill/assets/examples/decision/index.tsx +95 -0
  191. package/dist/skill/assets/examples/decision/styles.css +125 -0
  192. package/dist/skill/assets/examples/inbox/actions.ts +23 -0
  193. package/dist/skill/assets/examples/inbox/index.tsx +109 -0
  194. package/dist/skill/assets/examples/inbox/styles.css +125 -0
  195. package/dist/skill/assets/studio.css +125 -0
  196. package/dist/skill/references/answers.md +219 -0
  197. package/dist/skill/references/design.md +154 -0
  198. package/dist/skill/references/libraries.md +167 -0
  199. package/dist/skill/references/long-lived.md +148 -0
  200. package/dist/skill/references/mcp.md +68 -0
  201. package/dist/skill/references/page.md +131 -0
  202. package/dist/skill/references/server.md +146 -0
  203. package/dist/skill/references/sharing.md +123 -0
  204. package/dist/skill/references/teams.md +78 -0
  205. package/dist/skill/references/verify.md +71 -0
  206. package/package.json +10 -5
  207. package/src/gateway/actions.ts +20 -0
  208. package/src/gateway/browser.ts +128 -1
  209. package/src/gateway/capabilities.ts +8 -0
  210. package/src/gateway/http.ts +12 -1
  211. package/src/gateway/index.ts +210 -6
  212. package/src/gateway/listener.ts +31 -6
  213. package/src/gateway/routes.ts +8 -0
  214. package/src/gateway/team.ts +181 -0
  215. package/src/gc/index.ts +5 -0
  216. package/src/instance/index.ts +22 -2
  217. package/src/interaction/ephemeral.ts +21 -0
  218. package/src/interaction/events.ts +17 -0
  219. package/src/interaction/index.ts +325 -20
  220. package/src/interaction/pause.ts +106 -0
  221. package/src/interaction/roster.ts +585 -0
  222. package/src/interaction/submissions.ts +42 -1
  223. package/src/interaction/team.ts +426 -0
  224. package/src/interaction/viewers.ts +34 -1
  225. package/src/interaction/wait.ts +150 -0
  226. package/src/ledger/index.ts +20 -1
  227. package/src/ledger/migrations.ts +86 -0
  228. package/src/link/author.ts +215 -0
  229. package/src/link/hosted.ts +51 -4
  230. package/src/link/http.ts +6 -1
  231. package/src/link/index.ts +3 -1
  232. package/src/link/manager.ts +169 -35
  233. package/src/protocol-server/client.ts +53 -0
  234. package/src/protocol-server/index.ts +1 -1
  235. package/src/server/api.ts +514 -72
  236. package/src/server/auth.ts +600 -74
  237. package/src/server/authorize.ts +816 -0
  238. package/src/server/clients.ts +235 -0
  239. package/src/server/config.ts +7 -0
  240. package/src/server/data.ts +59 -1
  241. package/src/server/directory.ts +91 -0
  242. package/src/server/feed.ts +277 -0
  243. package/src/server/handle.ts +172 -0
  244. package/src/server/hosted-pages.ts +532 -0
  245. package/src/server/hosted.ts +551 -18
  246. package/src/server/index.ts +353 -61
  247. package/src/server/mcp.ts +330 -0
  248. package/src/server/metering.ts +156 -0
  249. package/src/server/oauth-clients.ts +510 -0
  250. package/src/server/operator.ts +557 -0
  251. package/src/server/providers.ts +284 -0
  252. package/src/server/remove.ts +148 -0
  253. package/src/server/routing.ts +275 -0
  254. package/src/share/index.ts +50 -2
  255. package/src/verify/index.ts +7 -0
  256. package/src/verify/runner.ts +27 -2
  257. package/dist/instance-FExcyENK.js.map +0 -1
@@ -2,9 +2,9 @@ import { C as STAGING_FILES, S as LIVE_DECLARATION, _ as DEV_METHOD, a as nameKe
2
2
  import { a as pathsOf, c as currentUserSid, d as runtimeRoot$1, f as serviceLauncherPath, i as ownedDirectory, l as helperPath, n as WINDOWS, o as runtimeDirFor, p as stopServiceLauncher, r as defaultHome, s as socketPathLimit, t as OS, u as runHelperAsync } from "./directories-BLJjeSPD.js";
3
3
  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
- import { basename, delimiter, dirname, extname, join, relative, resolve, sep, win32 } from "node:path";
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, 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, 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, portRelayCallMethod, portRelayCancelMethod, portRelayLiveMethod, portRelayReconcileMethod, portRelayRunMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, refusal, relayCallBatchMethod, relayEffectMethod, relayLiveValueMethod, relayRunUpdateMethod, 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";
@@ -22,6 +22,7 @@ import { getRequestListener } from "@hono/node-server";
22
22
  import { Hono } from "hono";
23
23
  import ignore from "ignore";
24
24
  import { AsyncLocalStorage } from "node:async_hooks";
25
+ import { defaultWorkspaceRoot, localWorkspace } from "@mostra/mcp";
25
26
  import { WebSocket } from "ws";
26
27
  import { request as request$1 } from "node:https";
27
28
  import { Resolver } from "node:dns/promises";
@@ -2851,6 +2852,81 @@ const MIGRATIONS = [
2851
2852
  ALTER TABLE submission ADD COLUMN origin_json TEXT;
2852
2853
  ALTER TABLE event ADD COLUMN origin_json TEXT;
2853
2854
  CREATE UNIQUE INDEX event_origin ON event (origin_json) WHERE origin_json IS NOT NULL;
2855
+ `);
2856
+ }
2857
+ },
2858
+ {
2859
+ version: 14,
2860
+ name: "pause, quarantine and the operator's cursor",
2861
+ up(db) {
2862
+ db.exec(`
2863
+ CREATE TABLE artifact_pause (
2864
+ artifact_id TEXT PRIMARY KEY REFERENCES artifact(id),
2865
+ by TEXT NOT NULL CHECK (by IN ('owner', 'operator')),
2866
+ reason TEXT,
2867
+ paused_at TEXT NOT NULL
2868
+ );
2869
+ CREATE TABLE quarantine (
2870
+ artifact_id TEXT NOT NULL REFERENCES artifact(id),
2871
+ version_id TEXT NOT NULL DEFAULT '',
2872
+ reason TEXT NOT NULL,
2873
+ at TEXT NOT NULL,
2874
+ PRIMARY KEY (artifact_id, version_id)
2875
+ );
2876
+ CREATE TABLE operator_cursor (
2877
+ id INTEGER PRIMARY KEY CHECK (id = 1),
2878
+ cursor INTEGER NOT NULL CHECK (cursor >= 0)
2879
+ );
2880
+ `);
2881
+ }
2882
+ },
2883
+ {
2884
+ version: 15,
2885
+ name: "an owner's pause and an operator's, apart",
2886
+ up(db) {
2887
+ db.exec(`
2888
+ CREATE TABLE artifact_pause_by (
2889
+ artifact_id TEXT NOT NULL REFERENCES artifact(id),
2890
+ by TEXT NOT NULL CHECK (by IN ('owner', 'operator')),
2891
+ reason TEXT,
2892
+ paused_at TEXT NOT NULL,
2893
+ PRIMARY KEY (artifact_id, by)
2894
+ );
2895
+ INSERT INTO artifact_pause_by (artifact_id, by, reason, paused_at)
2896
+ SELECT artifact_id, by, reason, paused_at FROM artifact_pause;
2897
+ DROP TABLE artifact_pause;
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;
2854
2930
  `);
2855
2931
  }
2856
2932
  }
@@ -3199,6 +3275,14 @@ function wrap(db, file, schemaVersion, migrated) {
3199
3275
  } catch {}
3200
3276
  return result;
3201
3277
  },
3278
+ removal(fn) {
3279
+ assertInPlace();
3280
+ const result = guarded(() => db.transaction(() => fn(target)).immediate());
3281
+ for (const listener of listeners) try {
3282
+ listener();
3283
+ } catch {}
3284
+ return result;
3285
+ },
3202
3286
  onCommit(listener) {
3203
3287
  listeners.add(listener);
3204
3288
  return () => listeners.delete(listener);
@@ -5207,6 +5291,52 @@ async function attach(path, client, timeoutMs = 5e3) {
5207
5291
  throw error;
5208
5292
  }
5209
5293
  }
5294
+ /**
5295
+ * Opens a session with a protocol server in this process, over a pair of in-memory streams, so a
5296
+ * part of the runtime acts as a client exactly as any host does (invariant 11): the same framing,
5297
+ * initialize, validation and session rules. `attributes` are the session's, as a transport sets
5298
+ * them (a remote MCP request's account and home). The caller closes the returned client.
5299
+ */
5300
+ async function attachInProcess(server, client, attributes = {}, timeoutMs = 5e3) {
5301
+ const toServer = new PassThrough();
5302
+ const toClient = new PassThrough();
5303
+ const peer = new RpcPeer({ send: (message) => void writeLine(toServer, message) });
5304
+ let markClosed = () => {};
5305
+ const closed = new Promise((done) => {
5306
+ markClosed = done;
5307
+ });
5308
+ server.serve("stdio", toServer, toClient, void 0, attributes);
5309
+ pump({
5310
+ input: toClient,
5311
+ output: toServer
5312
+ }, () => peer, () => {
5313
+ peer.close();
5314
+ markClosed();
5315
+ });
5316
+ const connection = {
5317
+ peer,
5318
+ closed,
5319
+ close: () => {
5320
+ peer.close();
5321
+ toServer.end();
5322
+ toClient.end();
5323
+ }
5324
+ };
5325
+ try {
5326
+ return {
5327
+ client: connection,
5328
+ result: await peer.call(mostraInitializeMethod, {
5329
+ client,
5330
+ revisions: [...HOST_PROTOCOL_REVISIONS],
5331
+ capabilities: {},
5332
+ ports: []
5333
+ }, { timeoutMs })
5334
+ };
5335
+ } catch (error) {
5336
+ connection.close();
5337
+ throw error;
5338
+ }
5339
+ }
5210
5340
  //#endregion
5211
5341
  //#region src/protocol-server/websocket.ts
5212
5342
  /**
@@ -5555,6 +5685,7 @@ function compactEvents(db, artifactId, before) {
5555
5685
  let removed = 0;
5556
5686
  let from = first.cursor;
5557
5687
  let latestVersion;
5688
+ let roster;
5558
5689
  for (const row of rows) {
5559
5690
  if (row.type === "artifact.compacted") {
5560
5691
  const earlier = JSON.parse(row.payload_json);
@@ -5562,10 +5693,22 @@ function compactEvents(db, artifactId, before) {
5562
5693
  removed += earlier.removed;
5563
5694
  for (const [type, count] of Object.entries(earlier.types)) types[type] = (types[type] ?? 0) + count;
5564
5695
  if (earlier.latestVersion) latestVersion = earlier.latestVersion;
5696
+ if (earlier.roster) roster = earlier.roster;
5565
5697
  continue;
5566
5698
  }
5567
5699
  removed += 1;
5568
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
+ }
5569
5712
  if (row.type === "version.published") {
5570
5713
  const payload = JSON.parse(row.payload_json);
5571
5714
  latestVersion = {
@@ -5580,7 +5723,8 @@ function compactEvents(db, artifactId, before) {
5580
5723
  through: last.cursor,
5581
5724
  removed,
5582
5725
  types,
5583
- ...latestVersion ? { latestVersion } : {}
5726
+ ...latestVersion ? { latestVersion } : {},
5727
+ ...roster ? { roster } : {}
5584
5728
  };
5585
5729
  db.run("DELETE FROM event WHERE artifact_id = ? AND cursor < ?", artifactId, before);
5586
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());
@@ -5968,7 +6112,9 @@ function viewerOf(row) {
5968
6112
  id: row.id,
5969
6113
  kind: row.kind,
5970
6114
  ...row.name !== null ? { name: row.name } : {},
5971
- ...row.kind === "token" || row.kind === "host" || row.kind === "tailnet" ? { ref: row.external_ref } : {}
6115
+ ...row.kind === "token" || row.kind === "host" || row.kind === "tailnet" ? { ref: row.external_ref } : {},
6116
+ ...row.kind === "account" ? { verified: true } : {},
6117
+ ...row.kind === "anonymous" ? { verified: false } : {}
5972
6118
  };
5973
6119
  }
5974
6120
  /** The home's local user (created on first use): who every session acts as without a viewer. */
@@ -6011,6 +6157,29 @@ function viewerForLink(db, tokenId, name) {
6011
6157
  name
6012
6158
  });
6013
6159
  }
6160
+ /**
6161
+ * A signed-in person on a hosted link minted without a viewer (D165 item 8): one viewer of kind
6162
+ * `account` per account, named as its identity provider verified it.
6163
+ */
6164
+ function viewerForAccount(db, accountId, name) {
6165
+ return viewerByRef(db, "account", {
6166
+ ref: accountId,
6167
+ ...name !== void 0 ? { name } : {}
6168
+ });
6169
+ }
6170
+ /**
6171
+ * A person who isn't signed in on a hosted link minted without a viewer (D165 item 8): one viewer
6172
+ * of kind `anonymous` per browser and route, by the route's derived key
6173
+ * (`HMAC-SHA-256(browser secret, routeId)`), never the shell's raw secret. A name they choose is
6174
+ * set apart, unverified ({@link nameAnonymous}).
6175
+ */
6176
+ function viewerForAnonymous(db, key) {
6177
+ return viewerByRef(db, "anonymous", { ref: key });
6178
+ }
6179
+ /** Sets the self-chosen, unverified name of an anonymous viewer; any other viewer is left alone. */
6180
+ function nameAnonymous(db, viewerId, name) {
6181
+ return db.run("UPDATE viewer SET name = ? WHERE id = ? AND kind = 'anonymous'", name, viewerId).changes > 0;
6182
+ }
6014
6183
  function viewerByRef(db, kind, spec) {
6015
6184
  const found = db.get("SELECT * FROM viewer WHERE kind = ? AND external_ref = ?", kind, spec.ref);
6016
6185
  if (found) {
@@ -6171,6 +6340,21 @@ function orphansOf(rows) {
6171
6340
  * `MOSTRA_SUBMIT_POLICY_NONE`, `MOSTRA_SUBMIT_ALREADY` (a {@link SubmitConflict}) under `once`,
6172
6341
  * `MOSTRA_SUBMIT_REVISION_MOVED` when the draft changed since the viewer saw it.
6173
6342
  */
6343
+ /**
6344
+ * Whether a submit would be judged afresh: not a repeat of one already recorded (which answers that
6345
+ * submission), not refused by the view or a pause before anything is recorded. Only such a submit
6346
+ * is admitted by the server's rates and the operator's limits (Fable review of WP-30, 8).
6347
+ */
6348
+ function wouldRecord(db, input) {
6349
+ try {
6350
+ const view = viewFor(db, input.viewId, input.artifactId, input.viewerId, input.tokenId);
6351
+ const draft = documentFor(db, input.artifactId, input.viewerId, false);
6352
+ if (draft !== void 0 && db.get("SELECT 1 FROM submission WHERE view_id = ? AND draft_document_id = ? AND draft_revision = ?", view.id, draft.id, input.expectedRevision)) return false;
6353
+ return !db.get("SELECT 1 FROM artifact_pause WHERE artifact_id = ?", input.artifactId);
6354
+ } catch {
6355
+ return false;
6356
+ }
6357
+ }
6174
6358
  function submit(db, input) {
6175
6359
  const view = viewFor(db, input.viewId, input.artifactId, input.viewerId, input.tokenId);
6176
6360
  assertChannel(view, input.channel);
@@ -6183,6 +6367,8 @@ function submit(db, input) {
6183
6367
  },
6184
6368
  created: false
6185
6369
  };
6370
+ const paused = db.get("SELECT by FROM artifact_pause WHERE artifact_id = ? ORDER BY by = 'operator' DESC LIMIT 1", input.artifactId);
6371
+ if (paused) throw new RpcError(createDiagnostic("MOSTRA_SUBMIT_PAUSED", { message: `This page is paused${paused.by === "operator" ? " by its server's operator" : ""}: it takes no answers until it is resumed, and the draft is kept.` }));
6186
6372
  const artifact = db.get("SELECT policy_json, latest_version_id FROM artifact WHERE id = ?", input.artifactId);
6187
6373
  if (!artifact) throw new Error(`No artifact ${input.artifactId}.`);
6188
6374
  const policy = storedPolicy(artifact.policy_json);
@@ -7018,6 +7204,432 @@ function outcomeOf(answer) {
7018
7204
  };
7019
7205
  }
7020
7206
  //#endregion
7207
+ //#region src/interaction/pause.ts
7208
+ /**
7209
+ * Pausing an artifact (D165 item 14, RM-09): a paused artifact stays viewable and its shell says
7210
+ * so; it takes no submissions (the submit transaction refuses them) and runs no actions until it
7211
+ * is resumed, and every draft is kept. The owner pauses and resumes its own pause; an operator's
7212
+ * pause is resumed only by the operator. One row per party that paused it (`artifact_pause`,
7213
+ * DATA_MODEL §7.2), in local and hosted homes alike; each change appends `artifact.paused` or
7214
+ * `artifact.resumed`, so open pages learn of it.
7215
+ */
7216
+ /**
7217
+ * The artifact's pause, or `undefined` when it isn't paused: the operator's when both paused it,
7218
+ * since only the operator lifts that one.
7219
+ */
7220
+ function pauseOf(db, artifactId) {
7221
+ const row = db.get("SELECT by, reason, paused_at FROM artifact_pause WHERE artifact_id = ? ORDER BY by = 'operator' DESC LIMIT 1", artifactId);
7222
+ return row ? {
7223
+ by: row.by,
7224
+ ...row.reason !== null ? { reason: row.reason } : {},
7225
+ at: row.paused_at
7226
+ } : void 0;
7227
+ }
7228
+ /**
7229
+ * Pauses or resumes an artifact, in the caller's write transaction, as `by`. The owner's pause and
7230
+ * the operator's are kept apart (one row each): pausing again keeps the earlier pause of the same
7231
+ * party, and a resume lifts only its own party's, so the artifact takes answers again once no
7232
+ * pause is left. The owner resuming while the operator's pause stands is
7233
+ * `MOSTRA_REMOTE_PAUSED_BY_OPERATOR`, and changes nothing.
7234
+ */
7235
+ function setPause(db, artifactId, change) {
7236
+ const own = db.get("SELECT by FROM artifact_pause WHERE artifact_id = ? AND by = ?", artifactId, change.by);
7237
+ const actor = change.by === "operator" ? { kind: "mostra" } : { kind: "agent" };
7238
+ if (change.paused) {
7239
+ if (!own) {
7240
+ const before = pauseOf(db, artifactId);
7241
+ db.run("INSERT INTO artifact_pause (artifact_id, by, reason, paused_at) VALUES (?, ?, ?, ?)", artifactId, change.by, change.reason ?? null, (/* @__PURE__ */ new Date()).toISOString());
7242
+ if (before === void 0 || change.by === "operator") appendEvent(db, {
7243
+ artifactId,
7244
+ type: "artifact.paused",
7245
+ actor,
7246
+ payload: {
7247
+ by: change.by,
7248
+ ...change.reason !== void 0 ? { reason: change.reason } : {}
7249
+ }
7250
+ });
7251
+ }
7252
+ return {
7253
+ paused: true,
7254
+ by: pauseOf(db, artifactId).by
7255
+ };
7256
+ }
7257
+ if (change.by === "owner" && pauseOf(db, artifactId)?.by === "operator") throw new RpcError(createDiagnostic("MOSTRA_REMOTE_PAUSED_BY_OPERATOR", { message: "The server's operator paused this artifact; only the operator resumes it." }));
7258
+ if (own) db.run("DELETE FROM artifact_pause WHERE artifact_id = ? AND by = ?", artifactId, change.by);
7259
+ const left = pauseOf(db, artifactId);
7260
+ if (left === void 0) {
7261
+ if (own) appendEvent(db, {
7262
+ artifactId,
7263
+ type: "artifact.resumed",
7264
+ actor,
7265
+ payload: { by: change.by }
7266
+ });
7267
+ return { paused: false };
7268
+ }
7269
+ if (own) appendEvent(db, {
7270
+ artifactId,
7271
+ type: "artifact.paused",
7272
+ actor: { kind: "agent" },
7273
+ payload: {
7274
+ by: left.by,
7275
+ ...left.reason !== void 0 ? { reason: left.reason } : {}
7276
+ }
7277
+ });
7278
+ return {
7279
+ paused: true,
7280
+ by: left.by
7281
+ };
7282
+ }
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
7021
7633
  //#region src/interaction/runs.ts
7022
7634
  /**
7023
7635
  * Action runs in the ledger (D24, D54, AC-02, AC-03; ARCHITECTURE §7): each invocation through
@@ -7417,6 +8029,87 @@ function submissionEvent(db, row) {
7417
8029
  };
7418
8030
  }
7419
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
+ /**
7420
8113
  * Checks a condition once, inside the caller's read transaction: the event that satisfies it, or
7421
8114
  * the newest cursor examined. Throws `MOSTRA_SUBMIT_POLICY_NONE` for `submitted` on an artifact
7422
8115
  * without submissions, and `MOSTRA_HOST_CURSOR_COMPACTED` for a cursor inside a compacted range.
@@ -7425,6 +8118,7 @@ function checkCondition(db, artifactId, until, after, explicitAfter = true) {
7425
8118
  const upTo = latestCursor(db);
7426
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);
7427
8120
  let found;
8121
+ if (until === "submitted:all" || /^submitted:[0-9]+$/.test(until)) return checkTeamCondition(db, artifactId, until, after, upTo, explicitAfter);
7428
8122
  if (until === "submitted") {
7429
8123
  const policy = storedPolicy(db.get("SELECT policy_json FROM artifact WHERE id = ?", artifactId)?.policy_json ?? null);
7430
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." }));
@@ -7506,6 +8200,11 @@ const POLL_QUEUE_MAX = 1e3;
7506
8200
  * - a run's delta that continues the one queued for the run merges into it, losing nothing.
7507
8201
  */
7508
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
+ }
7509
8208
  if (message.kind === "live") {
7510
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--) {
7511
8210
  const queued = queue[index];
@@ -7626,6 +8325,10 @@ function createEphemeralBus(options = {}) {
7626
8325
  if ((view.live.get(message.live.key)?.until ?? 0) > at) deliver(view, message);
7627
8326
  }
7628
8327
  },
8328
+ send(artifactId, viewId, message) {
8329
+ const view = views.get(viewId);
8330
+ if (view && view.artifactId === artifactId) deliver(view, message);
8331
+ },
7629
8332
  listen(artifactId, viewId, listener) {
7630
8333
  const view = viewOf(artifactId, viewId);
7631
8334
  view.listeners.add(listener);
@@ -7675,11 +8378,301 @@ function createEphemeralBus(options = {}) {
7675
8378
  activeViews() {
7676
8379
  const at = now();
7677
8380
  let count = 0;
7678
- for (const view of views.values()) if (view.listeners.size > 0 || (view.poll?.until ?? 0) > at) count += 1;
8381
+ for (const view of views.values()) if (view.listeners.size > 0 || (view.poll?.until ?? 0) > at) count += 1;
8382
+ return count;
8383
+ },
8384
+ close() {
8385
+ clearInterval(sweep);
8386
+ }
8387
+ };
8388
+ }
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;
7679
8663
  return count;
7680
8664
  },
7681
8665
  close() {
7682
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();
7683
8676
  }
7684
8677
  };
7685
8678
  }
@@ -7721,6 +8714,7 @@ function versionNumber(db, versionId) {
7721
8714
  */
7722
8715
  function visibleTo(event, page, run) {
7723
8716
  const viewerId = page.viewerId;
8717
+ if (ROSTER_EVENTS.has(event.type)) return false;
7724
8718
  if (event.type.startsWith("draft.")) return event.payload["viewerId"] === viewerId;
7725
8719
  if (event.type.startsWith("host.")) return false;
7726
8720
  if (event.type.startsWith("action.")) {
@@ -7732,16 +8726,36 @@ function visibleTo(event, page, run) {
7732
8726
  return true;
7733
8727
  }
7734
8728
  /**
7735
- * Another viewer as a page sees them: kind and display name, never their viewer or view IDs
7736
- * (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).
7737
8733
  */
7738
- function actorForPage(actor, viewerId) {
7739
- 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
+ };
7740
8741
  return {
7741
8742
  kind: "viewer",
7742
- ...actor.name !== void 0 ? { name: actor.name } : {}
8743
+ ...actor.name !== void 0 ? { name: actor.name } : {},
8744
+ key
7743
8745
  };
7744
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
+ }
7745
8759
  /** An event as a page sees it: other viewers' identities left out. */
7746
8760
  function eventForPage(event, viewerId) {
7747
8761
  if (event.type === "worker.crashed") {
@@ -7758,21 +8772,24 @@ function eventForPage(event, viewerId) {
7758
8772
  payload
7759
8773
  };
7760
8774
  }
7761
- 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;
7762
8779
  const { viewerId: _viewer, viewId: _view, ...payload } = event.payload;
7763
8780
  const causation = event.causation ? Object.fromEntries(Object.entries(event.causation).filter(([key]) => key !== "viewId")) : void 0;
7764
8781
  return {
7765
8782
  ...event,
7766
- actor: actorForPage(event.actor, viewerId),
8783
+ actor: actorForPage(event.actor, viewerId, event.artifactId ?? ""),
7767
8784
  ...causation ? { causation } : {},
7768
8785
  payload
7769
8786
  };
7770
8787
  }
7771
8788
  /** Fields as a page sees them: who last wrote each, without another viewer's ID. */
7772
- function fieldsForPage(fields, viewerId) {
8789
+ function fieldsForPage(fields, viewerId, artifactId) {
7773
8790
  return Object.fromEntries(Object.entries(fields).map(([id, field]) => [id, field.updatedBy ? {
7774
8791
  ...field,
7775
- updatedBy: actorForPage(field.updatedBy, viewerId)
8792
+ updatedBy: actorForPage(field.updatedBy, viewerId, artifactId)
7776
8793
  } : field]));
7777
8794
  }
7778
8795
  /**
@@ -7805,6 +8822,15 @@ function createInteraction(options) {
7805
8822
  }
7806
8823
  };
7807
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
+ };
7808
8834
  const { ledger, log, hosts } = options;
7809
8835
  const outbox = new Outbox({
7810
8836
  ledger,
@@ -7841,6 +8867,15 @@ function createInteraction(options) {
7841
8867
  kind: as,
7842
8868
  ...session.client ? { id: session.client.name } : {}
7843
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
+ };
7844
8879
  return {
7845
8880
  start() {
7846
8881
  outbox.start();
@@ -7859,8 +8894,15 @@ function createInteraction(options) {
7859
8894
  viewerForHost: (spec) => ledger.write((db) => viewerForHost(db, spec)),
7860
8895
  viewerForTailnet: (spec) => ledger.write((db) => viewerForTailnet(db, spec)),
7861
8896
  viewerForLink: (tokenId, name) => ledger.write((db) => viewerForLink(db, tokenId, name)),
8897
+ viewerForAccount: (accountId, name) => ledger.write((db) => viewerForAccount(db, accountId, name)),
8898
+ viewerForAnonymous: (key) => ledger.write((db) => viewerForAnonymous(db, key)),
8899
+ nameAnonymous: (viewerId, name) => ledger.write((db) => nameAnonymous(db, viewerId, name)),
8900
+ pause: (artifactId, change) => ledger.write((db) => setPause(db, artifactId, change)),
8901
+ pauseOf: (artifactId) => ledger.read((db) => pauseOf(db, artifactId)),
7862
8902
  openView(input) {
7863
- return ledger.write((db) => openView(db, input));
8903
+ const viewId = ledger.write((db) => openView(db, input));
8904
+ touched(input.artifactId);
8905
+ return viewId;
7864
8906
  },
7865
8907
  viewControls(page, viewId) {
7866
8908
  return ledger.read((db) => viewControls(viewFor(db, viewId, page.artifactId, page.viewerId, page.tokenId)));
@@ -7899,20 +8941,31 @@ function createInteraction(options) {
7899
8941
  ...outcome.result,
7900
8942
  conflicts: outcome.result.conflicts.map((conflict) => conflict.updatedBy ? {
7901
8943
  ...conflict,
7902
- updatedBy: actorForPage(conflict.updatedBy, page.viewerId)
8944
+ updatedBy: actorForPage(conflict.updatedBy, page.viewerId, page.artifactId)
7903
8945
  } : conflict)
7904
8946
  };
7905
- 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
+ }
7906
8951
  return result;
7907
8952
  },
7908
8953
  importSubmission(envelope, source) {
7909
8954
  const owners = options.deliveryOwners?.(envelope.artifactId) ?? outbox.owners();
7910
- const answer = ledger.write((db) => importSubmission(db, {
7911
- envelope,
7912
- source,
7913
- owners,
7914
- owned: (inner, artifactId) => inner.get("SELECT 1 FROM hosted_artifact WHERE artifact_id = ? AND server = ?", artifactId, source.server) !== void 0
7915
- }));
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);
7916
8969
  log.info("interaction.imported", {
7917
8970
  artifactId: envelope.artifactId,
7918
8971
  submissionId: envelope.submissionId,
@@ -7920,6 +8973,12 @@ function createInteraction(options) {
7920
8973
  });
7921
8974
  return answer;
7922
8975
  },
8976
+ resultsOf(submissionId) {
8977
+ return ledger.read((db) => {
8978
+ const submission = db.get("SELECT * FROM submission WHERE id = ?", submissionId);
8979
+ return submission ? buildResults(db, submission) : void 0;
8980
+ });
8981
+ },
7923
8982
  envelopeFor(submissionId, owner) {
7924
8983
  return ledger.read((db) => {
7925
8984
  const delivery = db.get("SELECT id, attempts FROM delivery WHERE submission_id = ? AND port_owner = ?", submissionId, owner);
@@ -7937,18 +8996,32 @@ function createInteraction(options) {
7937
8996
  };
7938
8997
  });
7939
8998
  },
7940
- submit(page, input) {
7941
- const owners = options.deliveryOwners?.(page.artifactId) ?? outbox.owners();
7942
- const outcome = asPage(() => ledger.write((db) => submit(db, {
8999
+ wouldRecord(page, input) {
9000
+ return ledger.read((db) => wouldRecord(db, {
7943
9001
  artifactId: page.artifactId,
7944
9002
  viewerId: page.viewerId,
7945
9003
  ...page.tokenId !== void 0 ? { tokenId: page.tokenId } : {},
7946
9004
  viewId: input.viewId,
7947
- expectedRevision: input.expectedRevision,
7948
- channel: input.channel,
7949
- owners,
7950
- covers: options.coverage
7951
- })));
9005
+ expectedRevision: input.expectedRevision
9006
+ }));
9007
+ },
9008
+ submit(page, input) {
9009
+ const owners = options.deliveryOwners?.(page.artifactId) ?? outbox.owners();
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);
7952
9025
  if (outcome.tallied) for (const listener of tallyListeners) try {
7953
9026
  listener(page.artifactId, outcome.tallied);
7954
9027
  } catch (error) {
@@ -8049,7 +9122,7 @@ function createInteraction(options) {
8049
9122
  const state = documentSnapshot(db, page.artifactId, null);
8050
9123
  return {
8051
9124
  ...state,
8052
- fields: fieldsForPage(state.fields, page.viewerId)
9125
+ fields: fieldsForPage(state.fields, page.viewerId, page.artifactId)
8053
9126
  };
8054
9127
  })(),
8055
9128
  ...latestOwn ? { submission: forPage(submissionSummary(db, latestOwn)) } : {},
@@ -8074,6 +9147,12 @@ function createInteraction(options) {
8074
9147
  if (!runs.has(runId)) runs.set(runId, runById(db, page.artifactId, runId));
8075
9148
  return runs.get(runId);
8076
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
+ };
8077
9156
  for (;;) {
8078
9157
  const read = readEvents(db, {
8079
9158
  filter: { artifacts: [page.artifactId] },
@@ -8087,6 +9166,16 @@ function createInteraction(options) {
8087
9166
  };
8088
9167
  cursor = Number(event.cursor);
8089
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
+ }
8090
9179
  if (visibleTo(event, page, runOf)) events.push(eventForPage(event, page.viewerId));
8091
9180
  }
8092
9181
  cursor = Math.max(cursor, Number(read.cursor));
@@ -8136,6 +9225,26 @@ function createInteraction(options) {
8136
9225
  };
8137
9226
  });
8138
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
+ }),
8139
9248
  handler(waitMethod, (params, session) => waitFor({
8140
9249
  ledger,
8141
9250
  artifactId: options.artifacts.resolve(params.artifact),
@@ -8330,7 +9439,58 @@ function createInteraction(options) {
8330
9439
  tallyListeners.add(listener);
8331
9440
  return () => tallyListeners.delete(listener);
8332
9441
  },
8333
- 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
+ }
8334
9494
  };
8335
9495
  }
8336
9496
  //#endregion
@@ -8811,12 +9971,14 @@ function documentHeaders(listener, frameOrigins) {
8811
9971
  "frame-ancestors 'none'",
8812
9972
  "base-uri 'none'",
8813
9973
  "form-action 'none'",
8814
- "object-src 'none'"
9974
+ "object-src 'none'",
9975
+ "require-trusted-types-for 'script'",
9976
+ "trusted-types 'none'"
8815
9977
  ].join("; "),
8816
9978
  "x-frame-options": "DENY",
8817
9979
  "cross-origin-opener-policy": "same-origin"
8818
9980
  };
8819
- return { "content-security-policy": `frame-ancestors ${listener.shellOrigin}` };
9981
+ return { "content-security-policy": `frame-ancestors ${listener.frameAncestors ?? listener.shellOrigin}` };
8820
9982
  }
8821
9983
  /** Every header of a request as `[name, value]` pairs, repeats kept. */
8822
9984
  function headerPairs(incoming) {
@@ -9015,6 +10177,15 @@ function actionRoutes(options) {
9015
10177
  };
9016
10178
  };
9017
10179
  const may = (page, fnId) => scopeAllows(page.scopes ?? [], `action:${fnId}`);
10180
+ /**
10181
+ * A paused artifact runs no actions (D165 item 14): a call or a new run is refused before
10182
+ * anything is recorded, started or relayed to the owner.
10183
+ */
10184
+ const paused = (page) => {
10185
+ const pause = interaction.pauseOf(page.artifactId);
10186
+ if (!pause) return void 0;
10187
+ return answer$1(createDiagnostic("MOSTRA_ACTION_PAUSED", { message: `This page is paused${pause.by === "operator" ? " by its server's operator" : ""}: its actions don't run until it is resumed.` }), 423);
10188
+ };
9018
10189
  return {
9019
10190
  async call(context) {
9020
10191
  const refused = served(context);
@@ -9024,6 +10195,8 @@ function actionRoutes(options) {
9024
10195
  if (request instanceof Response) return request;
9025
10196
  const page = pageOf(context);
9026
10197
  if (!may(page, fnId)) return denied(fnId);
10198
+ const pausedNow = paused(page);
10199
+ if (pausedNow) return pausedNow;
9027
10200
  let lines;
9028
10201
  const abort = new AbortController();
9029
10202
  context.request.signal.addEventListener("abort", () => abort.abort(), { once: true });
@@ -9071,6 +10244,8 @@ function actionRoutes(options) {
9071
10244
  if (request instanceof Response) return request;
9072
10245
  const page = pageOf(context);
9073
10246
  if (!may(page, request.fnId)) return denied(request.fnId);
10247
+ const pausedNow = paused(page);
10248
+ if (pausedNow) return pausedNow;
9074
10249
  try {
9075
10250
  return jsonResponse(actions.startRun(page, {
9076
10251
  viewId: request.viewId,
@@ -9159,7 +10334,9 @@ const STATUS = {
9159
10334
  MOSTRA_HOST_CURSOR_COMPACTED: 410,
9160
10335
  MOSTRA_HOME_DISK_FULL: 507,
9161
10336
  MOSTRA_HOME_GONE: 503,
9162
- MOSTRA_HYGIENE_SCOPE_DENIED: 403
10337
+ MOSTRA_HYGIENE_SCOPE_DENIED: 403,
10338
+ MOSTRA_SUBMIT_PAUSED: 423,
10339
+ MOSTRA_TEAM_PRESENCE_RATE_LIMITED: 429
9163
10340
  };
9164
10341
  /** A refusal or a diagnostic as the browser gets it. */
9165
10342
  function answer(diagnostic, status, extra = {}) {
@@ -9171,6 +10348,15 @@ function answer(diagnostic, status, extra = {}) {
9171
10348
  function malformed(message) {
9172
10349
  return answer(refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", message).diagnostic, 400);
9173
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
+ }
9174
10360
  /** Turns an interaction refusal into its response; anything else is a defect for `onError`. */
9175
10361
  function failure(error) {
9176
10362
  if (error instanceof SubmitConflict) return answer(error.diagnostic, 409, { submission: error.submission });
@@ -9224,6 +10410,21 @@ function browserRoutes(options) {
9224
10410
  scopes: session.grant.scopes
9225
10411
  };
9226
10412
  };
10413
+ /** The answer to a submit the server's rules refused before it reached the ledger. */
10414
+ const admit = async (context, request) => {
10415
+ if (!options.admitSubmit) return void 0;
10416
+ const page = pageOf(context);
10417
+ if (!interaction.wouldRecord(page, {
10418
+ viewId: request.viewId,
10419
+ expectedRevision: Number(request.expectedRevision)
10420
+ })) return;
10421
+ const refused = await options.admitSubmit(page, context);
10422
+ if (!refused) return void 0;
10423
+ return jsonResponse(refused.diagnostic, {
10424
+ status: refused.status,
10425
+ ...refused.retryAfter !== void 0 ? { headers: { "retry-after": String(refused.retryAfter) } } : {}
10426
+ });
10427
+ };
9227
10428
  /** The view a stream or poll is for, checked against the page (D104). */
9228
10429
  const viewOf = (context, page) => {
9229
10430
  const view = new URL(context.request.url).searchParams.get("view");
@@ -9260,6 +10461,8 @@ function browserRoutes(options) {
9260
10461
  if (refused) return refused;
9261
10462
  const request = await body(context, SubmitRequest);
9262
10463
  if (request instanceof Response) return request;
10464
+ const admitted = await admit(context, request);
10465
+ if (admitted) return admitted;
9263
10466
  try {
9264
10467
  return jsonResponse(interaction.submit(pageOf(context), {
9265
10468
  viewId: request.viewId,
@@ -9321,7 +10524,7 @@ function browserRoutes(options) {
9321
10524
  wake?.();
9322
10525
  });
9323
10526
  const held = [];
9324
- 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("");
9325
10528
  const unlisten = options.bus?.listen(page.artifactId, viewIdOf(context), (message) => {
9326
10529
  options.bus?.coalesce(page.artifactId, viewIdOf(context), held, message);
9327
10530
  if (held.length > EPHEMERAL_HELD) held.splice(0, held.length - EPHEMERAL_HELD);
@@ -9508,6 +10711,8 @@ function browserRoutes(options) {
9508
10711
  if (refused) return refused;
9509
10712
  const request = await body(context, ShellSubmitRequest);
9510
10713
  if (request instanceof Response) return request;
10714
+ const admitted = await admit(context, request);
10715
+ if (admitted) return admitted;
9511
10716
  const page = pageOf(context);
9512
10717
  let submission;
9513
10718
  try {
@@ -9586,6 +10791,43 @@ function browserRoutes(options) {
9586
10791
  return failure(error);
9587
10792
  }
9588
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
+ };
9589
10831
  return {
9590
10832
  fields,
9591
10833
  submit,
@@ -9593,6 +10835,8 @@ function browserRoutes(options) {
9593
10835
  stream,
9594
10836
  poll: pollFor(true),
9595
10837
  shellPoll: pollFor(false),
10838
+ respondents,
10839
+ presence,
9596
10840
  shellSubmit,
9597
10841
  choose,
9598
10842
  follow,
@@ -9718,6 +10962,7 @@ var Capabilities = class {
9718
10962
  #now;
9719
10963
  #shellOrigin;
9720
10964
  #servesShell;
10965
+ #onMinted;
9721
10966
  /** Single-use stream and socket tickets (D158 item 5), by the SHA-256 of their secret. */
9722
10967
  #streamTickets = /* @__PURE__ */ new Map();
9723
10968
  #tickets = /* @__PURE__ */ new Map();
@@ -9738,6 +10983,7 @@ var Capabilities = class {
9738
10983
  this.#now = options.now;
9739
10984
  this.#shellOrigin = options.shellOrigin;
9740
10985
  this.#servesShell = options.servesShell ?? ((origin) => origin === this.#shellOrigin());
10986
+ this.#onMinted = options.onMinted;
9741
10987
  }
9742
10988
  /** Runs `fn` in the caller's transaction, or in a new one. */
9743
10989
  #tx(db, fn) {
@@ -9759,6 +11005,10 @@ var Capabilities = class {
9759
11005
  const scopes = normalizeScopes(input.scopes);
9760
11006
  const shellOrigin = input.shellOrigin ?? this.#shellOrigin();
9761
11007
  db.run("INSERT INTO token (id, secret_hash, artifact_id, scopes_json, viewer_id, expires_at, revoked_at, created_at, is_default, pinned_version, shell_origin) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?)", tokenId, hashSecret(secret), input.artifactId, JSON.stringify(scopes), input.viewerId ?? null, input.expiresAt ?? null, this.#iso(this.#now()), input.isDefault ? 1 : 0, input.pinnedVersion ?? null, shellOrigin);
11008
+ this.#onMinted?.({
11009
+ tokenId,
11010
+ artifactId: input.artifactId
11011
+ });
9762
11012
  return {
9763
11013
  tokenId,
9764
11014
  secret,
@@ -10605,7 +11855,8 @@ function mount(app, checks, routes) {
10605
11855
  artifactId,
10606
11856
  ...session ? { session } : {},
10607
11857
  document,
10608
- remote: incoming.socket.remoteAddress
11858
+ remote: incoming.socket.remoteAddress,
11859
+ client: checks.client ? checks.client(incoming) : incoming.socket.remoteAddress
10609
11860
  });
10610
11861
  };
10611
11862
  if (route.method === "GET") app.get(route.path, handle);
@@ -10637,6 +11888,31 @@ const MAX_HEADER_SIZE = 1048576;
10637
11888
  * failed the connect at once with `ERR_NO_BUFFER_SPACE` (#66).
10638
11889
  */
10639
11890
  const KEEP_ALIVE_MS = 305e3;
11891
+ /**
11892
+ * Ends a server's connections when it stops, without leaving them in TIME_WAIT on its side (#132):
11893
+ * a connection the server closes first stays in TIME_WAIT on the server's port for minutes, and
11894
+ * Windows refuses a browser's next connect from a random local port that meets one of them with
11895
+ * `ERR_NO_BUFFER_SPACE`, the more often as a restarted instance listens on the same leased ports
11896
+ * (D99). A reset (`SO_LINGER` 0) leaves nothing behind; whatever a stopping server still had on a
11897
+ * connection was being cut anyway. Answers the function that stops it.
11898
+ */
11899
+ function resetOnClose(server) {
11900
+ const sockets = /* @__PURE__ */ new Set();
11901
+ server.on("connection", (socket) => {
11902
+ sockets.add(socket);
11903
+ socket.once("close", () => sockets.delete(socket));
11904
+ });
11905
+ return () => new Promise((resolve) => {
11906
+ if (!server.listening) return resolve();
11907
+ for (const socket of sockets) {
11908
+ if (socket.destroyed) continue;
11909
+ if (typeof socket.resetAndDestroy === "function" && socket.readyState === "open") socket.resetAndDestroy();
11910
+ else socket.destroy();
11911
+ }
11912
+ server.close(() => resolve());
11913
+ server.closeAllConnections();
11914
+ });
11915
+ }
10640
11916
  /** Writes a refusal straight to a socket, for upgrades and envelope failures before Hono. */
10641
11917
  function writeRaw(socket, refused, extra = {}) {
10642
11918
  const body = extra.html ?? JSON.stringify(refused.diagnostic);
@@ -10828,11 +12104,7 @@ function createListener(options) {
10828
12104
  return {
10829
12105
  server,
10830
12106
  app,
10831
- close: () => new Promise((resolve) => {
10832
- if (!server.listening) return resolve();
10833
- server.close(() => resolve());
10834
- server.closeAllConnections();
10835
- })
12107
+ close: resetOnClose(server)
10836
12108
  };
10837
12109
  }
10838
12110
  //#endregion
@@ -10962,6 +12234,124 @@ function fileResponse(file, request, headers) {
10962
12234
  });
10963
12235
  }
10964
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
10965
12355
  //#region src/gateway/worker.ts
10966
12356
  /**
10967
12357
  * Worker-mode frame sessions (D70, D158 item 5): where the shell and the artifact are two sites,
@@ -11334,6 +12724,20 @@ function laterArtifactRoutes(served, acting, ticket) {
11334
12724
  auth: "session",
11335
12725
  ...acting ? { handler: acting.live } : {}
11336
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
+ },
11337
12741
  {
11338
12742
  method: "POST",
11339
12743
  path: "/_mostra/v/:rev/ticket",
@@ -11361,7 +12765,13 @@ function laterArtifactRoutes(served, acting, ticket) {
11361
12765
  /** Creates the gateway; nothing is bound until {@link Gateway.start}. */
11362
12766
  function createGateway(options) {
11363
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;
11364
12773
  const served = browserRoutes({
12774
+ ...team ? { team } : {},
11365
12775
  interaction,
11366
12776
  capabilities,
11367
12777
  log,
@@ -11374,6 +12784,7 @@ function createGateway(options) {
11374
12784
  } : void 0;
11375
12785
  },
11376
12786
  activated: options.activated,
12787
+ ...options.hosted?.admitSubmit ? { admitSubmit: options.hosted.admitSubmit } : {},
11377
12788
  ...options.revisions ? { revisions: options.revisions } : {},
11378
12789
  ...options.bus ? { bus: options.bus } : {}
11379
12790
  });
@@ -11659,6 +13070,7 @@ function createGateway(options) {
11659
13070
  };
11660
13071
  /** Where an artifact's links point: a host's external base when it gives one, else loopback. */
11661
13072
  const linkBase = async (artifactId) => {
13073
+ if (hosted?.linkOrigin) return await hosted.linkOrigin(artifactId) ?? shellOrigin();
11662
13074
  return (await hostFace(artifactId, "shell"))?.origin ?? shellOrigin();
11663
13075
  };
11664
13076
  /** The artifact way a shell way opens frames on, or why there is none. */
@@ -11723,7 +13135,8 @@ function createGateway(options) {
11723
13135
  const own = way().artifactId;
11724
13136
  return id !== void 0 && ArtifactId.is(id) && (own === void 0 || own === id) ? id : void 0;
11725
13137
  },
11726
- streams: () => way().streams()
13138
+ streams: () => way().streams(),
13139
+ ...hosted?.client ? { client: hosted.client } : {}
11727
13140
  });
11728
13141
  const shellMissing = () => jsonResponse(createDiagnostic("MOSTRA_ENV_SHELL_MISSING", { message: "This Mostra runtime has no built shell." }), { status: 503 });
11729
13142
  /** The exchanges each browser made, by artifact (WP-12; see `exchange`). */
@@ -11763,7 +13176,8 @@ function createGateway(options) {
11763
13176
  const found = await artifactWayFor(way, group, context.artifactId).catch(() => void 0);
11764
13177
  frames = found && !isRefusal(found) ? found.way.origin() ?? "'none'" : "'none'";
11765
13178
  }
11766
- const html = readFileSync(join(options.shellDir, "index.html"));
13179
+ const file = readFileSync(join(options.shellDir, "index.html"));
13180
+ const html = way.by === "hosted" ? hostedPreview(file.toString("utf8"), previewTitle(context.artifactId)) : file;
11767
13181
  return new Response(context.request.method === "HEAD" ? null : html, { headers: {
11768
13182
  ...BASE_HEADERS,
11769
13183
  ...documentHeaders(shellKind(way), frames),
@@ -11771,6 +13185,15 @@ function createGateway(options) {
11771
13185
  "cache-control": "no-cache"
11772
13186
  } });
11773
13187
  };
13188
+ /** The title a hosted page's preview may show: its own only when the manifest asks (D161). */
13189
+ const previewTitle = (artifactId) => {
13190
+ try {
13191
+ const detail = artifacts.get({ artifactId });
13192
+ return detail.manifest.hosted?.preview === "title" ? detail.title : void 0;
13193
+ } catch {
13194
+ return;
13195
+ }
13196
+ };
11774
13197
  const shellAsset = async (context) => {
11775
13198
  if (options.shellDir === void 0) return shellMissing();
11776
13199
  const url = new URL(context.request.url);
@@ -11791,8 +13214,9 @@ function createGateway(options) {
11791
13214
  * 2): the home's local user on loopback; over a tunnel the tailnet person Tailscale Serve
11792
13215
  * named, else the link's own viewer, never the home's local user.
11793
13216
  */
11794
- const defaultViewer = (way, context, grant) => {
13217
+ const defaultViewer = (way, context, grant, browser) => {
11795
13218
  if (way.via === "local") return void 0;
13219
+ if (way.by === "hosted" && hosted?.anonymousViewer) return hosted.anonymousViewer(browser);
11796
13220
  if (way.via === "tailnet") {
11797
13221
  const person = tailnetPerson(context.request.headers, context.remote);
11798
13222
  if (person) return interaction.viewerForTailnet(person);
@@ -11855,7 +13279,7 @@ function createGateway(options) {
11855
13279
  });
11856
13280
  return jsonResponse(outcome.diagnostic, { status: 503 });
11857
13281
  }
11858
- viewerId = outcome.kind === "person" ? interaction.viewerForHost(outcome.viewer) : defaultViewer(way, context, grant);
13282
+ viewerId = outcome.kind === "person" ? interaction.viewerForHost(outcome.viewer) : defaultViewer(way, context, grant, typeof body["browser"] === "string" && browser !== void 0 ? body["browser"] : void 0);
11859
13283
  }
11860
13284
  const now = launch ? capabilities.presentLaunch(body["launch"], artifactId, true, origin) : capabilities.presentToken(body["token"], artifactId, origin);
11861
13285
  if (isRefusal(now)) return refuse(checks, now, meta);
@@ -11934,6 +13358,15 @@ function createGateway(options) {
11934
13358
  if (version.collected !== void 0) return jsonResponse(collectedDiagnostic(version.number), { status: 410 });
11935
13359
  const damage = options.dev ? void 0 : await integrity.check(version.id);
11936
13360
  if (damage !== void 0) return damaged(version.number, damage, false, "'none'");
13361
+ if (hosted?.admitView) {
13362
+ const refused = await hosted.admitView({
13363
+ artifactId,
13364
+ versionId: version.id,
13365
+ tokenId: session.grant.tokenId,
13366
+ client: context.client
13367
+ });
13368
+ if (refused) return refuse(checks, refused, meta);
13369
+ }
11937
13370
  const found = await artifactWayFor(way, group, artifactId);
11938
13371
  if (isRefusal(found)) return refuse(checks, found, meta);
11939
13372
  const artifactOrigin = found.way.origin();
@@ -11949,6 +13382,12 @@ function createGateway(options) {
11949
13382
  });
11950
13383
  const controls = await options.controls(detail);
11951
13384
  const viewerId = interaction.viewerOf(session.viewerId);
13385
+ const pause = interaction.pauseOf(artifactId);
13386
+ const chrome = hosted?.chrome ? await hosted.chrome({
13387
+ artifactId,
13388
+ tokenId: session.grant.tokenId,
13389
+ viewerId
13390
+ }) : void 0;
11952
13391
  return jsonResponse({
11953
13392
  artifactId,
11954
13393
  viewId: interaction.openView({
@@ -11980,7 +13419,12 @@ function createGateway(options) {
11980
13419
  pinned: pinned !== void 0,
11981
13420
  ...options.parked?.(version.id) ? { serverParked: true } : {},
11982
13421
  ...options.dev ? { devPreview: true } : {},
11983
- ...mode === "worker" ? { mode: "worker" } : {}
13422
+ ...mode === "worker" ? { mode: "worker" } : {},
13423
+ ...pause ? { paused: {
13424
+ by: pause.by,
13425
+ ...pause.reason !== void 0 ? { reason: pause.reason } : {}
13426
+ } } : {},
13427
+ ...chrome ? { hosted: chrome } : {}
11984
13428
  });
11985
13429
  };
11986
13430
  return [
@@ -12085,7 +13529,8 @@ function createGateway(options) {
12085
13529
  intent: "mutation",
12086
13530
  auth: "session",
12087
13531
  scope: () => "review"
12088
- }
13532
+ },
13533
+ ...hosted?.shellRoutes?.({ refuse: (refused, request) => refuse(checks, refused, request) }) ?? []
12089
13534
  ];
12090
13535
  };
12091
13536
  const artifactChecks = (artifactId, wayOf, group) => ({
@@ -12096,20 +13541,26 @@ function createGateway(options) {
12096
13541
  capabilities,
12097
13542
  log,
12098
13543
  cookieName: () => `mostra-${wayOf().port()}`,
12099
- frameAncestors: () => shellOf(wayOf(), group)?.origin() ?? "'none'",
13544
+ frameAncestors: () => {
13545
+ const way = wayOf();
13546
+ if (way.by === "hosted" && hosted?.frameAncestors) return hosted.frameAncestors(artifactId, way.origin() ?? "") || "'none'";
13547
+ return shellOf(way, group)?.origin() ?? "'none'";
13548
+ },
12100
13549
  artifactOf: () => artifactId,
12101
13550
  mode: () => modeOf(wayOf(), group),
12102
- streams: () => wayOf().streams()
13551
+ streams: () => wayOf().streams(),
13552
+ ...hosted?.client ? { client: hosted.client } : {}
12103
13553
  });
12104
13554
  const artifactRoutes = (artifactId, wayOf, group) => {
12105
13555
  const origin = () => wayOf().origin() ?? "";
12106
13556
  const shell = () => shellOf(wayOf(), group)?.origin() ?? "";
13557
+ const checks = artifactChecks(artifactId, wayOf, group);
12107
13558
  const kind = () => ({
12108
13559
  kind: "artifact",
12109
13560
  origin: origin(),
12110
- shellOrigin: shell()
13561
+ shellOrigin: shell(),
13562
+ ...wayOf().by === "hosted" ? { frameAncestors: checks.frameAncestors() } : {}
12111
13563
  });
12112
- const checks = artifactChecks(artifactId, wayOf, group);
12113
13564
  const mode = () => modeOf(wayOf(), group);
12114
13565
  const notServed = (context, message) => refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", message), {
12115
13566
  method: context.request.method,
@@ -12302,6 +13753,8 @@ function createGateway(options) {
12302
13753
  }
12303
13754
  }
12304
13755
  const checked = file ?? (context.document ? await findFile(root(versionId), "/index.html") : void 0);
13756
+ const withheld = hosted?.blocked?.(artifactId, from);
13757
+ if (withheld) return refuse(checks, withheld, meta);
12305
13758
  if (checked) {
12306
13759
  const damage = await integrity.serve(from, checked);
12307
13760
  if (damage !== void 0) {
@@ -12558,6 +14011,17 @@ function createGateway(options) {
12558
14011
  by: entry.spec.by
12559
14012
  })),
12560
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
+ }),
12561
14025
  handler(viewUrlMethod, async (params) => {
12562
14026
  const detail = artifacts.get(params.artifact);
12563
14027
  const version = versionOf(detail, params.version);
@@ -12602,6 +14066,7 @@ function createGateway(options) {
12602
14066
  ],
12603
14067
  artifactOrigins: () => new Map([...artifactListeners].map(([artifactId, entry]) => [artifactId, addressing.origin(entry.port)])),
12604
14068
  async close() {
14069
+ team?.close();
12605
14070
  await Promise.allSettled([...opening.values(), ...openingFaces.values()]);
12606
14071
  await Promise.all([
12607
14072
  shellListener?.close(),
@@ -12657,6 +14122,33 @@ function locateShell(env) {
12657
14122
  const dir = env["MOSTRA_SHELL_DIR"] ?? resolve(runtimeRoot$1(), "..", "shell", "dist");
12658
14123
  return existsSync(join(dir, "index.html")) ? dir : void 0;
12659
14124
  }
14125
+ /** The generic preview of every hosted page (D161): one title, one description, no image. */
14126
+ const HOSTED_PREVIEW = {
14127
+ title: "A page sent with Mostra",
14128
+ description: "Someone sent you this page. Open it to see it."
14129
+ };
14130
+ /** Text for an HTML attribute or element: nothing a tenant writes is ever markup. */
14131
+ function previewText(text) {
14132
+ return text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);
14133
+ }
14134
+ /**
14135
+ * The hosted shell's page with its link preview (D161): the generic title and description, or
14136
+ * the artifact's title alone when its manifest asks (`hosted.preview: "title"`), never its text or
14137
+ * images, and `noindex`.
14138
+ */
14139
+ function hostedPreview(html, title) {
14140
+ const shown = previewText(title ?? HOSTED_PREVIEW.title);
14141
+ const description = previewText(HOSTED_PREVIEW.description);
14142
+ const tags = [
14143
+ `<meta name="robots" content="noindex, nofollow">`,
14144
+ `<meta name="description" content="${description}">`,
14145
+ `<meta property="og:title" content="${shown}">`,
14146
+ `<meta property="og:description" content="${description}">`,
14147
+ `<meta property="og:site_name" content="Mostra">`,
14148
+ `<meta name="twitter:card" content="summary">`
14149
+ ].join("\n ");
14150
+ return html.replace(/<title>[^<]*<\/title>/, `<title>${shown}</title>\n ${tags}`);
14151
+ }
12660
14152
  //#endregion
12661
14153
  //#region src/live/index.ts
12662
14154
  /**
@@ -14296,6 +15788,14 @@ function runnerEnvironment(env, browsers) {
14296
15788
  if (browsers !== void 0) out["PLAYWRIGHT_BROWSERS_PATH"] = browsers;
14297
15789
  const idle = env["MOSTRA_TEST_VERIFY_IDLE_MS"];
14298
15790
  if (idle) out["MOSTRA_TEST_VERIFY_IDLE_MS"] = idle;
15791
+ for (const name of [
15792
+ "MOSTRA_TEST_VERIFY_LOSE_BROWSER",
15793
+ "MOSTRA_TEST_VERIFY_FAIL_ONCE",
15794
+ "MOSTRA_TEST_VERIFY_COLLIDE_ONCE"
15795
+ ]) {
15796
+ const value = env[name];
15797
+ if (value) out[name] = value;
15798
+ }
14299
15799
  return out;
14300
15800
  }
14301
15801
  /** Creates the client; nothing starts until the first request. */
@@ -14360,9 +15860,24 @@ function createRunnerClient(options) {
14360
15860
  }
14361
15861
  throw new RpcError(createDiagnostic("MOSTRA_VERIFY_TIMEOUT", { message: "Verify ran out of time: the browser stopped answering while it checked the page." }));
14362
15862
  }
15863
+ let failure = "";
14363
15864
  if (outcome.kind === "error" && outcome.error instanceof RpcError) {
14364
15865
  const code = outcome.error.diagnostic.code;
14365
15866
  if (code !== "MOSTRA_HOST_INTERNAL_ERROR" && !code.startsWith("MOSTRA_HOST_CONNECTION")) throw outcome.error;
15867
+ if (code === "MOSTRA_HOST_INTERNAL_ERROR") {
15868
+ failure = outcome.error.diagnostic.message;
15869
+ options.log.warn("verify.runner_failed", {
15870
+ method,
15871
+ error: failure.slice(0, 500)
15872
+ });
15873
+ if (child) {
15874
+ const failed = child;
15875
+ child = void 0;
15876
+ const stopped = await failed.catch(() => void 0);
15877
+ if (stopped) recycled.add(stopped);
15878
+ await stopped?.stop(2e3);
15879
+ }
15880
+ }
14366
15881
  }
14367
15882
  if (recycled.has(handle) && !retried) {
14368
15883
  options.log.info("verify.runner_retry", { method });
@@ -14370,7 +15885,8 @@ function createRunnerClient(options) {
14370
15885
  }
14371
15886
  const exit = outcome.kind === "exit" ? outcome.exit : await Promise.race([handle.exited, new Promise((done) => setTimeout(() => done(void 0), 1e3))]);
14372
15887
  const tail = exit?.stderrTail.slice(-10).join("\n") ?? "";
14373
- throw new RpcError(createDiagnostic("MOSTRA_VERIFY_CRASHED", { message: `The verify runner stopped before it answered${exit ? ` (${exit.signal ?? `code ${exit.code}`})` : ""}.${tail ? `\n${tail}` : ""}` }));
15888
+ const said = failure ? `\nThe runner said: ${failure.slice(0, 1e3)}` : "";
15889
+ throw new RpcError(createDiagnostic("MOSTRA_VERIFY_CRASHED", { message: `The verify runner stopped before it answered${exit ? ` (${exit.signal ?? `code ${exit.code}`})` : ""}.${tail ? `\n${tail}` : ""}${said}` }));
14374
15890
  };
14375
15891
  return {
14376
15892
  render: (request) => ask(VERIFY_RUNNER_METHODS.render, request, request.deadline),
@@ -14679,6 +16195,10 @@ function createVerifier(options) {
14679
16195
  if (error instanceof RpcError && error.diagnostic.code === "MOSTRA_VERIFY_TIMEOUT") return { timedOut: true };
14680
16196
  throw error;
14681
16197
  });
16198
+ if (result.renderedAgain !== void 0) options.log.info("verify.rendered_again", {
16199
+ name,
16200
+ why: options.redactor.redact(result.renderedAgain)
16201
+ });
14682
16202
  if (result.aria) {
14683
16203
  const text = options.redactor.redact(result.aria.text);
14684
16204
  await writeFile(result.aria.path, text);
@@ -17843,6 +19363,155 @@ function markHostConfigured(home, client, at = /* @__PURE__ */ new Date()) {
17843
19363
  return true;
17844
19364
  }
17845
19365
  //#endregion
19366
+ //#region src/link/author.ts
19367
+ /**
19368
+ * Authoring from a chat host, on the owner instance (INTERFACES §18.8, D165 item 5): the remote MCP
19369
+ * server relays `artifact/create`, `verify` and `publish`, and the workspace's files, to the
19370
+ * account's default owner instance as `port/relay.author`, and this module runs each here, on this
19371
+ * home's own protocol server, in an in-process session as any host would (invariant 11).
19372
+ *
19373
+ * The relay is a way in from outside this machine, so every directory it names stays inside this
19374
+ * home's MCP workspace (`MOSTRA_MCP_WORKSPACE`, default `~/mostra-artifacts`, as `mostra mcp`'s):
19375
+ * a relative one resolves there, an absolute one must already be there, and anything else is
19376
+ * `MOSTRA_ARTIFACT_PATH_INVALID`. A screenshot is read only from verify's own cache. A publish also
19377
+ * hosts the version on the server that asked and answers its hosted link.
19378
+ */
19379
+ /** The eight bytes every PNG file starts with. */
19380
+ const PNG_SIGNATURE = Buffer.from([
19381
+ 137,
19382
+ 80,
19383
+ 78,
19384
+ 71,
19385
+ 13,
19386
+ 10,
19387
+ 26,
19388
+ 10
19389
+ ]);
19390
+ function outside(message) {
19391
+ return new RpcError(createDiagnostic("MOSTRA_ARTIFACT_PATH_INVALID", { message }));
19392
+ }
19393
+ /** Whether `inner` is `outer` or inside it. */
19394
+ function within(outer, inner) {
19395
+ const between = relative(outer, inner);
19396
+ return between === "" || !between.startsWith("..") && !isAbsolute(between);
19397
+ }
19398
+ /** Creates the owner's answer to relayed authoring. */
19399
+ function createOwnerAuthor(options) {
19400
+ const configured = options.env["MOSTRA_MCP_WORKSPACE"];
19401
+ const root = resolve(configured !== void 0 && configured !== "" ? configured : defaultWorkspaceRoot());
19402
+ const workspace = localWorkspace(root);
19403
+ const verifyCache = join(options.home, "cache", "verify");
19404
+ /** A directory the relay names, inside the workspace or refused. */
19405
+ const dirOf = (dir) => {
19406
+ if (typeof dir !== "string" || dir === "") throw outside("Name an artifact's directory.");
19407
+ const absolute = isAbsolute(dir) ? resolve(dir) : workspace.resolveDir(dir);
19408
+ let real = absolute;
19409
+ try {
19410
+ real = realpathSync.native(absolute);
19411
+ } catch {}
19412
+ let base = root;
19413
+ try {
19414
+ base = realpathSync.native(root);
19415
+ } catch {}
19416
+ if (!within(root, absolute) || !within(base, real)) throw outside(`A chat host's authoring stays inside this machine's Mostra workspace (${root}); ${dir} is outside it.`);
19417
+ return absolute;
19418
+ };
19419
+ /** One call on this home's protocol server, in a session of its own. */
19420
+ const local = async (method, params) => {
19421
+ const protocol = options.protocol();
19422
+ if (protocol === void 0) throw new RpcError(createDiagnostic("MOSTRA_REMOTE_NO_INSTANCE", { message: "This Mostra instance is still starting; try again in a moment." }));
19423
+ const { client } = await attachInProcess(protocol, {
19424
+ name: "mostra-remote-author",
19425
+ version: options.runtimeVersion
19426
+ });
19427
+ try {
19428
+ return await client.peer.call(method, params);
19429
+ } finally {
19430
+ client.close();
19431
+ }
19432
+ };
19433
+ return async (server, raw) => {
19434
+ const { method, params } = portRelayAuthorMethod.params.parse(raw);
19435
+ const given = params ?? {};
19436
+ options.log.info("link.author", {
19437
+ server,
19438
+ method
19439
+ });
19440
+ switch (method) {
19441
+ case "workspace/root": return root;
19442
+ case "workspace/allocate": return workspace.allocateDir(typeof given["title"] === "string" ? given["title"] : void 0);
19443
+ case "workspace/read": {
19444
+ const content = await workspace.read(dirOf(given["dir"]), String(given["path"] ?? ""));
19445
+ return content === void 0 ? {} : { content: Buffer.from(content).toString("base64") };
19446
+ }
19447
+ case "workspace/apply": {
19448
+ const write = Array.isArray(given["write"]) ? given["write"] : [];
19449
+ const deletes = Array.isArray(given["delete"]) ? given["delete"] : [];
19450
+ return workspace.apply(dirOf(given["dir"]), {
19451
+ write: write.map((file) => {
19452
+ const entry = file;
19453
+ return {
19454
+ path: String(entry.path ?? ""),
19455
+ content: Buffer.from(String(entry.content ?? ""), "base64")
19456
+ };
19457
+ }),
19458
+ delete: deletes.map(String)
19459
+ });
19460
+ }
19461
+ case "verify/screenshot": {
19462
+ const path = resolve(String(given["path"] ?? ""));
19463
+ let real = path;
19464
+ try {
19465
+ real = realpathSync.native(path);
19466
+ } catch {
19467
+ return {};
19468
+ }
19469
+ if (!path.toLowerCase().endsWith(".png") || !within(verifyCache, path) || !within(realpathSync.native(verifyCache), real)) return {};
19470
+ try {
19471
+ const bytes = await readFile(real);
19472
+ return bytes.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE) ? { png: bytes.toString("base64") } : {};
19473
+ } catch {
19474
+ return {};
19475
+ }
19476
+ }
19477
+ case "artifact/create": return local(artifactCreateMethod, {
19478
+ ...given,
19479
+ dir: dirOf(given["dir"])
19480
+ });
19481
+ case "artifact/get": {
19482
+ const artifact = given["artifact"];
19483
+ const detail = await local(artifactGetMethod, { artifact: artifact?.path !== void 0 ? { path: dirOf(artifact.path) } : { artifactId: String(artifact?.artifactId ?? "") } });
19484
+ return {
19485
+ id: detail.id,
19486
+ title: detail.title
19487
+ };
19488
+ }
19489
+ case "artifact/verify": {
19490
+ const source = given["source"];
19491
+ return local(artifactVerifyMethod, {
19492
+ ...given,
19493
+ source: { path: dirOf(source?.path) }
19494
+ });
19495
+ }
19496
+ case "artifact/publish": {
19497
+ const source = given["source"];
19498
+ const receipt = await local(artifactPublishMethod, {
19499
+ ...given,
19500
+ source: { path: dirOf(source?.path) }
19501
+ });
19502
+ if (!options.hostedOn(receipt.artifactId).includes(server)) await local(shareStartMethod, {
19503
+ artifact: { artifactId: receipt.artifactId },
19504
+ via: "remote",
19505
+ server
19506
+ });
19507
+ const { url: _local, tokenId: _token, ...crossing } = receipt;
19508
+ return crossing;
19509
+ }
19510
+ default: throw outside(`The relay serves no authoring method ${method}.`);
19511
+ }
19512
+ };
19513
+ }
19514
+ //#endregion
17846
19515
  //#region src/link/binding.ts
17847
19516
  /**
17848
19517
  * The owner's side of the network binding (INTERFACES §18.2, D165 item 2): one WebSocket to a
@@ -18071,7 +19740,10 @@ function ownerInitialize(input) {
18071
19740
  const FORWARDED = /* @__PURE__ */ new Set([
18072
19741
  stateGetMethod.method,
18073
19742
  statePatchMethod.method,
18074
- livePushMethod.method
19743
+ livePushMethod.method,
19744
+ rosterAddMethod.method,
19745
+ rosterRemoveMethod.method,
19746
+ rosterGetMethod.method
18075
19747
  ]);
18076
19748
  /** Server code's `state` for an artifact hosted somewhere, else `undefined`. */
18077
19749
  function hostedState(link, artifactId) {
@@ -18094,8 +19766,8 @@ function hostedState(link, artifactId) {
18094
19766
  };
18095
19767
  }
18096
19768
  /**
18097
- * Wraps the instance's `state/get`, `state/patch` and `live/push` so that, for a hosted artifact,
18098
- * 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.
18099
19771
  */
18100
19772
  function forwardHosted(link, resolve, handlers) {
18101
19773
  return handlers.map((entry) => {
@@ -18115,6 +19787,32 @@ function forwardHosted(link, resolve, handlers) {
18115
19787
  };
18116
19788
  });
18117
19789
  }
19790
+ /**
19791
+ * The owner's `artifact/pause` (D165 item 14): pauses or resumes the artifact here and on every
19792
+ * server it is hosted on, each as its owner. A server where the operator paused it answers that
19793
+ * only the operator resumes it (`MOSTRA_REMOTE_PAUSED_BY_OPERATOR`); one that can't be reached is
19794
+ * `MOSTRA_REMOTE_UNREACHABLE`, and the call can be made again, since a pause is idempotent.
19795
+ */
19796
+ function pauseHandler(link, resolve, pause) {
19797
+ return handler(artifactPauseMethod, async (params) => {
19798
+ const artifactId = resolve(params.artifact);
19799
+ let byOperator = false;
19800
+ for (const server of link.hostedServers(artifactId)) if ((await link.forward(server, artifactPauseMethod, {
19801
+ artifact: { artifactId },
19802
+ paused: params.paused,
19803
+ ...params.reason !== void 0 ? { reason: params.reason } : {}
19804
+ })).by === "operator") byOperator = true;
19805
+ const local = pause(artifactId, {
19806
+ paused: params.paused,
19807
+ by: "owner",
19808
+ ...params.reason !== void 0 ? { reason: params.reason } : {}
19809
+ });
19810
+ return byOperator ? {
19811
+ paused: true,
19812
+ by: "operator"
19813
+ } : local;
19814
+ });
19815
+ }
18118
19816
  /** The largest answer the instance reads (the API answers JSON; files go the other way). */
18119
19817
  const MAX_ANSWER_BYTES = 4194304;
18120
19818
  /** Reads the test override, `host:port`, or nothing. */
@@ -18178,12 +19876,13 @@ function remoteRequest(server, path, init = {}) {
18178
19876
  });
18179
19877
  }
18180
19878
  /** Posts a form and reads a JSON answer, whatever its status. */
18181
- async function postForm(server, path, fields, connectTo) {
19879
+ async function postForm(server, path, fields, connectTo, bearer) {
18182
19880
  const answer = await remoteRequest(server, path, {
18183
19881
  method: "POST",
18184
19882
  headers: {
18185
19883
  "content-type": "application/x-www-form-urlencoded",
18186
- accept: "application/json"
19884
+ accept: "application/json",
19885
+ ...bearer !== void 0 ? { authorization: `Bearer ${bearer}` } : {}
18187
19886
  },
18188
19887
  body: new URLSearchParams(fields).toString(),
18189
19888
  ...connectTo ? { connectTo } : {}
@@ -18560,6 +20259,8 @@ function invalid(message) {
18560
20259
  function loginFailed(message) {
18561
20260
  return new RpcError(createDiagnostic("MOSTRA_REMOTE_LOGIN_FAILED", { message }));
18562
20261
  }
20262
+ /** The secret a home's credentials hold. */
20263
+ const credentialSecret = (credentials) => "key" in credentials ? credentials.key : credentials.refreshToken;
18563
20264
  /** Creates the owner's link manager. */
18564
20265
  function createLink(options) {
18565
20266
  const { ledger, log } = options;
@@ -18575,8 +20276,9 @@ function createLink(options) {
18575
20276
  if (!existsSync(file)) return void 0;
18576
20277
  try {
18577
20278
  const parsed = JSON.parse(readFileSync(file, "utf8"));
18578
- if (parsed.server !== server || typeof parsed.refreshToken !== "string") return void 0;
18579
- options.protect(parsed.refreshToken);
20279
+ const secret = parsed.refreshToken ?? parsed.key;
20280
+ if (parsed.server !== server || typeof secret !== "string") return void 0;
20281
+ options.protect(secret);
18580
20282
  return parsed;
18581
20283
  } catch {
18582
20284
  return;
@@ -18587,7 +20289,7 @@ function createLink(options) {
18587
20289
  recursive: true,
18588
20290
  mode: 448
18589
20291
  });
18590
- options.protect(credentials.refreshToken);
20292
+ options.protect(credentialSecret(credentials));
18591
20293
  const target = credentialsFile(credentials.server);
18592
20294
  const temporary = `${target}.${process.pid}.tmp`;
18593
20295
  writeFileSync(temporary, JSON.stringify(credentials), { mode: 384 });
@@ -18626,6 +20328,14 @@ function createLink(options) {
18626
20328
  const secret = /#t=([^&]+)/.exec(url)?.[1];
18627
20329
  if (secret !== void 0) options.protect(secret);
18628
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
+ };
18629
20339
  const linkRow = (db, server) => db.get("SELECT * FROM remote_link WHERE server = ?", server);
18630
20340
  const owned = (server) => (db, artifactId) => db.get("SELECT 1 FROM hosted_artifact WHERE artifact_id = ? AND server = ?", artifactId, server) !== void 0;
18631
20341
  /** A fresh access token, refreshing (and rotating the refresh token) when it's due. */
@@ -18636,6 +20346,7 @@ function createLink(options) {
18636
20346
  try {
18637
20347
  const credentials = readCredentials(connection.server);
18638
20348
  if (!credentials) throw loginFailed(`This home isn't signed in to ${connection.server}.`);
20349
+ if ("key" in credentials) return credentials.key;
18639
20350
  const answer = await postForm(connection.server, "/oauth/token", {
18640
20351
  client_id: CLIENT_ID,
18641
20352
  grant_type: "refresh_token",
@@ -18792,6 +20503,10 @@ function createLink(options) {
18792
20503
  ...options.liveChanged ? { liveChanged: options.liveChanged } : {}
18793
20504
  });
18794
20505
  const onRequest = (connection) => (method, params) => {
20506
+ if (method === portRelayAuthorMethod.method) {
20507
+ if (!options.author) throw new RpcError(createDiagnostic("MOSTRA_REMOTE_NO_INSTANCE", { message: "This instance takes no authoring from a chat host." }));
20508
+ return options.author(connection.server, params);
20509
+ }
18795
20510
  if (relay.handles(method)) return relay.request(connection.server, () => connection.binding.session ?? readySoon(connection), method, params, () => connection.binding.reconnect());
18796
20511
  if (method === portSubmissionsDeliverMethod.method) {
18797
20512
  const parsed = SubmissionEnvelope.safeParse(params?.envelope ?? params);
@@ -19090,6 +20805,68 @@ function createLink(options) {
19090
20805
  if (!last) throw invalid("Name the server to sign in to: mostra login <server>. No server is configured by default.");
19091
20806
  return last.server;
19092
20807
  };
20808
+ /** Records this home's link to a server, rebinding its marks only to the same link (WP-29). */
20809
+ const recordLink = (server, account, instanceId, isDefault) => {
20810
+ ledger.write((db) => db.run(`INSERT INTO remote_link (server, account_id, account_name, instance_id, is_default, linked_at, state)
20811
+ VALUES (?, ?, ?, ?, ?, ?, 'signed-in')
20812
+ ON CONFLICT (server) DO UPDATE SET
20813
+ -- Another link (after --forget, or another account) starts with no marks: a mark
20814
+ -- of the old link would make the new one's home look restored (Opus review of
20815
+ -- WP-29, 9).
20816
+ relay_mark = CASE WHEN remote_link.instance_id IS excluded.instance_id
20817
+ AND remote_link.account_id = excluded.account_id THEN remote_link.relay_mark ELSE 0 END,
20818
+ follow_cursor = CASE WHEN remote_link.instance_id IS excluded.instance_id
20819
+ AND remote_link.account_id = excluded.account_id THEN remote_link.follow_cursor ELSE NULL END,
20820
+ incarnation = CASE WHEN remote_link.instance_id IS excluded.instance_id
20821
+ AND remote_link.account_id = excluded.account_id THEN remote_link.incarnation ELSE NULL END,
20822
+ account_id = excluded.account_id, account_name = excluded.account_name,
20823
+ instance_id = excluded.instance_id, is_default = excluded.is_default, linked_at = excluded.linked_at,
20824
+ state = 'signed-in'`, server, account.id, account.name ?? null, instanceId, isDefault ? 1 : 0, new Date(now()).toISOString()));
20825
+ };
20826
+ /**
20827
+ * Links this home with a key the server's operator issued (`remote/link`, D167): the server says
20828
+ * which account and instance link the key binds, the key is kept like a refresh token, and the
20829
+ * binding opens with it at once.
20830
+ */
20831
+ const linkWithKey = async (requested, key, makeDefault) => {
20832
+ const server = serverOrigin(requested);
20833
+ options.protect(key);
20834
+ const answer = await postForm(server, "/link", makeDefault ? { default: "1" } : {}, connectTo, key);
20835
+ const account = answer.json["account"];
20836
+ const instanceId = answer.json["instanceId"];
20837
+ if (answer.status !== 200 || typeof account?.id !== "string" || typeof instanceId !== "string" || !LinkId.is(instanceId)) throw loginFailed(`${server} didn't admit this key (${String(answer.json["message"] ?? answer.status)}).`);
20838
+ const name = typeof account.name === "string" ? account.name : void 0;
20839
+ const isDefault = answer.json["default"] === true;
20840
+ writeCredentials({
20841
+ server,
20842
+ key,
20843
+ instanceId
20844
+ });
20845
+ recordLink(server, {
20846
+ id: account.id,
20847
+ name
20848
+ }, instanceId, isDefault);
20849
+ const previous = connections.get(server);
20850
+ if (previous) {
20851
+ await previous.binding.stop();
20852
+ if (previous.refreshTimer) clearTimeout(previous.refreshTimer);
20853
+ connections.delete(server);
20854
+ }
20855
+ connect(server);
20856
+ log.info("link.linked_with_key", {
20857
+ server,
20858
+ instanceId
20859
+ });
20860
+ return {
20861
+ server,
20862
+ account: {
20863
+ id: account.id,
20864
+ ...name !== void 0 ? { name } : {}
20865
+ },
20866
+ instanceId,
20867
+ default: isDefault
20868
+ };
20869
+ };
19093
20870
  /** Starts a sign-in: the device grant's code, then polls for the token in the background. */
19094
20871
  const login = async (requested, makeDefault = false) => {
19095
20872
  const server = resolveServer(requested);
@@ -19166,21 +20943,7 @@ function createLink(options) {
19166
20943
  refreshToken,
19167
20944
  instanceId
19168
20945
  });
19169
- ledger.write((db) => db.run(`INSERT INTO remote_link (server, account_id, account_name, instance_id, is_default, linked_at, state)
19170
- VALUES (?, ?, ?, ?, ?, ?, 'signed-in')
19171
- ON CONFLICT (server) DO UPDATE SET
19172
- -- Another link (after --forget, or another account) starts with no marks: a mark
19173
- -- of the old link would make the new one's home look restored (Opus review of
19174
- -- WP-29, 9).
19175
- relay_mark = CASE WHEN remote_link.instance_id IS excluded.instance_id
19176
- AND remote_link.account_id = excluded.account_id THEN remote_link.relay_mark ELSE 0 END,
19177
- follow_cursor = CASE WHEN remote_link.instance_id IS excluded.instance_id
19178
- AND remote_link.account_id = excluded.account_id THEN remote_link.follow_cursor ELSE NULL END,
19179
- incarnation = CASE WHEN remote_link.instance_id IS excluded.instance_id
19180
- AND remote_link.account_id = excluded.account_id THEN remote_link.incarnation ELSE NULL END,
19181
- account_id = excluded.account_id, account_name = excluded.account_name,
19182
- instance_id = excluded.instance_id, is_default = excluded.is_default, linked_at = excluded.linked_at,
19183
- state = 'signed-in'`, server, account.id, account.name ?? null, instanceId, answer.json["mostra_default"] === true ? 1 : 0, new Date(now()).toISOString()));
20946
+ recordLink(server, account, instanceId, answer.json["mostra_default"] === true);
19184
20947
  const previous = connections.get(server);
19185
20948
  if (previous) {
19186
20949
  await previous.binding.stop();
@@ -19238,6 +21001,7 @@ function createLink(options) {
19238
21001
  methods() {
19239
21002
  return [
19240
21003
  handler(remoteLoginMethod, (params) => login(params.server, params.default === true)),
21004
+ handler(remoteLinkMethod, (params) => linkWithKey(params.server, params.key, params.default === true)),
19241
21005
  handler(remoteLoginWaitMethod, async (params) => {
19242
21006
  const pending = logins.get(params.loginId);
19243
21007
  if (!pending) throw invalid(`No sign-in ${params.loginId} is in progress.`);
@@ -19270,7 +21034,7 @@ function createLink(options) {
19270
21034
  if (connection.pushTimer) clearTimeout(connection.pushTimer);
19271
21035
  connections.delete(server);
19272
21036
  }
19273
- if (credentials) try {
21037
+ if (credentials && "refreshToken" in credentials) try {
19274
21038
  await postForm(server, "/oauth/revoke", {
19275
21039
  token: credentials.refreshToken,
19276
21040
  client_id: CLIENT_ID
@@ -19364,6 +21128,7 @@ function createLink(options) {
19364
21128
  }
19365
21129
  return true;
19366
21130
  },
21131
+ hostedServers: (artifactId) => ledger.read((db) => db.all("SELECT server FROM hosted_artifact WHERE artifact_id = ? AND stopped_at IS NULL AND route_id != '' ORDER BY shared_at", artifactId).map((row) => row.server)),
19367
21132
  hostedOn: (artifactId) => ledger.read((db) => db.get("SELECT server FROM hosted_artifact WHERE artifact_id = ? AND stopped_at IS NULL AND route_id != '' ORDER BY shared_at LIMIT 1", artifactId)?.server),
19368
21133
  forward: async (server, definition, params) => {
19369
21134
  let session;
@@ -19373,7 +21138,9 @@ function createLink(options) {
19373
21138
  if (error instanceof RpcError) throw error;
19374
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.` }));
19375
21140
  }
19376
- return session.call(definition, params, { timeoutMs: 3e4 });
21141
+ const answer = await session.call(definition, params, { timeoutMs: 3e4 });
21142
+ protectLinksIn(answer);
21143
+ return answer;
19377
21144
  },
19378
21145
  shares: () => ({
19379
21146
  mint: async (input) => {
@@ -19398,6 +21165,16 @@ function createLink(options) {
19398
21165
  ...minted.expiresAt !== void 0 ? { expiresAt: minted.expiresAt } : {}
19399
21166
  };
19400
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
+ },
19401
21178
  url: (server, tokenId) => readLinks(server)[tokenId],
19402
21179
  revoke: async (server, tokenId) => {
19403
21180
  await (await self.session(server)).call(viewRevokeMethod, { tokenId });
@@ -20822,13 +22599,33 @@ function createShares(options) {
20822
22599
  const start = async (params) => {
20823
22600
  const detail = options.artifacts.get(params.artifact);
20824
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
+ };
20825
22622
  const key = requestKey("share/start", params);
20826
22623
  if (key !== void 0) {
20827
22624
  const replay = ledger.read((db) => recordedResult(db, key));
20828
22625
  const found = replay ? row(replay.shareId) : void 0;
20829
- if (found) return withUrl(toShare(found));
22626
+ if (found) return withRespondents(withUrl(toShare(found)));
20830
22627
  }
20831
- if (params.via === "remote") return startRemote(params, detail, key);
22628
+ if (params.via === "remote") return withRespondents(await startRemote(params, detail, key));
20832
22629
  const ttlMs = lifetime(params.via, params.ttl);
20833
22630
  const shareId = ShareId.create();
20834
22631
  const { shell, artifact, plan, hostname } = await setUp(shareId, detail.id, params.via, void 0);
@@ -21557,7 +23354,16 @@ async function assemble(home, options) {
21557
23354
  versionDir: (versionId) => registry.store.versionDir(versionId),
21558
23355
  actions,
21559
23356
  liveChanged: () => live.reconcile(),
21560
- now: () => Date.now() + clockOffset
23357
+ now: () => Date.now() + clockOffset,
23358
+ author: (from, params) => author(from, params)
23359
+ });
23360
+ const author = createOwnerAuthor({
23361
+ home: home.path,
23362
+ env: environment,
23363
+ log,
23364
+ runtimeVersion: runtimeVersion(),
23365
+ protocol: () => server,
23366
+ hostedOn: (artifactId) => link.hostedServers(artifactId)
21561
23367
  });
21562
23368
  const stopPushingPublishes = interaction.onPublished((artifactId, versionId) => link.published(artifactId, versionId));
21563
23369
  const shares = createShares({
@@ -21655,10 +23461,11 @@ async function assemble(home, options) {
21655
23461
  dependenciesAdded: (artifact) => dev.dependenciesChanged(artifact)
21656
23462
  }),
21657
23463
  ...dev.methods(),
21658
- ...gateway.methods(),
23464
+ ...forwardHosted(link, (ref) => registry.get(canonicalRef(ref)).id, gateway.methods()),
21659
23465
  ...shares.methods(),
21660
23466
  ...link.methods(),
21661
23467
  ...forwardHosted(link, (ref) => registry.get(canonicalRef(ref)).id, interaction.methods()),
23468
+ pauseHandler(link, (ref) => registry.get(canonicalRef(ref)).id, interaction.pause),
21662
23469
  ...secretMethods(secrets, (ref) => registry.get(canonicalRef(ref)).id),
21663
23470
  ...gcMethods(createGc({
21664
23471
  ledger: home.ledger,
@@ -21882,6 +23689,6 @@ function sourceDirectory(path) {
21882
23689
  }
21883
23690
  }
21884
23691
  //#endregion
21885
- export { MAX_FRAME_BYTES as A, coverageMatcher as B, finishRun as C, runState as D, markWaiting as E, openLedger as F, noFaults as I, readFieldCoverage as L, ProtocolServer as M, handler as N, appendEvent as O, holdLock as P, readServerFunctions as R, appendRunOutput as S, markUnknown as T, openFileLog as V, Capabilities as _, uninstallService as a, createInteraction as b, resolveHomePath as c, versionIdFor as d, createLive as f, shellAssetResponse as g, locateShell as h, serviceStatus as i, serveWebSocket as j, BINDING_SUBPROTOCOL as k, canonicalRef as l, createGateway as m, startInstance as n, checkPlatform as o, liveMethods as p, installService as r, platformName as s, runtimeVersion as t, listingDigest as u, capabilityKey as v, markRunning as w, createEphemeralBus as x, openRegistry as y, readProcess as z };
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 };
21886
23693
 
21887
- //# sourceMappingURL=instance-FExcyENK.js.map
23694
+ //# sourceMappingURL=instance-CBUlOmzG.js.map