@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/live/index.ts CHANGED
@@ -22,9 +22,16 @@ import {
22
22
  RpcError,
23
23
  ServerLiveValueParams,
24
24
  serializeAll,
25
+ TALLY_LIVE_PREFIX,
25
26
  type WireError,
26
27
  } from "@mostra/protocol";
27
- import type { EphemeralBus, Interaction, PageIdentity } from "../interaction/index.ts";
28
+ import {
29
+ type EphemeralBus,
30
+ type Interaction,
31
+ type PageIdentity,
32
+ tallyField,
33
+ tallyState,
34
+ } from "../interaction/index.ts";
28
35
  import type { Ledger, LedgerDb, RequestKey } from "../ledger/index.ts";
29
36
  import { recordedResult, recordResult, requestKey } from "../ledger/index.ts";
30
37
  import { type Log, redactFrames, redactValue } from "../log.ts";
@@ -47,7 +54,7 @@ export interface LiveOptions {
47
54
  readonly log: Log;
48
55
  readonly bus: EphemeralBus;
49
56
  readonly pool: WorkerPool;
50
- readonly interaction: Pick<Interaction, "subscribedArtifacts" | "checkView">;
57
+ readonly interaction: Pick<Interaction, "subscribedArtifacts" | "checkView" | "onTallied">;
51
58
  /** The latest version of an artifact with live sources, or `undefined`. */
52
59
  readonly latest: (artifactId: string) => LatestLive | undefined;
53
60
  /** Every artifact whose latest version defines live sources. */
@@ -58,6 +65,20 @@ export interface LiveOptions {
58
65
  readonly reconcileMs?: number;
59
66
  /** Removes secrets from every value stored (AC-06). */
60
67
  readonly redactor?: { redact(text: string): string };
68
+ /**
69
+ * More sources wanted than this home's views and hosts want: a hosted page's, which its hosted
70
+ * home relays (`port/relay.live`, D165 item 4).
71
+ */
72
+ readonly extraInterest?: () => Iterable<{ readonly artifactId: string; readonly key: string }>;
73
+ /**
74
+ * A produced value or failure of a hosted artifact, which lives on its hosted home (D165 item 1):
75
+ * `true` when it was sent there, and nothing is kept here.
76
+ */
77
+ readonly forward?: (
78
+ artifactId: string,
79
+ versionId: string,
80
+ produced: () => ServerLiveValueParams,
81
+ ) => boolean;
61
82
  }
62
83
 
63
84
  /** The live module. */
@@ -80,6 +101,15 @@ export interface Live {
80
101
  input: { readonly key: string; readonly value: unknown; readonly mode?: "replace" | "append" },
81
102
  requestKey?: RequestKey,
82
103
  ): Promise<{ revision: string }>;
104
+ /**
105
+ * A value or failure its owner's producer made for a hosted artifact (`relay/live.value`):
106
+ * stored and sent to viewers as a producer's own, with no producer here.
107
+ */
108
+ relayed(
109
+ artifactId: string,
110
+ versionId: string,
111
+ produced: ServerLiveValueParams,
112
+ ): { readonly revision?: string };
83
113
  /** A worker's `server/live.value`. */
84
114
  produced(
85
115
  worker: { readonly artifactId: string; readonly versionId: string },
@@ -154,6 +184,7 @@ export function createLive(options: LiveOptions): Live {
154
184
  message: `The artifact's server code keeps crashing, so its live sources stopped (${cause}).`,
155
185
  });
156
186
  let timer: ReturnType<typeof setInterval> | undefined;
187
+ let stopTallies: (() => void) | undefined;
157
188
  let scheduled = false;
158
189
  let stopped = false;
159
190
  /** A worker is starting only to say which of its version's sources are `always`. */
@@ -250,6 +281,7 @@ export function createLive(options: LiveOptions): Live {
250
281
  out.set(keyOf(artifactId, key), { artifactId, key });
251
282
  };
252
283
  for (const entry of bus.liveInterest()) add(entry.artifactId, entry.key);
284
+ for (const entry of options.extraInterest?.() ?? []) add(entry.artifactId, entry.key);
253
285
  const subscribed = options.interaction.subscribedArtifacts();
254
286
  for (const artifactId of options.artifactsWithLive()) {
255
287
  const latest = options.latest(artifactId);
@@ -379,6 +411,12 @@ export function createLive(options: LiveOptions): Live {
379
411
  };
380
412
 
381
413
  const stateOf = (db: LedgerDb, artifactId: string, key: string, window?: number): LiveState => {
414
+ // A tally's key reads its counts (D165 item 12): no producer, no push, no relay.
415
+ const field = tallyField(key);
416
+ if (field !== undefined) {
417
+ const tally = tallyState(db, artifactId, field);
418
+ return tally ? { key, revision: tally.revision, value: tally.batches } : { key };
419
+ }
382
420
  const row = db.get<LiveRow>(
383
421
  "SELECT revision, value_json, at FROM live_value WHERE artifact_id = ? AND key = ?",
384
422
  artifactId,
@@ -443,6 +481,14 @@ export function createLive(options: LiveOptions): Live {
443
481
  },
444
482
 
445
483
  async push(artifactId, input, requestKey) {
484
+ // A tally's key is the submit transaction's alone (D165 item 12): nothing pushes to it.
485
+ if (tallyField(input.key) !== undefined) {
486
+ throw new RpcError(
487
+ createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", {
488
+ message: `${input.key} is a tally's key: only accepted submissions count it.`,
489
+ }),
490
+ );
491
+ }
446
492
  let batches: Batches;
447
493
  try {
448
494
  batches = await serializeAll(input.value, { mode: "argument" });
@@ -479,6 +525,29 @@ export function createLive(options: LiveOptions): Live {
479
525
  return answer;
480
526
  },
481
527
 
528
+ relayed(artifactId, versionId, produced) {
529
+ if (produced.error) {
530
+ fail(artifactId, produced.key, produced.error);
531
+ return {};
532
+ }
533
+ const value = produced.value as Batches | undefined;
534
+ if (!value) return {};
535
+ if (JSON.stringify(value).length > LIVE_VALUE_MAX) throw tooLarge(produced.key);
536
+ const stored = ledger.write((db) =>
537
+ store(
538
+ db,
539
+ artifactId,
540
+ produced.key,
541
+ value as Frame[][],
542
+ versionId,
543
+ ringOf(produced.key, versionId),
544
+ ),
545
+ );
546
+ failures.delete(keyOf(artifactId, produced.key));
547
+ publishValue(artifactId, produced.key, stored.revision, stored.at, value);
548
+ return { revision: String(stored.revision) };
549
+ },
550
+
482
551
  produced(worker, params) {
483
552
  const parsed = ServerLiveValueParams.safeParse(params);
484
553
  if (!parsed.success) return;
@@ -486,6 +555,23 @@ export function createLive(options: LiveOptions): Live {
486
555
  const producer = running.get(keyOf(worker.artifactId, key));
487
556
  // Only the producer of the latest version writes the source; a stale one is ignored.
488
557
  if (!producer || producer.versionId !== worker.versionId) return;
558
+ // A hosted artifact's value goes to its hosted home as this home would keep it: its value and a
559
+ // failure's message redacted (AC-06), so no secret ever crosses the relay.
560
+ const outgoing = (): ServerLiveValueParams => ({
561
+ key,
562
+ ...(parsed.data.value !== undefined
563
+ ? { value: redactBatches(parsed.data.value as Batches) }
564
+ : {}),
565
+ ...(parsed.data.error !== undefined
566
+ ? {
567
+ error: options.redactor
568
+ ? redactValue(parsed.data.error, options.redactor)
569
+ : parsed.data.error,
570
+ }
571
+ : {}),
572
+ });
573
+ // Built only for a hosted artifact's value, so a local producer pays nothing for it.
574
+ if (options.forward?.(worker.artifactId, worker.versionId, outgoing)) return;
489
575
  if (parsed.data.error) {
490
576
  fail(worker.artifactId, key, parsed.data.error);
491
577
  return;
@@ -571,6 +657,28 @@ export function createLive(options: LiveOptions): Live {
571
657
 
572
658
  start() {
573
659
  stopped = false;
660
+ // A submission that counted a tallied field sends its viewers the new counts, on the live
661
+ // channel like any live value (D165 item 12).
662
+ stopTallies ??= options.interaction.onTallied((artifactId, fields) => {
663
+ for (const field of fields) {
664
+ const key = `${TALLY_LIVE_PREFIX}${field}`;
665
+ try {
666
+ const tally = ledger.read((db) => tallyState(db, artifactId, field));
667
+ if (!tally) continue;
668
+ bus.publishLive(artifactId, {
669
+ kind: "live",
670
+ live: {
671
+ key,
672
+ revision: tally.revision,
673
+ at: new Date().toISOString(),
674
+ value: tally.batches,
675
+ },
676
+ });
677
+ } catch (error) {
678
+ log.error("live.tally_failed", { key, error });
679
+ }
680
+ }
681
+ });
574
682
  bus.onLiveInterest(schedule);
575
683
  timer = setInterval(schedule, options.reconcileMs ?? 5_000);
576
684
  timer.unref?.();
@@ -580,6 +688,8 @@ export function createLive(options: LiveOptions): Live {
580
688
  stop() {
581
689
  stopped = true;
582
690
  if (timer !== undefined) clearInterval(timer);
691
+ stopTallies?.();
692
+ stopTallies = undefined;
583
693
  },
584
694
  };
585
695
  }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Whether a directory is on a network filesystem (D165 item 0b, DATA_MODEL §7.1): a remote
3
+ * server's data directory never is, since its locks and SQLite's WAL need a local disk, and a
4
+ * lock a network filesystem only pretends to hold would let two servers write one home.
5
+ *
6
+ * - **Linux:** the filesystem's magic number from `statfs(2)`: NFS, SMB, CIFS, SMB2, Ceph,
7
+ * AFS, Coda, 9P and FUSE (a FUSE mount may be sshfs or s3fs; a local FUSE data directory is
8
+ * refused too, rather than guessed at).
9
+ * - **macOS:** the filesystem's name (`stat -f %T`): `nfs`, `smbfs`, `afpfs`, `webdav`,
10
+ * `macfuse`/`osxfuse` and other FUSE names.
11
+ * - **Windows:** a UNC path (`\\server\share`), or a drive Windows reports as remote
12
+ * (`GetDriveTypeW`, through `fsutil fsinfo drivetype`).
13
+ *
14
+ * Answers the filesystem's name when it is a network one, `undefined` when it is local or can't
15
+ * be told (a check that can't run never refuses a disk it can't classify).
16
+ */
17
+ import { execFileSync } from "node:child_process";
18
+ import { statfsSync } from "node:fs";
19
+ import { parse } from "node:path";
20
+
21
+ /** Linux `statfs` magic numbers of network and user-space filesystems. */
22
+ const LINUX_NETWORK: ReadonlyMap<number, string> = new Map([
23
+ [0x6969, "nfs"],
24
+ [0x517b, "smb"],
25
+ [0xff534d42, "cifs"],
26
+ [0xfe534d42, "smb2"],
27
+ [0x00c36400, "ceph"],
28
+ [0x5346414f, "afs"],
29
+ [0x73757245, "coda"],
30
+ [0x01021997, "9p"],
31
+ [0x65735546, "fuse"],
32
+ ]);
33
+
34
+ const MAC_NETWORK = /^(nfs|smbfs|afpfs|webdav|cifs|ftp|macfuse|osxfuse|fuse.*)$/i;
35
+
36
+ /** The network filesystem `dir` is on, or `undefined` (local, or not knowable). */
37
+ export function networkFilesystem(dir: string): string | undefined {
38
+ if (process.platform === "linux") {
39
+ try {
40
+ // `type` is a signed long on some systems: compare as unsigned 32-bit.
41
+ const type = statfsSync(dir).type >>> 0;
42
+ return LINUX_NETWORK.get(type);
43
+ } catch {
44
+ return undefined;
45
+ }
46
+ }
47
+ if (process.platform === "darwin") {
48
+ try {
49
+ const name = execFileSync("/usr/bin/stat", ["-f", "%T", dir], {
50
+ encoding: "utf8",
51
+ stdio: ["ignore", "pipe", "ignore"],
52
+ }).trim();
53
+ return MAC_NETWORK.test(name) ? name : undefined;
54
+ } catch {
55
+ return undefined;
56
+ }
57
+ }
58
+ if (process.platform === "win32") {
59
+ if (/^\\\\[^\\?.]/.test(dir)) return "unc";
60
+ const drive = parse(dir).root.replace(/\\$/, "");
61
+ if (!/^[A-Za-z]:$/.test(drive)) return undefined;
62
+ try {
63
+ const answer = execFileSync(
64
+ `${process.env["SystemRoot"] ?? "C:\\Windows"}\\System32\\fsutil.exe`,
65
+ ["fsinfo", "drivetype", drive],
66
+ {
67
+ encoding: "utf8",
68
+ stdio: ["ignore", "pipe", "ignore"],
69
+ windowsHide: true,
70
+ },
71
+ );
72
+ return /remote|network/i.test(answer) ? "remote" : undefined;
73
+ } catch {
74
+ return undefined;
75
+ }
76
+ }
77
+ return undefined;
78
+ }
@@ -42,6 +42,7 @@ export {
42
42
  sealPlaced,
43
43
  sealTree,
44
44
  } from "./files.ts";
45
+ export { networkFilesystem } from "./filesystems.ts";
45
46
  export {
46
47
  currentUserSid,
47
48
  helperPath,
@@ -2,6 +2,8 @@
2
2
  * The client end of the home socket, used by a starter that finds another supervisor holding the
3
3
  * home (D81) and by tests. SDKs and the CLI implement the same few steps in their own packages.
4
4
  */
5
+
6
+ import { PassThrough } from "node:stream";
5
7
  import {
6
8
  type ClientInfo,
7
9
  createDiagnostic,
@@ -12,6 +14,7 @@ import {
12
14
  RpcPeer,
13
15
  } from "@mostra/protocol";
14
16
  import { ControlConnectError, connectControl } from "../platform/index.ts";
17
+ import type { ProtocolServer } from "./server.ts";
15
18
  import { pump, writeLine } from "./streams.ts";
16
19
 
17
20
  /** An open client connection to an instance's socket. */
@@ -93,3 +96,53 @@ export async function attach(
93
96
  throw error;
94
97
  }
95
98
  }
99
+
100
+ /**
101
+ * Opens a session with a protocol server in this process, over a pair of in-memory streams, so a
102
+ * part of the runtime acts as a client exactly as any host does (invariant 11): the same framing,
103
+ * initialize, validation and session rules. `attributes` are the session's, as a transport sets
104
+ * them (a remote MCP request's account and home). The caller closes the returned client.
105
+ */
106
+ export async function attachInProcess(
107
+ server: ProtocolServer,
108
+ client: ClientInfo,
109
+ attributes: Readonly<Record<string, unknown>> = {},
110
+ timeoutMs = 5000,
111
+ ): Promise<{ client: SocketClient; result: MostraInitializeResult }> {
112
+ const toServer = new PassThrough();
113
+ const toClient = new PassThrough();
114
+ const peer = new RpcPeer({ send: (message) => void writeLine(toServer, message) });
115
+ let markClosed: () => void = () => {};
116
+ const closed = new Promise<void>((done) => {
117
+ markClosed = done;
118
+ });
119
+ server.serve("stdio", toServer, toClient, undefined, attributes);
120
+ pump(
121
+ { input: toClient, output: toServer },
122
+ () => peer,
123
+ () => {
124
+ peer.close();
125
+ markClosed();
126
+ },
127
+ );
128
+ const connection: SocketClient = {
129
+ peer,
130
+ closed,
131
+ close: () => {
132
+ peer.close();
133
+ toServer.end();
134
+ toClient.end();
135
+ },
136
+ };
137
+ try {
138
+ const result = await peer.call(
139
+ mostraInitializeMethod,
140
+ { client, revisions: [...HOST_PROTOCOL_REVISIONS], capabilities: {}, ports: [] },
141
+ { timeoutMs },
142
+ );
143
+ return { client: connection, result };
144
+ } catch (error) {
145
+ connection.close();
146
+ throw error;
147
+ }
148
+ }
@@ -13,14 +13,28 @@ import {
13
13
  instanceCheckMethod,
14
14
  instanceStatusMethod,
15
15
  mostraShutdownMethod,
16
+ type RemoteLink,
16
17
  RpcError,
17
18
  type Share,
18
19
  type WorkerStatus,
19
20
  } from "@mostra/protocol";
20
21
  import { handler, type MethodHandler } from "./server.ts";
21
22
 
22
- export { attach, type SocketClient } from "./client.ts";
23
- export { handler, type MethodHandler, ProtocolServer, type Session } from "./server.ts";
23
+ export { attach, attachInProcess, type SocketClient } from "./client.ts";
24
+ export {
25
+ handler,
26
+ type MethodHandler,
27
+ ProtocolServer,
28
+ type Session,
29
+ } from "./server.ts";
30
+ export {
31
+ BINDING_SUBPROTOCOL,
32
+ type HeartbeatOptions,
33
+ keepAlive,
34
+ MAX_FRAME_BYTES,
35
+ readFrame,
36
+ serveWebSocket,
37
+ } from "./websocket.ts";
24
38
 
25
39
  /** What the session methods need from the instance. */
26
40
  export interface SessionMethodsOptions {
@@ -40,6 +54,8 @@ export interface SessionMethodsOptions {
40
54
  idleExitAt?(): string | undefined;
41
55
  /** The active shares (WP-13, D158). */
42
56
  shares?(): readonly Share[];
57
+ /** The home's links to remote servers (WP-29). */
58
+ links?(): readonly RemoteLink[];
43
59
  /**
44
60
  * The supervisor's own checks of its home (`instance/check`, D140 item 18), in order; `deep`
45
61
  * also hashes every version against its output digest.
@@ -66,6 +82,7 @@ export function sessionMethods(options: SessionMethodsOptions): MethodHandler[]
66
82
  ...(options.deliveries ? { deliveries: [...options.deliveries()] } : {}),
67
83
  ...(options.workers ? { workers: [...options.workers()] } : {}),
68
84
  ...(options.shares ? { shares: [...options.shares()] } : {}),
85
+ ...(options.links ? { links: [...options.links()] } : {}),
69
86
  ...(() => {
70
87
  const at = options.idleExitAt?.();
71
88
  return at === undefined ? {} : { idleExitAt: at };
@@ -15,9 +15,11 @@ import {
15
15
  type InstanceInfo,
16
16
  type JsonRpcParams,
17
17
  type MethodDefinition,
18
+ type MostraInitializeParams,
18
19
  type MostraInitializeResult,
19
20
  mostraInitializeMethod,
20
21
  negotiateRevision,
22
+ type OwnerLinkInfo,
21
23
  parseParams,
22
24
  type Revision,
23
25
  RpcError,
@@ -27,8 +29,8 @@ import type { Log } from "../log.ts";
27
29
  import { type ControlListener, type LaunchPipe, listenControl } from "../platform/index.ts";
28
30
  import { pump, writeLine } from "./streams.ts";
29
31
 
30
- /** How a connection reached the instance. */
31
- export type ConnectionKind = "stdio" | "socket";
32
+ /** How a connection reached the instance: also `websocket`, a remote server's binding (§18.2). */
33
+ export type ConnectionKind = "stdio" | "socket" | "websocket";
32
34
 
33
35
  /** One connection's session, as handlers see it. */
34
36
  export interface Session {
@@ -45,6 +47,13 @@ export interface Session {
45
47
  readonly notifications: ReadonlySet<string>;
46
48
  /** Aborts when the connection closes, so long requests (`wait`) end with it. */
47
49
  readonly signal: AbortSignal;
50
+ /**
51
+ * What the transport knows of the connection: on a remote server's binding, the account and
52
+ * grant its access token named (INTERFACES §18.2). Empty for stdio and the socket.
53
+ */
54
+ readonly attributes: Readonly<Record<string, unknown>>;
55
+ /** The owner link a binding session announced in `mostra/initialize` (§18.2). */
56
+ readonly link: OwnerLinkInfo | undefined;
48
57
  }
49
58
 
50
59
  /** A method a module serves. */
@@ -64,8 +73,13 @@ export function handler<P, R>(
64
73
  /** Options for {@link ProtocolServer}. */
65
74
  export interface ProtocolServerOptions {
66
75
  readonly log: Log;
67
- /** Describes the instance for `mostra/initialize`. */
68
- describe(): InstanceInfo;
76
+ /** Describes the instance for `mostra/initialize`, for the session being opened. */
77
+ describe(session?: Session): InstanceInfo;
78
+ /**
79
+ * Judges a session before `mostra/initialize` is answered: a remote server's hosted home checks
80
+ * the owner link there (its incarnation, its relay mark, D165). A throw refuses the session.
81
+ */
82
+ admit?(session: Session, params: MostraInitializeParams): void;
69
83
  /** Whether a client's `home.path` names this instance's home (D84). */
70
84
  servesHome(path: string): boolean;
71
85
  /**
@@ -108,6 +122,8 @@ interface Connection {
108
122
  interface MutableSession {
109
123
  id: number;
110
124
  kind: ConnectionKind;
125
+ attributes: Readonly<Record<string, unknown>>;
126
+ link: OwnerLinkInfo | undefined;
111
127
  client: ClientInfo | undefined;
112
128
  revision: Revision | undefined;
113
129
  ports: Set<string>;
@@ -152,11 +168,19 @@ export class ProtocolServer {
152
168
  * Serves one stream connection (stdio, or an accepted socket). `onClose` runs once when it
153
169
  * ends.
154
170
  */
155
- serve(kind: ConnectionKind, input: Readable, output: Writable, onClose?: () => void): Session {
171
+ serve(
172
+ kind: ConnectionKind,
173
+ input: Readable,
174
+ output: Writable,
175
+ onClose?: () => void,
176
+ attributes: Readonly<Record<string, unknown>> = {},
177
+ ): Session {
156
178
  const closed = new AbortController();
157
179
  const session: MutableSession = {
158
180
  id: this.#nextId++,
159
181
  kind,
182
+ attributes,
183
+ link: undefined,
160
184
  client: undefined,
161
185
  revision: undefined,
162
186
  ports: new Set(),
@@ -329,7 +353,12 @@ export class ProtocolServer {
329
353
  .filter((connection) => connection.session.initialized && connection.session.ports.has(port))
330
354
  .map((connection) => ({
331
355
  session: connection.session.id,
332
- owner: connection.session.client?.name ?? "",
356
+ // On a hosted home a delivery's owner is the owner instance's link, never a client name
357
+ // (D165, after the Opus review): two instances of one account are two owners.
358
+ // A network binding's owner is only ever its link: its client name is whatever it says.
359
+ owner:
360
+ connection.session.link?.instanceId ??
361
+ (connection.session.kind === "websocket" ? "" : (connection.session.client?.name ?? "")),
333
362
  }));
334
363
  }
335
364
 
@@ -472,7 +501,9 @@ export class ProtocolServer {
472
501
  this.#options.revisions ?? HOST_PROTOCOL_REVISIONS,
473
502
  );
474
503
  if (!negotiation.ok) throw new RpcError(negotiation.diagnostic);
475
- const instance = this.#options.describe();
504
+ session.link = params.link;
505
+ this.#options.admit?.(session, params);
506
+ const instance = this.#options.describe(session);
476
507
  if (params.home?.path !== undefined && !this.#options.servesHome(params.home.path)) {
477
508
  throw new RpcError(
478
509
  createDiagnostic("MOSTRA_HOME_MISMATCH", {
@@ -0,0 +1,161 @@
1
+ /**
2
+ * The host protocol over WebSocket (INTERFACES §18.2, D165 item 2): the network binding between an
3
+ * owner instance and its hosted home. One JSON-RPC message per text frame, at most
4
+ * `MAX_LINE_LENGTH` characters, checked on both sides; a binary frame closes the connection
5
+ * (1003), a longer message too (1009). Each side sends a WebSocket ping and the notification
6
+ * `mostra/ping` every 20 s, since some proxies count only data as activity, and closes a
7
+ * connection it heard nothing on for 45 s, inside the 60 s idle limit of the edges a server sits
8
+ * behind (VERIFIED_FACTS, WP-28).
9
+ *
10
+ * The server side adapts a socket to {@link ProtocolServer.serve}'s line streams, so every rule of
11
+ * the host protocol (initialize first, revisions, `requestId`s, port calls on the registering
12
+ * connection) is the same code as stdio and the home socket.
13
+ */
14
+ import { PassThrough, Writable } from "node:stream";
15
+ import { MAX_LINE_LENGTH } from "@mostra/protocol";
16
+ import type { WebSocket } from "ws";
17
+ import type { Log } from "../log.ts";
18
+ import type { ProtocolServer, Session } from "./server.ts";
19
+
20
+ /** The subprotocol a binding asks for (`Sec-WebSocket-Protocol`). */
21
+ export const BINDING_SUBPROTOCOL = "mostra.host";
22
+
23
+ /** How often each side pings, and how long a silent connection lives. */
24
+ export const HEARTBEAT = { intervalMs: 20_000, silenceMs: 45_000 } as const;
25
+
26
+ /** The largest frame a binding accepts, in bytes: a message's characters can take 4 bytes each. */
27
+ export const MAX_FRAME_BYTES: number = MAX_LINE_LENGTH * 4;
28
+
29
+ /** The JSON-RPC heartbeat beside the WebSocket ping (a notification nobody answers). */
30
+ const PING_LINE = JSON.stringify({ jsonrpc: "2.0", method: "mostra/ping" });
31
+
32
+ /** Options for {@link keepAlive}. */
33
+ export interface HeartbeatOptions {
34
+ readonly intervalMs?: number;
35
+ readonly silenceMs?: number;
36
+ /** Told when the connection is closed for its silence. */
37
+ readonly onSilent?: () => void;
38
+ }
39
+
40
+ /**
41
+ * Keeps a binding alive and judges it: pings each way every interval, and terminates the
42
+ * connection once nothing (a message, a ping or a pong) arrived for the silence limit. Returns a
43
+ * function that stops it; it stops by itself when the socket closes.
44
+ */
45
+ export function keepAlive(socket: WebSocket, options: HeartbeatOptions = {}): () => void {
46
+ const intervalMs = options.intervalMs ?? HEARTBEAT.intervalMs;
47
+ const silenceMs = options.silenceMs ?? HEARTBEAT.silenceMs;
48
+ let heard = Date.now();
49
+ const hear = (): void => {
50
+ heard = Date.now();
51
+ };
52
+ socket.on("message", hear);
53
+ socket.on("ping", hear);
54
+ socket.on("pong", hear);
55
+ const check = setInterval(
56
+ () => {
57
+ if (socket.readyState !== socket.OPEN) return;
58
+ if (Date.now() - heard >= silenceMs) {
59
+ options.onSilent?.();
60
+ socket.terminate();
61
+ return;
62
+ }
63
+ },
64
+ Math.min(1_000, Math.max(50, silenceMs / 10)),
65
+ );
66
+ const ping = setInterval(() => {
67
+ if (socket.readyState !== socket.OPEN) return;
68
+ socket.ping();
69
+ socket.send(PING_LINE);
70
+ }, intervalMs);
71
+ check.unref();
72
+ ping.unref();
73
+ const stop = (): void => {
74
+ clearInterval(check);
75
+ clearInterval(ping);
76
+ };
77
+ socket.once("close", stop);
78
+ return stop;
79
+ }
80
+
81
+ /**
82
+ * Checks one frame and returns its text, or closes the socket and returns `undefined`: binary
83
+ * frames close it with 1003, a message longer than the limit with 1009.
84
+ */
85
+ export function readFrame(
86
+ socket: WebSocket,
87
+ data: Buffer | ArrayBuffer | Buffer[],
88
+ isBinary: boolean,
89
+ log?: Log,
90
+ ): string | undefined {
91
+ if (isBinary) {
92
+ log?.warn("binding.binary_frame", {});
93
+ socket.close(1003, "binary frames are not part of the binding");
94
+ return undefined;
95
+ }
96
+ const text = Array.isArray(data)
97
+ ? Buffer.concat(data).toString("utf8")
98
+ : Buffer.from(data as ArrayBuffer).toString("utf8");
99
+ if (text.includes("\n")) {
100
+ log?.warn("binding.frame_with_newline", {});
101
+ socket.close(1007, "one message per frame");
102
+ return undefined;
103
+ }
104
+ if (text.length > MAX_LINE_LENGTH) {
105
+ log?.warn("binding.message_too_large", {
106
+ code: "MOSTRA_HOST_MESSAGE_TOO_LARGE",
107
+ length: text.length,
108
+ });
109
+ socket.close(1009, "message too large");
110
+ return undefined;
111
+ }
112
+ return text;
113
+ }
114
+
115
+ /**
116
+ * Serves one binding connection with `server`: frames in become lines, lines out become frames.
117
+ * The heartbeat is kept; `attributes` (the account and grant the access token named) are the
118
+ * session's. Returns the session.
119
+ */
120
+ export function serveWebSocket(
121
+ server: ProtocolServer,
122
+ socket: WebSocket,
123
+ options: {
124
+ readonly attributes: Readonly<Record<string, unknown>>;
125
+ readonly log: Log;
126
+ readonly heartbeat?: HeartbeatOptions;
127
+ readonly onClose?: () => void;
128
+ },
129
+ ): Session {
130
+ const input = new PassThrough();
131
+ const output = new Writable({
132
+ write(chunk: Buffer | string, _encoding, done): void {
133
+ const text = (typeof chunk === "string" ? chunk : chunk.toString("utf8")).replace(/\n$/, "");
134
+ if (socket.readyState !== socket.OPEN) {
135
+ done();
136
+ return;
137
+ }
138
+ socket.send(text, (error) => done(error ?? null));
139
+ },
140
+ final(done): void {
141
+ if (socket.readyState === socket.OPEN) socket.close(1000);
142
+ done();
143
+ },
144
+ });
145
+ output.on("error", () => {});
146
+ socket.on("message", (data, isBinary) => {
147
+ const text = readFrame(socket, data as Buffer, isBinary, options.log);
148
+ if (text === undefined) return;
149
+ if (text === PING_LINE) return;
150
+ input.write(`${text}\n`);
151
+ });
152
+ socket.once("close", () => {
153
+ input.end();
154
+ });
155
+ socket.on("error", (error) => options.log.warn("binding.socket_error", { error }));
156
+ keepAlive(socket, {
157
+ ...options.heartbeat,
158
+ onSilent: () => options.log.warn("binding.silent", {}),
159
+ });
160
+ return server.serve("websocket", input, output, options.onClose, options.attributes);
161
+ }