@mostra/runtime 0.10.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 (245) hide show
  1. package/dist/bin.js +4058 -310
  2. package/dist/bin.js.map +1 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/{instance-FExcyENK.js → instance-DCiUHvgZ.js} +682 -47
  6. package/dist/instance-DCiUHvgZ.js.map +1 -0
  7. package/dist/reference/cli.md +1322 -0
  8. package/dist/reference/diagnostics.json +1552 -0
  9. package/dist/reference/errors/MOSTRA_A11Y_MINOR.md +23 -0
  10. package/dist/reference/errors/MOSTRA_A11Y_SERIOUS.md +23 -0
  11. package/dist/reference/errors/MOSTRA_ACTION_CANCELLED.md +23 -0
  12. package/dist/reference/errors/MOSTRA_ACTION_EVENT_INVALID.md +23 -0
  13. package/dist/reference/errors/MOSTRA_ACTION_EXPORT_INVALID.md +23 -0
  14. package/dist/reference/errors/MOSTRA_ACTION_INTERRUPTED.md +23 -0
  15. package/dist/reference/errors/MOSTRA_ACTION_PAUSED.md +23 -0
  16. package/dist/reference/errors/MOSTRA_ACTION_RUN_NOT_FOUND.md +23 -0
  17. package/dist/reference/errors/MOSTRA_ACTION_THREW.md +23 -0
  18. package/dist/reference/errors/MOSTRA_ACTION_TOO_LARGE.md +23 -0
  19. package/dist/reference/errors/MOSTRA_ACTION_UNKNOWN_FUNCTION.md +23 -0
  20. package/dist/reference/errors/MOSTRA_ACTION_UNSERIALIZABLE.md +23 -0
  21. package/dist/reference/errors/MOSTRA_ARTIFACT_BUNDLE_INVALID.md +23 -0
  22. package/dist/reference/errors/MOSTRA_ARTIFACT_DIR_NOT_EMPTY.md +23 -0
  23. package/dist/reference/errors/MOSTRA_ARTIFACT_ENTRY_AMBIGUOUS.md +23 -0
  24. package/dist/reference/errors/MOSTRA_ARTIFACT_ID_DROPPED.md +23 -0
  25. package/dist/reference/errors/MOSTRA_ARTIFACT_NOT_FOUND.md +23 -0
  26. package/dist/reference/errors/MOSTRA_ARTIFACT_NO_ENTRY.md +23 -0
  27. package/dist/reference/errors/MOSTRA_ARTIFACT_NO_PAGE.md +23 -0
  28. package/dist/reference/errors/MOSTRA_ARTIFACT_PATCH_REJECTED.md +23 -0
  29. package/dist/reference/errors/MOSTRA_ARTIFACT_PATH_INVALID.md +23 -0
  30. package/dist/reference/errors/MOSTRA_ARTIFACT_SOURCE_MISSING.md +23 -0
  31. package/dist/reference/errors/MOSTRA_ARTIFACT_SOURCE_UNREADABLE.md +23 -0
  32. package/dist/reference/errors/MOSTRA_ARTIFACT_TEMPLATE_UNKNOWN.md +23 -0
  33. package/dist/reference/errors/MOSTRA_ARTIFACT_VERSION_COLLECTED.md +23 -0
  34. package/dist/reference/errors/MOSTRA_ARTIFACT_VERSION_NOT_FOUND.md +23 -0
  35. package/dist/reference/errors/MOSTRA_BUILD_CRASHED.md +23 -0
  36. package/dist/reference/errors/MOSTRA_BUILD_FAILED.md +23 -0
  37. package/dist/reference/errors/MOSTRA_BUILD_TIMEOUT.md +23 -0
  38. package/dist/reference/errors/MOSTRA_BUILD_UNRESOLVED.md +23 -0
  39. package/dist/reference/errors/MOSTRA_CLI_CONFIG_UNWRITABLE.md +23 -0
  40. package/dist/reference/errors/MOSTRA_CLI_UNKNOWN_COMMAND.md +23 -0
  41. package/dist/reference/errors/MOSTRA_CLI_USAGE.md +23 -0
  42. package/dist/reference/errors/MOSTRA_CONSOLE_ERROR.md +23 -0
  43. package/dist/reference/errors/MOSTRA_CONSOLE_WARNING.md +23 -0
  44. package/dist/reference/errors/MOSTRA_DEP_INSTALL_FAILED.md +23 -0
  45. package/dist/reference/errors/MOSTRA_DEP_MISSING.md +23 -0
  46. package/dist/reference/errors/MOSTRA_DEP_NOT_FOUND.md +23 -0
  47. package/dist/reference/errors/MOSTRA_DEP_OFFLINE.md +23 -0
  48. package/dist/reference/errors/MOSTRA_DEP_SPEC_INVALID.md +23 -0
  49. package/dist/reference/errors/MOSTRA_DEP_TIMEOUT.md +23 -0
  50. package/dist/reference/errors/MOSTRA_DEP_WARM_CONFLICT.md +23 -0
  51. package/dist/reference/errors/MOSTRA_ENV_BIND_FAILED.md +23 -0
  52. package/dist/reference/errors/MOSTRA_ENV_BROWSER_MISSING.md +23 -0
  53. package/dist/reference/errors/MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED.md +23 -0
  54. package/dist/reference/errors/MOSTRA_ENV_BUNDLE_INVALID.md +23 -0
  55. package/dist/reference/errors/MOSTRA_ENV_BUNDLE_UNAVAILABLE.md +23 -0
  56. package/dist/reference/errors/MOSTRA_ENV_HELPER_MISSING.md +23 -0
  57. package/dist/reference/errors/MOSTRA_ENV_NODE_UNSUPPORTED.md +23 -0
  58. package/dist/reference/errors/MOSTRA_ENV_PORT_TAKEN.md +23 -0
  59. package/dist/reference/errors/MOSTRA_ENV_RUNTIME_INSTALLING.md +23 -0
  60. package/dist/reference/errors/MOSTRA_ENV_RUNTIME_MISSING.md +23 -0
  61. package/dist/reference/errors/MOSTRA_ENV_SERVICE_FAILED.md +23 -0
  62. package/dist/reference/errors/MOSTRA_ENV_SHELL_MISSING.md +23 -0
  63. package/dist/reference/errors/MOSTRA_ENV_WARM_MISSING.md +23 -0
  64. package/dist/reference/errors/MOSTRA_FIELD_CONFLICT.md +23 -0
  65. package/dist/reference/errors/MOSTRA_FIELD_DUPLICATE_ID.md +23 -0
  66. package/dist/reference/errors/MOSTRA_FIELD_ID_INVALID.md +23 -0
  67. package/dist/reference/errors/MOSTRA_FIELD_ID_UNSTABLE.md +23 -0
  68. package/dist/reference/errors/MOSTRA_FIELD_MUTATION_ID_REUSED.md +23 -0
  69. package/dist/reference/errors/MOSTRA_FIELD_SHARED.md +23 -0
  70. package/dist/reference/errors/MOSTRA_FIELD_TOO_LARGE.md +23 -0
  71. package/dist/reference/errors/MOSTRA_FIELD_UNBOUND.md +23 -0
  72. package/dist/reference/errors/MOSTRA_HOME_DISK_FULL.md +23 -0
  73. package/dist/reference/errors/MOSTRA_HOME_GC_INCOMPLETE.md +23 -0
  74. package/dist/reference/errors/MOSTRA_HOME_GONE.md +23 -0
  75. package/dist/reference/errors/MOSTRA_HOME_INTEGRITY.md +23 -0
  76. package/dist/reference/errors/MOSTRA_HOME_LEDGER_UNREADABLE.md +23 -0
  77. package/dist/reference/errors/MOSTRA_HOME_LOCKED.md +23 -0
  78. package/dist/reference/errors/MOSTRA_HOME_MISMATCH.md +23 -0
  79. package/dist/reference/errors/MOSTRA_HOME_NETWORK_FILESYSTEM.md +23 -0
  80. package/dist/reference/errors/MOSTRA_HOME_NOT_ALWAYS_ON.md +23 -0
  81. package/dist/reference/errors/MOSTRA_HOME_NOT_OWNED.md +23 -0
  82. package/dist/reference/errors/MOSTRA_HOME_SOCKET_TOO_LONG.md +23 -0
  83. package/dist/reference/errors/MOSTRA_HOME_TOO_NEW.md +23 -0
  84. package/dist/reference/errors/MOSTRA_HOST_CONNECTION_CLOSED.md +23 -0
  85. package/dist/reference/errors/MOSTRA_HOST_CURSOR_COMPACTED.md +23 -0
  86. package/dist/reference/errors/MOSTRA_HOST_IDENTITY_UNAVAILABLE.md +23 -0
  87. package/dist/reference/errors/MOSTRA_HOST_INITIALIZE_ORDER.md +23 -0
  88. package/dist/reference/errors/MOSTRA_HOST_INTERNAL_ERROR.md +23 -0
  89. package/dist/reference/errors/MOSTRA_HOST_INVALID_PARAMS.md +23 -0
  90. package/dist/reference/errors/MOSTRA_HOST_MALFORMED.md +23 -0
  91. package/dist/reference/errors/MOSTRA_HOST_MESSAGE_TOO_LARGE.md +23 -0
  92. package/dist/reference/errors/MOSTRA_HOST_METHOD_UNKNOWN.md +23 -0
  93. package/dist/reference/errors/MOSTRA_HOST_NOTIFICATION_UNSUPPORTED.md +23 -0
  94. package/dist/reference/errors/MOSTRA_HOST_PORT_UNSUPPORTED.md +23 -0
  95. package/dist/reference/errors/MOSTRA_HOST_REQUEST_ID_REUSED.md +23 -0
  96. package/dist/reference/errors/MOSTRA_HOST_REVISION_UNSUPPORTED.md +23 -0
  97. package/dist/reference/errors/MOSTRA_HOST_SHUTDOWN_REFUSED.md +23 -0
  98. package/dist/reference/errors/MOSTRA_HOST_SUBSCRIPTION_UNKNOWN.md +23 -0
  99. package/dist/reference/errors/MOSTRA_HOST_TIMEOUT.md +23 -0
  100. package/dist/reference/errors/MOSTRA_HYGIENE_CONTENT_TYPE.md +23 -0
  101. package/dist/reference/errors/MOSTRA_HYGIENE_CSRF_MISSING.md +23 -0
  102. package/dist/reference/errors/MOSTRA_HYGIENE_FRAME_SESSION.md +23 -0
  103. package/dist/reference/errors/MOSTRA_HYGIENE_HEADERS_TOO_LARGE.md +23 -0
  104. package/dist/reference/errors/MOSTRA_HYGIENE_HOST_REFUSED.md +23 -0
  105. package/dist/reference/errors/MOSTRA_HYGIENE_NOT_SERVED.md +23 -0
  106. package/dist/reference/errors/MOSTRA_HYGIENE_ORIGIN_REFUSED.md +23 -0
  107. package/dist/reference/errors/MOSTRA_HYGIENE_RATE_LIMITED.md +23 -0
  108. package/dist/reference/errors/MOSTRA_HYGIENE_REQUEST_MALFORMED.md +23 -0
  109. package/dist/reference/errors/MOSTRA_HYGIENE_SCOPE_DENIED.md +23 -0
  110. package/dist/reference/errors/MOSTRA_HYGIENE_SESSION_CONFLICT.md +23 -0
  111. package/dist/reference/errors/MOSTRA_HYGIENE_SESSION_MISSING.md +23 -0
  112. package/dist/reference/errors/MOSTRA_HYGIENE_TOKEN_INVALID.md +23 -0
  113. package/dist/reference/errors/MOSTRA_HYGIENE_TOKEN_REVOKED.md +23 -0
  114. package/dist/reference/errors/MOSTRA_LIVE_SOURCE_FAILED.md +23 -0
  115. package/dist/reference/errors/MOSTRA_LIVE_TOO_LARGE.md +23 -0
  116. package/dist/reference/errors/MOSTRA_MANIFEST_INVALID.md +23 -0
  117. package/dist/reference/errors/MOSTRA_MANIFEST_NOT_LITERAL.md +23 -0
  118. package/dist/reference/errors/MOSTRA_MANIFEST_UNKNOWN_KEY.md +23 -0
  119. package/dist/reference/errors/MOSTRA_NETWORK_EXTERNAL_FAILED.md +23 -0
  120. package/dist/reference/errors/MOSTRA_NETWORK_REQUEST_FAILED.md +23 -0
  121. package/dist/reference/errors/MOSTRA_PLATFORM_UNSUPPORTED.md +23 -0
  122. package/dist/reference/errors/MOSTRA_PUBLISH_ID_CONFLICT.md +23 -0
  123. package/dist/reference/errors/MOSTRA_PUBLISH_SOURCE_CHANGED.md +23 -0
  124. package/dist/reference/errors/MOSTRA_PUBLISH_VERIFY_FAILED.md +23 -0
  125. package/dist/reference/errors/MOSTRA_REGRESSION_ACTION_REMOVED.md +23 -0
  126. package/dist/reference/errors/MOSTRA_REGRESSION_ARIA.md +23 -0
  127. package/dist/reference/errors/MOSTRA_REGRESSION_FIELD_REMOVED.md +23 -0
  128. package/dist/reference/errors/MOSTRA_REGRESSION_LIVE_REMOVED.md +23 -0
  129. package/dist/reference/errors/MOSTRA_REGRESSION_PAGE_REMOVED.md +23 -0
  130. package/dist/reference/errors/MOSTRA_REGRESSION_PIXELS.md +23 -0
  131. package/dist/reference/errors/MOSTRA_REMOTE_CONFIG_INVALID.md +23 -0
  132. package/dist/reference/errors/MOSTRA_REMOTE_HOME_MOVING.md +23 -0
  133. package/dist/reference/errors/MOSTRA_REMOTE_HOME_SUSPENDED.md +23 -0
  134. package/dist/reference/errors/MOSTRA_REMOTE_LIMIT_REACHED.md +23 -0
  135. package/dist/reference/errors/MOSTRA_REMOTE_LOGIN_FAILED.md +23 -0
  136. package/dist/reference/errors/MOSTRA_REMOTE_NOT_OWNER_INSTANCE.md +23 -0
  137. package/dist/reference/errors/MOSTRA_REMOTE_NO_INSTANCE.md +23 -0
  138. package/dist/reference/errors/MOSTRA_REMOTE_OPERATOR_UNAVAILABLE.md +23 -0
  139. package/dist/reference/errors/MOSTRA_REMOTE_OWNER_OFFLINE.md +23 -0
  140. package/dist/reference/errors/MOSTRA_REMOTE_PAUSED_BY_OPERATOR.md +23 -0
  141. package/dist/reference/errors/MOSTRA_REMOTE_QUEUE_FULL.md +23 -0
  142. package/dist/reference/errors/MOSTRA_REMOTE_RATE_LIMITED.md +23 -0
  143. package/dist/reference/errors/MOSTRA_REMOTE_SIGN_IN_REQUIRED.md +23 -0
  144. package/dist/reference/errors/MOSTRA_REMOTE_UNDER_REVIEW.md +23 -0
  145. package/dist/reference/errors/MOSTRA_REMOTE_UNREACHABLE.md +23 -0
  146. package/dist/reference/errors/MOSTRA_RUNTIME_BLANK.md +23 -0
  147. package/dist/reference/errors/MOSTRA_RUNTIME_NOT_READY.md +23 -0
  148. package/dist/reference/errors/MOSTRA_RUNTIME_PAGE_ERROR.md +23 -0
  149. package/dist/reference/errors/MOSTRA_RUNTIME_WORKER_CRASHED.md +23 -0
  150. package/dist/reference/errors/MOSTRA_RUNTIME_WORKER_PARKED.md +23 -0
  151. package/dist/reference/errors/MOSTRA_SECRET_MISSING.md +23 -0
  152. package/dist/reference/errors/MOSTRA_SHARE_NOT_ENABLED.md +23 -0
  153. package/dist/reference/errors/MOSTRA_SHARE_NOT_FOUND.md +23 -0
  154. package/dist/reference/errors/MOSTRA_SHARE_PORTS_EXHAUSTED.md +23 -0
  155. package/dist/reference/errors/MOSTRA_SHARE_TOOL_MISSING.md +23 -0
  156. package/dist/reference/errors/MOSTRA_SHARE_TOOL_NOT_READY.md +23 -0
  157. package/dist/reference/errors/MOSTRA_SHARE_TTL_INVALID.md +23 -0
  158. package/dist/reference/errors/MOSTRA_SHARE_TUNNEL_FAILED.md +23 -0
  159. package/dist/reference/errors/MOSTRA_SMOKE_BUDGET.md +23 -0
  160. package/dist/reference/errors/MOSTRA_SMOKE_NO_EFFECT.md +23 -0
  161. package/dist/reference/errors/MOSTRA_SUBMIT_ALREADY.md +23 -0
  162. package/dist/reference/errors/MOSTRA_SUBMIT_BLOCKED.md +23 -0
  163. package/dist/reference/errors/MOSTRA_SUBMIT_CHANNEL_DENIED.md +23 -0
  164. package/dist/reference/errors/MOSTRA_SUBMIT_NOT_FOUND.md +23 -0
  165. package/dist/reference/errors/MOSTRA_SUBMIT_PAUSED.md +23 -0
  166. package/dist/reference/errors/MOSTRA_SUBMIT_POLICY_NONE.md +23 -0
  167. package/dist/reference/errors/MOSTRA_SUBMIT_REVISION_MOVED.md +23 -0
  168. package/dist/reference/errors/MOSTRA_SUBMIT_SIGNAL_INVALID.md +23 -0
  169. package/dist/reference/errors/MOSTRA_SUBMIT_VIEW_INVALID.md +23 -0
  170. package/dist/reference/errors/MOSTRA_TARGET_UNAVAILABLE.md +23 -0
  171. package/dist/reference/errors/MOSTRA_TYPE_ERROR.md +23 -0
  172. package/dist/reference/errors/MOSTRA_TYPE_UNTYPED_PACKAGE.md +23 -0
  173. package/dist/reference/errors/MOSTRA_VERIFY_ACTION_SKIPPED.md +23 -0
  174. package/dist/reference/errors/MOSTRA_VERIFY_BASELINE_MISSING.md +23 -0
  175. package/dist/reference/errors/MOSTRA_VERIFY_CRASHED.md +23 -0
  176. package/dist/reference/errors/MOSTRA_VERIFY_LIVE_FAILED.md +23 -0
  177. package/dist/reference/errors/MOSTRA_VERIFY_NO_BASELINE.md +23 -0
  178. package/dist/reference/errors/MOSTRA_VERIFY_SECRET_MISSING.md +23 -0
  179. package/dist/reference/errors/MOSTRA_VERIFY_SKIP_CONSEQUENCE.md +23 -0
  180. package/dist/reference/errors/MOSTRA_VERIFY_TIMEOUT.md +23 -0
  181. package/dist/reference/self-hosting.md +130 -0
  182. package/dist/reference/telemetry.md +84 -0
  183. package/dist/skill/SKILL.md +122 -0
  184. package/dist/skill/assets/examples/dashboard/index.tsx +161 -0
  185. package/dist/skill/assets/examples/dashboard/live.ts +25 -0
  186. package/dist/skill/assets/examples/dashboard/styles.css +125 -0
  187. package/dist/skill/assets/examples/decision/index.tsx +95 -0
  188. package/dist/skill/assets/examples/decision/styles.css +125 -0
  189. package/dist/skill/assets/examples/inbox/actions.ts +23 -0
  190. package/dist/skill/assets/examples/inbox/index.tsx +109 -0
  191. package/dist/skill/assets/examples/inbox/styles.css +125 -0
  192. package/dist/skill/assets/studio.css +125 -0
  193. package/dist/skill/references/answers.md +217 -0
  194. package/dist/skill/references/design.md +154 -0
  195. package/dist/skill/references/libraries.md +167 -0
  196. package/dist/skill/references/long-lived.md +148 -0
  197. package/dist/skill/references/mcp.md +68 -0
  198. package/dist/skill/references/page.md +131 -0
  199. package/dist/skill/references/server.md +146 -0
  200. package/dist/skill/references/sharing.md +123 -0
  201. package/dist/skill/references/verify.md +71 -0
  202. package/package.json +10 -5
  203. package/src/gateway/actions.ts +20 -0
  204. package/src/gateway/browser.ts +44 -0
  205. package/src/gateway/capabilities.ts +8 -0
  206. package/src/gateway/http.ts +12 -1
  207. package/src/gateway/index.ts +170 -5
  208. package/src/gateway/listener.ts +31 -6
  209. package/src/gateway/routes.ts +8 -0
  210. package/src/gc/index.ts +5 -0
  211. package/src/instance/index.ts +20 -1
  212. package/src/interaction/index.ts +60 -0
  213. package/src/interaction/pause.ts +106 -0
  214. package/src/interaction/submissions.ts +42 -1
  215. package/src/interaction/viewers.ts +34 -1
  216. package/src/ledger/index.ts +20 -1
  217. package/src/ledger/migrations.ts +51 -0
  218. package/src/link/author.ts +215 -0
  219. package/src/link/hosted.ts +37 -1
  220. package/src/link/http.ts +6 -1
  221. package/src/link/index.ts +3 -1
  222. package/src/link/manager.ts +138 -34
  223. package/src/protocol-server/client.ts +53 -0
  224. package/src/protocol-server/index.ts +1 -1
  225. package/src/server/api.ts +514 -72
  226. package/src/server/auth.ts +600 -74
  227. package/src/server/authorize.ts +816 -0
  228. package/src/server/clients.ts +235 -0
  229. package/src/server/config.ts +7 -0
  230. package/src/server/data.ts +59 -1
  231. package/src/server/directory.ts +69 -0
  232. package/src/server/feed.ts +191 -0
  233. package/src/server/handle.ts +172 -0
  234. package/src/server/hosted-pages.ts +532 -0
  235. package/src/server/hosted.ts +519 -18
  236. package/src/server/index.ts +343 -61
  237. package/src/server/mcp.ts +330 -0
  238. package/src/server/metering.ts +156 -0
  239. package/src/server/oauth-clients.ts +510 -0
  240. package/src/server/operator.ts +498 -0
  241. package/src/server/providers.ts +284 -0
  242. package/src/server/remove.ts +148 -0
  243. package/src/server/routing.ts +275 -0
  244. package/src/verify/runner.ts +23 -2
  245. package/dist/instance-FExcyENK.js.map +0 -1
@@ -2,9 +2,9 @@ import { C as STAGING_FILES, S as LIVE_DECLARATION, _ as DEV_METHOD, a as nameKe
2
2
  import { a as pathsOf, c as currentUserSid, d as runtimeRoot$1, f as serviceLauncherPath, i as ownedDirectory, l as helperPath, n as WINDOWS, o as runtimeDirFor, p as stopServiceLauncher, r as defaultHome, s as socketPathLimit, t as OS, u as runHelperAsync } from "./directories-BLJjeSPD.js";
3
3
  import { builtinModules, createRequire } from "node:module";
4
4
  import { accessSync, appendFileSync, chmodSync, closeSync, constants, createReadStream, createWriteStream, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync, writeSync } from "node:fs";
5
- import { basename, delimiter, dirname, extname, join, relative, resolve, sep, win32 } from "node:path";
5
+ import { basename, delimiter, dirname, extname, isAbsolute, join, relative, resolve, sep, win32 } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
- import { ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, ArtifactId, ArtifactManifest, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, CLI_CLIENT_NAME, CallRequest, ChooseRequest, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DeliveryId, EVENTS_NOTIFY, EnterRequest, FRAME_SESSION_HEADER, FieldsRequest, FollowRequest, HOST_PROTOCOL_REVISIONS, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, LiveRequest, MAX_LINE_LENGTH, MutationId, PUBLIC_SHARE_DEFAULT_TTL, PUBLIC_SHARE_MAX_TTL_MS, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RpcError, RpcPeer, RunAttachRequest, RunCancelRequest, RunId, RunRequest, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SHELL_SESSION_HEADER, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, ServerEmitParams, ServerLiveValueParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, ShareId, ShellSubmitRequest, SignalRequest, StreamTicketRequest, SubmissionEnvelope, SubmissionId, SubmissionPolicy, SubmitRequest, TALLY_LIVE_PREFIX, TokenId, VERIFY_RUNNER_METHODS, VerifyVerdict, VersionId, ViewId, ViewerId, WORKER_METHODS, WorkerBatchParams, WorkerCallOutcome, WorkerPingResult, WorkerStartResult, ariaSummary, artifactCreateMethod, artifactExportMethod, artifactGetMethod, artifactImportMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, canonicalJson, checkArgumentFrames, checkRequest, createDiagnostic, depsAddMethod, devStartMethod, devStopMethod, durationMs, encodeLine, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fromBase64, gcRunMethod, hostedPushMethod, hostedSubmissionMethod, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, livePushMethod, manifestProblem, mostraInitializeMethod, mostraShutdownMethod, negotiateRevision, normalizeScopes, parseParams, portAddressingExternalBaseMethod, portDraftsMirrorMethod, portIdentityResolveMethod, portRelayCallMethod, portRelayCancelMethod, portRelayLiveMethod, portRelayReconcileMethod, portRelayRunMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, refusal, relayCallBatchMethod, relayEffectMethod, relayLiveValueMethod, relayRunUpdateMethod, remoteLoginMethod, remoteLoginWaitMethod, remoteLogoutMethod, remoteStatusMethod, remoteTokenMethod, resultsGetMethod, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretListMethod, secretSetMethod, serializeAll, shareListMethod, shareStartMethod, shareStopMethod, stateGetMethod, statePatchMethod, toBase64, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod } from "@mostra/protocol";
7
+ import { ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, ArtifactId, ArtifactManifest, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, CLI_CLIENT_NAME, CallRequest, ChooseRequest, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DeliveryId, EVENTS_NOTIFY, EnterRequest, FRAME_SESSION_HEADER, FieldsRequest, FollowRequest, HOST_PROTOCOL_REVISIONS, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, LinkId, LiveRequest, MAX_LINE_LENGTH, MutationId, PUBLIC_SHARE_DEFAULT_TTL, PUBLIC_SHARE_MAX_TTL_MS, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RpcError, RpcPeer, RunAttachRequest, RunCancelRequest, RunId, RunRequest, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SHELL_SESSION_HEADER, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, ServerEmitParams, ServerLiveValueParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, ShareId, ShellSubmitRequest, SignalRequest, StreamTicketRequest, SubmissionEnvelope, SubmissionId, SubmissionPolicy, SubmitRequest, TALLY_LIVE_PREFIX, TokenId, VERIFY_RUNNER_METHODS, VerifyVerdict, VersionId, ViewId, ViewerId, WORKER_METHODS, WorkerBatchParams, WorkerCallOutcome, WorkerPingResult, WorkerStartResult, ariaSummary, artifactCreateMethod, artifactExportMethod, artifactGetMethod, artifactImportMethod, artifactListMethod, artifactPauseMethod, artifactPublishMethod, artifactVerifyMethod, canonicalJson, checkArgumentFrames, checkRequest, createDiagnostic, depsAddMethod, devStartMethod, devStopMethod, durationMs, encodeLine, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fromBase64, gcRunMethod, hostedPushMethod, hostedSubmissionMethod, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, livePushMethod, manifestProblem, mostraInitializeMethod, mostraShutdownMethod, negotiateRevision, normalizeScopes, parseParams, portAddressingExternalBaseMethod, portDraftsMirrorMethod, portIdentityResolveMethod, portRelayAuthorMethod, portRelayCallMethod, portRelayCancelMethod, portRelayLiveMethod, portRelayReconcileMethod, portRelayRunMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, refusal, relayCallBatchMethod, relayEffectMethod, relayLiveValueMethod, relayRunUpdateMethod, remoteLinkMethod, remoteLoginMethod, remoteLoginWaitMethod, remoteLogoutMethod, remoteStatusMethod, remoteTokenMethod, resultsGetMethod, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretListMethod, secretSetMethod, serializeAll, shareListMethod, shareStartMethod, shareStopMethod, stateGetMethod, statePatchMethod, toBase64, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod } from "@mostra/protocol";
8
8
  import { createHash, createHmac, randomBytes, randomInt, randomUUID } from "node:crypto";
9
9
  import { connect, createConnection, createServer, isIP } from "node:net";
10
10
  import { execFile, execFileSync, spawn } from "node:child_process";
@@ -22,6 +22,7 @@ import { getRequestListener } from "@hono/node-server";
22
22
  import { Hono } from "hono";
23
23
  import ignore from "ignore";
24
24
  import { AsyncLocalStorage } from "node:async_hooks";
25
+ import { defaultWorkspaceRoot, localWorkspace } from "@mostra/mcp";
25
26
  import { WebSocket } from "ws";
26
27
  import { request as request$1 } from "node:https";
27
28
  import { Resolver } from "node:dns/promises";
@@ -2851,6 +2852,50 @@ const MIGRATIONS = [
2851
2852
  ALTER TABLE submission ADD COLUMN origin_json TEXT;
2852
2853
  ALTER TABLE event ADD COLUMN origin_json TEXT;
2853
2854
  CREATE UNIQUE INDEX event_origin ON event (origin_json) WHERE origin_json IS NOT NULL;
2855
+ `);
2856
+ }
2857
+ },
2858
+ {
2859
+ version: 14,
2860
+ name: "pause, quarantine and the operator's cursor",
2861
+ up(db) {
2862
+ db.exec(`
2863
+ CREATE TABLE artifact_pause (
2864
+ artifact_id TEXT PRIMARY KEY REFERENCES artifact(id),
2865
+ by TEXT NOT NULL CHECK (by IN ('owner', 'operator')),
2866
+ reason TEXT,
2867
+ paused_at TEXT NOT NULL
2868
+ );
2869
+ CREATE TABLE quarantine (
2870
+ artifact_id TEXT NOT NULL REFERENCES artifact(id),
2871
+ version_id TEXT NOT NULL DEFAULT '',
2872
+ reason TEXT NOT NULL,
2873
+ at TEXT NOT NULL,
2874
+ PRIMARY KEY (artifact_id, version_id)
2875
+ );
2876
+ CREATE TABLE operator_cursor (
2877
+ id INTEGER PRIMARY KEY CHECK (id = 1),
2878
+ cursor INTEGER NOT NULL CHECK (cursor >= 0)
2879
+ );
2880
+ `);
2881
+ }
2882
+ },
2883
+ {
2884
+ version: 15,
2885
+ name: "an owner's pause and an operator's, apart",
2886
+ up(db) {
2887
+ db.exec(`
2888
+ CREATE TABLE artifact_pause_by (
2889
+ artifact_id TEXT NOT NULL REFERENCES artifact(id),
2890
+ by TEXT NOT NULL CHECK (by IN ('owner', 'operator')),
2891
+ reason TEXT,
2892
+ paused_at TEXT NOT NULL,
2893
+ PRIMARY KEY (artifact_id, by)
2894
+ );
2895
+ INSERT INTO artifact_pause_by (artifact_id, by, reason, paused_at)
2896
+ SELECT artifact_id, by, reason, paused_at FROM artifact_pause;
2897
+ DROP TABLE artifact_pause;
2898
+ ALTER TABLE artifact_pause_by RENAME TO artifact_pause;
2854
2899
  `);
2855
2900
  }
2856
2901
  }
@@ -3199,6 +3244,14 @@ function wrap(db, file, schemaVersion, migrated) {
3199
3244
  } catch {}
3200
3245
  return result;
3201
3246
  },
3247
+ removal(fn) {
3248
+ assertInPlace();
3249
+ const result = guarded(() => db.transaction(() => fn(target)).immediate());
3250
+ for (const listener of listeners) try {
3251
+ listener();
3252
+ } catch {}
3253
+ return result;
3254
+ },
3202
3255
  onCommit(listener) {
3203
3256
  listeners.add(listener);
3204
3257
  return () => listeners.delete(listener);
@@ -5207,6 +5260,52 @@ async function attach(path, client, timeoutMs = 5e3) {
5207
5260
  throw error;
5208
5261
  }
5209
5262
  }
5263
+ /**
5264
+ * Opens a session with a protocol server in this process, over a pair of in-memory streams, so a
5265
+ * part of the runtime acts as a client exactly as any host does (invariant 11): the same framing,
5266
+ * initialize, validation and session rules. `attributes` are the session's, as a transport sets
5267
+ * them (a remote MCP request's account and home). The caller closes the returned client.
5268
+ */
5269
+ async function attachInProcess(server, client, attributes = {}, timeoutMs = 5e3) {
5270
+ const toServer = new PassThrough();
5271
+ const toClient = new PassThrough();
5272
+ const peer = new RpcPeer({ send: (message) => void writeLine(toServer, message) });
5273
+ let markClosed = () => {};
5274
+ const closed = new Promise((done) => {
5275
+ markClosed = done;
5276
+ });
5277
+ server.serve("stdio", toServer, toClient, void 0, attributes);
5278
+ pump({
5279
+ input: toClient,
5280
+ output: toServer
5281
+ }, () => peer, () => {
5282
+ peer.close();
5283
+ markClosed();
5284
+ });
5285
+ const connection = {
5286
+ peer,
5287
+ closed,
5288
+ close: () => {
5289
+ peer.close();
5290
+ toServer.end();
5291
+ toClient.end();
5292
+ }
5293
+ };
5294
+ try {
5295
+ return {
5296
+ client: connection,
5297
+ result: await peer.call(mostraInitializeMethod, {
5298
+ client,
5299
+ revisions: [...HOST_PROTOCOL_REVISIONS],
5300
+ capabilities: {},
5301
+ ports: []
5302
+ }, { timeoutMs })
5303
+ };
5304
+ } catch (error) {
5305
+ connection.close();
5306
+ throw error;
5307
+ }
5308
+ }
5210
5309
  //#endregion
5211
5310
  //#region src/protocol-server/websocket.ts
5212
5311
  /**
@@ -5968,7 +6067,9 @@ function viewerOf(row) {
5968
6067
  id: row.id,
5969
6068
  kind: row.kind,
5970
6069
  ...row.name !== null ? { name: row.name } : {},
5971
- ...row.kind === "token" || row.kind === "host" || row.kind === "tailnet" ? { ref: row.external_ref } : {}
6070
+ ...row.kind === "token" || row.kind === "host" || row.kind === "tailnet" ? { ref: row.external_ref } : {},
6071
+ ...row.kind === "account" ? { verified: true } : {},
6072
+ ...row.kind === "anonymous" ? { verified: false } : {}
5972
6073
  };
5973
6074
  }
5974
6075
  /** The home's local user (created on first use): who every session acts as without a viewer. */
@@ -6011,6 +6112,29 @@ function viewerForLink(db, tokenId, name) {
6011
6112
  name
6012
6113
  });
6013
6114
  }
6115
+ /**
6116
+ * A signed-in person on a hosted link minted without a viewer (D165 item 8): one viewer of kind
6117
+ * `account` per account, named as its identity provider verified it.
6118
+ */
6119
+ function viewerForAccount(db, accountId, name) {
6120
+ return viewerByRef(db, "account", {
6121
+ ref: accountId,
6122
+ ...name !== void 0 ? { name } : {}
6123
+ });
6124
+ }
6125
+ /**
6126
+ * A person who isn't signed in on a hosted link minted without a viewer (D165 item 8): one viewer
6127
+ * of kind `anonymous` per browser and route, by the route's derived key
6128
+ * (`HMAC-SHA-256(browser secret, routeId)`), never the shell's raw secret. A name they choose is
6129
+ * set apart, unverified ({@link nameAnonymous}).
6130
+ */
6131
+ function viewerForAnonymous(db, key) {
6132
+ return viewerByRef(db, "anonymous", { ref: key });
6133
+ }
6134
+ /** Sets the self-chosen, unverified name of an anonymous viewer; any other viewer is left alone. */
6135
+ function nameAnonymous(db, viewerId, name) {
6136
+ return db.run("UPDATE viewer SET name = ? WHERE id = ? AND kind = 'anonymous'", name, viewerId).changes > 0;
6137
+ }
6014
6138
  function viewerByRef(db, kind, spec) {
6015
6139
  const found = db.get("SELECT * FROM viewer WHERE kind = ? AND external_ref = ?", kind, spec.ref);
6016
6140
  if (found) {
@@ -6171,6 +6295,21 @@ function orphansOf(rows) {
6171
6295
  * `MOSTRA_SUBMIT_POLICY_NONE`, `MOSTRA_SUBMIT_ALREADY` (a {@link SubmitConflict}) under `once`,
6172
6296
  * `MOSTRA_SUBMIT_REVISION_MOVED` when the draft changed since the viewer saw it.
6173
6297
  */
6298
+ /**
6299
+ * Whether a submit would be judged afresh: not a repeat of one already recorded (which answers that
6300
+ * submission), not refused by the view or a pause before anything is recorded. Only such a submit
6301
+ * is admitted by the server's rates and the operator's limits (Fable review of WP-30, 8).
6302
+ */
6303
+ function wouldRecord(db, input) {
6304
+ try {
6305
+ const view = viewFor(db, input.viewId, input.artifactId, input.viewerId, input.tokenId);
6306
+ const draft = documentFor(db, input.artifactId, input.viewerId, false);
6307
+ if (draft !== void 0 && db.get("SELECT 1 FROM submission WHERE view_id = ? AND draft_document_id = ? AND draft_revision = ?", view.id, draft.id, input.expectedRevision)) return false;
6308
+ return !db.get("SELECT 1 FROM artifact_pause WHERE artifact_id = ?", input.artifactId);
6309
+ } catch {
6310
+ return false;
6311
+ }
6312
+ }
6174
6313
  function submit(db, input) {
6175
6314
  const view = viewFor(db, input.viewId, input.artifactId, input.viewerId, input.tokenId);
6176
6315
  assertChannel(view, input.channel);
@@ -6183,6 +6322,8 @@ function submit(db, input) {
6183
6322
  },
6184
6323
  created: false
6185
6324
  };
6325
+ const paused = db.get("SELECT by FROM artifact_pause WHERE artifact_id = ? ORDER BY by = 'operator' DESC LIMIT 1", input.artifactId);
6326
+ if (paused) throw new RpcError(createDiagnostic("MOSTRA_SUBMIT_PAUSED", { message: `This page is paused${paused.by === "operator" ? " by its server's operator" : ""}: it takes no answers until it is resumed, and the draft is kept.` }));
6186
6327
  const artifact = db.get("SELECT policy_json, latest_version_id FROM artifact WHERE id = ?", input.artifactId);
6187
6328
  if (!artifact) throw new Error(`No artifact ${input.artifactId}.`);
6188
6329
  const policy = storedPolicy(artifact.policy_json);
@@ -7018,6 +7159,83 @@ function outcomeOf(answer) {
7018
7159
  };
7019
7160
  }
7020
7161
  //#endregion
7162
+ //#region src/interaction/pause.ts
7163
+ /**
7164
+ * Pausing an artifact (D165 item 14, RM-09): a paused artifact stays viewable and its shell says
7165
+ * so; it takes no submissions (the submit transaction refuses them) and runs no actions until it
7166
+ * is resumed, and every draft is kept. The owner pauses and resumes its own pause; an operator's
7167
+ * pause is resumed only by the operator. One row per party that paused it (`artifact_pause`,
7168
+ * DATA_MODEL §7.2), in local and hosted homes alike; each change appends `artifact.paused` or
7169
+ * `artifact.resumed`, so open pages learn of it.
7170
+ */
7171
+ /**
7172
+ * The artifact's pause, or `undefined` when it isn't paused: the operator's when both paused it,
7173
+ * since only the operator lifts that one.
7174
+ */
7175
+ function pauseOf(db, artifactId) {
7176
+ const row = db.get("SELECT by, reason, paused_at FROM artifact_pause WHERE artifact_id = ? ORDER BY by = 'operator' DESC LIMIT 1", artifactId);
7177
+ return row ? {
7178
+ by: row.by,
7179
+ ...row.reason !== null ? { reason: row.reason } : {},
7180
+ at: row.paused_at
7181
+ } : void 0;
7182
+ }
7183
+ /**
7184
+ * Pauses or resumes an artifact, in the caller's write transaction, as `by`. The owner's pause and
7185
+ * the operator's are kept apart (one row each): pausing again keeps the earlier pause of the same
7186
+ * party, and a resume lifts only its own party's, so the artifact takes answers again once no
7187
+ * pause is left. The owner resuming while the operator's pause stands is
7188
+ * `MOSTRA_REMOTE_PAUSED_BY_OPERATOR`, and changes nothing.
7189
+ */
7190
+ function setPause(db, artifactId, change) {
7191
+ const own = db.get("SELECT by FROM artifact_pause WHERE artifact_id = ? AND by = ?", artifactId, change.by);
7192
+ const actor = change.by === "operator" ? { kind: "mostra" } : { kind: "agent" };
7193
+ if (change.paused) {
7194
+ if (!own) {
7195
+ const before = pauseOf(db, artifactId);
7196
+ db.run("INSERT INTO artifact_pause (artifact_id, by, reason, paused_at) VALUES (?, ?, ?, ?)", artifactId, change.by, change.reason ?? null, (/* @__PURE__ */ new Date()).toISOString());
7197
+ if (before === void 0 || change.by === "operator") appendEvent(db, {
7198
+ artifactId,
7199
+ type: "artifact.paused",
7200
+ actor,
7201
+ payload: {
7202
+ by: change.by,
7203
+ ...change.reason !== void 0 ? { reason: change.reason } : {}
7204
+ }
7205
+ });
7206
+ }
7207
+ return {
7208
+ paused: true,
7209
+ by: pauseOf(db, artifactId).by
7210
+ };
7211
+ }
7212
+ if (change.by === "owner" && pauseOf(db, artifactId)?.by === "operator") throw new RpcError(createDiagnostic("MOSTRA_REMOTE_PAUSED_BY_OPERATOR", { message: "The server's operator paused this artifact; only the operator resumes it." }));
7213
+ if (own) db.run("DELETE FROM artifact_pause WHERE artifact_id = ? AND by = ?", artifactId, change.by);
7214
+ const left = pauseOf(db, artifactId);
7215
+ if (left === void 0) {
7216
+ if (own) appendEvent(db, {
7217
+ artifactId,
7218
+ type: "artifact.resumed",
7219
+ actor,
7220
+ payload: { by: change.by }
7221
+ });
7222
+ return { paused: false };
7223
+ }
7224
+ if (own) appendEvent(db, {
7225
+ artifactId,
7226
+ type: "artifact.paused",
7227
+ actor: { kind: "agent" },
7228
+ payload: {
7229
+ by: left.by,
7230
+ ...left.reason !== void 0 ? { reason: left.reason } : {}
7231
+ }
7232
+ });
7233
+ return {
7234
+ paused: true,
7235
+ by: left.by
7236
+ };
7237
+ }
7238
+ //#endregion
7021
7239
  //#region src/interaction/runs.ts
7022
7240
  /**
7023
7241
  * Action runs in the ledger (D24, D54, AC-02, AC-03; ARCHITECTURE §7): each invocation through
@@ -7859,6 +8077,11 @@ function createInteraction(options) {
7859
8077
  viewerForHost: (spec) => ledger.write((db) => viewerForHost(db, spec)),
7860
8078
  viewerForTailnet: (spec) => ledger.write((db) => viewerForTailnet(db, spec)),
7861
8079
  viewerForLink: (tokenId, name) => ledger.write((db) => viewerForLink(db, tokenId, name)),
8080
+ viewerForAccount: (accountId, name) => ledger.write((db) => viewerForAccount(db, accountId, name)),
8081
+ viewerForAnonymous: (key) => ledger.write((db) => viewerForAnonymous(db, key)),
8082
+ nameAnonymous: (viewerId, name) => ledger.write((db) => nameAnonymous(db, viewerId, name)),
8083
+ pause: (artifactId, change) => ledger.write((db) => setPause(db, artifactId, change)),
8084
+ pauseOf: (artifactId) => ledger.read((db) => pauseOf(db, artifactId)),
7862
8085
  openView(input) {
7863
8086
  return ledger.write((db) => openView(db, input));
7864
8087
  },
@@ -7920,6 +8143,12 @@ function createInteraction(options) {
7920
8143
  });
7921
8144
  return answer;
7922
8145
  },
8146
+ resultsOf(submissionId) {
8147
+ return ledger.read((db) => {
8148
+ const submission = db.get("SELECT * FROM submission WHERE id = ?", submissionId);
8149
+ return submission ? buildResults(db, submission) : void 0;
8150
+ });
8151
+ },
7923
8152
  envelopeFor(submissionId, owner) {
7924
8153
  return ledger.read((db) => {
7925
8154
  const delivery = db.get("SELECT id, attempts FROM delivery WHERE submission_id = ? AND port_owner = ?", submissionId, owner);
@@ -7937,6 +8166,15 @@ function createInteraction(options) {
7937
8166
  };
7938
8167
  });
7939
8168
  },
8169
+ wouldRecord(page, input) {
8170
+ return ledger.read((db) => wouldRecord(db, {
8171
+ artifactId: page.artifactId,
8172
+ viewerId: page.viewerId,
8173
+ ...page.tokenId !== void 0 ? { tokenId: page.tokenId } : {},
8174
+ viewId: input.viewId,
8175
+ expectedRevision: input.expectedRevision
8176
+ }));
8177
+ },
7940
8178
  submit(page, input) {
7941
8179
  const owners = options.deliveryOwners?.(page.artifactId) ?? outbox.owners();
7942
8180
  const outcome = asPage(() => ledger.write((db) => submit(db, {
@@ -8811,12 +9049,14 @@ function documentHeaders(listener, frameOrigins) {
8811
9049
  "frame-ancestors 'none'",
8812
9050
  "base-uri 'none'",
8813
9051
  "form-action 'none'",
8814
- "object-src 'none'"
9052
+ "object-src 'none'",
9053
+ "require-trusted-types-for 'script'",
9054
+ "trusted-types 'none'"
8815
9055
  ].join("; "),
8816
9056
  "x-frame-options": "DENY",
8817
9057
  "cross-origin-opener-policy": "same-origin"
8818
9058
  };
8819
- return { "content-security-policy": `frame-ancestors ${listener.shellOrigin}` };
9059
+ return { "content-security-policy": `frame-ancestors ${listener.frameAncestors ?? listener.shellOrigin}` };
8820
9060
  }
8821
9061
  /** Every header of a request as `[name, value]` pairs, repeats kept. */
8822
9062
  function headerPairs(incoming) {
@@ -9015,6 +9255,15 @@ function actionRoutes(options) {
9015
9255
  };
9016
9256
  };
9017
9257
  const may = (page, fnId) => scopeAllows(page.scopes ?? [], `action:${fnId}`);
9258
+ /**
9259
+ * A paused artifact runs no actions (D165 item 14): a call or a new run is refused before
9260
+ * anything is recorded, started or relayed to the owner.
9261
+ */
9262
+ const paused = (page) => {
9263
+ const pause = interaction.pauseOf(page.artifactId);
9264
+ if (!pause) return void 0;
9265
+ return answer$1(createDiagnostic("MOSTRA_ACTION_PAUSED", { message: `This page is paused${pause.by === "operator" ? " by its server's operator" : ""}: its actions don't run until it is resumed.` }), 423);
9266
+ };
9018
9267
  return {
9019
9268
  async call(context) {
9020
9269
  const refused = served(context);
@@ -9024,6 +9273,8 @@ function actionRoutes(options) {
9024
9273
  if (request instanceof Response) return request;
9025
9274
  const page = pageOf(context);
9026
9275
  if (!may(page, fnId)) return denied(fnId);
9276
+ const pausedNow = paused(page);
9277
+ if (pausedNow) return pausedNow;
9027
9278
  let lines;
9028
9279
  const abort = new AbortController();
9029
9280
  context.request.signal.addEventListener("abort", () => abort.abort(), { once: true });
@@ -9071,6 +9322,8 @@ function actionRoutes(options) {
9071
9322
  if (request instanceof Response) return request;
9072
9323
  const page = pageOf(context);
9073
9324
  if (!may(page, request.fnId)) return denied(request.fnId);
9325
+ const pausedNow = paused(page);
9326
+ if (pausedNow) return pausedNow;
9074
9327
  try {
9075
9328
  return jsonResponse(actions.startRun(page, {
9076
9329
  viewId: request.viewId,
@@ -9159,7 +9412,8 @@ const STATUS = {
9159
9412
  MOSTRA_HOST_CURSOR_COMPACTED: 410,
9160
9413
  MOSTRA_HOME_DISK_FULL: 507,
9161
9414
  MOSTRA_HOME_GONE: 503,
9162
- MOSTRA_HYGIENE_SCOPE_DENIED: 403
9415
+ MOSTRA_HYGIENE_SCOPE_DENIED: 403,
9416
+ MOSTRA_SUBMIT_PAUSED: 423
9163
9417
  };
9164
9418
  /** A refusal or a diagnostic as the browser gets it. */
9165
9419
  function answer(diagnostic, status, extra = {}) {
@@ -9224,6 +9478,21 @@ function browserRoutes(options) {
9224
9478
  scopes: session.grant.scopes
9225
9479
  };
9226
9480
  };
9481
+ /** The answer to a submit the server's rules refused before it reached the ledger. */
9482
+ const admit = async (context, request) => {
9483
+ if (!options.admitSubmit) return void 0;
9484
+ const page = pageOf(context);
9485
+ if (!interaction.wouldRecord(page, {
9486
+ viewId: request.viewId,
9487
+ expectedRevision: Number(request.expectedRevision)
9488
+ })) return;
9489
+ const refused = await options.admitSubmit(page, context);
9490
+ if (!refused) return void 0;
9491
+ return jsonResponse(refused.diagnostic, {
9492
+ status: refused.status,
9493
+ ...refused.retryAfter !== void 0 ? { headers: { "retry-after": String(refused.retryAfter) } } : {}
9494
+ });
9495
+ };
9227
9496
  /** The view a stream or poll is for, checked against the page (D104). */
9228
9497
  const viewOf = (context, page) => {
9229
9498
  const view = new URL(context.request.url).searchParams.get("view");
@@ -9260,6 +9529,8 @@ function browserRoutes(options) {
9260
9529
  if (refused) return refused;
9261
9530
  const request = await body(context, SubmitRequest);
9262
9531
  if (request instanceof Response) return request;
9532
+ const admitted = await admit(context, request);
9533
+ if (admitted) return admitted;
9263
9534
  try {
9264
9535
  return jsonResponse(interaction.submit(pageOf(context), {
9265
9536
  viewId: request.viewId,
@@ -9508,6 +9779,8 @@ function browserRoutes(options) {
9508
9779
  if (refused) return refused;
9509
9780
  const request = await body(context, ShellSubmitRequest);
9510
9781
  if (request instanceof Response) return request;
9782
+ const admitted = await admit(context, request);
9783
+ if (admitted) return admitted;
9511
9784
  const page = pageOf(context);
9512
9785
  let submission;
9513
9786
  try {
@@ -9718,6 +9991,7 @@ var Capabilities = class {
9718
9991
  #now;
9719
9992
  #shellOrigin;
9720
9993
  #servesShell;
9994
+ #onMinted;
9721
9995
  /** Single-use stream and socket tickets (D158 item 5), by the SHA-256 of their secret. */
9722
9996
  #streamTickets = /* @__PURE__ */ new Map();
9723
9997
  #tickets = /* @__PURE__ */ new Map();
@@ -9738,6 +10012,7 @@ var Capabilities = class {
9738
10012
  this.#now = options.now;
9739
10013
  this.#shellOrigin = options.shellOrigin;
9740
10014
  this.#servesShell = options.servesShell ?? ((origin) => origin === this.#shellOrigin());
10015
+ this.#onMinted = options.onMinted;
9741
10016
  }
9742
10017
  /** Runs `fn` in the caller's transaction, or in a new one. */
9743
10018
  #tx(db, fn) {
@@ -9759,6 +10034,10 @@ var Capabilities = class {
9759
10034
  const scopes = normalizeScopes(input.scopes);
9760
10035
  const shellOrigin = input.shellOrigin ?? this.#shellOrigin();
9761
10036
  db.run("INSERT INTO token (id, secret_hash, artifact_id, scopes_json, viewer_id, expires_at, revoked_at, created_at, is_default, pinned_version, shell_origin) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?)", tokenId, hashSecret(secret), input.artifactId, JSON.stringify(scopes), input.viewerId ?? null, input.expiresAt ?? null, this.#iso(this.#now()), input.isDefault ? 1 : 0, input.pinnedVersion ?? null, shellOrigin);
10037
+ this.#onMinted?.({
10038
+ tokenId,
10039
+ artifactId: input.artifactId
10040
+ });
9762
10041
  return {
9763
10042
  tokenId,
9764
10043
  secret,
@@ -10605,7 +10884,8 @@ function mount(app, checks, routes) {
10605
10884
  artifactId,
10606
10885
  ...session ? { session } : {},
10607
10886
  document,
10608
- remote: incoming.socket.remoteAddress
10887
+ remote: incoming.socket.remoteAddress,
10888
+ client: checks.client ? checks.client(incoming) : incoming.socket.remoteAddress
10609
10889
  });
10610
10890
  };
10611
10891
  if (route.method === "GET") app.get(route.path, handle);
@@ -10637,6 +10917,31 @@ const MAX_HEADER_SIZE = 1048576;
10637
10917
  * failed the connect at once with `ERR_NO_BUFFER_SPACE` (#66).
10638
10918
  */
10639
10919
  const KEEP_ALIVE_MS = 305e3;
10920
+ /**
10921
+ * Ends a server's connections when it stops, without leaving them in TIME_WAIT on its side (#132):
10922
+ * a connection the server closes first stays in TIME_WAIT on the server's port for minutes, and
10923
+ * Windows refuses a browser's next connect from a random local port that meets one of them with
10924
+ * `ERR_NO_BUFFER_SPACE`, the more often as a restarted instance listens on the same leased ports
10925
+ * (D99). A reset (`SO_LINGER` 0) leaves nothing behind; whatever a stopping server still had on a
10926
+ * connection was being cut anyway. Answers the function that stops it.
10927
+ */
10928
+ function resetOnClose(server) {
10929
+ const sockets = /* @__PURE__ */ new Set();
10930
+ server.on("connection", (socket) => {
10931
+ sockets.add(socket);
10932
+ socket.once("close", () => sockets.delete(socket));
10933
+ });
10934
+ return () => new Promise((resolve) => {
10935
+ if (!server.listening) return resolve();
10936
+ for (const socket of sockets) {
10937
+ if (socket.destroyed) continue;
10938
+ if (typeof socket.resetAndDestroy === "function" && socket.readyState === "open") socket.resetAndDestroy();
10939
+ else socket.destroy();
10940
+ }
10941
+ server.close(() => resolve());
10942
+ server.closeAllConnections();
10943
+ });
10944
+ }
10640
10945
  /** Writes a refusal straight to a socket, for upgrades and envelope failures before Hono. */
10641
10946
  function writeRaw(socket, refused, extra = {}) {
10642
10947
  const body = extra.html ?? JSON.stringify(refused.diagnostic);
@@ -10828,11 +11133,7 @@ function createListener(options) {
10828
11133
  return {
10829
11134
  server,
10830
11135
  app,
10831
- close: () => new Promise((resolve) => {
10832
- if (!server.listening) return resolve();
10833
- server.close(() => resolve());
10834
- server.closeAllConnections();
10835
- })
11136
+ close: resetOnClose(server)
10836
11137
  };
10837
11138
  }
10838
11139
  //#endregion
@@ -11374,6 +11675,7 @@ function createGateway(options) {
11374
11675
  } : void 0;
11375
11676
  },
11376
11677
  activated: options.activated,
11678
+ ...options.hosted?.admitSubmit ? { admitSubmit: options.hosted.admitSubmit } : {},
11377
11679
  ...options.revisions ? { revisions: options.revisions } : {},
11378
11680
  ...options.bus ? { bus: options.bus } : {}
11379
11681
  });
@@ -11659,6 +11961,7 @@ function createGateway(options) {
11659
11961
  };
11660
11962
  /** Where an artifact's links point: a host's external base when it gives one, else loopback. */
11661
11963
  const linkBase = async (artifactId) => {
11964
+ if (hosted?.linkOrigin) return await hosted.linkOrigin(artifactId) ?? shellOrigin();
11662
11965
  return (await hostFace(artifactId, "shell"))?.origin ?? shellOrigin();
11663
11966
  };
11664
11967
  /** The artifact way a shell way opens frames on, or why there is none. */
@@ -11723,7 +12026,8 @@ function createGateway(options) {
11723
12026
  const own = way().artifactId;
11724
12027
  return id !== void 0 && ArtifactId.is(id) && (own === void 0 || own === id) ? id : void 0;
11725
12028
  },
11726
- streams: () => way().streams()
12029
+ streams: () => way().streams(),
12030
+ ...hosted?.client ? { client: hosted.client } : {}
11727
12031
  });
11728
12032
  const shellMissing = () => jsonResponse(createDiagnostic("MOSTRA_ENV_SHELL_MISSING", { message: "This Mostra runtime has no built shell." }), { status: 503 });
11729
12033
  /** The exchanges each browser made, by artifact (WP-12; see `exchange`). */
@@ -11763,7 +12067,8 @@ function createGateway(options) {
11763
12067
  const found = await artifactWayFor(way, group, context.artifactId).catch(() => void 0);
11764
12068
  frames = found && !isRefusal(found) ? found.way.origin() ?? "'none'" : "'none'";
11765
12069
  }
11766
- const html = readFileSync(join(options.shellDir, "index.html"));
12070
+ const file = readFileSync(join(options.shellDir, "index.html"));
12071
+ const html = way.by === "hosted" ? hostedPreview(file.toString("utf8"), previewTitle(context.artifactId)) : file;
11767
12072
  return new Response(context.request.method === "HEAD" ? null : html, { headers: {
11768
12073
  ...BASE_HEADERS,
11769
12074
  ...documentHeaders(shellKind(way), frames),
@@ -11771,6 +12076,15 @@ function createGateway(options) {
11771
12076
  "cache-control": "no-cache"
11772
12077
  } });
11773
12078
  };
12079
+ /** The title a hosted page's preview may show: its own only when the manifest asks (D161). */
12080
+ const previewTitle = (artifactId) => {
12081
+ try {
12082
+ const detail = artifacts.get({ artifactId });
12083
+ return detail.manifest.hosted?.preview === "title" ? detail.title : void 0;
12084
+ } catch {
12085
+ return;
12086
+ }
12087
+ };
11774
12088
  const shellAsset = async (context) => {
11775
12089
  if (options.shellDir === void 0) return shellMissing();
11776
12090
  const url = new URL(context.request.url);
@@ -11791,8 +12105,9 @@ function createGateway(options) {
11791
12105
  * 2): the home's local user on loopback; over a tunnel the tailnet person Tailscale Serve
11792
12106
  * named, else the link's own viewer, never the home's local user.
11793
12107
  */
11794
- const defaultViewer = (way, context, grant) => {
12108
+ const defaultViewer = (way, context, grant, browser) => {
11795
12109
  if (way.via === "local") return void 0;
12110
+ if (way.by === "hosted" && hosted?.anonymousViewer) return hosted.anonymousViewer(browser);
11796
12111
  if (way.via === "tailnet") {
11797
12112
  const person = tailnetPerson(context.request.headers, context.remote);
11798
12113
  if (person) return interaction.viewerForTailnet(person);
@@ -11855,7 +12170,7 @@ function createGateway(options) {
11855
12170
  });
11856
12171
  return jsonResponse(outcome.diagnostic, { status: 503 });
11857
12172
  }
11858
- viewerId = outcome.kind === "person" ? interaction.viewerForHost(outcome.viewer) : defaultViewer(way, context, grant);
12173
+ viewerId = outcome.kind === "person" ? interaction.viewerForHost(outcome.viewer) : defaultViewer(way, context, grant, typeof body["browser"] === "string" && browser !== void 0 ? body["browser"] : void 0);
11859
12174
  }
11860
12175
  const now = launch ? capabilities.presentLaunch(body["launch"], artifactId, true, origin) : capabilities.presentToken(body["token"], artifactId, origin);
11861
12176
  if (isRefusal(now)) return refuse(checks, now, meta);
@@ -11934,6 +12249,15 @@ function createGateway(options) {
11934
12249
  if (version.collected !== void 0) return jsonResponse(collectedDiagnostic(version.number), { status: 410 });
11935
12250
  const damage = options.dev ? void 0 : await integrity.check(version.id);
11936
12251
  if (damage !== void 0) return damaged(version.number, damage, false, "'none'");
12252
+ if (hosted?.admitView) {
12253
+ const refused = await hosted.admitView({
12254
+ artifactId,
12255
+ versionId: version.id,
12256
+ tokenId: session.grant.tokenId,
12257
+ client: context.client
12258
+ });
12259
+ if (refused) return refuse(checks, refused, meta);
12260
+ }
11937
12261
  const found = await artifactWayFor(way, group, artifactId);
11938
12262
  if (isRefusal(found)) return refuse(checks, found, meta);
11939
12263
  const artifactOrigin = found.way.origin();
@@ -11949,6 +12273,12 @@ function createGateway(options) {
11949
12273
  });
11950
12274
  const controls = await options.controls(detail);
11951
12275
  const viewerId = interaction.viewerOf(session.viewerId);
12276
+ const pause = interaction.pauseOf(artifactId);
12277
+ const chrome = hosted?.chrome ? await hosted.chrome({
12278
+ artifactId,
12279
+ tokenId: session.grant.tokenId,
12280
+ viewerId
12281
+ }) : void 0;
11952
12282
  return jsonResponse({
11953
12283
  artifactId,
11954
12284
  viewId: interaction.openView({
@@ -11980,7 +12310,12 @@ function createGateway(options) {
11980
12310
  pinned: pinned !== void 0,
11981
12311
  ...options.parked?.(version.id) ? { serverParked: true } : {},
11982
12312
  ...options.dev ? { devPreview: true } : {},
11983
- ...mode === "worker" ? { mode: "worker" } : {}
12313
+ ...mode === "worker" ? { mode: "worker" } : {},
12314
+ ...pause ? { paused: {
12315
+ by: pause.by,
12316
+ ...pause.reason !== void 0 ? { reason: pause.reason } : {}
12317
+ } } : {},
12318
+ ...chrome ? { hosted: chrome } : {}
11984
12319
  });
11985
12320
  };
11986
12321
  return [
@@ -12085,7 +12420,8 @@ function createGateway(options) {
12085
12420
  intent: "mutation",
12086
12421
  auth: "session",
12087
12422
  scope: () => "review"
12088
- }
12423
+ },
12424
+ ...hosted?.shellRoutes?.({ refuse: (refused, request) => refuse(checks, refused, request) }) ?? []
12089
12425
  ];
12090
12426
  };
12091
12427
  const artifactChecks = (artifactId, wayOf, group) => ({
@@ -12096,20 +12432,26 @@ function createGateway(options) {
12096
12432
  capabilities,
12097
12433
  log,
12098
12434
  cookieName: () => `mostra-${wayOf().port()}`,
12099
- frameAncestors: () => shellOf(wayOf(), group)?.origin() ?? "'none'",
12435
+ frameAncestors: () => {
12436
+ const way = wayOf();
12437
+ if (way.by === "hosted" && hosted?.frameAncestors) return hosted.frameAncestors(artifactId, way.origin() ?? "") || "'none'";
12438
+ return shellOf(way, group)?.origin() ?? "'none'";
12439
+ },
12100
12440
  artifactOf: () => artifactId,
12101
12441
  mode: () => modeOf(wayOf(), group),
12102
- streams: () => wayOf().streams()
12442
+ streams: () => wayOf().streams(),
12443
+ ...hosted?.client ? { client: hosted.client } : {}
12103
12444
  });
12104
12445
  const artifactRoutes = (artifactId, wayOf, group) => {
12105
12446
  const origin = () => wayOf().origin() ?? "";
12106
12447
  const shell = () => shellOf(wayOf(), group)?.origin() ?? "";
12448
+ const checks = artifactChecks(artifactId, wayOf, group);
12107
12449
  const kind = () => ({
12108
12450
  kind: "artifact",
12109
12451
  origin: origin(),
12110
- shellOrigin: shell()
12452
+ shellOrigin: shell(),
12453
+ ...wayOf().by === "hosted" ? { frameAncestors: checks.frameAncestors() } : {}
12111
12454
  });
12112
- const checks = artifactChecks(artifactId, wayOf, group);
12113
12455
  const mode = () => modeOf(wayOf(), group);
12114
12456
  const notServed = (context, message) => refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", message), {
12115
12457
  method: context.request.method,
@@ -12302,6 +12644,8 @@ function createGateway(options) {
12302
12644
  }
12303
12645
  }
12304
12646
  const checked = file ?? (context.document ? await findFile(root(versionId), "/index.html") : void 0);
12647
+ const withheld = hosted?.blocked?.(artifactId, from);
12648
+ if (withheld) return refuse(checks, withheld, meta);
12305
12649
  if (checked) {
12306
12650
  const damage = await integrity.serve(from, checked);
12307
12651
  if (damage !== void 0) {
@@ -12657,6 +13001,33 @@ function locateShell(env) {
12657
13001
  const dir = env["MOSTRA_SHELL_DIR"] ?? resolve(runtimeRoot$1(), "..", "shell", "dist");
12658
13002
  return existsSync(join(dir, "index.html")) ? dir : void 0;
12659
13003
  }
13004
+ /** The generic preview of every hosted page (D161): one title, one description, no image. */
13005
+ const HOSTED_PREVIEW = {
13006
+ title: "A page sent with Mostra",
13007
+ description: "Someone sent you this page. Open it to see it."
13008
+ };
13009
+ /** Text for an HTML attribute or element: nothing a tenant writes is ever markup. */
13010
+ function previewText(text) {
13011
+ return text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);
13012
+ }
13013
+ /**
13014
+ * The hosted shell's page with its link preview (D161): the generic title and description, or
13015
+ * the artifact's title alone when its manifest asks (`hosted.preview: "title"`), never its text or
13016
+ * images, and `noindex`.
13017
+ */
13018
+ function hostedPreview(html, title) {
13019
+ const shown = previewText(title ?? HOSTED_PREVIEW.title);
13020
+ const description = previewText(HOSTED_PREVIEW.description);
13021
+ const tags = [
13022
+ `<meta name="robots" content="noindex, nofollow">`,
13023
+ `<meta name="description" content="${description}">`,
13024
+ `<meta property="og:title" content="${shown}">`,
13025
+ `<meta property="og:description" content="${description}">`,
13026
+ `<meta property="og:site_name" content="Mostra">`,
13027
+ `<meta name="twitter:card" content="summary">`
13028
+ ].join("\n ");
13029
+ return html.replace(/<title>[^<]*<\/title>/, `<title>${shown}</title>\n ${tags}`);
13030
+ }
12660
13031
  //#endregion
12661
13032
  //#region src/live/index.ts
12662
13033
  /**
@@ -14296,6 +14667,10 @@ function runnerEnvironment(env, browsers) {
14296
14667
  if (browsers !== void 0) out["PLAYWRIGHT_BROWSERS_PATH"] = browsers;
14297
14668
  const idle = env["MOSTRA_TEST_VERIFY_IDLE_MS"];
14298
14669
  if (idle) out["MOSTRA_TEST_VERIFY_IDLE_MS"] = idle;
14670
+ for (const name of ["MOSTRA_TEST_VERIFY_LOSE_BROWSER", "MOSTRA_TEST_VERIFY_FAIL_ONCE"]) {
14671
+ const value = env[name];
14672
+ if (value) out[name] = value;
14673
+ }
14299
14674
  return out;
14300
14675
  }
14301
14676
  /** Creates the client; nothing starts until the first request. */
@@ -14360,9 +14735,24 @@ function createRunnerClient(options) {
14360
14735
  }
14361
14736
  throw new RpcError(createDiagnostic("MOSTRA_VERIFY_TIMEOUT", { message: "Verify ran out of time: the browser stopped answering while it checked the page." }));
14362
14737
  }
14738
+ let failure = "";
14363
14739
  if (outcome.kind === "error" && outcome.error instanceof RpcError) {
14364
14740
  const code = outcome.error.diagnostic.code;
14365
14741
  if (code !== "MOSTRA_HOST_INTERNAL_ERROR" && !code.startsWith("MOSTRA_HOST_CONNECTION")) throw outcome.error;
14742
+ if (code === "MOSTRA_HOST_INTERNAL_ERROR") {
14743
+ failure = outcome.error.diagnostic.message;
14744
+ options.log.warn("verify.runner_failed", {
14745
+ method,
14746
+ error: failure.slice(0, 500)
14747
+ });
14748
+ if (child) {
14749
+ const failed = child;
14750
+ child = void 0;
14751
+ const stopped = await failed.catch(() => void 0);
14752
+ if (stopped) recycled.add(stopped);
14753
+ await stopped?.stop(2e3);
14754
+ }
14755
+ }
14366
14756
  }
14367
14757
  if (recycled.has(handle) && !retried) {
14368
14758
  options.log.info("verify.runner_retry", { method });
@@ -14370,7 +14760,8 @@ function createRunnerClient(options) {
14370
14760
  }
14371
14761
  const exit = outcome.kind === "exit" ? outcome.exit : await Promise.race([handle.exited, new Promise((done) => setTimeout(() => done(void 0), 1e3))]);
14372
14762
  const tail = exit?.stderrTail.slice(-10).join("\n") ?? "";
14373
- throw new RpcError(createDiagnostic("MOSTRA_VERIFY_CRASHED", { message: `The verify runner stopped before it answered${exit ? ` (${exit.signal ?? `code ${exit.code}`})` : ""}.${tail ? `\n${tail}` : ""}` }));
14763
+ const said = failure ? `\nThe runner said: ${failure.slice(0, 1e3)}` : "";
14764
+ throw new RpcError(createDiagnostic("MOSTRA_VERIFY_CRASHED", { message: `The verify runner stopped before it answered${exit ? ` (${exit.signal ?? `code ${exit.code}`})` : ""}.${tail ? `\n${tail}` : ""}${said}` }));
14374
14765
  };
14375
14766
  return {
14376
14767
  render: (request) => ask(VERIFY_RUNNER_METHODS.render, request, request.deadline),
@@ -17843,6 +18234,155 @@ function markHostConfigured(home, client, at = /* @__PURE__ */ new Date()) {
17843
18234
  return true;
17844
18235
  }
17845
18236
  //#endregion
18237
+ //#region src/link/author.ts
18238
+ /**
18239
+ * Authoring from a chat host, on the owner instance (INTERFACES §18.8, D165 item 5): the remote MCP
18240
+ * server relays `artifact/create`, `verify` and `publish`, and the workspace's files, to the
18241
+ * account's default owner instance as `port/relay.author`, and this module runs each here, on this
18242
+ * home's own protocol server, in an in-process session as any host would (invariant 11).
18243
+ *
18244
+ * The relay is a way in from outside this machine, so every directory it names stays inside this
18245
+ * home's MCP workspace (`MOSTRA_MCP_WORKSPACE`, default `~/mostra-artifacts`, as `mostra mcp`'s):
18246
+ * a relative one resolves there, an absolute one must already be there, and anything else is
18247
+ * `MOSTRA_ARTIFACT_PATH_INVALID`. A screenshot is read only from verify's own cache. A publish also
18248
+ * hosts the version on the server that asked and answers its hosted link.
18249
+ */
18250
+ /** The eight bytes every PNG file starts with. */
18251
+ const PNG_SIGNATURE = Buffer.from([
18252
+ 137,
18253
+ 80,
18254
+ 78,
18255
+ 71,
18256
+ 13,
18257
+ 10,
18258
+ 26,
18259
+ 10
18260
+ ]);
18261
+ function outside(message) {
18262
+ return new RpcError(createDiagnostic("MOSTRA_ARTIFACT_PATH_INVALID", { message }));
18263
+ }
18264
+ /** Whether `inner` is `outer` or inside it. */
18265
+ function within(outer, inner) {
18266
+ const between = relative(outer, inner);
18267
+ return between === "" || !between.startsWith("..") && !isAbsolute(between);
18268
+ }
18269
+ /** Creates the owner's answer to relayed authoring. */
18270
+ function createOwnerAuthor(options) {
18271
+ const configured = options.env["MOSTRA_MCP_WORKSPACE"];
18272
+ const root = resolve(configured !== void 0 && configured !== "" ? configured : defaultWorkspaceRoot());
18273
+ const workspace = localWorkspace(root);
18274
+ const verifyCache = join(options.home, "cache", "verify");
18275
+ /** A directory the relay names, inside the workspace or refused. */
18276
+ const dirOf = (dir) => {
18277
+ if (typeof dir !== "string" || dir === "") throw outside("Name an artifact's directory.");
18278
+ const absolute = isAbsolute(dir) ? resolve(dir) : workspace.resolveDir(dir);
18279
+ let real = absolute;
18280
+ try {
18281
+ real = realpathSync.native(absolute);
18282
+ } catch {}
18283
+ let base = root;
18284
+ try {
18285
+ base = realpathSync.native(root);
18286
+ } catch {}
18287
+ if (!within(root, absolute) || !within(base, real)) throw outside(`A chat host's authoring stays inside this machine's Mostra workspace (${root}); ${dir} is outside it.`);
18288
+ return absolute;
18289
+ };
18290
+ /** One call on this home's protocol server, in a session of its own. */
18291
+ const local = async (method, params) => {
18292
+ const protocol = options.protocol();
18293
+ if (protocol === void 0) throw new RpcError(createDiagnostic("MOSTRA_REMOTE_NO_INSTANCE", { message: "This Mostra instance is still starting; try again in a moment." }));
18294
+ const { client } = await attachInProcess(protocol, {
18295
+ name: "mostra-remote-author",
18296
+ version: options.runtimeVersion
18297
+ });
18298
+ try {
18299
+ return await client.peer.call(method, params);
18300
+ } finally {
18301
+ client.close();
18302
+ }
18303
+ };
18304
+ return async (server, raw) => {
18305
+ const { method, params } = portRelayAuthorMethod.params.parse(raw);
18306
+ const given = params ?? {};
18307
+ options.log.info("link.author", {
18308
+ server,
18309
+ method
18310
+ });
18311
+ switch (method) {
18312
+ case "workspace/root": return root;
18313
+ case "workspace/allocate": return workspace.allocateDir(typeof given["title"] === "string" ? given["title"] : void 0);
18314
+ case "workspace/read": {
18315
+ const content = await workspace.read(dirOf(given["dir"]), String(given["path"] ?? ""));
18316
+ return content === void 0 ? {} : { content: Buffer.from(content).toString("base64") };
18317
+ }
18318
+ case "workspace/apply": {
18319
+ const write = Array.isArray(given["write"]) ? given["write"] : [];
18320
+ const deletes = Array.isArray(given["delete"]) ? given["delete"] : [];
18321
+ return workspace.apply(dirOf(given["dir"]), {
18322
+ write: write.map((file) => {
18323
+ const entry = file;
18324
+ return {
18325
+ path: String(entry.path ?? ""),
18326
+ content: Buffer.from(String(entry.content ?? ""), "base64")
18327
+ };
18328
+ }),
18329
+ delete: deletes.map(String)
18330
+ });
18331
+ }
18332
+ case "verify/screenshot": {
18333
+ const path = resolve(String(given["path"] ?? ""));
18334
+ let real = path;
18335
+ try {
18336
+ real = realpathSync.native(path);
18337
+ } catch {
18338
+ return {};
18339
+ }
18340
+ if (!path.toLowerCase().endsWith(".png") || !within(verifyCache, path) || !within(realpathSync.native(verifyCache), real)) return {};
18341
+ try {
18342
+ const bytes = await readFile(real);
18343
+ return bytes.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE) ? { png: bytes.toString("base64") } : {};
18344
+ } catch {
18345
+ return {};
18346
+ }
18347
+ }
18348
+ case "artifact/create": return local(artifactCreateMethod, {
18349
+ ...given,
18350
+ dir: dirOf(given["dir"])
18351
+ });
18352
+ case "artifact/get": {
18353
+ const artifact = given["artifact"];
18354
+ const detail = await local(artifactGetMethod, { artifact: artifact?.path !== void 0 ? { path: dirOf(artifact.path) } : { artifactId: String(artifact?.artifactId ?? "") } });
18355
+ return {
18356
+ id: detail.id,
18357
+ title: detail.title
18358
+ };
18359
+ }
18360
+ case "artifact/verify": {
18361
+ const source = given["source"];
18362
+ return local(artifactVerifyMethod, {
18363
+ ...given,
18364
+ source: { path: dirOf(source?.path) }
18365
+ });
18366
+ }
18367
+ case "artifact/publish": {
18368
+ const source = given["source"];
18369
+ const receipt = await local(artifactPublishMethod, {
18370
+ ...given,
18371
+ source: { path: dirOf(source?.path) }
18372
+ });
18373
+ if (!options.hostedOn(receipt.artifactId).includes(server)) await local(shareStartMethod, {
18374
+ artifact: { artifactId: receipt.artifactId },
18375
+ via: "remote",
18376
+ server
18377
+ });
18378
+ const { url: _local, tokenId: _token, ...crossing } = receipt;
18379
+ return crossing;
18380
+ }
18381
+ default: throw outside(`The relay serves no authoring method ${method}.`);
18382
+ }
18383
+ };
18384
+ }
18385
+ //#endregion
17846
18386
  //#region src/link/binding.ts
17847
18387
  /**
17848
18388
  * The owner's side of the network binding (INTERFACES §18.2, D165 item 2): one WebSocket to a
@@ -18115,6 +18655,32 @@ function forwardHosted(link, resolve, handlers) {
18115
18655
  };
18116
18656
  });
18117
18657
  }
18658
+ /**
18659
+ * The owner's `artifact/pause` (D165 item 14): pauses or resumes the artifact here and on every
18660
+ * server it is hosted on, each as its owner. A server where the operator paused it answers that
18661
+ * only the operator resumes it (`MOSTRA_REMOTE_PAUSED_BY_OPERATOR`); one that can't be reached is
18662
+ * `MOSTRA_REMOTE_UNREACHABLE`, and the call can be made again, since a pause is idempotent.
18663
+ */
18664
+ function pauseHandler(link, resolve, pause) {
18665
+ return handler(artifactPauseMethod, async (params) => {
18666
+ const artifactId = resolve(params.artifact);
18667
+ let byOperator = false;
18668
+ for (const server of link.hostedServers(artifactId)) if ((await link.forward(server, artifactPauseMethod, {
18669
+ artifact: { artifactId },
18670
+ paused: params.paused,
18671
+ ...params.reason !== void 0 ? { reason: params.reason } : {}
18672
+ })).by === "operator") byOperator = true;
18673
+ const local = pause(artifactId, {
18674
+ paused: params.paused,
18675
+ by: "owner",
18676
+ ...params.reason !== void 0 ? { reason: params.reason } : {}
18677
+ });
18678
+ return byOperator ? {
18679
+ paused: true,
18680
+ by: "operator"
18681
+ } : local;
18682
+ });
18683
+ }
18118
18684
  /** The largest answer the instance reads (the API answers JSON; files go the other way). */
18119
18685
  const MAX_ANSWER_BYTES = 4194304;
18120
18686
  /** Reads the test override, `host:port`, or nothing. */
@@ -18178,12 +18744,13 @@ function remoteRequest(server, path, init = {}) {
18178
18744
  });
18179
18745
  }
18180
18746
  /** Posts a form and reads a JSON answer, whatever its status. */
18181
- async function postForm(server, path, fields, connectTo) {
18747
+ async function postForm(server, path, fields, connectTo, bearer) {
18182
18748
  const answer = await remoteRequest(server, path, {
18183
18749
  method: "POST",
18184
18750
  headers: {
18185
18751
  "content-type": "application/x-www-form-urlencoded",
18186
- accept: "application/json"
18752
+ accept: "application/json",
18753
+ ...bearer !== void 0 ? { authorization: `Bearer ${bearer}` } : {}
18187
18754
  },
18188
18755
  body: new URLSearchParams(fields).toString(),
18189
18756
  ...connectTo ? { connectTo } : {}
@@ -18560,6 +19127,8 @@ function invalid(message) {
18560
19127
  function loginFailed(message) {
18561
19128
  return new RpcError(createDiagnostic("MOSTRA_REMOTE_LOGIN_FAILED", { message }));
18562
19129
  }
19130
+ /** The secret a home's credentials hold. */
19131
+ const credentialSecret = (credentials) => "key" in credentials ? credentials.key : credentials.refreshToken;
18563
19132
  /** Creates the owner's link manager. */
18564
19133
  function createLink(options) {
18565
19134
  const { ledger, log } = options;
@@ -18575,8 +19144,9 @@ function createLink(options) {
18575
19144
  if (!existsSync(file)) return void 0;
18576
19145
  try {
18577
19146
  const parsed = JSON.parse(readFileSync(file, "utf8"));
18578
- if (parsed.server !== server || typeof parsed.refreshToken !== "string") return void 0;
18579
- options.protect(parsed.refreshToken);
19147
+ const secret = parsed.refreshToken ?? parsed.key;
19148
+ if (parsed.server !== server || typeof secret !== "string") return void 0;
19149
+ options.protect(secret);
18580
19150
  return parsed;
18581
19151
  } catch {
18582
19152
  return;
@@ -18587,7 +19157,7 @@ function createLink(options) {
18587
19157
  recursive: true,
18588
19158
  mode: 448
18589
19159
  });
18590
- options.protect(credentials.refreshToken);
19160
+ options.protect(credentialSecret(credentials));
18591
19161
  const target = credentialsFile(credentials.server);
18592
19162
  const temporary = `${target}.${process.pid}.tmp`;
18593
19163
  writeFileSync(temporary, JSON.stringify(credentials), { mode: 384 });
@@ -18636,6 +19206,7 @@ function createLink(options) {
18636
19206
  try {
18637
19207
  const credentials = readCredentials(connection.server);
18638
19208
  if (!credentials) throw loginFailed(`This home isn't signed in to ${connection.server}.`);
19209
+ if ("key" in credentials) return credentials.key;
18639
19210
  const answer = await postForm(connection.server, "/oauth/token", {
18640
19211
  client_id: CLIENT_ID,
18641
19212
  grant_type: "refresh_token",
@@ -18792,6 +19363,10 @@ function createLink(options) {
18792
19363
  ...options.liveChanged ? { liveChanged: options.liveChanged } : {}
18793
19364
  });
18794
19365
  const onRequest = (connection) => (method, params) => {
19366
+ if (method === portRelayAuthorMethod.method) {
19367
+ if (!options.author) throw new RpcError(createDiagnostic("MOSTRA_REMOTE_NO_INSTANCE", { message: "This instance takes no authoring from a chat host." }));
19368
+ return options.author(connection.server, params);
19369
+ }
18795
19370
  if (relay.handles(method)) return relay.request(connection.server, () => connection.binding.session ?? readySoon(connection), method, params, () => connection.binding.reconnect());
18796
19371
  if (method === portSubmissionsDeliverMethod.method) {
18797
19372
  const parsed = SubmissionEnvelope.safeParse(params?.envelope ?? params);
@@ -19090,6 +19665,68 @@ function createLink(options) {
19090
19665
  if (!last) throw invalid("Name the server to sign in to: mostra login <server>. No server is configured by default.");
19091
19666
  return last.server;
19092
19667
  };
19668
+ /** Records this home's link to a server, rebinding its marks only to the same link (WP-29). */
19669
+ const recordLink = (server, account, instanceId, isDefault) => {
19670
+ ledger.write((db) => db.run(`INSERT INTO remote_link (server, account_id, account_name, instance_id, is_default, linked_at, state)
19671
+ VALUES (?, ?, ?, ?, ?, ?, 'signed-in')
19672
+ ON CONFLICT (server) DO UPDATE SET
19673
+ -- Another link (after --forget, or another account) starts with no marks: a mark
19674
+ -- of the old link would make the new one's home look restored (Opus review of
19675
+ -- WP-29, 9).
19676
+ relay_mark = CASE WHEN remote_link.instance_id IS excluded.instance_id
19677
+ AND remote_link.account_id = excluded.account_id THEN remote_link.relay_mark ELSE 0 END,
19678
+ follow_cursor = CASE WHEN remote_link.instance_id IS excluded.instance_id
19679
+ AND remote_link.account_id = excluded.account_id THEN remote_link.follow_cursor ELSE NULL END,
19680
+ incarnation = CASE WHEN remote_link.instance_id IS excluded.instance_id
19681
+ AND remote_link.account_id = excluded.account_id THEN remote_link.incarnation ELSE NULL END,
19682
+ account_id = excluded.account_id, account_name = excluded.account_name,
19683
+ instance_id = excluded.instance_id, is_default = excluded.is_default, linked_at = excluded.linked_at,
19684
+ state = 'signed-in'`, server, account.id, account.name ?? null, instanceId, isDefault ? 1 : 0, new Date(now()).toISOString()));
19685
+ };
19686
+ /**
19687
+ * Links this home with a key the server's operator issued (`remote/link`, D167): the server says
19688
+ * which account and instance link the key binds, the key is kept like a refresh token, and the
19689
+ * binding opens with it at once.
19690
+ */
19691
+ const linkWithKey = async (requested, key, makeDefault) => {
19692
+ const server = serverOrigin(requested);
19693
+ options.protect(key);
19694
+ const answer = await postForm(server, "/link", makeDefault ? { default: "1" } : {}, connectTo, key);
19695
+ const account = answer.json["account"];
19696
+ const instanceId = answer.json["instanceId"];
19697
+ if (answer.status !== 200 || typeof account?.id !== "string" || typeof instanceId !== "string" || !LinkId.is(instanceId)) throw loginFailed(`${server} didn't admit this key (${String(answer.json["message"] ?? answer.status)}).`);
19698
+ const name = typeof account.name === "string" ? account.name : void 0;
19699
+ const isDefault = answer.json["default"] === true;
19700
+ writeCredentials({
19701
+ server,
19702
+ key,
19703
+ instanceId
19704
+ });
19705
+ recordLink(server, {
19706
+ id: account.id,
19707
+ name
19708
+ }, instanceId, isDefault);
19709
+ const previous = connections.get(server);
19710
+ if (previous) {
19711
+ await previous.binding.stop();
19712
+ if (previous.refreshTimer) clearTimeout(previous.refreshTimer);
19713
+ connections.delete(server);
19714
+ }
19715
+ connect(server);
19716
+ log.info("link.linked_with_key", {
19717
+ server,
19718
+ instanceId
19719
+ });
19720
+ return {
19721
+ server,
19722
+ account: {
19723
+ id: account.id,
19724
+ ...name !== void 0 ? { name } : {}
19725
+ },
19726
+ instanceId,
19727
+ default: isDefault
19728
+ };
19729
+ };
19093
19730
  /** Starts a sign-in: the device grant's code, then polls for the token in the background. */
19094
19731
  const login = async (requested, makeDefault = false) => {
19095
19732
  const server = resolveServer(requested);
@@ -19166,21 +19803,7 @@ function createLink(options) {
19166
19803
  refreshToken,
19167
19804
  instanceId
19168
19805
  });
19169
- ledger.write((db) => db.run(`INSERT INTO remote_link (server, account_id, account_name, instance_id, is_default, linked_at, state)
19170
- VALUES (?, ?, ?, ?, ?, ?, 'signed-in')
19171
- ON CONFLICT (server) DO UPDATE SET
19172
- -- Another link (after --forget, or another account) starts with no marks: a mark
19173
- -- of the old link would make the new one's home look restored (Opus review of
19174
- -- WP-29, 9).
19175
- relay_mark = CASE WHEN remote_link.instance_id IS excluded.instance_id
19176
- AND remote_link.account_id = excluded.account_id THEN remote_link.relay_mark ELSE 0 END,
19177
- follow_cursor = CASE WHEN remote_link.instance_id IS excluded.instance_id
19178
- AND remote_link.account_id = excluded.account_id THEN remote_link.follow_cursor ELSE NULL END,
19179
- incarnation = CASE WHEN remote_link.instance_id IS excluded.instance_id
19180
- AND remote_link.account_id = excluded.account_id THEN remote_link.incarnation ELSE NULL END,
19181
- account_id = excluded.account_id, account_name = excluded.account_name,
19182
- instance_id = excluded.instance_id, is_default = excluded.is_default, linked_at = excluded.linked_at,
19183
- state = 'signed-in'`, server, account.id, account.name ?? null, instanceId, answer.json["mostra_default"] === true ? 1 : 0, new Date(now()).toISOString()));
19806
+ recordLink(server, account, instanceId, answer.json["mostra_default"] === true);
19184
19807
  const previous = connections.get(server);
19185
19808
  if (previous) {
19186
19809
  await previous.binding.stop();
@@ -19238,6 +19861,7 @@ function createLink(options) {
19238
19861
  methods() {
19239
19862
  return [
19240
19863
  handler(remoteLoginMethod, (params) => login(params.server, params.default === true)),
19864
+ handler(remoteLinkMethod, (params) => linkWithKey(params.server, params.key, params.default === true)),
19241
19865
  handler(remoteLoginWaitMethod, async (params) => {
19242
19866
  const pending = logins.get(params.loginId);
19243
19867
  if (!pending) throw invalid(`No sign-in ${params.loginId} is in progress.`);
@@ -19270,7 +19894,7 @@ function createLink(options) {
19270
19894
  if (connection.pushTimer) clearTimeout(connection.pushTimer);
19271
19895
  connections.delete(server);
19272
19896
  }
19273
- if (credentials) try {
19897
+ if (credentials && "refreshToken" in credentials) try {
19274
19898
  await postForm(server, "/oauth/revoke", {
19275
19899
  token: credentials.refreshToken,
19276
19900
  client_id: CLIENT_ID
@@ -19364,6 +19988,7 @@ function createLink(options) {
19364
19988
  }
19365
19989
  return true;
19366
19990
  },
19991
+ hostedServers: (artifactId) => ledger.read((db) => db.all("SELECT server FROM hosted_artifact WHERE artifact_id = ? AND stopped_at IS NULL AND route_id != '' ORDER BY shared_at", artifactId).map((row) => row.server)),
19367
19992
  hostedOn: (artifactId) => ledger.read((db) => db.get("SELECT server FROM hosted_artifact WHERE artifact_id = ? AND stopped_at IS NULL AND route_id != '' ORDER BY shared_at LIMIT 1", artifactId)?.server),
19368
19993
  forward: async (server, definition, params) => {
19369
19994
  let session;
@@ -21557,7 +22182,16 @@ async function assemble(home, options) {
21557
22182
  versionDir: (versionId) => registry.store.versionDir(versionId),
21558
22183
  actions,
21559
22184
  liveChanged: () => live.reconcile(),
21560
- now: () => Date.now() + clockOffset
22185
+ now: () => Date.now() + clockOffset,
22186
+ author: (from, params) => author(from, params)
22187
+ });
22188
+ const author = createOwnerAuthor({
22189
+ home: home.path,
22190
+ env: environment,
22191
+ log,
22192
+ runtimeVersion: runtimeVersion(),
22193
+ protocol: () => server,
22194
+ hostedOn: (artifactId) => link.hostedServers(artifactId)
21561
22195
  });
21562
22196
  const stopPushingPublishes = interaction.onPublished((artifactId, versionId) => link.published(artifactId, versionId));
21563
22197
  const shares = createShares({
@@ -21659,6 +22293,7 @@ async function assemble(home, options) {
21659
22293
  ...shares.methods(),
21660
22294
  ...link.methods(),
21661
22295
  ...forwardHosted(link, (ref) => registry.get(canonicalRef(ref)).id, interaction.methods()),
22296
+ pauseHandler(link, (ref) => registry.get(canonicalRef(ref)).id, interaction.pause),
21662
22297
  ...secretMethods(secrets, (ref) => registry.get(canonicalRef(ref)).id),
21663
22298
  ...gcMethods(createGc({
21664
22299
  ledger: home.ledger,
@@ -21882,6 +22517,6 @@ function sourceDirectory(path) {
21882
22517
  }
21883
22518
  }
21884
22519
  //#endregion
21885
- export { MAX_FRAME_BYTES as A, coverageMatcher as B, finishRun as C, runState as D, markWaiting as E, openLedger as F, noFaults as I, readFieldCoverage as L, ProtocolServer as M, handler as N, appendEvent as O, holdLock as P, readServerFunctions as R, appendRunOutput as S, markUnknown as T, openFileLog as V, Capabilities as _, uninstallService as a, createInteraction as b, resolveHomePath as c, versionIdFor as d, createLive as f, shellAssetResponse as g, locateShell as h, serviceStatus as i, serveWebSocket as j, BINDING_SUBPROTOCOL as k, canonicalRef as l, createGateway as m, startInstance as n, checkPlatform as o, liveMethods as p, installService as r, platformName as s, runtimeVersion as t, listingDigest as u, capabilityKey as v, markRunning as w, createEphemeralBus as x, openRegistry as y, readProcess as z };
22520
+ export { markRunning as A, handler as B, jsonResponse as C, createEphemeralBus as D, createInteraction as E, BINDING_SUBPROTOCOL as F, readFieldCoverage as G, openLedger as H, MAX_FRAME_BYTES as I, coverageMatcher as J, readServerFunctions as K, serveWebSocket as L, markWaiting as M, runState as N, appendRunOutput as O, appendEvent as P, attachInProcess as R, isRefusal as S, openRegistry as T, faultsFrom as U, holdLock as V, noFaults as W, openFileLog as Y, resetOnClose as _, uninstallService as a, BASE_HEADERS as b, resolveHomePath as c, versionIdFor as d, createLive as f, shellAssetResponse as g, locateShell as h, serviceStatus as i, markUnknown as j, finishRun as k, canonicalRef as l, createGateway as m, startInstance as n, checkPlatform as o, liveMethods as p, readProcess as q, installService as r, platformName as s, runtimeVersion as t, listingDigest as u, Capabilities as v, readJsonObject as w, documentHeaders as x, capabilityKey as y, ProtocolServer as z };
21886
22521
 
21887
- //# sourceMappingURL=instance-FExcyENK.js.map
22522
+ //# sourceMappingURL=instance-DCiUHvgZ.js.map