@mostra/runtime 0.9.0 → 0.11.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 (279) hide show
  1. package/dist/bin.js +6628 -9
  2. package/dist/bin.js.map +1 -1
  3. package/dist/builder/child/main.js +2 -2
  4. package/dist/{child-Chiavhdx.js → child-BmNZ4a70.js} +2 -2
  5. package/dist/{child-Chiavhdx.js.map → child-BmNZ4a70.js.map} +1 -1
  6. package/dist/deps/child/install.js +1 -1
  7. package/dist/{directories-mJ1qlVht.js → directories-BLJjeSPD.js} +5 -5
  8. package/dist/directories-BLJjeSPD.js.map +1 -0
  9. package/dist/{files-FygSJIzK.js → files-DGeWuE4I.js} +2 -2
  10. package/dist/{files-FygSJIzK.js.map → files-DGeWuE4I.js.map} +1 -1
  11. package/dist/index.d.ts +2 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +2 -2
  14. package/dist/{instance-EnaZPs14.js → instance-DCiUHvgZ.js} +3835 -255
  15. package/dist/instance-DCiUHvgZ.js.map +1 -0
  16. package/dist/reference/cli.md +1322 -0
  17. package/dist/reference/diagnostics.json +1552 -0
  18. package/dist/reference/errors/MOSTRA_A11Y_MINOR.md +23 -0
  19. package/dist/reference/errors/MOSTRA_A11Y_SERIOUS.md +23 -0
  20. package/dist/reference/errors/MOSTRA_ACTION_CANCELLED.md +23 -0
  21. package/dist/reference/errors/MOSTRA_ACTION_EVENT_INVALID.md +23 -0
  22. package/dist/reference/errors/MOSTRA_ACTION_EXPORT_INVALID.md +23 -0
  23. package/dist/reference/errors/MOSTRA_ACTION_INTERRUPTED.md +23 -0
  24. package/dist/reference/errors/MOSTRA_ACTION_PAUSED.md +23 -0
  25. package/dist/reference/errors/MOSTRA_ACTION_RUN_NOT_FOUND.md +23 -0
  26. package/dist/reference/errors/MOSTRA_ACTION_THREW.md +23 -0
  27. package/dist/reference/errors/MOSTRA_ACTION_TOO_LARGE.md +23 -0
  28. package/dist/reference/errors/MOSTRA_ACTION_UNKNOWN_FUNCTION.md +23 -0
  29. package/dist/reference/errors/MOSTRA_ACTION_UNSERIALIZABLE.md +23 -0
  30. package/dist/reference/errors/MOSTRA_ARTIFACT_BUNDLE_INVALID.md +23 -0
  31. package/dist/reference/errors/MOSTRA_ARTIFACT_DIR_NOT_EMPTY.md +23 -0
  32. package/dist/reference/errors/MOSTRA_ARTIFACT_ENTRY_AMBIGUOUS.md +23 -0
  33. package/dist/reference/errors/MOSTRA_ARTIFACT_ID_DROPPED.md +23 -0
  34. package/dist/reference/errors/MOSTRA_ARTIFACT_NOT_FOUND.md +23 -0
  35. package/dist/reference/errors/MOSTRA_ARTIFACT_NO_ENTRY.md +23 -0
  36. package/dist/reference/errors/MOSTRA_ARTIFACT_NO_PAGE.md +23 -0
  37. package/dist/reference/errors/MOSTRA_ARTIFACT_PATCH_REJECTED.md +23 -0
  38. package/dist/reference/errors/MOSTRA_ARTIFACT_PATH_INVALID.md +23 -0
  39. package/dist/reference/errors/MOSTRA_ARTIFACT_SOURCE_MISSING.md +23 -0
  40. package/dist/reference/errors/MOSTRA_ARTIFACT_SOURCE_UNREADABLE.md +23 -0
  41. package/dist/reference/errors/MOSTRA_ARTIFACT_TEMPLATE_UNKNOWN.md +23 -0
  42. package/dist/reference/errors/MOSTRA_ARTIFACT_VERSION_COLLECTED.md +23 -0
  43. package/dist/reference/errors/MOSTRA_ARTIFACT_VERSION_NOT_FOUND.md +23 -0
  44. package/dist/reference/errors/MOSTRA_BUILD_CRASHED.md +23 -0
  45. package/dist/reference/errors/MOSTRA_BUILD_FAILED.md +23 -0
  46. package/dist/reference/errors/MOSTRA_BUILD_TIMEOUT.md +23 -0
  47. package/dist/reference/errors/MOSTRA_BUILD_UNRESOLVED.md +23 -0
  48. package/dist/reference/errors/MOSTRA_CLI_CONFIG_UNWRITABLE.md +23 -0
  49. package/dist/reference/errors/MOSTRA_CLI_UNKNOWN_COMMAND.md +23 -0
  50. package/dist/reference/errors/MOSTRA_CLI_USAGE.md +23 -0
  51. package/dist/reference/errors/MOSTRA_CONSOLE_ERROR.md +23 -0
  52. package/dist/reference/errors/MOSTRA_CONSOLE_WARNING.md +23 -0
  53. package/dist/reference/errors/MOSTRA_DEP_INSTALL_FAILED.md +23 -0
  54. package/dist/reference/errors/MOSTRA_DEP_MISSING.md +23 -0
  55. package/dist/reference/errors/MOSTRA_DEP_NOT_FOUND.md +23 -0
  56. package/dist/reference/errors/MOSTRA_DEP_OFFLINE.md +23 -0
  57. package/dist/reference/errors/MOSTRA_DEP_SPEC_INVALID.md +23 -0
  58. package/dist/reference/errors/MOSTRA_DEP_TIMEOUT.md +23 -0
  59. package/dist/reference/errors/MOSTRA_DEP_WARM_CONFLICT.md +23 -0
  60. package/dist/reference/errors/MOSTRA_ENV_BIND_FAILED.md +23 -0
  61. package/dist/reference/errors/MOSTRA_ENV_BROWSER_MISSING.md +23 -0
  62. package/dist/reference/errors/MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED.md +23 -0
  63. package/dist/reference/errors/MOSTRA_ENV_BUNDLE_INVALID.md +23 -0
  64. package/dist/reference/errors/MOSTRA_ENV_BUNDLE_UNAVAILABLE.md +23 -0
  65. package/dist/reference/errors/MOSTRA_ENV_HELPER_MISSING.md +23 -0
  66. package/dist/reference/errors/MOSTRA_ENV_NODE_UNSUPPORTED.md +23 -0
  67. package/dist/reference/errors/MOSTRA_ENV_PORT_TAKEN.md +23 -0
  68. package/dist/reference/errors/MOSTRA_ENV_RUNTIME_INSTALLING.md +23 -0
  69. package/dist/reference/errors/MOSTRA_ENV_RUNTIME_MISSING.md +23 -0
  70. package/dist/reference/errors/MOSTRA_ENV_SERVICE_FAILED.md +23 -0
  71. package/dist/reference/errors/MOSTRA_ENV_SHELL_MISSING.md +23 -0
  72. package/dist/reference/errors/MOSTRA_ENV_WARM_MISSING.md +23 -0
  73. package/dist/reference/errors/MOSTRA_FIELD_CONFLICT.md +23 -0
  74. package/dist/reference/errors/MOSTRA_FIELD_DUPLICATE_ID.md +23 -0
  75. package/dist/reference/errors/MOSTRA_FIELD_ID_INVALID.md +23 -0
  76. package/dist/reference/errors/MOSTRA_FIELD_ID_UNSTABLE.md +23 -0
  77. package/dist/reference/errors/MOSTRA_FIELD_MUTATION_ID_REUSED.md +23 -0
  78. package/dist/reference/errors/MOSTRA_FIELD_SHARED.md +23 -0
  79. package/dist/reference/errors/MOSTRA_FIELD_TOO_LARGE.md +23 -0
  80. package/dist/reference/errors/MOSTRA_FIELD_UNBOUND.md +23 -0
  81. package/dist/reference/errors/MOSTRA_HOME_DISK_FULL.md +23 -0
  82. package/dist/reference/errors/MOSTRA_HOME_GC_INCOMPLETE.md +23 -0
  83. package/dist/reference/errors/MOSTRA_HOME_GONE.md +23 -0
  84. package/dist/reference/errors/MOSTRA_HOME_INTEGRITY.md +23 -0
  85. package/dist/reference/errors/MOSTRA_HOME_LEDGER_UNREADABLE.md +23 -0
  86. package/dist/reference/errors/MOSTRA_HOME_LOCKED.md +23 -0
  87. package/dist/reference/errors/MOSTRA_HOME_MISMATCH.md +23 -0
  88. package/dist/reference/errors/MOSTRA_HOME_NETWORK_FILESYSTEM.md +23 -0
  89. package/dist/reference/errors/MOSTRA_HOME_NOT_ALWAYS_ON.md +23 -0
  90. package/dist/reference/errors/MOSTRA_HOME_NOT_OWNED.md +23 -0
  91. package/dist/reference/errors/MOSTRA_HOME_SOCKET_TOO_LONG.md +23 -0
  92. package/dist/reference/errors/MOSTRA_HOME_TOO_NEW.md +23 -0
  93. package/dist/reference/errors/MOSTRA_HOST_CONNECTION_CLOSED.md +23 -0
  94. package/dist/reference/errors/MOSTRA_HOST_CURSOR_COMPACTED.md +23 -0
  95. package/dist/reference/errors/MOSTRA_HOST_IDENTITY_UNAVAILABLE.md +23 -0
  96. package/dist/reference/errors/MOSTRA_HOST_INITIALIZE_ORDER.md +23 -0
  97. package/dist/reference/errors/MOSTRA_HOST_INTERNAL_ERROR.md +23 -0
  98. package/dist/reference/errors/MOSTRA_HOST_INVALID_PARAMS.md +23 -0
  99. package/dist/reference/errors/MOSTRA_HOST_MALFORMED.md +23 -0
  100. package/dist/reference/errors/MOSTRA_HOST_MESSAGE_TOO_LARGE.md +23 -0
  101. package/dist/reference/errors/MOSTRA_HOST_METHOD_UNKNOWN.md +23 -0
  102. package/dist/reference/errors/MOSTRA_HOST_NOTIFICATION_UNSUPPORTED.md +23 -0
  103. package/dist/reference/errors/MOSTRA_HOST_PORT_UNSUPPORTED.md +23 -0
  104. package/dist/reference/errors/MOSTRA_HOST_REQUEST_ID_REUSED.md +23 -0
  105. package/dist/reference/errors/MOSTRA_HOST_REVISION_UNSUPPORTED.md +23 -0
  106. package/dist/reference/errors/MOSTRA_HOST_SHUTDOWN_REFUSED.md +23 -0
  107. package/dist/reference/errors/MOSTRA_HOST_SUBSCRIPTION_UNKNOWN.md +23 -0
  108. package/dist/reference/errors/MOSTRA_HOST_TIMEOUT.md +23 -0
  109. package/dist/reference/errors/MOSTRA_HYGIENE_CONTENT_TYPE.md +23 -0
  110. package/dist/reference/errors/MOSTRA_HYGIENE_CSRF_MISSING.md +23 -0
  111. package/dist/reference/errors/MOSTRA_HYGIENE_FRAME_SESSION.md +23 -0
  112. package/dist/reference/errors/MOSTRA_HYGIENE_HEADERS_TOO_LARGE.md +23 -0
  113. package/dist/reference/errors/MOSTRA_HYGIENE_HOST_REFUSED.md +23 -0
  114. package/dist/reference/errors/MOSTRA_HYGIENE_NOT_SERVED.md +23 -0
  115. package/dist/reference/errors/MOSTRA_HYGIENE_ORIGIN_REFUSED.md +23 -0
  116. package/dist/reference/errors/MOSTRA_HYGIENE_RATE_LIMITED.md +23 -0
  117. package/dist/reference/errors/MOSTRA_HYGIENE_REQUEST_MALFORMED.md +23 -0
  118. package/dist/reference/errors/MOSTRA_HYGIENE_SCOPE_DENIED.md +23 -0
  119. package/dist/reference/errors/MOSTRA_HYGIENE_SESSION_CONFLICT.md +23 -0
  120. package/dist/reference/errors/MOSTRA_HYGIENE_SESSION_MISSING.md +23 -0
  121. package/dist/reference/errors/MOSTRA_HYGIENE_TOKEN_INVALID.md +23 -0
  122. package/dist/reference/errors/MOSTRA_HYGIENE_TOKEN_REVOKED.md +23 -0
  123. package/dist/reference/errors/MOSTRA_LIVE_SOURCE_FAILED.md +23 -0
  124. package/dist/reference/errors/MOSTRA_LIVE_TOO_LARGE.md +23 -0
  125. package/dist/reference/errors/MOSTRA_MANIFEST_INVALID.md +23 -0
  126. package/dist/reference/errors/MOSTRA_MANIFEST_NOT_LITERAL.md +23 -0
  127. package/dist/reference/errors/MOSTRA_MANIFEST_UNKNOWN_KEY.md +23 -0
  128. package/dist/reference/errors/MOSTRA_NETWORK_EXTERNAL_FAILED.md +23 -0
  129. package/dist/reference/errors/MOSTRA_NETWORK_REQUEST_FAILED.md +23 -0
  130. package/dist/reference/errors/MOSTRA_PLATFORM_UNSUPPORTED.md +23 -0
  131. package/dist/reference/errors/MOSTRA_PUBLISH_ID_CONFLICT.md +23 -0
  132. package/dist/reference/errors/MOSTRA_PUBLISH_SOURCE_CHANGED.md +23 -0
  133. package/dist/reference/errors/MOSTRA_PUBLISH_VERIFY_FAILED.md +23 -0
  134. package/dist/reference/errors/MOSTRA_REGRESSION_ACTION_REMOVED.md +23 -0
  135. package/dist/reference/errors/MOSTRA_REGRESSION_ARIA.md +23 -0
  136. package/dist/reference/errors/MOSTRA_REGRESSION_FIELD_REMOVED.md +23 -0
  137. package/dist/reference/errors/MOSTRA_REGRESSION_LIVE_REMOVED.md +23 -0
  138. package/dist/reference/errors/MOSTRA_REGRESSION_PAGE_REMOVED.md +23 -0
  139. package/dist/reference/errors/MOSTRA_REGRESSION_PIXELS.md +23 -0
  140. package/dist/reference/errors/MOSTRA_REMOTE_CONFIG_INVALID.md +23 -0
  141. package/dist/reference/errors/MOSTRA_REMOTE_HOME_MOVING.md +23 -0
  142. package/dist/reference/errors/MOSTRA_REMOTE_HOME_SUSPENDED.md +23 -0
  143. package/dist/reference/errors/MOSTRA_REMOTE_LIMIT_REACHED.md +23 -0
  144. package/dist/reference/errors/MOSTRA_REMOTE_LOGIN_FAILED.md +23 -0
  145. package/dist/reference/errors/MOSTRA_REMOTE_NOT_OWNER_INSTANCE.md +23 -0
  146. package/dist/reference/errors/MOSTRA_REMOTE_NO_INSTANCE.md +23 -0
  147. package/dist/reference/errors/MOSTRA_REMOTE_OPERATOR_UNAVAILABLE.md +23 -0
  148. package/dist/reference/errors/MOSTRA_REMOTE_OWNER_OFFLINE.md +23 -0
  149. package/dist/reference/errors/MOSTRA_REMOTE_PAUSED_BY_OPERATOR.md +23 -0
  150. package/dist/reference/errors/MOSTRA_REMOTE_QUEUE_FULL.md +23 -0
  151. package/dist/reference/errors/MOSTRA_REMOTE_RATE_LIMITED.md +23 -0
  152. package/dist/reference/errors/MOSTRA_REMOTE_SIGN_IN_REQUIRED.md +23 -0
  153. package/dist/reference/errors/MOSTRA_REMOTE_UNDER_REVIEW.md +23 -0
  154. package/dist/reference/errors/MOSTRA_REMOTE_UNREACHABLE.md +23 -0
  155. package/dist/reference/errors/MOSTRA_RUNTIME_BLANK.md +23 -0
  156. package/dist/reference/errors/MOSTRA_RUNTIME_NOT_READY.md +23 -0
  157. package/dist/reference/errors/MOSTRA_RUNTIME_PAGE_ERROR.md +23 -0
  158. package/dist/reference/errors/MOSTRA_RUNTIME_WORKER_CRASHED.md +23 -0
  159. package/dist/reference/errors/MOSTRA_RUNTIME_WORKER_PARKED.md +23 -0
  160. package/dist/reference/errors/MOSTRA_SECRET_MISSING.md +23 -0
  161. package/dist/reference/errors/MOSTRA_SHARE_NOT_ENABLED.md +23 -0
  162. package/dist/reference/errors/MOSTRA_SHARE_NOT_FOUND.md +23 -0
  163. package/dist/reference/errors/MOSTRA_SHARE_PORTS_EXHAUSTED.md +23 -0
  164. package/dist/reference/errors/MOSTRA_SHARE_TOOL_MISSING.md +23 -0
  165. package/dist/reference/errors/MOSTRA_SHARE_TOOL_NOT_READY.md +23 -0
  166. package/dist/reference/errors/MOSTRA_SHARE_TTL_INVALID.md +23 -0
  167. package/dist/reference/errors/MOSTRA_SHARE_TUNNEL_FAILED.md +23 -0
  168. package/dist/reference/errors/MOSTRA_SMOKE_BUDGET.md +23 -0
  169. package/dist/reference/errors/MOSTRA_SMOKE_NO_EFFECT.md +23 -0
  170. package/dist/reference/errors/MOSTRA_SUBMIT_ALREADY.md +23 -0
  171. package/dist/reference/errors/MOSTRA_SUBMIT_BLOCKED.md +23 -0
  172. package/dist/reference/errors/MOSTRA_SUBMIT_CHANNEL_DENIED.md +23 -0
  173. package/dist/reference/errors/MOSTRA_SUBMIT_NOT_FOUND.md +23 -0
  174. package/dist/reference/errors/MOSTRA_SUBMIT_PAUSED.md +23 -0
  175. package/dist/reference/errors/MOSTRA_SUBMIT_POLICY_NONE.md +23 -0
  176. package/dist/reference/errors/MOSTRA_SUBMIT_REVISION_MOVED.md +23 -0
  177. package/dist/reference/errors/MOSTRA_SUBMIT_SIGNAL_INVALID.md +23 -0
  178. package/dist/reference/errors/MOSTRA_SUBMIT_VIEW_INVALID.md +23 -0
  179. package/dist/reference/errors/MOSTRA_TARGET_UNAVAILABLE.md +23 -0
  180. package/dist/reference/errors/MOSTRA_TYPE_ERROR.md +23 -0
  181. package/dist/reference/errors/MOSTRA_TYPE_UNTYPED_PACKAGE.md +23 -0
  182. package/dist/reference/errors/MOSTRA_VERIFY_ACTION_SKIPPED.md +23 -0
  183. package/dist/reference/errors/MOSTRA_VERIFY_BASELINE_MISSING.md +23 -0
  184. package/dist/reference/errors/MOSTRA_VERIFY_CRASHED.md +23 -0
  185. package/dist/reference/errors/MOSTRA_VERIFY_LIVE_FAILED.md +23 -0
  186. package/dist/reference/errors/MOSTRA_VERIFY_NO_BASELINE.md +23 -0
  187. package/dist/reference/errors/MOSTRA_VERIFY_SECRET_MISSING.md +23 -0
  188. package/dist/reference/errors/MOSTRA_VERIFY_SKIP_CONSEQUENCE.md +23 -0
  189. package/dist/reference/errors/MOSTRA_VERIFY_TIMEOUT.md +23 -0
  190. package/dist/reference/self-hosting.md +130 -0
  191. package/dist/reference/telemetry.md +84 -0
  192. package/dist/skill/SKILL.md +122 -0
  193. package/dist/skill/assets/examples/dashboard/index.tsx +161 -0
  194. package/dist/skill/assets/examples/dashboard/live.ts +25 -0
  195. package/dist/skill/assets/examples/dashboard/styles.css +125 -0
  196. package/dist/skill/assets/examples/decision/index.tsx +95 -0
  197. package/dist/skill/assets/examples/decision/styles.css +125 -0
  198. package/dist/skill/assets/examples/inbox/actions.ts +23 -0
  199. package/dist/skill/assets/examples/inbox/index.tsx +109 -0
  200. package/dist/skill/assets/examples/inbox/styles.css +125 -0
  201. package/dist/skill/assets/studio.css +125 -0
  202. package/dist/skill/references/answers.md +217 -0
  203. package/dist/skill/references/design.md +154 -0
  204. package/dist/skill/references/libraries.md +167 -0
  205. package/dist/skill/references/long-lived.md +148 -0
  206. package/dist/skill/references/mcp.md +68 -0
  207. package/dist/skill/references/page.md +131 -0
  208. package/dist/skill/references/server.md +146 -0
  209. package/dist/skill/references/sharing.md +123 -0
  210. package/dist/skill/references/verify.md +71 -0
  211. package/package.json +12 -5
  212. package/src/actions/index.ts +163 -10
  213. package/src/bin.ts +78 -1
  214. package/src/gateway/actions.ts +40 -4
  215. package/src/gateway/browser.ts +162 -95
  216. package/src/gateway/capabilities.ts +23 -6
  217. package/src/gateway/http.ts +12 -1
  218. package/src/gateway/index.ts +282 -20
  219. package/src/gateway/listener.ts +31 -6
  220. package/src/gateway/routes.ts +23 -7
  221. package/src/gc/index.ts +19 -0
  222. package/src/instance/index.ts +60 -2
  223. package/src/interaction/ephemeral.ts +32 -23
  224. package/src/interaction/events.ts +21 -1
  225. package/src/interaction/imports.ts +317 -0
  226. package/src/interaction/index.ts +228 -15
  227. package/src/interaction/outbox.ts +9 -0
  228. package/src/interaction/pause.ts +106 -0
  229. package/src/interaction/results.ts +8 -1
  230. package/src/interaction/runs.ts +52 -2
  231. package/src/interaction/submissions.ts +59 -2
  232. package/src/interaction/tally.ts +129 -0
  233. package/src/interaction/viewers.ts +34 -1
  234. package/src/ledger/index.ts +124 -10
  235. package/src/ledger/migrations.ts +234 -0
  236. package/src/ledger/types.ts +8 -0
  237. package/src/link/author.ts +215 -0
  238. package/src/link/binding.ts +289 -0
  239. package/src/link/hosted.ts +101 -0
  240. package/src/link/http.ts +141 -0
  241. package/src/link/index.ts +10 -0
  242. package/src/link/manager.ts +1489 -0
  243. package/src/link/relay.ts +512 -0
  244. package/src/live/index.ts +112 -2
  245. package/src/platform/filesystems.ts +78 -0
  246. package/src/platform/index.ts +1 -0
  247. package/src/protocol-server/client.ts +53 -0
  248. package/src/protocol-server/index.ts +19 -2
  249. package/src/protocol-server/server.ts +38 -7
  250. package/src/protocol-server/websocket.ts +161 -0
  251. package/src/publish/bundle.ts +398 -0
  252. package/src/publish/manifest.ts +9 -0
  253. package/src/publish/methods.ts +12 -1
  254. package/src/publish/publisher.ts +127 -0
  255. package/src/registry/index.ts +35 -14
  256. package/src/server/api.ts +881 -0
  257. package/src/server/auth.ts +1139 -0
  258. package/src/server/authorize.ts +816 -0
  259. package/src/server/clients.ts +235 -0
  260. package/src/server/config.ts +228 -0
  261. package/src/server/data.ts +427 -0
  262. package/src/server/directory.ts +210 -0
  263. package/src/server/feed.ts +191 -0
  264. package/src/server/handle.ts +172 -0
  265. package/src/server/hosted-pages.ts +532 -0
  266. package/src/server/hosted.ts +1323 -0
  267. package/src/server/index.ts +650 -0
  268. package/src/server/mcp.ts +330 -0
  269. package/src/server/metering.ts +156 -0
  270. package/src/server/oauth-clients.ts +510 -0
  271. package/src/server/operator.ts +498 -0
  272. package/src/server/providers.ts +284 -0
  273. package/src/server/relay.ts +1163 -0
  274. package/src/server/remove.ts +148 -0
  275. package/src/server/routing.ts +275 -0
  276. package/src/share/index.ts +110 -6
  277. package/src/verify/runner.ts +23 -2
  278. package/dist/directories-mJ1qlVht.js.map +0 -1
  279. package/dist/instance-EnaZPs14.js.map +0 -1
package/src/gc/index.ts CHANGED
@@ -112,6 +112,20 @@ export const REFERENCE_SOURCES: readonly ReferenceSource[] = [
112
112
  covers: ["view.version_id"],
113
113
  keep: (db) => column<string>(db, "SELECT version_id AS value FROM view"),
114
114
  },
115
+ {
116
+ // A publish waiting to reach a remote server needs its files until it gets there; a relayed
117
+ // run's version is its action run's (WP-29, DATA_MODEL §7.3).
118
+ name: "pushes and relayed runs",
119
+ covers: ["version_push.version_id", "relayed_run.version_id"],
120
+ keep: function* (db) {
121
+ if (!tableExists(db, "version_push")) return;
122
+ yield* column<string>(
123
+ db,
124
+ "SELECT version_id AS value FROM version_push WHERE state = 'pending'",
125
+ );
126
+ yield* column<string>(db, "SELECT version_id AS value FROM relayed_run");
127
+ },
128
+ },
115
129
  {
116
130
  name: "comment threads",
117
131
  covers: ["thread.version_id", "thread.anchor_json"],
@@ -199,6 +213,11 @@ export const EXEMPT_COLUMNS: readonly ExemptColumn[] = [
199
213
  column: "schema_migration.runtime_version",
200
214
  reason: "the runtime release that ran a migration",
201
215
  },
216
+ {
217
+ column: "quarantine.version_id",
218
+ reason:
219
+ "an operator's quarantine of a hosted version (WP-30), which withholds it and keeps nothing; a hosted home runs no gc",
220
+ },
202
221
  ];
203
222
 
204
223
  /** The versions some source keeps. */
@@ -80,6 +80,14 @@ import {
80
80
  type Interaction,
81
81
  redactEvents,
82
82
  } from "../interaction/index.ts";
83
+ import {
84
+ createLink,
85
+ createOwnerAuthor,
86
+ forwardHosted,
87
+ hostedState,
88
+ type Link,
89
+ pauseHandler,
90
+ } from "../link/index.ts";
83
91
  import { createLive, type LatestLive, liveMethods } from "../live/index.ts";
84
92
  import type { Environment, Log } from "../log.ts";
85
93
  import { helperPath, type LaunchPipe, realPath } from "../platform/index.ts";
@@ -563,6 +571,9 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
563
571
  : {}),
564
572
  });
565
573
  const actions = createActions({
574
+ // Server code's `state` of a hosted artifact acts on its hosted home (D165 item 1); the link
575
+ // is made below, and asked only once runs start.
576
+ hostedState: (artifactId) => hostedState(link, artifactId),
566
577
  interaction,
567
578
  pool,
568
579
  bus,
@@ -597,6 +608,10 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
597
608
  return versionId ? { versionId, sources: sourcesOf(versionId) } : undefined;
598
609
  };
599
610
  const live = createLive({
611
+ // A hosted artifact's live sources: produced here while its hosted pages want them, their
612
+ // values kept on its hosted home (D165 items 1 and 4). The link is made below.
613
+ extraInterest: () => link.liveInterest(),
614
+ forward: (artifactId, versionId, produced) => link.forwardLive(artifactId, versionId, produced),
600
615
  ledger: home.ledger,
601
616
  log,
602
617
  bus,
@@ -738,6 +753,34 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
738
753
  }
739
754
  },
740
755
  });
756
+ // The owner's side of remote servers (WP-29, D165): sign-in, the bindings, hosted deliveries
757
+ // imported into this home's outbox, the sync cursor, and version pushes.
758
+ const link: Link = createLink({
759
+ home: home.path,
760
+ ledger: home.ledger,
761
+ log,
762
+ env: environment,
763
+ runtimeVersion: runtimeVersion(),
764
+ protect: (value) => home.redactor.protect(value),
765
+ importSubmission: (envelope, source) => interaction.importSubmission(envelope, source),
766
+ versionDir: (versionId) => registry.store.versionDir(versionId),
767
+ actions,
768
+ liveChanged: () => live.reconcile(),
769
+ now: () => Date.now() + clockOffset,
770
+ // Remote MCP's authoring runs here, on this home's own protocol server (D165 item 5).
771
+ author: (from, params) => author(from, params),
772
+ });
773
+ const author = createOwnerAuthor({
774
+ home: home.path,
775
+ env: environment,
776
+ log,
777
+ runtimeVersion: runtimeVersion(),
778
+ protocol: () => server,
779
+ hostedOn: (artifactId) => link.hostedServers(artifactId),
780
+ });
781
+ const stopPushingPublishes = interaction.onPublished((artifactId, versionId) =>
782
+ link.published(artifactId, versionId),
783
+ );
741
784
  // Shares (WP-13, D158): tunnels to the gateway's faces, each with a link of its own.
742
785
  const shares: Shares = createShares({
743
786
  ledger: home.ledger,
@@ -751,6 +794,8 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
751
794
  toolEnvironment: artifactEnvironment(environment),
752
795
  cacheDir: shareCacheDir(home.path),
753
796
  now: () => Date.now() + clockOffset,
797
+ // Shares to a remote server go through the owner's link (D165, INTERFACES §18.2).
798
+ remote: link.shares(),
754
799
  ...(environment["MOSTRA_TEST_SHARE_PROBE_MS"] !== undefined
755
800
  ? { probeMs: Number(environment["MOSTRA_TEST_SHARE_PROBE_MS"]) }
756
801
  : {}),
@@ -850,7 +895,11 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
850
895
  ...dev.methods(),
851
896
  ...gateway.methods(),
852
897
  ...shares.methods(),
853
- ...interaction.methods(),
898
+ ...link.methods(),
899
+ // A hosted artifact's state and live values act on its hosted home (D165 item 1).
900
+ ...forwardHosted(link, (ref) => registry.get(canonicalRef(ref)).id, interaction.methods()),
901
+ // Pausing acts here and on every server the artifact is hosted on (D165 item 14).
902
+ pauseHandler(link, (ref) => registry.get(canonicalRef(ref)).id, interaction.pause),
854
903
  ...secretMethods(secrets, (ref) => registry.get(canonicalRef(ref)).id),
855
904
  ...gcMethods(
856
905
  createGc({
@@ -868,7 +917,11 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
868
917
  faults,
869
918
  }),
870
919
  ),
871
- ...liveMethods(live, (ref) => registry.get(canonicalRef(ref)).id),
920
+ ...forwardHosted(
921
+ link,
922
+ (ref) => registry.get(canonicalRef(ref)).id,
923
+ liveMethods(live, (ref) => registry.get(canonicalRef(ref)).id),
924
+ ),
872
925
  ...sessionMethods({
873
926
  describe: () => info,
874
927
  startedAt: home.startedAt,
@@ -888,6 +941,7 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
888
941
  }
889
942
  : undefined,
890
943
  shares: () => shares.active(),
944
+ links: () => link.status(),
891
945
  deliveries: () => interaction.deliveries(),
892
946
  workers: () => pool.status(),
893
947
  idleExitAt: () => idle?.exitAt(),
@@ -917,6 +971,8 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
917
971
  log.info("instance.stopping", { reason, exitCode, ...(diagnostic ? { diagnostic } : {}) });
918
972
  idle?.stop();
919
973
  stopWatchingPublishes();
974
+ stopPushingPublishes();
975
+ await link.stop();
920
976
  live.stop();
921
977
  interaction.stop();
922
978
  // Before any child stops: on Windows the pipe's helper is a child, and it hands clients
@@ -973,6 +1029,8 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
973
1029
  interaction.start();
974
1030
  // Producers that `always` run, and those hosts subscribe to, start now (LL-04).
975
1031
  live.start();
1032
+ // Every server this home is signed in to is dialled again (D165 item 2).
1033
+ link.start();
976
1034
  // Tailnet and Funnel shares come back; what can't continue ends, with its reason (D158).
977
1035
  void shares.recover().catch((error: unknown) => log.error("share.recover_failed", { error }));
978
1036
  home.publish(options.mode, server.socketPath ?? home.socketPath);
@@ -14,15 +14,22 @@ export const INTEREST_LEASE_MS: number = 60_000;
14
14
  /** The most messages a polling view keeps between polls; older ones are dropped. */
15
15
  const POLL_QUEUE_MAX = 1000;
16
16
 
17
+ /** A polling view's messages collected between its polls. */
18
+ interface PollQueue {
19
+ readonly messages: EphemeralMessage[];
20
+ until: number;
21
+ /** The polls waiting now; each is woken by the next message. */
22
+ readonly wakes: Set<() => void>;
23
+ }
24
+
17
25
  /** What a view listens to. */
18
26
  interface ViewInterest {
19
27
  readonly artifactId: string;
20
28
  readonly runs: Map<string, number>;
21
29
  readonly live: Map<string, { until: number; window?: number }>;
22
30
  readonly listeners: Set<(message: EphemeralMessage) => void>;
23
- queue?: EphemeralMessage[];
24
- queueUntil?: number;
25
- wake?: () => void;
31
+ /** Its frame's poll queue, once the frame polled. */
32
+ poll?: PollQueue;
26
33
  }
27
34
 
28
35
  type RunMessage = Extract<EphemeralMessage, { kind: "run" }>;
@@ -123,9 +130,12 @@ export interface EphemeralBus {
123
130
  viewId: string,
124
131
  listener: (message: EphemeralMessage) => void,
125
132
  ): () => void;
126
- /** Takes what the view collected since its last poll, starting its queue on the first. */
133
+ /**
134
+ * Takes what the view's frame collected since its last poll, starting its queue on the first.
135
+ * Only the frame polls for these: the shell's poll of the same view never takes them (#119).
136
+ */
127
137
  drain(artifactId: string, viewId: string): EphemeralMessage[];
128
- /** Resolves when the polling view has something, or after `ms`. */
138
+ /** Resolves when the polling view has something, or after `ms`; several polls may wait. */
129
139
  wait(artifactId: string, viewId: string, ms: number, signal?: AbortSignal): Promise<void>;
130
140
  /** The live sources views read now. */
131
141
  liveInterest(): LiveInterest[];
@@ -181,12 +191,12 @@ export function createEphemeralBus(
181
191
 
182
192
  const deliver = (view: ViewInterest, message: EphemeralMessage): void => {
183
193
  for (const listener of view.listeners) listener(message);
184
- if (view.queue && (view.queueUntil ?? 0) > now()) {
185
- coalesceInto(view, view.queue, message);
186
- if (view.queue.length > POLL_QUEUE_MAX)
187
- view.queue.splice(0, view.queue.length - POLL_QUEUE_MAX);
188
- view.wake?.();
189
- }
194
+ const poll = view.poll;
195
+ if (!poll || poll.until <= now()) return;
196
+ coalesceInto(view, poll.messages, message);
197
+ if (poll.messages.length > POLL_QUEUE_MAX)
198
+ poll.messages.splice(0, poll.messages.length - POLL_QUEUE_MAX);
199
+ for (const wake of [...poll.wakes]) wake();
190
200
  };
191
201
 
192
202
  // Expired leases end; views with nothing left are forgotten.
@@ -196,15 +206,12 @@ export function createEphemeralBus(
196
206
  for (const [viewId, view] of views) {
197
207
  for (const [runId, until] of view.runs) if (until <= at) view.runs.delete(runId);
198
208
  for (const [key, lease] of view.live) if (lease.until <= at) view.live.delete(key);
199
- if (view.queue && (view.queueUntil ?? 0) <= at) {
200
- delete view.queue;
201
- delete view.queueUntil;
202
- }
209
+ if (view.poll && view.poll.until <= at && view.poll.wakes.size === 0) delete view.poll;
203
210
  if (
204
211
  view.runs.size === 0 &&
205
212
  view.live.size === 0 &&
206
213
  view.listeners.size === 0 &&
207
- !view.queue
214
+ !view.poll
208
215
  ) {
209
216
  views.delete(viewId);
210
217
  }
@@ -258,24 +265,26 @@ export function createEphemeralBus(
258
265
  },
259
266
  drain(artifactId, viewId) {
260
267
  const view = viewOf(artifactId, viewId);
261
- const taken = view.queue ?? [];
262
- view.queue = [];
263
- view.queueUntil = now() + lease;
268
+ const taken = view.poll ? view.poll.messages.splice(0) : [];
269
+ if (view.poll) view.poll.until = now() + lease;
270
+ else view.poll = { messages: [], until: now() + lease, wakes: new Set() };
264
271
  return taken;
265
272
  },
266
273
  wait(artifactId, viewId, ms, signal) {
267
274
  const view = viewOf(artifactId, viewId);
268
- if (view.queue && view.queue.length > 0) return Promise.resolve();
275
+ view.poll ??= { messages: [], until: now() + lease, wakes: new Set() };
276
+ if (view.poll.messages.length > 0) return Promise.resolve();
277
+ const waiting = view.poll;
269
278
  return new Promise((resolve) => {
270
279
  const done = (): void => {
271
280
  clearTimeout(timer);
272
281
  signal?.removeEventListener("abort", done);
273
- if (view.wake === done) delete view.wake;
282
+ waiting.wakes.delete(done);
274
283
  resolve();
275
284
  };
276
285
  const timer = setTimeout(done, ms);
277
286
  signal?.addEventListener("abort", done, { once: true });
278
- view.wake = done;
287
+ waiting.wakes.add(done);
279
288
  });
280
289
  },
281
290
  liveInterest: currentInterest,
@@ -289,7 +298,7 @@ export function createEphemeralBus(
289
298
  const at = now();
290
299
  let count = 0;
291
300
  for (const view of views.values()) {
292
- if (view.listeners.size > 0 || (view.queueUntil ?? 0) > at) count += 1;
301
+ if (view.listeners.size > 0 || (view.poll?.until ?? 0) > at) count += 1;
293
302
  }
294
303
  return count;
295
304
  },
@@ -19,6 +19,7 @@ import {
19
19
  createDiagnostic,
20
20
  type Diagnostic,
21
21
  type EventFilter,
22
+ type EventOrigin,
22
23
  type EventRecord,
23
24
  RpcError,
24
25
  } from "@mostra/protocol";
@@ -39,6 +40,8 @@ export interface NewEvent {
39
40
  readonly causation?: Readonly<Record<string, string>>;
40
41
  /** The event's data, JSON. Never a sensitive field's value (D52). */
41
42
  readonly payload: Readonly<Record<string, unknown>>;
43
+ /** For an event an owner instance copies from its hosted home: where it came from (§18.2). */
44
+ readonly origin?: EventOrigin;
42
45
  }
43
46
 
44
47
  /** Redactors whose secrets no event may carry (D44, AC-06): the instances of this process. */
@@ -89,7 +92,11 @@ export function appendEvent(db: LedgerDb, event: NewEvent): string {
89
92
  event.artifactId,
90
93
  )?.next ?? 1);
91
94
  const result = db.run(
92
- "INSERT INTO event (artifact_id, seq, type, actor_json, causation_json, payload_json, at) VALUES (?, ?, ?, ?, ?, ?, ?)",
95
+ // `origin_json` (migration 13) is named only for a followed event, so a ledger still at an older
96
+ // schema (a migration's own tests) appends as before.
97
+ event.origin === undefined
98
+ ? "INSERT INTO event (artifact_id, seq, type, actor_json, causation_json, payload_json, at) VALUES (?, ?, ?, ?, ?, ?, ?)"
99
+ : "INSERT INTO event (artifact_id, seq, type, actor_json, causation_json, payload_json, at, origin_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
93
100
  event.artifactId,
94
101
  seq,
95
102
  event.type,
@@ -97,6 +104,7 @@ export function appendEvent(db: LedgerDb, event: NewEvent): string {
97
104
  event.causation === undefined ? null : JSON.stringify(event.causation),
98
105
  JSON.stringify(redacted(event.payload)),
99
106
  new Date().toISOString(),
107
+ ...(event.origin === undefined ? [] : [originJson(event.origin)]),
100
108
  );
101
109
  return String(result.lastInsertRowid);
102
110
  }
@@ -111,6 +119,17 @@ export interface EventRow {
111
119
  readonly causation_json: string | null;
112
120
  readonly payload_json: string;
113
121
  readonly at: string;
122
+ readonly origin_json?: string | null;
123
+ }
124
+
125
+ /** An origin's stored form: its keys in one order, so one origin is one text (the unique index). */
126
+ export function originJson(origin: EventOrigin): string {
127
+ return JSON.stringify({
128
+ server: origin.server,
129
+ home: origin.home,
130
+ incarnation: origin.incarnation,
131
+ cursor: origin.cursor,
132
+ });
114
133
  }
115
134
 
116
135
  /** An event row as the wire carries it. */
@@ -126,6 +145,7 @@ export function eventRecord(row: EventRow): EventRecord {
126
145
  ? { causation: JSON.parse(row.causation_json) as Record<string, string> }
127
146
  : {}),
128
147
  payload: JSON.parse(row.payload_json) as Record<string, unknown>,
148
+ ...(row.origin_json ? { origin: JSON.parse(row.origin_json) as EventOrigin } : {}),
129
149
  };
130
150
  }
131
151
 
@@ -0,0 +1,317 @@
1
+ /**
2
+ * The owner instance's copies of its hosted homes' records (D165 item 1, DATA_MODEL §7.3): the
3
+ * submissions a hosted home delivers to it, stored with their hosted IDs, digest and snapshot and
4
+ * enqueued to the owner's own hosts in the same transaction, so remote submissions reach local hosts
5
+ * through the local outbox (RM-02, H-04); and the events the sync cursor follows, each appended
6
+ * once, with where it came from.
7
+ */
8
+ import { createHash } from "node:crypto";
9
+ import {
10
+ type EventOrigin,
11
+ type EventRecord,
12
+ type SubmissionEnvelope,
13
+ type SubmissionsDeliverResult,
14
+ ViewerId,
15
+ } from "@mostra/protocol";
16
+ import type { LedgerDb } from "../ledger/index.ts";
17
+ import { appendEvent, originJson } from "./events.ts";
18
+ import { documentFor } from "./fields.ts";
19
+ import type { Snapshot } from "./submissions.ts";
20
+
21
+ /** The built-in adapter's owner name, as `submit` uses it (D105). */
22
+ import { BUILT_IN_OWNER } from "./submissions.ts";
23
+
24
+ const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
25
+
26
+ /**
27
+ * A local delivery's ID for an imported submission and one of the owner's hosts: `dlv_` and 26
28
+ * Crockford base32 characters of SHA-256(submission ID ‖ 0x00 ‖ host owner), its first two bits
29
+ * cleared so it reads as a ULID. A re-import (the owner's home restored) repeats it, so a host
30
+ * that dedupes by delivery ID sees one delivery (DATA_MODEL §7.3, D105's identity).
31
+ */
32
+ export function importedDeliveryId(submissionId: string, owner: string): string {
33
+ const digest = createHash("sha256")
34
+ .update(
35
+ Buffer.concat([
36
+ Buffer.from(submissionId, "utf8"),
37
+ Buffer.from([0]),
38
+ Buffer.from(owner, "utf8"),
39
+ ]),
40
+ )
41
+ .digest();
42
+ digest[0] = (digest[0] as number) & 0x3f;
43
+ let out = "";
44
+ let buffer = 0;
45
+ let bits = 0;
46
+ for (const byte of digest) {
47
+ buffer = (buffer << 8) | byte;
48
+ bits += 8;
49
+ while (bits >= 5 && out.length < 26) {
50
+ bits -= 5;
51
+ out += CROCKFORD.charAt((buffer >> bits) & 31);
52
+ }
53
+ if (out.length >= 26) break;
54
+ }
55
+ return `dlv_${out}`;
56
+ }
57
+
58
+ /** Where an imported record came from, without its own cursor. */
59
+ export interface ImportSource {
60
+ /** The server's API origin. */
61
+ readonly server: string;
62
+ /** A short, stable key of the server: imported viewers' references are prefixed by it. */
63
+ readonly serverKey: string;
64
+ /** The hosted home and its incarnation now. */
65
+ readonly home: string;
66
+ readonly incarnation: string;
67
+ }
68
+
69
+ /** What {@link importSubmission} needs. */
70
+ export interface SubmissionImport {
71
+ readonly envelope: SubmissionEnvelope;
72
+ readonly source: ImportSource;
73
+ /** The owner's own hosts for submissions, or none (the built-in adapter accepts). */
74
+ readonly owners: readonly string[];
75
+ /** Whether this instance owns the artifact on that server (its `hosted_artifact` row). */
76
+ readonly owned: (db: LedgerDb, artifactId: string) => boolean;
77
+ }
78
+
79
+ /**
80
+ * Stores a delivered hosted submission and its local deliveries in the caller's transaction, and
81
+ * answers the hosted home as a host does (D105): `accepted` once it is durable here, a repeat of
82
+ * one already held too; a submission it can never hold is refused for good.
83
+ */
84
+ export function importSubmission(db: LedgerDb, input: SubmissionImport): SubmissionsDeliverResult {
85
+ const { envelope, source } = input;
86
+ const refuse = (reason: string): SubmissionsDeliverResult => ({
87
+ accepted: false,
88
+ reason,
89
+ retry: false,
90
+ });
91
+ if (db.get("SELECT 1 FROM submission WHERE id = ?", envelope.submissionId))
92
+ return { accepted: true };
93
+ if (envelope.snapshot === undefined) return refuse("invalid: the delivery carries no snapshot");
94
+ const digest = createHash("sha256").update(envelope.snapshot, "utf8").digest("hex");
95
+ if (digest !== envelope.results.submission.digest) {
96
+ return refuse("invalid: the snapshot doesn't match the submission's digest");
97
+ }
98
+ let snapshot: Snapshot;
99
+ try {
100
+ snapshot = JSON.parse(envelope.snapshot) as Snapshot;
101
+ } catch {
102
+ return refuse("invalid: the snapshot isn't JSON");
103
+ }
104
+ if (
105
+ snapshot.submissionId !== envelope.submissionId ||
106
+ snapshot.artifactId !== envelope.artifactId ||
107
+ typeof snapshot.versionId !== "string" ||
108
+ typeof snapshot.viewId !== "string"
109
+ ) {
110
+ return refuse("invalid: the snapshot names another submission");
111
+ }
112
+ if (!input.owned(db, snapshot.artifactId)) {
113
+ // Never sent to an instance that doesn't own the artifact (D165 item 1b); refused for good.
114
+ return refuse("undeliverable: this instance doesn't own the artifact");
115
+ }
116
+ if (
117
+ !db.get(
118
+ "SELECT 1 FROM version WHERE id = ? AND artifact_id = ?",
119
+ snapshot.versionId,
120
+ snapshot.artifactId,
121
+ )
122
+ ) {
123
+ return refuse("undeliverable: this instance doesn't hold the submission's version");
124
+ }
125
+
126
+ // The viewer, as a row of its kind keyed by the server (DATA_MODEL §7.3).
127
+ const hostedViewer = snapshot.viewer;
128
+ const kind = hostedViewer.kind === "local" ? "token" : hostedViewer.kind;
129
+ const ref = `${source.serverKey}:${hostedViewer.ref ?? hostedViewer.id}`;
130
+ let viewerId = db.get<{ id: string }>(
131
+ "SELECT id FROM viewer WHERE kind = ? AND external_ref = ?",
132
+ kind,
133
+ ref,
134
+ )?.id;
135
+ if (viewerId === undefined) {
136
+ viewerId = db.get("SELECT 1 FROM viewer WHERE id = ?", hostedViewer.id)
137
+ ? ViewerId.create()
138
+ : hostedViewer.id;
139
+ db.run(
140
+ "INSERT INTO viewer (id, kind, external_ref, name, created_at) VALUES (?, ?, ?, ?, ?)",
141
+ viewerId,
142
+ kind,
143
+ ref,
144
+ hostedViewer.name ?? null,
145
+ snapshot.at,
146
+ );
147
+ }
148
+ // The view it named, under its hosted ID, so the submission names exactly what its tab showed.
149
+ const view = db.get<{ artifact_id: string }>(
150
+ "SELECT artifact_id FROM view WHERE id = ?",
151
+ snapshot.viewId,
152
+ );
153
+ if (view && view.artifact_id !== snapshot.artifactId)
154
+ return refuse("invalid: the view is another artifact's");
155
+ if (!view) {
156
+ db.run(
157
+ "INSERT INTO view (id, artifact_id, version_id, viewer_id, token_id, opened_cursor, opened_at) VALUES (?, ?, ?, ?, NULL, NULL, ?)",
158
+ snapshot.viewId,
159
+ snapshot.artifactId,
160
+ snapshot.versionId,
161
+ viewerId,
162
+ snapshot.at,
163
+ );
164
+ }
165
+ const draft = documentFor(db, snapshot.artifactId, viewerId, true);
166
+ const previous =
167
+ snapshot.previous !== undefined &&
168
+ db.get("SELECT 1 FROM submission WHERE id = ?", snapshot.previous)
169
+ ? snapshot.previous
170
+ : null;
171
+ const origin = {
172
+ server: source.server,
173
+ home: source.home,
174
+ incarnation: source.incarnation,
175
+ cursor: envelope.cursor ?? ("0" as EventOrigin["cursor"]),
176
+ };
177
+ // Its own `submission.created` here, whose cursor is its local position (the order the owner's
178
+ // deliveries replay in); the followed hosted one is never appended itself.
179
+ const localPosition = Number(
180
+ appendEvent(db, {
181
+ artifactId: snapshot.artifactId,
182
+ type: "submission.created",
183
+ actor: { kind: "viewer", id: viewerId },
184
+ causation: { submissionId: snapshot.submissionId },
185
+ payload: {
186
+ submissionId: snapshot.submissionId,
187
+ versionId: snapshot.versionId,
188
+ version: snapshot.version,
189
+ viewId: snapshot.viewId,
190
+ viewerId,
191
+ channel: snapshot.channel,
192
+ epoch: snapshot.epoch,
193
+ staleView: snapshot.staleView,
194
+ digest,
195
+ imported: true,
196
+ },
197
+ }),
198
+ );
199
+ db.run(
200
+ `INSERT INTO submission (id, position, artifact_id, version_id, view_id, viewer_id, channel, policy_json, epoch, scope_key,
201
+ previous_id, draft_document_id, draft_revision, state_revision, latest_version_number, snapshot_json, digest, stale_view,
202
+ request_id, created_at, origin_json)
203
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?)`,
204
+ snapshot.submissionId,
205
+ localPosition,
206
+ snapshot.artifactId,
207
+ snapshot.versionId,
208
+ snapshot.viewId,
209
+ viewerId,
210
+ snapshot.channel,
211
+ JSON.stringify(snapshot.policy),
212
+ snapshot.epoch,
213
+ // Hosted answers are their own audience (D165 item 1): they never meet the owner's own links'
214
+ // `once` scopes, and each imported submission is its own key.
215
+ `remote:${source.serverKey}:${snapshot.submissionId}`,
216
+ previous,
217
+ draft.id,
218
+ Number(snapshot.draft.revision),
219
+ snapshot.state ? Number(snapshot.state.revision) : null,
220
+ snapshot.latestVersion ?? null,
221
+ envelope.snapshot,
222
+ digest,
223
+ snapshot.staleView ? 1 : 0,
224
+ snapshot.at,
225
+ originJson(origin),
226
+ );
227
+ const at = new Date().toISOString();
228
+ const owners = input.owners.length > 0 ? [...new Set(input.owners)].sort() : [BUILT_IN_OWNER];
229
+ for (const owner of owners) {
230
+ db.run(
231
+ "INSERT INTO delivery (id, submission_id, position, port_owner, state, attempts, next_attempt_at, updated_at) VALUES (?, ?, ?, ?, 'pending', 0, ?, ?)",
232
+ importedDeliveryId(snapshot.submissionId, owner),
233
+ snapshot.submissionId,
234
+ localPosition,
235
+ owner,
236
+ at,
237
+ at,
238
+ );
239
+ }
240
+ return { accepted: true };
241
+ }
242
+
243
+ /**
244
+ * Types a follow never copies: the owner publishes its versions itself, and its own deliveries
245
+ * record their own outcomes. (A hosted `submission.created` is never appended either: its
246
+ * submission arrives as a delivery, below.)
247
+ */
248
+ const NOT_FOLLOWED = new Set([
249
+ "artifact.created",
250
+ "version.published",
251
+ "submission.retrying",
252
+ "submission.delivered",
253
+ "submission.rejected",
254
+ "submission.undeliverable",
255
+ ]);
256
+
257
+ /** The outcome of copying one page of followed events. */
258
+ export interface FollowOutcome {
259
+ /** Events appended now. */
260
+ readonly appended: number;
261
+ /** Hosted submissions named by a followed `submission.created` that this home lacks. */
262
+ readonly missing: readonly string[];
263
+ }
264
+
265
+ /**
266
+ * Copies a page of the hosted home's events into this home's log, in the caller's transaction:
267
+ * only the artifacts this instance owns, each event once (its origin is unique), with local
268
+ * cursors. A followed `submission.created` this home lacks is reported, so the caller has it
269
+ * delivered again rather than appending a record without its submission.
270
+ */
271
+ export function followEvents(
272
+ db: LedgerDb,
273
+ input: {
274
+ readonly events: readonly EventRecord[];
275
+ readonly source: ImportSource;
276
+ readonly owned: (db: LedgerDb, artifactId: string) => boolean;
277
+ },
278
+ ): FollowOutcome {
279
+ let appended = 0;
280
+ const missing: string[] = [];
281
+ for (const event of input.events) {
282
+ if (event.artifactId === null || !input.owned(db, event.artifactId)) continue;
283
+ if (event.type === "submission.created") {
284
+ const id = event.payload["submissionId"];
285
+ if (typeof id === "string" && !db.get("SELECT 1 FROM submission WHERE id = ?", id))
286
+ missing.push(id);
287
+ continue;
288
+ }
289
+ if (NOT_FOLLOWED.has(event.type)) continue;
290
+ // A run this home ran for the hosted home records its own events (relayed); the hosted copy
291
+ // of them would say each twice (Opus review of WP-29). Events of a run that never reached this
292
+ // home (it waited, failed while the owner was offline, was cancelled unsent) are copied.
293
+ if (event.type.startsWith("action.")) {
294
+ const runId = (event.payload as { runId?: unknown } | undefined)?.runId;
295
+ if (typeof runId === "string" && db.get("SELECT 1 FROM action_run WHERE id = ?", runId)) {
296
+ continue;
297
+ }
298
+ }
299
+ const origin: EventOrigin = {
300
+ server: input.source.server,
301
+ home: input.source.home,
302
+ incarnation: input.source.incarnation,
303
+ cursor: event.cursor,
304
+ };
305
+ if (db.get("SELECT 1 FROM event WHERE origin_json = ?", originJson(origin))) continue;
306
+ appendEvent(db, {
307
+ artifactId: event.artifactId,
308
+ type: event.type,
309
+ actor: event.actor,
310
+ ...(event.causation !== undefined ? { causation: event.causation } : {}),
311
+ payload: event.payload,
312
+ origin,
313
+ });
314
+ appended += 1;
315
+ }
316
+ return { appended, missing };
317
+ }