@qvac/core 0.4.1 → 0.6.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 (417) hide show
  1. package/CHANGELOG.md +262 -1
  2. package/README.md +1 -1
  3. package/dist-lib/lib/api/agents.js +3 -2
  4. package/dist-lib/lib/api/app-config.d.ts +1 -1
  5. package/dist-lib/lib/api/app-config.js +54 -15
  6. package/dist-lib/lib/api/attachments.d.ts +6 -5
  7. package/dist-lib/lib/api/attachments.js +4 -2
  8. package/dist-lib/lib/api/chat.d.ts +7 -3
  9. package/dist-lib/lib/api/chat.js +4 -4
  10. package/dist-lib/lib/api/chunks.js +3 -3
  11. package/dist-lib/lib/api/config.js +2 -2
  12. package/dist-lib/lib/api/current-mesh.d.ts +3 -4
  13. package/dist-lib/lib/api/current-mesh.js +9 -4
  14. package/dist-lib/lib/api/custom-models.d.ts +8 -1
  15. package/dist-lib/lib/api/custom-models.js +53 -16
  16. package/dist-lib/lib/api/devices.d.ts +14 -5
  17. package/dist-lib/lib/api/devices.js +14 -9
  18. package/dist-lib/lib/api/diagnostics.d.ts +1 -0
  19. package/dist-lib/lib/api/diagnostics.js +1 -1
  20. package/dist-lib/lib/api/effective-ctx-size.d.ts +6 -1
  21. package/dist-lib/lib/api/effective-ctx-size.js +5 -3
  22. package/dist-lib/lib/api/execution.js +9 -2
  23. package/dist-lib/lib/api/files.js +2 -1
  24. package/dist-lib/lib/api/index.d.ts +7 -1
  25. package/dist-lib/lib/api/index.js +101 -101
  26. package/dist-lib/lib/api/instrument.js +29 -20
  27. package/dist-lib/lib/api/knowledge.d.ts +6 -5
  28. package/dist-lib/lib/api/knowledge.js +8 -6
  29. package/dist-lib/lib/api/local-files.js +1 -1
  30. package/dist-lib/lib/api/logs.js +6 -3
  31. package/dist-lib/lib/api/members.js +22 -13
  32. package/dist-lib/lib/api/mesh.d.ts +7 -2
  33. package/dist-lib/lib/api/mesh.js +10 -5
  34. package/dist-lib/lib/api/model-download.js +1 -1
  35. package/dist-lib/lib/api/network.d.ts +1 -0
  36. package/dist-lib/lib/api/network.js +1 -1
  37. package/dist-lib/lib/api/notifications.js +23 -13
  38. package/dist-lib/lib/api/rag.d.ts +6 -1
  39. package/dist-lib/lib/api/rag.js +20 -11
  40. package/dist-lib/lib/api/range.d.ts +2 -2
  41. package/dist-lib/lib/api/sync.js +1 -1
  42. package/dist-lib/lib/api/tool-activity.js +7 -3
  43. package/dist-lib/lib/api/tool-configs.js +2 -4
  44. package/dist-lib/lib/api/upload-frames.d.ts +7 -8
  45. package/dist-lib/lib/api/upload-frames.js +2 -1
  46. package/dist-lib/lib/api/watchable.d.ts +6 -1
  47. package/dist-lib/lib/api/watchable.js +23 -14
  48. package/dist-lib/lib/assistant/fetch-body.js +4 -2
  49. package/dist-lib/lib/assistant/harness.d.ts +72 -24
  50. package/dist-lib/lib/assistant/harness.js +53 -15
  51. package/dist-lib/lib/assistant/history.d.ts +9 -7
  52. package/dist-lib/lib/assistant/history.js +77 -42
  53. package/dist-lib/lib/assistant/message.d.ts +5 -3
  54. package/dist-lib/lib/assistant/message.js +4 -2
  55. package/dist-lib/lib/assistant/skill-encode.d.ts +3 -1
  56. package/dist-lib/lib/assistant/skill-encode.js +52 -62
  57. package/dist-lib/lib/assistant-client.js +7 -4
  58. package/dist-lib/lib/assistant-tree.js +36 -11
  59. package/dist-lib/lib/assistant.d.ts +37 -12
  60. package/dist-lib/lib/assistant.js +977 -373
  61. package/dist-lib/lib/audio-format.d.ts +1 -1
  62. package/dist-lib/lib/audio-format.js +1 -1
  63. package/dist-lib/lib/chat-title.js +9 -4
  64. package/dist-lib/lib/client.js +3 -2
  65. package/dist-lib/lib/collabora/convert.d.ts +2 -2
  66. package/dist-lib/lib/collabora/convert.js +6 -3
  67. package/dist-lib/lib/collabora/entry.js +9 -5
  68. package/dist-lib/lib/collabora/protocol.d.ts +2 -2
  69. package/dist-lib/lib/collabora/protocol.js +14 -7
  70. package/dist-lib/lib/collabora/worker.js +14 -7
  71. package/dist-lib/lib/compaction.d.ts +5 -6
  72. package/dist-lib/lib/compaction.js +14 -7
  73. package/dist-lib/lib/constants.d.ts +2 -0
  74. package/dist-lib/lib/constants.js +4 -0
  75. package/dist-lib/lib/core/account-recovery.d.ts +4 -3
  76. package/dist-lib/lib/core/account-recovery.js +7 -4
  77. package/dist-lib/lib/core/agent.d.ts +0 -1
  78. package/dist-lib/lib/core/agent.js +18 -16
  79. package/dist-lib/lib/core/approval-rules.d.ts +7 -6
  80. package/dist-lib/lib/core/approval-rules.js +12 -6
  81. package/dist-lib/lib/core/archived-mesh.d.ts +7 -5
  82. package/dist-lib/lib/core/archived-mesh.js +25 -22
  83. package/dist-lib/lib/core/async-iterable.js +10 -5
  84. package/dist-lib/lib/core/attachment-link.d.ts +2 -2
  85. package/dist-lib/lib/core/audio-attachment.js +1 -1
  86. package/dist-lib/lib/core/blind-peers.d.ts +2 -2
  87. package/dist-lib/lib/core/chat-activity.d.ts +2 -2
  88. package/dist-lib/lib/core/chat-activity.js +42 -21
  89. package/dist-lib/lib/core/chat-group.d.ts +8 -6
  90. package/dist-lib/lib/core/chat-group.js +17 -10
  91. package/dist-lib/lib/core/chat-order.d.ts +11 -9
  92. package/dist-lib/lib/core/chat-order.js +1 -3
  93. package/dist-lib/lib/core/chat-search.d.ts +4 -4
  94. package/dist-lib/lib/core/chat-search.js +38 -24
  95. package/dist-lib/lib/core/chat.d.ts +20 -14
  96. package/dist-lib/lib/core/chat.js +42 -28
  97. package/dist-lib/lib/core/chunk.d.ts +20 -24
  98. package/dist-lib/lib/core/chunk.js +34 -22
  99. package/dist-lib/lib/core/collections.d.ts +69 -0
  100. package/dist-lib/lib/core/collections.js +69 -0
  101. package/dist-lib/lib/core/contract/activity.d.ts +8 -2
  102. package/dist-lib/lib/core/contract/activity.js +39 -11
  103. package/dist-lib/lib/core/contract/agents.js +3 -2
  104. package/dist-lib/lib/core/contract/approval-rules.js +1 -1
  105. package/dist-lib/lib/core/contract/attestations.js +1 -1
  106. package/dist-lib/lib/core/contract/chat-group.js +1 -1
  107. package/dist-lib/lib/core/contract/chat.js +1 -1
  108. package/dist-lib/lib/core/contract/chunks.js +16 -9
  109. package/dist-lib/lib/core/contract/compute.js +2 -1
  110. package/dist-lib/lib/core/contract/devices.js +10 -6
  111. package/dist-lib/lib/core/contract/grant-order.d.ts +5 -0
  112. package/dist-lib/lib/core/contract/grant-order.js +20 -0
  113. package/dist-lib/lib/core/contract/index.d.ts +1 -1
  114. package/dist-lib/lib/core/contract/index.js +27 -2
  115. package/dist-lib/lib/core/contract/indexing.js +3 -3
  116. package/dist-lib/lib/core/contract/invites.d.ts +16 -0
  117. package/dist-lib/lib/core/contract/invites.js +256 -0
  118. package/dist-lib/lib/core/contract/joined-meshes.js +22 -22
  119. package/dist-lib/lib/core/contract/knowledge.js +5 -5
  120. package/dist-lib/lib/core/contract/members.d.ts +15 -0
  121. package/dist-lib/lib/core/contract/members.js +116 -31
  122. package/dist-lib/lib/core/contract/mesh-kind.d.ts +6 -0
  123. package/dist-lib/lib/core/contract/mesh-kind.js +49 -0
  124. package/dist-lib/lib/core/contract/seal.js +1 -1
  125. package/dist-lib/lib/core/contract/seed-defaults.js +1 -3
  126. package/dist-lib/lib/core/contract/tool-activity.js +5 -5
  127. package/dist-lib/lib/core/contract/tool-configs.js +1 -2
  128. package/dist-lib/lib/core/contract/writers.d.ts +13 -0
  129. package/dist-lib/lib/core/contract/writers.js +181 -24
  130. package/dist-lib/lib/core/departures.js +16 -8
  131. package/dist-lib/lib/core/device-attestation.d.ts +5 -0
  132. package/dist-lib/lib/core/device-attestation.js +24 -0
  133. package/dist-lib/lib/core/device-invites.d.ts +2 -0
  134. package/dist-lib/lib/core/device-invites.js +29 -7
  135. package/dist-lib/lib/core/devices.d.ts +2 -1
  136. package/dist-lib/lib/core/devices.js +52 -2
  137. package/dist-lib/lib/core/document-attachment.d.ts +20 -11
  138. package/dist-lib/lib/core/document-attachment.js +10 -5
  139. package/dist-lib/lib/core/files/attachments.d.ts +2 -5
  140. package/dist-lib/lib/core/files/attachments.js +6 -3
  141. package/dist-lib/lib/core/files/index.d.ts +44 -52
  142. package/dist-lib/lib/core/files/index.js +142 -93
  143. package/dist-lib/lib/core/files/knowledge.d.ts +2 -5
  144. package/dist-lib/lib/core/files/local-index.js +9 -5
  145. package/dist-lib/lib/core/files/preview/image.d.ts +0 -1
  146. package/dist-lib/lib/core/files/preview/image.js +9 -6
  147. package/dist-lib/lib/core/files/preview/index.d.ts +8 -11
  148. package/dist-lib/lib/core/files/preview/index.js +20 -15
  149. package/dist-lib/lib/core/files/processing/claims.d.ts +6 -5
  150. package/dist-lib/lib/core/files/processing/claims.js +16 -8
  151. package/dist-lib/lib/core/files/processing/document.d.ts +21 -50
  152. package/dist-lib/lib/core/files/processing/index.d.ts +18 -13
  153. package/dist-lib/lib/core/files/processing/index.js +65 -37
  154. package/dist-lib/lib/core/files/processing/ownership.d.ts +8 -1
  155. package/dist-lib/lib/core/files/processing/ownership.js +1 -1
  156. package/dist-lib/lib/core/files/processing/protocol.d.ts +19 -19
  157. package/dist-lib/lib/core/files/processing/protocol.js +5 -5
  158. package/dist-lib/lib/core/files/processing/settle.d.ts +10 -7
  159. package/dist-lib/lib/core/files/processing/settle.js +22 -11
  160. package/dist-lib/lib/core/files/processing/source.js +14 -8
  161. package/dist-lib/lib/core/files/processing/state.d.ts +13 -11
  162. package/dist-lib/lib/core/files/processing/state.js +19 -12
  163. package/dist-lib/lib/core/files/rag/build.d.ts +2 -2
  164. package/dist-lib/lib/core/files/rag/build.js +2 -1
  165. package/dist-lib/lib/core/files/rag/document-types.d.ts +4 -6
  166. package/dist-lib/lib/core/files/rag/index.d.ts +10 -13
  167. package/dist-lib/lib/core/files/rag/index.js +3 -2
  168. package/dist-lib/lib/core/files/rag/load.d.ts +10 -9
  169. package/dist-lib/lib/core/files/rag/load.js +26 -13
  170. package/dist-lib/lib/core/files/rag/policy.js +2 -1
  171. package/dist-lib/lib/core/files/rag/produce.js +33 -19
  172. package/dist-lib/lib/core/files/rag/retrieval/full-text.d.ts +5 -3
  173. package/dist-lib/lib/core/files/rag/retrieval/full-text.js +30 -10
  174. package/dist-lib/lib/core/files/records/chunks.js +4 -2
  175. package/dist-lib/lib/core/files/records/knowledge.d.ts +10 -11
  176. package/dist-lib/lib/core/files/records/knowledge.js +9 -8
  177. package/dist-lib/lib/core/files/records/linkage.js +6 -3
  178. package/dist-lib/lib/core/files/records/output.d.ts +5 -4
  179. package/dist-lib/lib/core/files/records/output.js +8 -4
  180. package/dist-lib/lib/core/files/records/reclaim.js +41 -25
  181. package/dist-lib/lib/core/files/records/routing.d.ts +4 -6
  182. package/dist-lib/lib/core/files/records/routing.js +15 -8
  183. package/dist-lib/lib/core/files/records/source.d.ts +5 -4
  184. package/dist-lib/lib/core/files/records/source.js +20 -14
  185. package/dist-lib/lib/core/files/records/sweep.js +1 -3
  186. package/dist-lib/lib/core/files/store/blob.d.ts +10 -10
  187. package/dist-lib/lib/core/files/store/blob.js +25 -19
  188. package/dist-lib/lib/core/files/store/index.d.ts +1 -6
  189. package/dist-lib/lib/core/files/store/index.js +4 -4
  190. package/dist-lib/lib/core/files/store/inline.d.ts +2 -2
  191. package/dist-lib/lib/core/files/store/inline.js +6 -3
  192. package/dist-lib/lib/core/files/store/reference.d.ts +6 -9
  193. package/dist-lib/lib/core/files/store/reference.js +25 -17
  194. package/dist-lib/lib/core/files/store/server.d.ts +7 -6
  195. package/dist-lib/lib/core/files/store/server.js +22 -11
  196. package/dist-lib/lib/core/files/store/sweep.js +13 -7
  197. package/dist-lib/lib/core/files/upload-input.d.ts +4 -12
  198. package/dist-lib/lib/core/files/upload-input.js +10 -5
  199. package/dist-lib/lib/core/files/upload.d.ts +27 -24
  200. package/dist-lib/lib/core/files/upload.js +74 -51
  201. package/dist-lib/lib/core/fs-drives.js +4 -2
  202. package/dist-lib/lib/core/grant-expiry.d.ts +11 -0
  203. package/dist-lib/lib/core/grant-expiry.js +66 -0
  204. package/dist-lib/lib/core/handoff-channel.d.ts +2 -1
  205. package/dist-lib/lib/core/handoff-channel.js +36 -15
  206. package/dist-lib/lib/core/harness-loan.js +35 -17
  207. package/dist-lib/lib/core/helpers/index.d.ts +2 -1
  208. package/dist-lib/lib/core/helpers/index.js +11 -6
  209. package/dist-lib/lib/core/hosted-agents.js +19 -12
  210. package/dist-lib/lib/core/id.js +1 -1
  211. package/dist-lib/lib/core/identity.d.ts +1 -0
  212. package/dist-lib/lib/core/identity.js +11 -3
  213. package/dist-lib/lib/core/image/cache-sweep.d.ts +12 -10
  214. package/dist-lib/lib/core/image/cache-sweep.js +11 -6
  215. package/dist-lib/lib/core/image/normalize.d.ts +6 -0
  216. package/dist-lib/lib/core/image/normalize.js +12 -2
  217. package/dist-lib/lib/core/image/sniff.js +42 -21
  218. package/dist-lib/lib/core/inference-calls-receiver.js +7 -4
  219. package/dist-lib/lib/core/invite-grants.d.ts +20 -0
  220. package/dist-lib/lib/core/invite-grants.js +46 -0
  221. package/dist-lib/lib/core/invite.d.ts +3 -0
  222. package/dist-lib/lib/core/invite.js +6 -3
  223. package/dist-lib/lib/core/local/files.js +20 -19
  224. package/dist-lib/lib/core/local/index.d.ts +70 -45
  225. package/dist-lib/lib/core/local/index.js +157 -126
  226. package/dist-lib/lib/core/membership.d.ts +15 -2
  227. package/dist-lib/lib/core/membership.js +95 -20
  228. package/dist-lib/lib/core/mesh-seed-handoff.d.ts +12 -4
  229. package/dist-lib/lib/core/mesh-seed-handoff.js +23 -5
  230. package/dist-lib/lib/core/mesh.d.ts +57 -30
  231. package/dist-lib/lib/core/mesh.js +232 -78
  232. package/dist-lib/lib/core/migrations/agent-catalog.js +3 -2
  233. package/dist-lib/lib/core/migrations/agent-indexes.js +3 -3
  234. package/dist-lib/lib/core/migrations/device-indexes.d.ts +2 -0
  235. package/dist-lib/lib/core/migrations/device-indexes.js +7 -0
  236. package/dist-lib/lib/core/migrations/file-index.js +7 -4
  237. package/dist-lib/lib/core/migrations/index.d.ts +4 -3
  238. package/dist-lib/lib/core/migrations/index.js +3 -1
  239. package/dist-lib/lib/core/migrations/membership.js +9 -4
  240. package/dist-lib/lib/core/migrations/seal.js +3 -2
  241. package/dist-lib/lib/core/min-version.js +4 -2
  242. package/dist-lib/lib/core/next-frame.d.ts +5 -4
  243. package/dist-lib/lib/core/next-frame.js +6 -3
  244. package/dist-lib/lib/core/notification.d.ts +5 -1
  245. package/dist-lib/lib/core/notification.js +89 -77
  246. package/dist-lib/lib/core/ota-config.js +2 -1
  247. package/dist-lib/lib/core/pdf/rasterize.d.ts +18 -0
  248. package/dist-lib/lib/core/pdf/rasterize.js +57 -0
  249. package/dist-lib/lib/core/prompt-history.js +4 -2
  250. package/dist-lib/lib/core/range.d.ts +4 -4
  251. package/dist-lib/lib/core/range.js +12 -6
  252. package/dist-lib/lib/core/rank.d.ts +5 -4
  253. package/dist-lib/lib/core/rank.js +2 -1
  254. package/dist-lib/lib/core/send.d.ts +8 -5
  255. package/dist-lib/lib/core/send.js +9 -3
  256. package/dist-lib/lib/core/skill-overlay-receiver.js +7 -4
  257. package/dist-lib/lib/core/skill-secrets.js +16 -9
  258. package/dist-lib/lib/core/sync/chunks.js +2 -1
  259. package/dist-lib/lib/core/sync/devices.js +3 -1
  260. package/dist-lib/lib/core/sync/files.d.ts +2 -4
  261. package/dist-lib/lib/core/sync/files.js +28 -20
  262. package/dist-lib/lib/core/sync/index.d.ts +2 -5
  263. package/dist-lib/lib/core/sync/index.js +33 -17
  264. package/dist-lib/lib/core/sync-status.js +10 -7
  265. package/dist-lib/lib/core/system-info.js +4 -2
  266. package/dist-lib/lib/core/tool-activity.d.ts +4 -3
  267. package/dist-lib/lib/core/tool-activity.js +1 -1
  268. package/dist-lib/lib/core/tool-configs.js +12 -7
  269. package/dist-lib/lib/core.d.ts +107 -45
  270. package/dist-lib/lib/core.js +1765 -595
  271. package/dist-lib/lib/credential-pusher.d.ts +12 -17
  272. package/dist-lib/lib/credential-pusher.js +61 -42
  273. package/dist-lib/lib/custom-model-pusher.d.ts +7 -3
  274. package/dist-lib/lib/custom-model-pusher.js +15 -7
  275. package/dist-lib/lib/custom-model-task.d.ts +1 -0
  276. package/dist-lib/lib/custom-model-task.js +12 -0
  277. package/dist-lib/lib/deadline.js +4 -2
  278. package/dist-lib/lib/diagnostics.d.ts +1 -5
  279. package/dist-lib/lib/frame-readable.d.ts +3 -0
  280. package/dist-lib/lib/frame-readable.js +3 -0
  281. package/dist-lib/lib/fs-drive-bridge.js +24 -14
  282. package/dist-lib/lib/fs-grants.js +13 -8
  283. package/dist-lib/lib/guards.d.ts +3 -0
  284. package/dist-lib/lib/guards.js +9 -0
  285. package/dist-lib/lib/inference-calls.d.ts +28 -23
  286. package/dist-lib/lib/inference-calls.js +25 -13
  287. package/dist-lib/lib/integrations/mcp-providers.d.ts +2 -2
  288. package/dist-lib/lib/integrations/setup-routes.d.ts +2 -2
  289. package/dist-lib/lib/knowledge-search.d.ts +6 -5
  290. package/dist-lib/lib/knowledge-search.js +26 -18
  291. package/dist-lib/lib/kv-cache-reclaim.js +4 -2
  292. package/dist-lib/lib/kv-cache.js +8 -4
  293. package/dist-lib/lib/legacy-core-domain.d.ts +42 -42
  294. package/dist-lib/lib/log-buffer.js +2 -1
  295. package/dist-lib/lib/log.js +25 -15
  296. package/dist-lib/lib/mesh-scoped-engine.js +14 -4
  297. package/dist-lib/lib/model-catalog-revision.js +6 -3
  298. package/dist-lib/lib/model-clamp.js +6 -3
  299. package/dist-lib/lib/model-context.d.ts +8 -3
  300. package/dist-lib/lib/model-context.js +13 -5
  301. package/dist-lib/lib/model-download-status.js +4 -2
  302. package/dist-lib/lib/model-download.d.ts +12 -4
  303. package/dist-lib/lib/model-download.js +200 -103
  304. package/dist-lib/lib/model-idle-pusher.d.ts +10 -0
  305. package/dist-lib/lib/model-idle-pusher.js +41 -0
  306. package/dist-lib/lib/oauth/browser-connect.d.ts +10 -8
  307. package/dist-lib/lib/oauth/browser-connect.js +33 -20
  308. package/dist-lib/lib/oauth/client.d.ts +2 -2
  309. package/dist-lib/lib/oauth/flow-core.js +23 -9
  310. package/dist-lib/lib/oauth/flow.d.ts +1 -3
  311. package/dist-lib/lib/oauth/flow.js +9 -5
  312. package/dist-lib/lib/oauth/keys.d.ts +4 -4
  313. package/dist-lib/lib/oauth/keys.js +18 -12
  314. package/dist-lib/lib/oauth/loopback.d.ts +2 -2
  315. package/dist-lib/lib/oauth/loopback.js +147 -107
  316. package/dist-lib/lib/oauth/loopback.stub.d.ts +2 -2
  317. package/dist-lib/lib/oauth/loopback.stub.js +1 -1
  318. package/dist-lib/lib/oauth/pkce.d.ts +4 -2
  319. package/dist-lib/lib/oauth/pkce.js +10 -0
  320. package/dist-lib/lib/oauth/providers.js +5 -5
  321. package/dist-lib/lib/oauth/redirect-types.d.ts +12 -7
  322. package/dist-lib/lib/oauth/register.js +3 -2
  323. package/dist-lib/lib/oauth/registry.d.ts +2 -2
  324. package/dist-lib/lib/oauth/registry.js +2 -1
  325. package/dist-lib/lib/oauth/resolve.d.ts +30 -10
  326. package/dist-lib/lib/oauth/resolve.js +12 -6
  327. package/dist-lib/lib/oauth/token-exchange-core.d.ts +12 -4
  328. package/dist-lib/lib/oauth/token-exchange-core.js +1 -1
  329. package/dist-lib/lib/oauth/types.d.ts +12 -12
  330. package/dist-lib/lib/oauth.d.ts +4 -5
  331. package/dist-lib/lib/oauth.js +2 -3
  332. package/dist-lib/lib/reconnecting-watch.d.ts +1 -1
  333. package/dist-lib/lib/reconnecting-watch.js +6 -6
  334. package/dist-lib/lib/retry-budget.js +6 -3
  335. package/dist-lib/lib/run-notices.d.ts +2 -0
  336. package/dist-lib/lib/run-notices.js +7 -3
  337. package/dist-lib/lib/run-transcript.d.ts +2 -4
  338. package/dist-lib/lib/run-transcript.js +4 -2
  339. package/dist-lib/lib/skill-readiness.d.ts +1 -0
  340. package/dist-lib/lib/skill-readiness.js +17 -2
  341. package/dist-lib/lib/skill-types.d.ts +16 -16
  342. package/dist-lib/lib/suspend-lifecycle.d.ts +4 -4
  343. package/dist-lib/lib/suspend-lifecycle.js +10 -5
  344. package/dist-lib/lib/task.d.ts +5 -1
  345. package/dist-lib/lib/task.js +29 -12
  346. package/dist-lib/lib/unref.d.ts +3 -2
  347. package/dist-lib/lib/unref.js +2 -1
  348. package/dist-lib/lib/wav-duration.js +10 -5
  349. package/dist-lib/lib/write-queue.d.ts +5 -4
  350. package/dist-lib/lib/write-queue.js +2 -1
  351. package/dist-lib/schema/build.js +16 -8
  352. package/dist-lib/schema/config.d.ts +3 -4
  353. package/dist-lib/schema/config.js +1 -1
  354. package/dist-lib/schema/content.d.ts +18 -2
  355. package/dist-lib/schema/content.js +4 -1
  356. package/dist-lib/schema/engine.d.ts +3 -2
  357. package/dist-lib/schema/engine.js +192 -12
  358. package/dist-lib/schema/field-order.js +22 -11
  359. package/dist-lib/schema/indexes.d.ts +22 -0
  360. package/dist-lib/schema/{helpers.js → indexes.js} +19 -57
  361. package/dist-lib/schema/local.d.ts +3 -2
  362. package/dist-lib/schema/local.js +9 -3
  363. package/dist-lib/schema/media-kind.d.ts +8 -0
  364. package/dist-lib/schema/media-kind.js +52 -0
  365. package/dist-lib/schema/qvac.d.ts +12 -9
  366. package/dist-lib/schema/qvac.js +132 -7
  367. package/dist-lib/spec/bind.js +21 -0
  368. package/dist-lib/spec/calls.js +7 -0
  369. package/dist-lib/spec/capabilities.d.ts +18 -4
  370. package/dist-lib/spec/config/hyperconf/index.js +1 -1
  371. package/dist-lib/spec/hrpc/hrpc.json +93 -2
  372. package/dist-lib/spec/hrpc/index.js +89 -5
  373. package/dist-lib/spec/hrpc/messages.js +1568 -941
  374. package/dist-lib/spec/hyperschema/index.js +1568 -941
  375. package/dist-lib/spec/hyperschema/schema.json +531 -1
  376. package/dist-lib/spec/hyperschema/types.d.ts +145 -1
  377. package/dist-lib/spec/local/hyperdb/index.js +1 -1
  378. package/dist-lib/spec/local/hyperdb/messages.js +92 -20
  379. package/dist-lib/spec/local/hyperschema/index.js +47 -11
  380. package/dist-lib/spec/local/hyperschema/schema.json +32 -1
  381. package/dist-lib/spec/local/hyperschema/types.d.ts +7 -1
  382. package/dist-lib/spec/mesh/hyperdb/db.json +131 -3
  383. package/dist-lib/spec/mesh/hyperdb/index.js +548 -5
  384. package/dist-lib/spec/mesh/hyperdb/messages.js +2444 -893
  385. package/dist-lib/spec/mesh/hyperdispatch/dispatch.json +37 -1
  386. package/dist-lib/spec/mesh/hyperdispatch/index.js +104 -2
  387. package/dist-lib/spec/mesh/hyperdispatch/messages.js +1035 -11
  388. package/dist-lib/spec/mesh/hyperschema/index.js +1035 -11
  389. package/dist-lib/spec/mesh/hyperschema/schema.json +553 -1
  390. package/dist-lib/spec/mesh/hyperschema/types.d.ts +143 -1
  391. package/package.json +11 -5
  392. package/tui/app.mjs +2624 -986
  393. package/tui/boot.mjs +17 -46
  394. package/tui/index.mjs +10 -5
  395. package/tui/lib/boot-timing.mjs +8 -8
  396. package/tui/lib/busy-words.mjs +21 -22
  397. package/tui/lib/export.mjs +100 -32
  398. package/tui/lib/knowledge-command.mjs +64 -19
  399. package/tui/lib/knowledge-import.mjs +52 -18
  400. package/tui/lib/render.mjs +65 -33
  401. package/tui/lib/save-file.mjs +30 -13
  402. package/tui/lib/select.mjs +23 -5
  403. package/tui/lib/selection.mjs +6 -4
  404. package/tui/lib/setup.mjs +11 -19
  405. package/tui/lib/sidebar.mjs +23 -13
  406. package/tui/lib/splash.mjs +6 -7
  407. package/tui/lib/upload-frames.mjs +1 -2
  408. package/tui/lib/usage.mjs +13 -9
  409. package/tui/lib/wrap.mjs +35 -6
  410. package/tui/main.mjs +54 -78
  411. package/worker/assistant-sidecar.mjs +5 -10
  412. package/worker/stow-entry.mjs +7 -4
  413. package/dist-lib/lib/custom-model-source.d.ts +0 -15
  414. package/dist-lib/lib/custom-model-source.js +0 -46
  415. package/dist-lib/lib/oauth/common.d.ts +0 -38
  416. package/dist-lib/lib/oauth/common.js +0 -34
  417. package/dist-lib/schema/helpers.d.ts +0 -32
@@ -1,4 +1,5 @@
1
1
  import b4a from 'b4a';
2
+ import crypto from 'hypercore-crypto';
2
3
  import BlindPeering from 'blind-peering';
3
4
  import Corestore from 'corestore';
4
5
  import CorestoreStorage from 'hypercore-storage';
@@ -21,31 +22,36 @@ import { sweepDriveStaging } from './fs-drive-bridge.js';
21
22
  import { closeCollaboraWorker } from './collabora/worker.js';
22
23
  import { decodeMeshInvite, encodeMeshInvite } from './core/invite.js';
23
24
  import { fileKeyOf, knownFile, referencedFile } from './core/files/local-index.js';
25
+ import { grantKeyPair, inviteGrantTermsRefusal } from './core/invite-grants.js';
26
+ import { belongsToAnotherMember, inviteStanding, memberStanding } from './core/contract/invites.js';
27
+ import { syncStatusSnapshot } from './core/sync-status.js';
24
28
  import { openLocalStore } from './core/local/index.js';
25
- import { getAgent, ownDefaultAgents } from './core/agent.js';
29
+ import { getAgent } from './core/agent.js';
26
30
  import { countContents, migrateContents, withArchivedMesh } from './core/archived-mesh.js';
27
31
  import { HostedAgents } from './core/hosted-agents.js';
28
32
  import { HarnessLoan } from './core/harness-loan.js';
29
33
  import { duplexPair } from '@qvac/harness/transport';
30
- import { MeshSeedHandoff } from './core/mesh-seed-handoff.js';
34
+ import { signMemberWriterClaim, signWriterClaim, verifyMemberWriterClaim, verifyWriterClaim } from './core/device-attestation.js';
35
+ import { HOST_SILENT, HOST_UNREACHABLE } from './core/handoff-channel.js';
36
+ import { MeshSeedHandoff, SEED_REFUSED, SEED_ASKER_UNSEEN } from './core/mesh-seed-handoff.js';
31
37
  import { SecretHandoff } from './core/secret-handoff.js';
32
38
  import { InferenceCallsHandoff } from './core/inference-calls-handoff.js';
33
39
  import { createInferenceCallsReceiver, NO_RECORD_STORE } from './core/inference-calls-receiver.js';
34
40
  import { SkillOverlayHandoff } from './core/skill-overlay-handoff.js';
35
41
  import { createSkillOverlayReceiver } from './core/skill-overlay-receiver.js';
36
42
  import { createSkillSecretReceiver, HOST_REVOKED, NO_SUCH_AGENT, NOT_THE_HOST } from './core/skill-secrets.js';
37
- import { attestMemberClaim, claimAttestation, openIdentity } from './core/identity.js';
43
+ import { attestMemberClaim, claimAttestation, deviceInviteToken, openIdentity } from './core/identity.js';
38
44
  import { openRecoveryCore, publishRecovery, readRecovery, recoveryKeys } from './core/account-recovery.js';
39
- import { attestUnattestedDevices, claimOwnMembership, legacyNameStamp, namedAt, renameFoundedMember } from './core/membership.js';
40
- import { openDeviceInvites } from './core/device-invites.js';
45
+ import { admitInvitedDevice, attestUnattestedDevices, claimOwnMembership, legacyNameStamp, namedAt, renameFoundedMember, sealAccount } from './core/membership.js';
46
+ import { DEVICE_INVITE_SPENT, openDeviceInvites } from './core/device-invites.js';
41
47
  import { runMigrations } from './core/migrations/index.js';
42
48
  import { backfillFileIndex } from './core/migrations/file-index.js';
43
- import { advertiseDeviceVersion } from './core/devices.js';
49
+ import { advertiseDeviceVersion, retractInventory } from './core/devices.js';
44
50
  import { OtaConfigReader, configCoreFor, resolveConfigChannel, vendoredMinSupportedVersion } from './core/ota-config.js';
45
51
  import { updateRequired } from './core/min-version.js';
46
52
  import { PendingDepartures } from './core/departures.js';
47
- import { buildDefaultSeed } from './core/helpers/index.js';
48
- import { Mesh } from './core/mesh.js';
53
+ import { isKickedRow } from './core/helpers/index.js';
54
+ import { Mesh, claimableDevice, meshPublicKeyFromSeed } from './core/mesh.js';
49
55
  import { raceResource } from './race-resource.js';
50
56
  import { createSystemInfoSampler } from './core/system-info.js';
51
57
  import { setLogger } from './logger.js';
@@ -53,32 +59,55 @@ import { settleOnClose } from '@qvac/harness/rpc';
53
59
  import { openLocalSpec } from './spec-loader.js';
54
60
  import { unref } from './unref.js';
55
61
  import { local } from '../spec/index.js';
62
+ import { isRecord } from './guards.js';
63
+ import { CHUNKS, DEVICES, JOINED_MESHES, MEMBERS, MESH_BLIND_PEERS, MESH_INVITE_GRANTS, MESH_INVITE_SPENDS, MESH_KINDS } from './core/collections.js';
56
64
  const QvacState = local.getEnum('@local/qvac-state');
57
65
  const top = new Top();
58
66
  const FILE_GC_INTERVAL_MS = 24 * 60 * 60 * 1000;
59
67
  const SWARM_KEYPAIR_NAME = 'qvac-swarm-keypair';
60
68
  const QVAC_CORE_NAMESPACE = 'qvac-core';
61
69
  const MESH_JOIN_CANCELED = 'Mesh join canceled';
70
+ const GRANT_JOIN_TIMED_OUT = 'Join did not complete in time - the invite may already be spent, expired or revoked';
62
71
  const MESH_ID = /^[0-9a-f]{64}$/;
63
72
  const MESH_BELOW_FLOOR = 'Build is below the mesh floor';
64
73
  const LEAVE_HOME_REFUSED = 'Your account cannot be left while other meshes remain';
65
- const ROOM_WITHOUT_ACCOUNT = 'A room needs an account mesh to be recorded in';
74
+ const MESH_WITHOUT_ACCOUNT = 'Recording a mesh needs the account mesh';
75
+ export const ACCOUNT_MEMBER_UNKNOWN = 'This device is not part of its account yet';
76
+ export const AWAITING_ADMISSION = 'awaiting-admission';
77
+ const MESH_WITHOUT_MEMBER = 'A mesh needs this device to belong to its account member';
66
78
  const NO_WRITABLE_ACCOUNT = 'The account mesh is not writable';
67
79
  const NOT_AN_ARCHIVED_ACCOUNT = 'Not an account this device left';
68
80
  const NO_ACCOUNT_TO_RECOVER = 'This device has no account to make recoverable';
69
81
  const PHRASE_NOT_OURS = 'The phrase does not derive the identity this device holds';
82
+ const PHRASE_NOT_A_MEMBER = "The phrase names no member of this account, so it could not recover it: publish from a device holding the account's phrase";
70
83
  const NO_RECOVERY_RECORD = 'No recovery record was found for this phrase';
84
+ const RECOVERY_DEVICE_REMOVED = 'This device was removed from the account, so it cannot recover it: wipe it and recover as a new device';
71
85
  const RECOVERY_WAIT_MS = 30_000;
72
86
  export const MEMBER_INVITE_HOME_REFUSED = 'An account mesh cannot be invited into';
73
- export const DEVICE_INVITE_ROOM_REFUSED = 'Only an account mesh can take a device invite';
87
+ export const DEVICE_INVITE_MESH_REFUSED = 'Only an account mesh can take a device invite';
74
88
  export const INVITE_ACCOUNT_UNREADABLE = 'This device cannot reach its account to check';
75
- export const ROOM_HELD_BY_SIBLING = 'Another of your devices holds this room: bring that device online, or invite from it instead';
76
- const ROOM_NOT_EMPTY = 'this room is not empty: everyone in it will see the newcomer arrive, and the newcomer replays the whole history of the room, including what earlier members wrote';
77
- const JOINED_MESHES = '@qvac/joined-meshes';
89
+ export const MESH_HELD_BY_SIBLING = 'Another of your devices holds this mesh: bring that device online, or invite from it instead';
90
+ export const INVITE_GRANT_REVOKED = 'This invite was revoked';
91
+ export const MESH_ALREADY_JOINED = 'This device is already in this mesh';
92
+ export const MESH_ADMISSION_PENDING = 'This mesh has not admitted this device yet: try again in a moment';
93
+ export const MEMBER_ALREADY_IN_MESH = 'Another of your devices is already in this mesh: join through it once it is online';
94
+ export const DEVICE_OF_ANOTHER_MEMBER = 'This device belongs to another member in this mesh';
95
+ export const MEMBER_REMOVED_SINCE_INVITE = 'You were removed from this mesh after this invite was made: ask for a new one';
96
+ export const INVITE_GRANT_EXPIRED = 'This invite has expired';
97
+ export const INVITE_GRANT_EXHAUSTED = 'This invite has already been used';
98
+ export const SEALED_ACCOUNT_READER = 'This account admits no device by its seed alone: pair this device with a device invite';
99
+ export const INVITER_OFFLINE = 'The device that made this invite is not online: bring it online and try again';
100
+ const MESH_NOT_EMPTY = 'this mesh is not empty: everyone in it will see the newcomer arrive, and the newcomer replays the whole history of the mesh, including what earlier members wrote';
101
+ const UNANSWERED_SEED_REQUESTS = new Set([HOST_SILENT, SEED_ASKER_UNSEEN]);
78
102
  const INVITE_DHT_NODES_LIMIT = 3;
79
103
  const INVITE_BLIND_PEERS_LIMIT = 3;
104
+ const GRANT_DEFAULT_MAX_USES = 1;
105
+ const GRANT_DEFAULT_TTL_MS = 48 * 60 * 60 * 1000;
106
+ const GRANT_VISIBLE_MS = 10_000;
80
107
  const DIAGNOSTICS_SAMPLE_MS = 2000;
81
108
  const ACCOUNT_WRITABLE_MS = 15_000;
109
+ const GRANT_WRITABLE_MS = 60_000;
110
+ const INVITER_RETRY_MS = 1_000;
82
111
  export class Core extends ReadyResource {
83
112
  _storagePath;
84
113
  store;
@@ -119,6 +148,8 @@ export class Core extends ReadyResource {
119
148
  _modelCatalogWatchSource = new ReadyGuard();
120
149
  _retryModelDownload;
121
150
  _transcribe;
151
+ _detectLanguage;
152
+ _previewModelSource;
122
153
  _speak;
123
154
  _speakStream;
124
155
  _embedder;
@@ -128,6 +159,8 @@ export class Core extends ReadyResource {
128
159
  _meshTransitionLock = new ScopeLock();
129
160
  _opening = new Map();
130
161
  _retiring = new Map();
162
+ _debugBeforeMeshOpen;
163
+ _debugOnMeshOpened;
131
164
  _skills;
132
165
  _skillCatalog;
133
166
  _skillManagement;
@@ -161,7 +194,11 @@ export class Core extends ReadyResource {
161
194
  _meshSeedHandoff;
162
195
  _harnessLoan;
163
196
  _serveLoanedHarness = null;
164
- _following = new Set();
197
+ _following = new Map();
198
+ _revokingInMeshes = null;
199
+ _revokeInMeshesAgain = false;
200
+ _sweepUnknownEverywhere = false;
201
+ _sweepUnknownIn = new Set();
165
202
  _secretHandoff;
166
203
  _skillOverlayHandoff;
167
204
  _inferenceCallsHandoff;
@@ -174,10 +211,11 @@ export class Core extends ReadyResource {
174
211
  _listing;
175
212
  _diagnosticsProviders;
176
213
  _inferenceCalls = null;
214
+ _modelResidency = null;
177
215
  _systemInfo;
178
216
  _statusError;
179
217
  _upgradeRequired;
180
- constructor(transport, { storagePath, logger = null, spec = openLocalSpec, bootstrapNodes = undefined, device = undefined, app = undefined, minSupportedVersion = undefined, otaConfigCore = undefined, blindPeerKeys = undefined, blindPeeringOpts = undefined, fileGc = null, meshSeed = undefined, meshKey = undefined, additionalNodes = undefined, listModels = undefined, deleteModel = undefined, clearKvCache = undefined, deleteChatKvCache = undefined, compactChat = undefined, modelCatalogWatch = undefined, retryModelDownload = undefined, transcribe = undefined, speak = undefined, speakStream = undefined, embedder = undefined, extractors = undefined, skills = undefined, skillCatalog = undefined, tools = undefined, hostsModelSource = false, vectorIndex = undefined, apiLifecycle = undefined }) {
218
+ constructor(transport, { storagePath, logger = null, spec = openLocalSpec, bootstrapNodes = undefined, device = undefined, app = undefined, minSupportedVersion = undefined, otaConfigCore = undefined, blindPeerKeys = undefined, blindPeeringOpts = undefined, fileGc = null, meshSeed = undefined, meshKey = undefined, additionalNodes = undefined, listModels = undefined, deleteModel = undefined, clearKvCache = undefined, deleteChatKvCache = undefined, compactChat = undefined, modelCatalogWatch = undefined, retryModelDownload = undefined, transcribe = undefined, detectLanguage = undefined, previewModelSource = undefined, speak = undefined, speakStream = undefined, embedder = undefined, extractors = undefined, skills = undefined, skillCatalog = undefined, tools = undefined, hostsModelSource = false, vectorIndex = undefined, apiLifecycle = undefined }) {
181
219
  super();
182
220
  this._transport = transport;
183
221
  this._apiLifecycle = apiLifecycle ?? {
@@ -185,8 +223,9 @@ export class Core extends ReadyResource {
185
223
  resume: () => this.resume()
186
224
  };
187
225
  this._log = logger;
188
- if (logger)
226
+ if (logger) {
189
227
  setLogger(logger);
228
+ }
190
229
  this._storagePath = storagePath;
191
230
  this.storage = new CorestoreStorage(this._storagePath, {
192
231
  blobGarbageCollectionAgeCutOff: 1.0,
@@ -208,8 +247,9 @@ export class Core extends ReadyResource {
208
247
  const channel = resolveConfigChannel(app?.channel);
209
248
  const lane = channel ? configCoreFor(channel) : null;
210
249
  this._otaConfigCore = minSupportedVersion ? null : (otaConfigCore ?? lane);
211
- if (!minSupportedVersion)
250
+ if (!minSupportedVersion) {
212
251
  this._minSupportedVersion = vendoredMinSupportedVersion();
252
+ }
213
253
  this._localDevice = null;
214
254
  this._blindPeerKeys = blindPeerKeys;
215
255
  this._blindPeeringOpts = blindPeeringOpts;
@@ -227,6 +267,8 @@ export class Core extends ReadyResource {
227
267
  void this._modelCatalogWatchSource.ready().catch(noop);
228
268
  this._retryModelDownload = retryModelDownload ?? null;
229
269
  this._transcribe = transcribe ?? null;
270
+ this._detectLanguage = detectLanguage ?? null;
271
+ this._previewModelSource = previewModelSource ?? null;
230
272
  this._speak = speak ?? null;
231
273
  this._speakStream = speakStream ?? null;
232
274
  this._embedder = embedder ?? null;
@@ -239,17 +281,18 @@ export class Core extends ReadyResource {
239
281
  this._openCatalogHooks();
240
282
  void this._catalogHooks.ready().catch(noop);
241
283
  this._spareVectorIndex = vectorIndex ?? (embedder ? new MemoryVectorIndex() : null);
242
- this._closeSignal = new Promise((resolve) => {
243
- this._signalClose = resolve;
244
- });
284
+ const closeSignal = Promise.withResolvers();
285
+ this._closeSignal = closeSignal.promise;
286
+ this._signalClose = closeSignal.resolve;
245
287
  this._closeListeners = new Set();
246
288
  this._closeSignaled = false;
247
289
  void this._closeSignal.then(() => {
248
290
  this._closeSignaled = true;
249
291
  const listeners = [...this._closeListeners];
250
292
  this._closeListeners.clear();
251
- for (const listener of listeners)
293
+ for (const listener of listeners) {
252
294
  listener();
295
+ }
253
296
  });
254
297
  this._meshes = new Map();
255
298
  this._accountId = null;
@@ -291,6 +334,12 @@ export class Core extends ReadyResource {
291
334
  get devicePublicKey() {
292
335
  return this._deviceKeyPair?.publicKey ?? null;
293
336
  }
337
+ _requireDeviceKeyPair() {
338
+ if (!this._deviceKeyPair) {
339
+ throw new Error('device key pair read before the offline boot');
340
+ }
341
+ return this._deviceKeyPair;
342
+ }
294
343
  get fsDrives() {
295
344
  return this._fsDrives;
296
345
  }
@@ -320,10 +369,10 @@ export class Core extends ReadyResource {
320
369
  try {
321
370
  this._deviceKeyPair = await this.store.createKeyPair(SWARM_KEYPAIR_NAME);
322
371
  this._identityPublicKey = (await this.local.readIdentity())?.publicKey ?? null;
323
- this._localDevice = await this.local.ensureDevice(this.devicePublicKey, this._device);
324
- this._openSwarm(this._deviceKeyPair);
372
+ this._localDevice = await this.local.ensureDevice(this._deviceKeyPair.publicKey, this._device);
373
+ const swarm = this._openSwarm(this._deviceKeyPair);
325
374
  this._departures = new PendingDepartures(this.store, this.local, {
326
- swarm: this._swarm,
375
+ swarm,
327
376
  isPooled: (key) => this._pooled(b4a.toHex(key)) !== null,
328
377
  logger: this._log,
329
378
  blindPeerKeys: this._resolveBlindPeerKeys(),
@@ -331,7 +380,7 @@ export class Core extends ReadyResource {
331
380
  wakeup: this._wakeup
332
381
  });
333
382
  this._fsDrives = createFsDriveHost(this.store, {
334
- swarm: this._swarm,
383
+ swarm,
335
384
  blindPeerKeys: this._resolveBlindPeerKeys(),
336
385
  blindPeeringOpts: this._blindPeeringOpts
337
386
  });
@@ -370,6 +419,14 @@ export class Core extends ReadyResource {
370
419
  ? (options) => this._deleteModel?.(options) ??
371
420
  Promise.resolve({ name: options.name, removed: 0, freedBytes: 0 })
372
421
  : null,
422
+ loadModel: this._hostsModelSource
423
+ ? ({ name }) => this._modelResidency?.load(name) ??
424
+ Promise.reject(new Error('no model runtime is bound'))
425
+ : null,
426
+ unloadModel: this._hostsModelSource
427
+ ? ({ name }) => this._modelResidency?.unload(name) ??
428
+ Promise.reject(new Error('no model runtime is bound'))
429
+ : null,
373
430
  clearKvCache: () => this._clearKvCache?.() ??
374
431
  Promise.resolve({
375
432
  status: 'unsupported',
@@ -393,6 +450,12 @@ export class Core extends ReadyResource {
393
450
  ? (request) => this._transcribe?.(request) ??
394
451
  Promise.reject(new Error('no transcription source bound'))
395
452
  : null,
453
+ detectLanguage: this._hostsModelSource || this._detectLanguage
454
+ ? (request) => this._detectLanguage?.(request) ??
455
+ Promise.reject(new Error('no language detector bound'))
456
+ : null,
457
+ previewModelSource: (request) => this._previewModelSource?.(request) ??
458
+ Promise.reject(new Error('no model source preview bound')),
396
459
  speak: this._hostsModelSource || this._speak
397
460
  ? (request) => this._speak?.(request) ?? Promise.reject(new Error('no tts source bound'))
398
461
  : null,
@@ -413,7 +476,8 @@ export class Core extends ReadyResource {
413
476
  recommendedModelName: this._localDevice.recommendedModelName,
414
477
  platform: this._localDevice.platform
415
478
  }
416
- : null
479
+ : null,
480
+ isAccount: (mesh) => this._isAccount(mesh)
417
481
  },
418
482
  skills: this._hostsModelSource || this._skills
419
483
  ? (agentId, modelName, options) => this._skills?.(agentId, modelName, options) ?? Promise.resolve([])
@@ -484,8 +548,9 @@ export class Core extends ReadyResource {
484
548
  logger.info('core', 'closing local');
485
549
  await this.local?.close();
486
550
  logger.info('core', 'closing mesh');
487
- for (const { mesh } of this._meshes.values())
551
+ for (const { mesh } of this._meshes.values()) {
488
552
  await mesh.close();
553
+ }
489
554
  logger.info('core', 'closing storage');
490
555
  await this.store?.close();
491
556
  await this.rootCorestore?.close();
@@ -496,8 +561,9 @@ export class Core extends ReadyResource {
496
561
  }
497
562
  }
498
563
  async _openBootMesh() {
499
- if (this._blockedByMinVersion() || this._accountMesh() || this._minting)
564
+ if (this._blockedByMinVersion() || this._accountMesh() || this._minting) {
500
565
  return;
566
+ }
501
567
  try {
502
568
  const mesh = await this._switchToMesh({
503
569
  seed: this._meshSeed,
@@ -506,8 +572,9 @@ export class Core extends ReadyResource {
506
572
  });
507
573
  }
508
574
  catch (err) {
509
- if (this.closing)
575
+ if (this.closing) {
510
576
  return;
577
+ }
511
578
  if (!this._upgradeRequired) {
512
579
  this._statusError = statusErrorMessage('opening the local database failed', err);
513
580
  }
@@ -519,36 +586,44 @@ export class Core extends ReadyResource {
519
586
  void this.onlineBoot.ready().catch(noop);
520
587
  try {
521
588
  await this._offlineBoot.ready();
522
- if (this.closing)
589
+ if (this.closing) {
523
590
  return;
591
+ }
524
592
  const mesh = this._accountMesh();
525
- if (mesh)
593
+ if (mesh) {
526
594
  this._bringMeshOnline(mesh);
595
+ }
527
596
  }
528
597
  catch (err) {
529
- if (this.closing)
598
+ if (this.closing) {
530
599
  return;
600
+ }
531
601
  this._log?.error(['p2p', 'mesh'], 'online boot failed', err);
532
602
  }
533
603
  finally {
534
- if (!this.closing && !this._offlineBoot.destroyed)
604
+ if (!this.closing && !this._offlineBoot.destroyed) {
535
605
  this._peerConfigCore();
536
- if (!this.closing)
606
+ }
607
+ if (!this.closing) {
537
608
  this._departures?.flush();
538
- if (!this.closing)
609
+ }
610
+ if (!this.closing) {
539
611
  this._startFileGc({ now: true });
612
+ }
540
613
  this.onlineBoot.exit();
541
614
  }
542
615
  }
543
616
  async _reopenMesh() {
544
617
  try {
545
- if (this.closing || this._accountMesh() || this._minting)
618
+ if (this.closing || this._accountMesh() || this._minting) {
546
619
  return;
620
+ }
547
621
  await this._startMesh({ seed: this._meshSeed, baseKey: this._meshKey, account: true });
548
622
  }
549
623
  catch (err) {
550
- if (this.closing)
624
+ if (this.closing) {
551
625
  return;
626
+ }
552
627
  if (!this._upgradeRequired) {
553
628
  this._statusError = statusErrorMessage('reopening the local database failed', err);
554
629
  }
@@ -568,8 +643,9 @@ export class Core extends ReadyResource {
568
643
  });
569
644
  return;
570
645
  }
571
- if (this._otaConfig || this.closing)
646
+ if (this._otaConfig || this.closing) {
572
647
  return;
648
+ }
573
649
  const config = new OtaConfigReader(this.store, core);
574
650
  this._otaConfig = config;
575
651
  try {
@@ -579,8 +655,9 @@ export class Core extends ReadyResource {
579
655
  return;
580
656
  }
581
657
  await config.ready();
582
- if (this.closing)
658
+ if (this.closing) {
583
659
  return;
660
+ }
584
661
  config.on('update', () => {
585
662
  this._logFloor(config, 'updated');
586
663
  this.setMinSupportedVersion(config.minSupportedVersion);
@@ -608,11 +685,13 @@ export class Core extends ReadyResource {
608
685
  }
609
686
  _peerConfigCore() {
610
687
  const config = this._otaConfig;
611
- if (!config || this._configPeering || this._accountMesh() || !this._swarm)
688
+ if (!config || this._configPeering || this._accountMesh() || !this._swarm) {
612
689
  return;
690
+ }
613
691
  const keys = this._resolveBlindPeerKeys();
614
- if (keys.length === 0)
692
+ if (keys.length === 0) {
615
693
  return;
694
+ }
616
695
  this._configPeering = new BlindPeering(this._swarm.dht, this.store, {
617
696
  pick: keys.length,
618
697
  ...this._blindPeeringOpts
@@ -622,8 +701,9 @@ export class Core extends ReadyResource {
622
701
  }
623
702
  async _closeConfigPeering() {
624
703
  const peering = this._configPeering;
625
- if (!peering)
704
+ if (!peering) {
626
705
  return;
706
+ }
627
707
  this._configPeering = null;
628
708
  await peering.close();
629
709
  }
@@ -636,12 +716,14 @@ export class Core extends ReadyResource {
636
716
  const range = this._minSupportedVersion;
637
717
  const appVersion = this._app?.version;
638
718
  if (!updateRequired({ range, appVersion })) {
639
- if (this._upgradeRequired === 'floor')
719
+ if (this._upgradeRequired === 'floor') {
640
720
  this._setUpgradeRequired(null);
721
+ }
641
722
  return false;
642
723
  }
643
- if (this._upgradeRequired)
724
+ if (this._upgradeRequired) {
644
725
  return true;
726
+ }
645
727
  this._log?.error(['p2p', 'mesh'], 'mesh requires a newer build - not opening', {
646
728
  range,
647
729
  appVersion
@@ -657,15 +739,18 @@ export class Core extends ReadyResource {
657
739
  }
658
740
  setMinSupportedVersion(required) {
659
741
  const next = required || undefined;
660
- if (this._minSupportedVersion === next)
742
+ if (this._minSupportedVersion === next) {
661
743
  return;
744
+ }
662
745
  this._minSupportedVersion = next;
663
- if (this.closing)
746
+ if (this.closing) {
664
747
  return;
748
+ }
665
749
  const withheld = this._upgradeRequired === 'floor';
666
750
  if (!this._blockedByMinVersion()) {
667
- if (withheld)
751
+ if (withheld) {
668
752
  void this._reopenMesh();
753
+ }
669
754
  return;
670
755
  }
671
756
  for (const { mesh } of [...this._meshes.values()]) {
@@ -678,8 +763,9 @@ export class Core extends ReadyResource {
678
763
  async connect(stream) {
679
764
  if (!this.opened)
680
765
  await this.ready();
681
- if (this.closing || !this._api)
766
+ if (this.closing || !this._api) {
682
767
  throw new Error('core is closing');
768
+ }
683
769
  const { bindApi, HRPC } = await this._spec();
684
770
  const rpc = settleOnClose(new HRPC(stream));
685
771
  bindApi(rpc, this._api);
@@ -696,8 +782,9 @@ export class Core extends ReadyResource {
696
782
  return;
697
783
  this.state = QvacState.WAKEUP;
698
784
  logger.info('core', 'wakeup');
699
- if (!this.opened)
785
+ if (!this.opened) {
700
786
  await this.ready();
787
+ }
701
788
  await this.resume();
702
789
  }
703
790
  async presuspend() {
@@ -705,66 +792,86 @@ export class Core extends ReadyResource {
705
792
  return;
706
793
  this.state = QvacState.PRESUSPEND;
707
794
  logger.info('core', 'presuspend');
708
- if (!this.opened)
795
+ if (!this.opened) {
709
796
  await this.ready();
797
+ }
710
798
  }
711
799
  async suspend() {
712
800
  logger.info('core', 'suspend called');
713
- if (this.state === QvacState.SUSPEND)
801
+ if (this.state === QvacState.SUSPEND) {
714
802
  return;
715
- if (this.closing)
803
+ }
804
+ if (this.closing) {
716
805
  return;
806
+ }
717
807
  this.state = QvacState.SUSPEND;
718
- if (!this.opened)
808
+ if (!this.opened) {
719
809
  await this.ready();
810
+ }
720
811
  logger.info('core', 'suspending');
721
812
  await this._stopFileGc();
722
- for (const { mesh } of this._meshes.values())
813
+ for (const { mesh } of this._meshes.values()) {
723
814
  await mesh.suspend();
724
- if (this._departures)
815
+ }
816
+ if (this._departures) {
725
817
  await this._departures.suspend();
726
- if (this._configPeering)
818
+ }
819
+ if (this._configPeering) {
727
820
  await this._configPeering.suspend();
728
- if (this._recoveryPeering)
821
+ }
822
+ if (this._recoveryPeering) {
729
823
  await this._recoveryPeering.suspend();
730
- if (this._swarm)
824
+ }
825
+ if (this._swarm) {
731
826
  await this._swarm.suspend();
732
- if (this._blobServer)
827
+ }
828
+ if (this._blobServer) {
733
829
  await this._blobServer.suspend();
830
+ }
734
831
  await this.store.suspend();
735
832
  this._log?.info('lifecycle', 'core suspend');
736
833
  }
737
834
  async resume() {
738
835
  logger.info('core', 'resume called');
739
- if (this.state === QvacState.RESUME)
836
+ if (this.state === QvacState.RESUME) {
740
837
  return;
741
- if (this.closing)
838
+ }
839
+ if (this.closing) {
742
840
  return;
841
+ }
743
842
  if (this.state === QvacState.PRESUSPEND) {
744
843
  this.state = QvacState.RESUME;
745
844
  return;
746
845
  }
747
846
  this.state = QvacState.RESUME;
748
- if (!this.opened)
847
+ if (!this.opened) {
749
848
  await this.ready();
849
+ }
750
850
  logger.info('core', 'resuming');
751
851
  await this.store.resume();
752
- if (this._blobServer)
852
+ if (this._blobServer) {
753
853
  await this._blobServer.resume();
754
- if (this._swarm)
854
+ }
855
+ if (this._swarm) {
755
856
  await this._swarm.resume();
756
- if (this._configPeering)
857
+ }
858
+ if (this._configPeering) {
757
859
  await this._configPeering.resume();
758
- if (this._recoveryPeering)
860
+ }
861
+ if (this._recoveryPeering) {
759
862
  await this._recoveryPeering.resume();
760
- for (const { mesh } of this._meshes.values())
863
+ }
864
+ for (const { mesh } of this._meshes.values()) {
761
865
  await mesh.resume();
762
- if (this._departures)
866
+ }
867
+ if (this._departures) {
763
868
  await this._departures.resume();
869
+ }
764
870
  this._departures?.flush();
765
871
  this._startFileGc();
766
- if (this._swarm)
872
+ if (this._swarm) {
767
873
  void this._refreshTopics(this._swarm).catch(noop);
874
+ }
768
875
  void this._pushIdentityPhrase();
769
876
  this._log?.info('lifecycle', 'core resume');
770
877
  }
@@ -776,8 +883,9 @@ export class Core extends ReadyResource {
776
883
  }
777
884
  async _close() {
778
885
  logger.info('core', 'closing');
779
- if (this.state === QvacState.SUSPEND)
886
+ if (this.state === QvacState.SUSPEND) {
780
887
  await this.store.resume();
888
+ }
781
889
  this._catalogHooks.destroy(new Error('core is closing'));
782
890
  this._modelCatalogWatchSource.destroy(new Error('core is closing'));
783
891
  this._offlineBoot.destroy(new Error('core is closing'));
@@ -785,13 +893,16 @@ export class Core extends ReadyResource {
785
893
  this._signalClose();
786
894
  this._notifyStatus();
787
895
  await this._stopFileGc();
788
- if (this._stream)
896
+ if (this._stream) {
789
897
  this._stream.destroy();
790
- for (const client of this._clients)
898
+ }
899
+ for (const client of this._clients) {
791
900
  client.destroy();
901
+ }
792
902
  this._clients.clear();
793
- for (const entry of this._meshes.values())
903
+ for (const entry of this._meshes.values()) {
794
904
  await this._stopHostedAgents(entry);
905
+ }
795
906
  await this._stopIndexing();
796
907
  closeCollaboraWorker();
797
908
  await this._blobServer?.close();
@@ -831,16 +942,20 @@ export class Core extends ReadyResource {
831
942
  this._log?.info(['p2p', 'swarm'], 'swarm created', {
832
943
  deviceKey: b4a.toHex(keyPair.publicKey).slice(0, 8)
833
944
  });
834
- for (const node of this._additionalNodes ?? [])
945
+ for (const node of this._additionalNodes ?? []) {
835
946
  this._swarm.dht.addNode(node);
947
+ }
948
+ return this._swarm;
836
949
  }
837
950
  _resolveBlindPeerKeys(extra = []) {
838
951
  const defaults = this._bootstrapNodes ? [] : BLIND_PEER_KEYS;
839
952
  const merged = new Map(defaults.map((key) => [b4a.toHex(key), key]));
840
- for (const key of this._blindPeerKeys ?? [])
953
+ for (const key of this._blindPeerKeys ?? []) {
841
954
  merged.set(b4a.toHex(key), key);
842
- for (const key of extra)
955
+ }
956
+ for (const key of extra) {
843
957
  merged.set(b4a.toHex(key), key);
958
+ }
844
959
  return [...merged.values()];
845
960
  }
846
961
  async _startMesh(opts = {}) {
@@ -854,8 +969,9 @@ export class Core extends ReadyResource {
854
969
  if (this._blockedByMinVersion())
855
970
  throw new Error(MESH_BELOW_FLOOR);
856
971
  const previous = this._accountMesh();
857
- if (previous)
972
+ if (previous) {
858
973
  await this._retirePooledMesh(previous);
974
+ }
859
975
  const mesh = await this._openMesh(opts);
860
976
  if (this.closing) {
861
977
  await this._retireMesh(mesh);
@@ -870,11 +986,11 @@ export class Core extends ReadyResource {
870
986
  return mesh;
871
987
  }
872
988
  async _openMesh(opts = {}) {
873
- const session = await this.local.resolveSession(this._deviceKeyPair.publicKey, opts);
989
+ const session = await this.local.resolveSession(this._requireDeviceKeyPair().publicKey, opts);
874
990
  return this._openMeshSession(session, opts);
875
991
  }
876
- async _openMeshSession(session, { blindPeerKeys, account, room } = {}) {
877
- const deviceId = this._deviceKeyPair.publicKey;
992
+ async _openMeshSession(session, { blindPeerKeys, account, sharing } = {}) {
993
+ const deviceId = this._requireDeviceKeyPair().publicKey;
878
994
  const mesh = new Mesh(this.store, {
879
995
  seed: session.seed,
880
996
  key: session.baseKey ?? null,
@@ -891,9 +1007,14 @@ export class Core extends ReadyResource {
891
1007
  try {
892
1008
  await mesh.ready();
893
1009
  await raceResource(mesh.autobee, (async () => {
894
- const birth = await this._mintBirthMember(mesh, deviceId, session);
895
- await mesh.appendBirthOp(this._deviceKeyPair, this._localDevice ?? undefined, birth?.member, undefined, { room });
896
- await this.local.recordMesh(deviceId, mesh.key, session, { account });
1010
+ const birth = sharing
1011
+ ? await this._accountBirthMember(mesh, session)
1012
+ : await this._mintBirthMember(mesh, deviceId, session);
1013
+ await mesh.appendBirthOp(this._requireDeviceKeyPair(), this._localDevice ?? undefined, {
1014
+ member: birth?.member,
1015
+ sharing
1016
+ });
1017
+ await this.local.recordMesh(mesh.key, session, { deviceId, account });
897
1018
  if (account && birth?.mnemonic) {
898
1019
  await this._publishRecovery(birth.mnemonic, {
899
1020
  meshKey: mesh.key,
@@ -910,10 +1031,32 @@ export class Core extends ReadyResource {
910
1031
  this._poolEntry(mesh);
911
1032
  return mesh;
912
1033
  }
1034
+ async _accountBirthMember(mesh, session) {
1035
+ if (!this._localDevice || session.baseKey || mesh.localLength > 0) {
1036
+ return undefined;
1037
+ }
1038
+ const known = await this._knownMember(mesh);
1039
+ if (!known) {
1040
+ return undefined;
1041
+ }
1042
+ return {
1043
+ member: {
1044
+ member: {
1045
+ id: known.id,
1046
+ name: known.name,
1047
+ joinedAt: Date.now(),
1048
+ updatedAt: known.updatedAt
1049
+ },
1050
+ proof: known.proof
1051
+ },
1052
+ mnemonic: null
1053
+ };
1054
+ }
913
1055
  async _mintBirthMember(mesh, deviceId, session) {
914
1056
  const local = this._localDevice;
915
- if (!local || session.baseKey || mesh.localLength > 0)
1057
+ if (!local || session.baseKey || mesh.localLength > 0) {
916
1058
  return undefined;
1059
+ }
917
1060
  const now = Date.now();
918
1061
  const { identity, mnemonic } = await this.local.ensureIdentity(deviceId, now);
919
1062
  this._identityPublicKey = identity.publicKey;
@@ -934,31 +1077,44 @@ export class Core extends ReadyResource {
934
1077
  async publishAccountRecovery(mnemonic) {
935
1078
  if (!this.opened)
936
1079
  await this.ready();
937
- const account = await this.local.accountMesh(this._deviceKeyPair.publicKey);
938
- if (!account)
1080
+ const account = await this.local.accountMesh(this._requireDeviceKeyPair().publicKey);
1081
+ const mesh = this._accountMesh();
1082
+ if (!account || !(mesh?.key && b4a.equals(mesh?.key, account.key))) {
939
1083
  throw new Error(NO_ACCOUNT_TO_RECOVER);
1084
+ }
940
1085
  const record = { meshKey: account.key, seed: account.seed, createdAt: Date.now() };
941
- return this._publishRecovery(mnemonic, record);
1086
+ return this._publishRecovery(mnemonic, record, mesh);
942
1087
  }
943
1088
  async accountRecoverable() {
944
1089
  if (!this.opened)
945
1090
  await this.ready();
946
- const account = await this.local.accountMesh(this._deviceKeyPair.publicKey);
947
- if (!account)
1091
+ const account = await this.local.accountMesh(this._requireDeviceKeyPair().publicKey);
1092
+ if (!account) {
948
1093
  return false;
1094
+ }
949
1095
  const recovery = await this.local.readAccountRecovery(account.key);
950
1096
  return recovery !== null;
951
1097
  }
952
- async _publishRecovery(mnemonic, record) {
1098
+ async _publishRecovery(mnemonic, record, account) {
953
1099
  const identity = await openIdentity(mnemonic);
954
- if (!this._identityPublicKey?.equals(identity.identityPublicKey)) {
1100
+ if (!this._identityPublicKey ||
1101
+ !b4a.equals(this._identityPublicKey, identity.identityPublicKey)) {
955
1102
  throw new Error(PHRASE_NOT_OURS);
956
1103
  }
1104
+ if (account) {
1105
+ const member = await account.view
1106
+ .get(MEMBERS, { id: identity.identityPublicKey })
1107
+ .catch(noop);
1108
+ if (!member) {
1109
+ throw new Error(PHRASE_NOT_A_MEMBER);
1110
+ }
1111
+ }
957
1112
  const core = await this._openOwnRecoveryCore(recoveryKeys(identity));
958
1113
  const appended = await publishRecovery(core, record);
959
1114
  const held = await readRecovery(core);
960
- if (held?.meshKey.equals(record.meshKey))
1115
+ if (held?.meshKey && b4a.equals(held.meshKey, record.meshKey)) {
961
1116
  await this._markRecoverable(held, core);
1117
+ }
962
1118
  this._peerRecoveryCore(core);
963
1119
  return appended;
964
1120
  }
@@ -971,8 +1127,9 @@ export class Core extends ReadyResource {
971
1127
  }
972
1128
  async _openOwnRecoveryCore(keys) {
973
1129
  const signer = keys.coreKeyPair.publicKey;
974
- if (this._recoveryCore && this._recoverySigner?.equals(signer))
1130
+ if (this._recoveryCore && this._recoverySigner && b4a.equals(this._recoverySigner, signer)) {
975
1131
  return this._recoveryCore;
1132
+ }
976
1133
  const core = openRecoveryCore(this.store, keys);
977
1134
  await core.ready();
978
1135
  await this._adoptRecoveryCore(core, signer);
@@ -1000,10 +1157,12 @@ export class Core extends ReadyResource {
1000
1157
  await this._meshTransitionLock.lock();
1001
1158
  let ownsTransition = false;
1002
1159
  try {
1003
- if (this.closing)
1160
+ if (this.closing) {
1004
1161
  throw new Error('Core is closing');
1005
- if (this._leaving || this._minting)
1162
+ }
1163
+ if (this._leaving || this._minting) {
1006
1164
  throw new Error('Mesh transition already in progress');
1165
+ }
1007
1166
  ownsTransition = true;
1008
1167
  this._minting = true;
1009
1168
  this._notifyStatus();
@@ -1016,31 +1175,37 @@ export class Core extends ReadyResource {
1016
1175
  throw err;
1017
1176
  }
1018
1177
  finally {
1019
- if (ownsTransition)
1178
+ if (ownsTransition) {
1020
1179
  this._minting = false;
1180
+ }
1021
1181
  this._meshTransitionLock.unlock();
1022
1182
  this._notifyStatus();
1023
1183
  this._departures?.flush();
1024
1184
  }
1025
1185
  }
1026
1186
  async _recoverAccount(identity, record) {
1027
- const deviceId = this._deviceKeyPair.publicKey;
1187
+ const deviceId = this._requireDeviceKeyPair().publicKey;
1188
+ const proof = await identity.bootstrap(deviceId);
1028
1189
  const meshId = b4a.toHex(record.meshKey);
1029
1190
  await this._opening.get(meshId)?.catch(noop);
1030
1191
  const pooled = this._pooled(meshId);
1192
+ const recovery = pooled?.writable ? undefined : { memberId: identity.identityPublicKey, proof };
1031
1193
  if (pooled?.writable) {
1032
- if (!this._isAccount(pooled))
1194
+ if (!this._isAccount(pooled)) {
1033
1195
  await this._adoptAccount(pooled);
1196
+ }
1034
1197
  }
1035
1198
  else {
1036
- await this._joinMesh({ seed: record.seed, baseKey: record.meshKey, fastForward: null }, pooled);
1199
+ await this._joinMesh({ seed: record.seed, baseKey: record.meshKey, fastForward: null, recovery }, pooled);
1037
1200
  }
1038
1201
  const mesh = this._accountMesh();
1039
- if (!mesh?.key.equals(record.meshKey))
1202
+ if (!mesh?.key || !b4a.equals(mesh.key, record.meshKey)) {
1040
1203
  throw new Error('the recovered account did not adopt');
1041
- if (this._identityPublicKey?.equals(identity.identityPublicKey))
1204
+ }
1205
+ if (this._identityPublicKey &&
1206
+ b4a.equals(this._identityPublicKey, identity.identityPublicKey)) {
1042
1207
  return;
1043
- const proof = await identity.bootstrap(deviceId);
1208
+ }
1044
1209
  const now = Date.now();
1045
1210
  await this.local.replaceIdentity({
1046
1211
  publicKey: identity.identityPublicKey,
@@ -1048,6 +1213,9 @@ export class Core extends ReadyResource {
1048
1213
  createdAt: now
1049
1214
  });
1050
1215
  this._identityPublicKey = identity.identityPublicKey;
1216
+ if (recovery) {
1217
+ return;
1218
+ }
1051
1219
  await mesh.dispatch('attest-member-device', {
1052
1220
  deviceId,
1053
1221
  memberId: identity.identityPublicKey,
@@ -1060,8 +1228,9 @@ export class Core extends ReadyResource {
1060
1228
  this._peerRecoveryCore(core);
1061
1229
  try {
1062
1230
  const record = await readRecovery(core, { timeout });
1063
- if (record)
1231
+ if (record) {
1064
1232
  return record;
1233
+ }
1065
1234
  }
1066
1235
  catch (err) {
1067
1236
  this._log?.warn(['p2p', 'mesh'], 'no blind peer served a recovery record', err);
@@ -1072,8 +1241,9 @@ export class Core extends ReadyResource {
1072
1241
  if (!this._swarm || this.closing)
1073
1242
  return;
1074
1243
  const keys = this._resolveBlindPeerKeys();
1075
- if (keys.length === 0)
1244
+ if (keys.length === 0) {
1076
1245
  return;
1246
+ }
1077
1247
  if (!this._recoveryPeering) {
1078
1248
  this._recoveryPeering = new BlindPeering(this._swarm.dht, this.store, {
1079
1249
  pick: keys.length,
@@ -1094,28 +1264,30 @@ export class Core extends ReadyResource {
1094
1264
  }
1095
1265
  async _joinBirthMember(mesh, deviceId) {
1096
1266
  const local = this._localDevice;
1097
- if (!local || mesh.localLength > 0)
1267
+ if (!local || mesh.localLength > 0) {
1098
1268
  return undefined;
1269
+ }
1099
1270
  const now = Date.now();
1100
1271
  const attestation = claimAttestation(mesh.publicKey, deviceId, mesh.localWriterKey);
1101
1272
  const known = await this._knownMember(mesh);
1102
1273
  if (known) {
1103
1274
  const identity = await this.local.readIdentity();
1104
- const ours = identity?.displayName && namedAt(identity) >= known.updatedAt;
1275
+ const name = identity?.displayName;
1276
+ const ours = identity && name && namedAt(identity) >= known.updatedAt;
1105
1277
  return {
1106
1278
  member: {
1107
1279
  id: known.id,
1108
- name: ours ? identity.displayName : known.name,
1280
+ name: ours ? name : known.name,
1109
1281
  joinedAt: now,
1110
1282
  updatedAt: ours ? namedAt(identity) : known.updatedAt
1111
1283
  },
1112
- proof: await attestMemberClaim(attestation, this._deviceKeyPair, known.proof)
1284
+ proof: await attestMemberClaim(attestation, this._requireDeviceKeyPair(), known.proof)
1113
1285
  };
1114
1286
  }
1115
1287
  const { identity, mnemonic } = await this.local.ensureIdentity(deviceId, now);
1116
1288
  this._identityPublicKey = identity.publicKey;
1117
1289
  this._holdIdentityPhrase(mnemonic);
1118
- const proof = await attestMemberClaim(attestation, this._deviceKeyPair, identity.proof);
1290
+ const proof = await attestMemberClaim(attestation, this._requireDeviceKeyPair(), identity.proof);
1119
1291
  return {
1120
1292
  member: {
1121
1293
  id: identity.publicKey,
@@ -1134,8 +1306,9 @@ export class Core extends ReadyResource {
1134
1306
  }
1135
1307
  async _pushIdentityPhrase() {
1136
1308
  const phrase = this._identityPhrase;
1137
- if (!phrase || this._rpcs.size === 0 || this.closing)
1309
+ if (!phrase || this._rpcs.size === 0 || this.closing) {
1138
1310
  return;
1311
+ }
1139
1312
  this._identityPhrase = null;
1140
1313
  for (const rpc of this._rpcs) {
1141
1314
  if (await this._offerIdentityPhrase(rpc, phrase))
@@ -1158,29 +1331,34 @@ export class Core extends ReadyResource {
1158
1331
  if (this._swarm) {
1159
1332
  this._swarm.join(mesh.discoveryKey, { server: true, client: true });
1160
1333
  mesh.startBlindPeering(this._swarm.dht);
1161
- if (this.suspended)
1334
+ if (this.suspended) {
1162
1335
  void mesh.suspend().catch(noop);
1336
+ }
1163
1337
  this._log?.info(['p2p', 'swarm'], 'announced and peering the mesh');
1164
1338
  }
1165
- if (!opts.new)
1339
+ if (!opts.new) {
1166
1340
  void this._ensureNotRevoked(mesh);
1341
+ }
1167
1342
  this._departures?.flush();
1168
- void this._advertiseAppVersion(mesh, this._deviceKeyPair.publicKey);
1169
- void this._advertiseDeviceProfile(mesh, this._deviceKeyPair.publicKey);
1343
+ void this._advertiseAppVersion(mesh, this._requireDeviceKeyPair().publicKey);
1344
+ void this._advertiseDeviceProfile(mesh, this._requireDeviceKeyPair().publicKey);
1345
+ void this._retractInventory(mesh, this._requireDeviceKeyPair().publicKey);
1170
1346
  void this._settleMembership(mesh, { migrate: true });
1171
1347
  }
1172
1348
  async _advertiseDeviceProfile(mesh, deviceId) {
1173
1349
  const local = this._localDevice;
1174
- if (!local?.platform)
1350
+ if (!local?.platform) {
1175
1351
  return;
1352
+ }
1176
1353
  try {
1177
1354
  await mesh.waitForWritable();
1178
- if (!this._isPooled(mesh))
1355
+ if (!this._isPooled(mesh)) {
1179
1356
  return;
1357
+ }
1180
1358
  const snap = mesh.view.snapshot();
1181
1359
  let existing;
1182
1360
  try {
1183
- existing = await snap.get('@qvac/devices', { id: deviceId });
1361
+ existing = await snap.get(DEVICES, { id: deviceId });
1184
1362
  }
1185
1363
  finally {
1186
1364
  await snap.close();
@@ -1203,16 +1381,18 @@ export class Core extends ReadyResource {
1203
1381
  }
1204
1382
  async _advertiseAppVersion(mesh, deviceId) {
1205
1383
  const app = this._app;
1206
- if (!app)
1384
+ if (!app) {
1207
1385
  return;
1386
+ }
1208
1387
  try {
1209
1388
  await mesh.waitForWritable();
1210
- if (!this._isPooled(mesh))
1389
+ if (!this._isPooled(mesh) || !this._isAccount(mesh)) {
1211
1390
  return;
1391
+ }
1212
1392
  const snap = mesh.view.snapshot();
1213
1393
  let existing;
1214
1394
  try {
1215
- existing = await snap.get('@qvac/devices', { id: deviceId });
1395
+ existing = await snap.get(DEVICES, { id: deviceId });
1216
1396
  }
1217
1397
  finally {
1218
1398
  await snap.close();
@@ -1228,22 +1408,38 @@ export class Core extends ReadyResource {
1228
1408
  this._log?.warn(['p2p', 'mesh'], 'advertising app version failed', err);
1229
1409
  }
1230
1410
  }
1411
+ async _retractInventory(mesh, deviceId) {
1412
+ try {
1413
+ await mesh.waitForWritable();
1414
+ if (!this._isPooled(mesh)) {
1415
+ return;
1416
+ }
1417
+ await retractInventory(mesh, deviceId, (held) => this._isAccount(held));
1418
+ }
1419
+ catch (err) {
1420
+ this._log?.warn(['p2p', 'mesh'], 'retracting the device inventory failed', err);
1421
+ }
1422
+ }
1231
1423
  async _settleMembership(mesh, { migrate = false } = {}) {
1232
1424
  if (!this._localDevice)
1233
1425
  return;
1234
1426
  const entry = this._meshes.get(this._meshIdOf(mesh));
1235
- if (entry?.mesh !== mesh)
1427
+ if (entry?.mesh !== mesh) {
1236
1428
  return;
1237
- if (!(await entry.memberLock.lock()))
1429
+ }
1430
+ if (!(await entry.memberLock.lock())) {
1238
1431
  return;
1432
+ }
1239
1433
  try {
1240
1434
  await mesh.waitForWritable();
1241
- if (!this._isPooled(mesh))
1435
+ if (!this._isPooled(mesh)) {
1242
1436
  return;
1437
+ }
1243
1438
  await mesh.autobee.update();
1244
- if (!this._isPooled(mesh))
1439
+ if (!this._isPooled(mesh)) {
1245
1440
  return;
1246
- const context = { deviceKeyPair: this._deviceKeyPair, log: this._log };
1441
+ }
1442
+ const context = { deviceKeyPair: this._requireDeviceKeyPair(), log: this._log };
1247
1443
  if (migrate) {
1248
1444
  await runMigrations(mesh, { ...context, ...this._migrationContext() }, {
1249
1445
  catalog: await this._isStoredAccount(mesh)
@@ -1251,7 +1447,9 @@ export class Core extends ReadyResource {
1251
1447
  }
1252
1448
  await this._claimOwnMembership(mesh, context);
1253
1449
  await attestUnattestedDevices(mesh, context, this._deviceInvites);
1450
+ await this._sealAccount(mesh);
1254
1451
  await this._renameFoundedMember(mesh, context);
1452
+ await this._revokeInMeshes();
1255
1453
  }
1256
1454
  catch (err) {
1257
1455
  this._log?.warn(['p2p', 'mesh'], 'settling membership failed', err);
@@ -1260,23 +1458,31 @@ export class Core extends ReadyResource {
1260
1458
  entry.memberLock.unlock();
1261
1459
  }
1262
1460
  }
1461
+ async _sealAccount(mesh) {
1462
+ if ((this._meshSeed && b4a.equals(this._meshSeed, mesh.seed)) || !this._isAccount(mesh)) {
1463
+ return;
1464
+ }
1465
+ await sealAccount(mesh, { deviceKeyPair: this._requireDeviceKeyPair(), log: this._log });
1466
+ }
1263
1467
  async _renameFoundedMember(mesh, context) {
1264
1468
  let identity = await this.local.readIdentity();
1265
- if (!identity)
1469
+ if (!identity) {
1266
1470
  return;
1471
+ }
1267
1472
  const adopt = (name, at) => this._adoptName(name, at);
1268
1473
  if (!identity.displayName || identity.displayNameAt) {
1269
- await renameFoundedMember(mesh, context, identity, adopt);
1474
+ await renameFoundedMember(mesh, context, { identity, adopt });
1270
1475
  return;
1271
1476
  }
1272
- if (!this._isAccount(mesh))
1477
+ if (!this._isAccount(mesh)) {
1273
1478
  return;
1479
+ }
1274
1480
  const stamp = await legacyNameStamp(mesh, context, identity);
1275
1481
  if (stamp) {
1276
1482
  const stamped = await this.local.saveDisplayName(identity.displayName, stamp);
1277
1483
  identity = stamped ?? identity;
1278
1484
  }
1279
- await renameFoundedMember(mesh, context, identity, adopt);
1485
+ await renameFoundedMember(mesh, context, { identity, adopt });
1280
1486
  const named = await this.local.readIdentity();
1281
1487
  if (named?.displayNameAt) {
1282
1488
  void this._followAccountName(mesh);
@@ -1287,35 +1493,36 @@ export class Core extends ReadyResource {
1287
1493
  this._notifyStatus();
1288
1494
  }
1289
1495
  async _followAccountName(account) {
1290
- const context = { deviceKeyPair: this._deviceKeyPair, log: this._log };
1496
+ const context = { deviceKeyPair: this._requireDeviceKeyPair(), log: this._log };
1291
1497
  const rename = (mesh) => this._renameFoundedMember(mesh, context).catch((err) => this._log?.warn(['p2p', 'mesh'], 'naming the member in this mesh failed', err));
1292
1498
  if (account.writable) {
1293
1499
  await rename(account);
1294
1500
  }
1295
1501
  for (const { mesh } of this._meshes.values()) {
1296
- if (mesh.writable && mesh !== account)
1502
+ if (mesh.writable && mesh !== account) {
1297
1503
  void rename(mesh);
1504
+ }
1298
1505
  }
1299
1506
  }
1300
1507
  async _claimOwnMembership(mesh, context) {
1301
1508
  if (mesh.ourMemberId)
1302
1509
  return;
1303
1510
  const known = await this._knownMember(mesh);
1304
- if (known)
1511
+ if (known) {
1305
1512
  await claimOwnMembership(mesh, context, known);
1513
+ }
1306
1514
  }
1307
1515
  async _knownMember(exclude) {
1308
- const deviceId = this._deviceKeyPair.publicKey;
1516
+ const deviceId = this._requireDeviceKeyPair().publicKey;
1309
1517
  for (const entry of this._meshes.values()) {
1310
1518
  if (entry.mesh === exclude || !entry.mesh.ourMemberId)
1311
1519
  continue;
1312
- const own = await entry.mesh.view
1313
- .get('@qvac/devices', { id: deviceId })
1314
- .catch(noop);
1315
- if (!own?.memberId || !own.memberProof)
1520
+ const own = await entry.mesh.view.get(DEVICES, { id: deviceId }).catch(noop);
1521
+ if (!own?.memberId || !own.memberProof) {
1316
1522
  continue;
1523
+ }
1317
1524
  const member = await entry.mesh.view
1318
- .get('@qvac/members', { id: own.memberId })
1525
+ .get(MEMBERS, { id: own.memberId })
1319
1526
  .catch(noop);
1320
1527
  if (member) {
1321
1528
  return {
@@ -1329,12 +1536,16 @@ export class Core extends ReadyResource {
1329
1536
  return null;
1330
1537
  }
1331
1538
  _migrationContext() {
1539
+ const local = this._localDevice;
1540
+ if (!local) {
1541
+ throw new Error('local device read before the offline boot');
1542
+ }
1332
1543
  return {
1333
1544
  device: {
1334
- id: this._deviceKeyPair.publicKey,
1335
- platform: this._device?.platform ?? this._localDevice.platform
1545
+ id: this._requireDeviceKeyPair().publicKey,
1546
+ platform: this._device?.platform ?? local.platform
1336
1547
  },
1337
- deviceName: this._localDevice.name,
1548
+ deviceName: local.name,
1338
1549
  mintRoot: async (deviceId, at) => {
1339
1550
  const { identity, mnemonic } = await this.local.ensureIdentity(deviceId, at);
1340
1551
  this._identityPublicKey = identity.publicKey;
@@ -1343,14 +1554,9 @@ export class Core extends ReadyResource {
1343
1554
  }
1344
1555
  };
1345
1556
  }
1346
- async _recordMemberProof(mesh, own) {
1557
+ async _recordMemberProof(mesh, membership) {
1347
1558
  try {
1348
- await this.local.recordMemberProof({
1349
- meshKey: mesh.key,
1350
- memberId: own.memberId,
1351
- proof: own.memberProof,
1352
- attestedAt: own.attestedAt || 0
1353
- });
1559
+ await this.local.recordMemberProof({ meshKey: mesh.key, ...membership });
1354
1560
  }
1355
1561
  catch (err) {
1356
1562
  this._log?.warn(['p2p', 'mesh'], 'keeping our membership proof failed', err);
@@ -1359,19 +1565,22 @@ export class Core extends ReadyResource {
1359
1565
  async _ensureNotRevoked(mesh) {
1360
1566
  const wasAccount = this._isAccount(mesh);
1361
1567
  try {
1362
- const revocation = await mesh.checkResumedRevocation();
1363
- if (!revocation || !this._isPooled(mesh))
1568
+ const revocation = (await mesh.checkResumedRevocation()) ?? ((await mesh.ownWriterRefused()) ? 'kicked' : null);
1569
+ if (!revocation || !this._isPooled(mesh)) {
1364
1570
  return;
1571
+ }
1365
1572
  if (!wasAccount || !this._isAccount(mesh)) {
1366
- if (revocation !== 'kicked')
1573
+ if (revocation !== 'kicked') {
1367
1574
  return;
1575
+ }
1368
1576
  this._log?.info(['p2p', 'mesh'], 'a sibling mesh kicked this device, closing it');
1369
1577
  await this._departRevokedMesh(mesh);
1370
1578
  return;
1371
1579
  }
1372
1580
  this._log?.info(['p2p', 'mesh'], `resumed already revoked (${revocation} while offline), replacing the account`);
1373
- if (revocation === 'kicked')
1581
+ if (revocation === 'kicked') {
1374
1582
  this._kickedPending = true;
1583
+ }
1375
1584
  await this._replaceRevokedAccount(mesh);
1376
1585
  }
1377
1586
  catch (err) {
@@ -1380,15 +1589,17 @@ export class Core extends ReadyResource {
1380
1589
  }
1381
1590
  async _retireMesh(mesh) {
1382
1591
  this._unpoolMesh(mesh);
1383
- if (this._swarm)
1384
- await this._swarm.leave(mesh.discoveryKey).catch(() => { });
1592
+ if (this._swarm) {
1593
+ await this._swarm.leave(mesh.discoveryKey).catch(noop);
1594
+ }
1385
1595
  await mesh.close();
1386
1596
  }
1387
1597
  _retirePooledMesh(mesh) {
1388
1598
  const key = this._meshIdOf(mesh);
1389
1599
  const retiring = this._retirePooled(mesh).finally(() => {
1390
- if (this._retiring.get(key) === retiring)
1600
+ if (this._retiring.get(key) === retiring) {
1391
1601
  this._retiring.delete(key);
1602
+ }
1392
1603
  });
1393
1604
  this._retiring.set(key, retiring);
1394
1605
  return retiring;
@@ -1417,11 +1628,13 @@ export class Core extends ReadyResource {
1417
1628
  }
1418
1629
  async _stopEntryIndexing(entry) {
1419
1630
  const files = entry.processingFiles;
1420
- if (!files)
1631
+ if (!files) {
1421
1632
  return;
1633
+ }
1422
1634
  entry.processingFiles = null;
1423
- if (!(await files.stopProcessing()))
1635
+ if (!(await files.stopProcessing())) {
1424
1636
  entry.vectorIndex = null;
1637
+ }
1425
1638
  }
1426
1639
  _releaseVectorIndex(entry) {
1427
1640
  this._spareVectorIndex ??= entry.vectorIndex;
@@ -1486,13 +1699,15 @@ export class Core extends ReadyResource {
1486
1699
  this.emit('mesh-changed', await this._startMesh({ new: true, account: true }));
1487
1700
  }
1488
1701
  catch (err) {
1489
- if (this.closing)
1702
+ if (this.closing) {
1490
1703
  return;
1704
+ }
1491
1705
  if (!this._upgradeRequired) {
1492
1706
  this._statusError = statusErrorMessage('creating a new mesh failed', err);
1493
1707
  }
1494
- if (!this.emit('mesh-error', err))
1708
+ if (!this.emit('mesh-error', err)) {
1495
1709
  throw err;
1710
+ }
1496
1711
  }
1497
1712
  finally {
1498
1713
  this._minting = false;
@@ -1525,21 +1740,25 @@ export class Core extends ReadyResource {
1525
1740
  }
1526
1741
  async joinMesh(rawInvite) {
1527
1742
  const invite = decodeMeshInvite(rawInvite);
1528
- if (!invite)
1743
+ if (!invite) {
1529
1744
  throw new Error('Invalid mesh invite');
1745
+ }
1530
1746
  await this._awaitMesh();
1531
1747
  await this._meshTransitionLock.lock();
1532
1748
  let ownsTransition = false;
1533
1749
  try {
1534
- if (this.closing)
1750
+ if (this.closing) {
1535
1751
  throw new Error('Core is closing');
1536
- if (this._leaving || this._minting)
1752
+ }
1753
+ if (this._leaving || this._minting) {
1537
1754
  throw new Error('Mesh transition already in progress');
1755
+ }
1538
1756
  await this._opening.get(b4a.toHex(invite.baseKey))?.catch(noop);
1539
1757
  const pooled = this._pooled(b4a.toHex(invite.baseKey));
1540
1758
  if (pooled?.writable) {
1541
- if (!invite.memberInvite && !this._isAccount(pooled))
1759
+ if (!invite.memberInvite && !this._isAccount(pooled)) {
1542
1760
  await this._adoptAccount(pooled);
1761
+ }
1543
1762
  return;
1544
1763
  }
1545
1764
  ownsTransition = true;
@@ -1548,16 +1767,18 @@ export class Core extends ReadyResource {
1548
1767
  await this._joinMesh(invite, pooled);
1549
1768
  }
1550
1769
  finally {
1551
- if (ownsTransition)
1770
+ if (ownsTransition) {
1552
1771
  this._minting = false;
1772
+ }
1553
1773
  this._meshTransitionLock.unlock();
1554
1774
  this._notifyStatus();
1555
1775
  this._departures?.flush();
1556
1776
  }
1557
1777
  }
1558
1778
  cancelMeshJoin() {
1559
- if (this._joinCancellation?.accepting)
1779
+ if (this._joinCancellation?.accepting) {
1560
1780
  this._joinCancellation.canceled = true;
1781
+ }
1561
1782
  this._cancelCandidateJoin?.();
1562
1783
  }
1563
1784
  _throwIfJoinCanceled() {
@@ -1565,8 +1786,55 @@ export class Core extends ReadyResource {
1565
1786
  throw new Error(MESH_JOIN_CANCELED);
1566
1787
  }
1567
1788
  async _joinMesh(invite, retire = null) {
1568
- const cancellation = { canceled: false, accepting: true };
1789
+ const cancellation = {
1790
+ canceled: false,
1791
+ accepting: true,
1792
+ deadline: Date.now() + GRANT_VISIBLE_MS,
1793
+ account: !invite.memberInvite
1794
+ };
1569
1795
  this._joinCancellation = cancellation;
1796
+ try {
1797
+ if (invite.memberInvite && invite.inviteNonce) {
1798
+ await this._joinMeshInvite(invite);
1799
+ }
1800
+ else if (await this._reopenOwnAccount(invite)) {
1801
+ return;
1802
+ }
1803
+ else {
1804
+ await this._claimJoin(invite, retire ?? this._pooled(b4a.toHex(invite.baseKey)));
1805
+ }
1806
+ }
1807
+ finally {
1808
+ if (this._joinCancellation === cancellation) {
1809
+ this._joinCancellation = null;
1810
+ }
1811
+ }
1812
+ }
1813
+ async _reopenOwnAccount(invite) {
1814
+ if (invite.recovery || !invite.memberId || !invite.inviteNonce)
1815
+ return false;
1816
+ const stored = await this._storedAccountKey();
1817
+ if (!stored || !b4a.equals(stored, invite.baseKey)) {
1818
+ return false;
1819
+ }
1820
+ if (!(await this.local.readMeshSession(invite.baseKey))) {
1821
+ return false;
1822
+ }
1823
+ const account = await this._openPooledMesh(b4a.toHex(invite.baseKey));
1824
+ const own = await account.view.get(DEVICES, {
1825
+ id: this._requireDeviceKeyPair().publicKey
1826
+ });
1827
+ if (!own ||
1828
+ own.revoked ||
1829
+ !(own.writerKey && b4a.equals(own.writerKey, account.localWriterKey))) {
1830
+ return false;
1831
+ }
1832
+ if (!this._isAccount(account)) {
1833
+ await this._adoptAccount(account);
1834
+ }
1835
+ return true;
1836
+ }
1837
+ async _claimJoin(invite, retire) {
1570
1838
  const meshId = b4a.toHex(invite.baseKey);
1571
1839
  const claim = Promise.withResolvers();
1572
1840
  claim.promise.catch(noop);
@@ -1582,26 +1850,45 @@ export class Core extends ReadyResource {
1582
1850
  throw error;
1583
1851
  }
1584
1852
  finally {
1585
- if (this._opening.get(meshId) === claim.promise)
1853
+ if (this._opening.get(meshId) === claim.promise) {
1586
1854
  this._opening.delete(meshId);
1587
- if (this._joinCancellation === cancellation)
1588
- this._joinCancellation = null;
1855
+ }
1856
+ }
1857
+ }
1858
+ async _joinMeshInvite(invite) {
1859
+ const meshId = b4a.toHex(invite.baseKey);
1860
+ await this._following.get(meshId);
1861
+ const joining = (async () => {
1862
+ if (!(await this._openOwnMesh(invite))) {
1863
+ await this._claimJoin(invite, this._pooled(meshId));
1864
+ }
1865
+ })();
1866
+ const slot = joining.catch(noop);
1867
+ this._following.set(meshId, slot);
1868
+ try {
1869
+ await joining;
1870
+ }
1871
+ finally {
1872
+ if (this._following.get(meshId) === slot) {
1873
+ this._following.delete(meshId);
1874
+ }
1589
1875
  }
1590
1876
  }
1591
1877
  async _runJoinMesh(invite, claim) {
1592
- const deviceId = this._deviceKeyPair.publicKey;
1878
+ const deviceId = this._requireDeviceKeyPair().publicKey;
1593
1879
  const source = this._accountMesh();
1594
- for (const node of invite.additionalNodes ?? [])
1880
+ for (const node of invite.additionalNodes ?? []) {
1595
1881
  this._swarm?.dht.addNode(node);
1882
+ }
1596
1883
  await this._departures?.park(invite.baseKey);
1597
1884
  try {
1598
- await this._joinParkedMesh(invite, source, deviceId, claim);
1885
+ await this._joinParkedMesh(invite, claim, { source, deviceId });
1599
1886
  }
1600
1887
  finally {
1601
1888
  this._departures?.unpark(invite.baseKey);
1602
1889
  }
1603
1890
  }
1604
- async _joinParkedMesh(invite, source, deviceId, claim) {
1891
+ async _joinParkedMesh(invite, claim, { source, deviceId }) {
1605
1892
  const mesh = await this._joinCandidate(invite, source, deviceId);
1606
1893
  if (mesh) {
1607
1894
  claim.resolve(mesh);
@@ -1621,26 +1908,29 @@ export class Core extends ReadyResource {
1621
1908
  throw error;
1622
1909
  }
1623
1910
  this._throwIfJoinCanceled();
1624
- if (this._joinCancellation)
1911
+ if (this._joinCancellation) {
1625
1912
  this._joinCancellation.accepting = false;
1913
+ }
1626
1914
  try {
1627
1915
  if (source && !invite.memberInvite && (await this._departureHasAudience(source))) {
1628
1916
  await this.local.recordDeparture(source.key, { creator: source.minted });
1629
1917
  }
1630
- await this.local.recordMesh(deviceId, candidate.key, session);
1918
+ await this.local.recordMesh(candidate.key, session, { deviceId });
1631
1919
  }
1632
1920
  catch (error) {
1633
1921
  await this._discardCandidateMesh();
1634
1922
  throw error;
1635
1923
  }
1636
- return this._landJoinedMesh(invite, candidate, source, deviceId);
1924
+ return this._landJoinedMesh(invite, candidate, { source, deviceId });
1637
1925
  }
1638
- async _landJoinedMesh(invite, candidate, source, deviceId) {
1639
- if (!invite.memberInvite)
1926
+ async _landJoinedMesh(invite, candidate, { source, deviceId }) {
1927
+ if (!invite.memberInvite) {
1640
1928
  await this._departOldAccount(candidate.key, source);
1929
+ }
1641
1930
  if (this._blockedByMinVersion()) {
1642
- if (!invite.memberInvite)
1931
+ if (!invite.memberInvite) {
1643
1932
  await this.local.setAccountMesh(deviceId, candidate.key);
1933
+ }
1644
1934
  await this._retireMesh(candidate).catch((err) => this._log?.warn(['p2p', 'mesh'], 'withholding the joined mesh failed', err));
1645
1935
  return null;
1646
1936
  }
@@ -1655,27 +1945,31 @@ export class Core extends ReadyResource {
1655
1945
  }
1656
1946
  void this._departures?.drop(candidate.key).catch(noop);
1657
1947
  void this._advertiseDeviceProfile(candidate, deviceId);
1948
+ void candidate.refreshOurMember().catch(noop);
1658
1949
  void this._settleMembership(candidate, { migrate: true });
1659
1950
  if (invite.memberInvite && !candidate.compute) {
1660
- void this._recordJoinedRoom(candidate.key);
1661
- void this._seedMemberDefaults(candidate);
1951
+ void this._recordJoinedMesh(candidate.key);
1662
1952
  }
1663
1953
  this.emit('mesh-changed', candidate);
1664
1954
  return candidate;
1665
1955
  }
1666
1956
  async _departOldAccount(joined, source) {
1667
1957
  const account = (await this._storedAccountKey()) ?? source?.key;
1668
- if (account?.equals(joined))
1958
+ if (account && b4a.equals(account, joined)) {
1669
1959
  return;
1670
- const rows = (await this.local.listMeshes()).filter((row) => !row.key.equals(joined));
1671
- const rooms = rows.filter((row) => !account?.equals(row.key));
1672
- if (account)
1960
+ }
1961
+ const rows = (await this.local.listMeshes()).filter((row) => !b4a.equals(row.key, joined));
1962
+ const meshes = rows.filter((row) => !(account && b4a.equals(account, row.key)));
1963
+ if (account) {
1673
1964
  await this._writableAccount();
1674
- for (const room of rooms)
1675
- await this._departIfPooled(room.key, 'room');
1676
- await this.local.adoptAccountMesh(this._deviceKeyPair.publicKey, joined, { account });
1677
- if (account)
1965
+ }
1966
+ for (const mesh of meshes) {
1967
+ await this._departIfPooled(mesh.key, 'mesh');
1968
+ }
1969
+ await this.local.adoptAccountMesh(this._requireDeviceKeyPair().publicKey, joined, { account });
1970
+ if (account) {
1678
1971
  await this._departIfPooled(account, 'account');
1972
+ }
1679
1973
  }
1680
1974
  async _departIfPooled(key, kind) {
1681
1975
  const meshId = b4a.toHex(key);
@@ -1699,68 +1993,49 @@ export class Core extends ReadyResource {
1699
1993
  this._log?.warn(['p2p', 'mesh'], `departing the old ${kind} failed`, error);
1700
1994
  }
1701
1995
  }
1702
- async _seedMemberDefaults(mesh) {
1703
- const local = this._localDevice;
1704
- if (!local)
1705
- return;
1996
+ async _recordJoinedMesh(meshKey) {
1706
1997
  try {
1707
- await Promise.race([mesh.waitForWritable(), this._closeSignal]);
1708
- if (!this._isPooled(mesh))
1709
- return;
1710
- await mesh.autobee.update();
1711
- if (!this._isPooled(mesh) || (await this._hasOwnDefaultAgent(mesh)))
1712
- return;
1713
- const deviceId = this._deviceKeyPair.publicKey;
1714
- const member = mesh.ourMemberId
1715
- ? await mesh.view.get('@qvac/members', { id: mesh.ourMemberId })
1716
- : null;
1717
- await mesh.dispatch('seed-defaults', buildDefaultSeed({ id: deviceId, recommendedModelName: local.recommendedModelName }, [], member?.name ?? local.name));
1998
+ await this._registerMesh(meshKey, { shared: false });
1718
1999
  }
1719
2000
  catch (error) {
1720
- this._log?.warn(['p2p', 'mesh'], 'seeding this member defaults in the room failed', error);
2001
+ this._log?.warn(['p2p', 'mesh'], 'recording the joined mesh failed', error);
1721
2002
  }
1722
2003
  }
1723
- async _hasOwnDefaultAgent(mesh) {
1724
- return (await ownDefaultAgents(mesh)).length > 0;
1725
- }
1726
- async _recordJoinedRoom(meshKey) {
1727
- try {
1728
- await this._registerRoom(meshKey, false);
1729
- }
1730
- catch (error) {
1731
- this._log?.warn(['p2p', 'mesh'], 'recording the joined room failed', error);
2004
+ async _registerMesh(meshKey, opts) {
2005
+ const { shared } = opts;
2006
+ const registry = opts.registry ?? (await this._writableAccount());
2007
+ if (!registry) {
2008
+ throw new Error(MESH_WITHOUT_ACCOUNT);
1732
2009
  }
1733
- }
1734
- async _registerRoom(meshKey, shared, held) {
1735
- const registry = held ?? (await this._writableAccount());
1736
- if (!registry)
1737
- throw new Error(ROOM_WITHOUT_ACCOUNT);
1738
2010
  const ours = registry.ourMemberId;
1739
- if (!ours)
1740
- throw new Error('our member is not known yet');
2011
+ if (!ours) {
2012
+ throw new Error(ACCOUNT_MEMBER_UNKNOWN);
2013
+ }
1741
2014
  const now = Date.now();
1742
2015
  await registry.dispatch('put-joined-mesh', {
1743
2016
  room: { meshKey, memberId: ours, joinedAt: now, shared, sharedAt: shared ? now : 0 }
1744
2017
  });
1745
2018
  }
1746
- async _releaseJoinedRoom(meshKey, registry) {
2019
+ async _releaseJoinedMesh(meshKey, registry) {
1747
2020
  try {
1748
2021
  const held = registry ? [registry] : [...this._meshes.values()].map((entry) => entry.mesh);
1749
2022
  for (const mesh of held) {
1750
2023
  const ours = mesh.ourMemberId;
1751
- if (!mesh.writable || !ours || mesh.key.equals(meshKey))
2024
+ if (!mesh.writable || !ours || b4a.equals(mesh.key, meshKey)) {
1752
2025
  continue;
1753
- const room = await mesh.view.get(JOINED_MESHES, { meshKey });
1754
- if (!room?.memberId.equals(ours))
2026
+ }
2027
+ const joined = await mesh.view.get(JOINED_MESHES, { meshKey });
2028
+ if (!(joined?.memberId && b4a.equals(joined?.memberId, ours))) {
1755
2029
  continue;
2030
+ }
1756
2031
  await mesh.dispatch('put-joined-mesh', {
1757
- room: { meshKey, memberId: ours, joinedAt: room.joinedAt, leftAt: Date.now() }
2032
+ room: { meshKey, memberId: ours, joinedAt: joined.joinedAt, leftAt: Date.now() }
1758
2033
  });
1759
2034
  return;
1760
2035
  }
1761
2036
  }
1762
2037
  catch (error) {
1763
- this._log?.warn(['p2p', 'mesh'], 'releasing the joined room failed', error);
2038
+ this._log?.warn(['p2p', 'mesh'], 'releasing the joined mesh failed', error);
1764
2039
  }
1765
2040
  }
1766
2041
  async _writableAccount() {
@@ -1772,75 +2047,205 @@ export class Core extends ReadyResource {
1772
2047
  if (mesh && !mesh.writable) {
1773
2048
  await Promise.race([mesh.waitForWritable(), this._closeSignal, after(ACCOUNT_WRITABLE_MS)]);
1774
2049
  }
1775
- if (mesh && !mesh.ourMemberId)
2050
+ if (mesh && !mesh.ourMemberId) {
1776
2051
  await mesh.refreshOurMember();
2052
+ }
1777
2053
  if (!mesh?.writable) {
1778
- if (mesh && !held)
2054
+ if (mesh && !held) {
1779
2055
  await this._retirePooledMesh(mesh).catch(noop);
2056
+ }
1780
2057
  this._log?.warn(['p2p', 'mesh'], 'no writable account mesh');
1781
2058
  return null;
1782
2059
  }
1783
2060
  return mesh;
1784
2061
  }
1785
- async _openCandidateMesh(invite, session) {
1786
- this._throwIfJoinCanceled();
1787
- const candidate = new Mesh(this.store, {
1788
- seed: session.seed,
1789
- key: session.baseKey ?? null,
1790
- compute: session.compute,
1791
- deviceId: this._deviceKeyPair.publicKey,
1792
- writerSeed: session.writerSeed,
1793
- logger: this._log,
1794
- blindPeerKeys: this._resolveBlindPeerKeys(invite.blindPeers),
1795
- blindPeeringOpts: this._blindPeeringOpts,
1796
- bootFrom: invite.fastForward,
1797
- wakeup: this._wakeup,
1798
- attachmentUrl: (attachment) => this._linkAttachment(attachment, candidate),
1799
- fileIndex: this._fileIndexFor(() => candidate)
2062
+ async _awaitGrantRow(mesh, grantKey) {
2063
+ await this._untilDeadline(async () => Boolean(await mesh.view.get(MESH_INVITE_GRANTS, { grantKey })));
2064
+ }
2065
+ async _untilDeadline(done) {
2066
+ const deadline = this._joinCancellation?.deadline ?? Date.now();
2067
+ for (;;) {
2068
+ if (await done())
2069
+ return true;
2070
+ if (Date.now() >= deadline)
2071
+ return false;
2072
+ this._throwIfJoinCanceled();
2073
+ await after(250);
2074
+ }
2075
+ }
2076
+ async _refuseIfGrantUnusable(candidate, grantSecret, memberId) {
2077
+ const grantKey = grantKeyPair(grantSecret).publicKey;
2078
+ await this._awaitGrantRow(candidate, grantKey);
2079
+ await this._untilDeadline(async () => {
2080
+ await candidate.autobee.update();
2081
+ const status = await syncStatusSnapshot(candidate);
2082
+ return !!status.devices?.length && status.state === 'synced';
1800
2083
  });
1801
- this._candidateMesh = candidate;
1802
- if (this._swarm)
1803
- this._swarm.join(candidate.discoveryKey, { server: true, client: true });
1804
- const onOpenCanceled = () => candidate.interruptBoot();
1805
- this._cancelCandidateJoin = onOpenCanceled;
1806
- const disarm = () => {
1807
- if (this._cancelCandidateJoin === onOpenCanceled)
1808
- this._cancelCandidateJoin = null;
1809
- };
2084
+ await this._refuseUnredeemable(candidate, grantKey, memberId);
2085
+ }
2086
+ async _refuseUnredeemable(mesh, grantKey, memberId) {
2087
+ const deviceId = this._requireDeviceKeyPair().publicKey;
2088
+ const snap = mesh.view.snapshot();
2089
+ try {
2090
+ const grant = await snap.get(MESH_INVITE_GRANTS, { grantKey });
2091
+ if (!grant) {
2092
+ return;
2093
+ }
2094
+ const issuer = grant.issuerDeviceId && (await snap.get(DEVICES, { id: grant.issuerDeviceId }));
2095
+ const spent = await snap.get(MESH_INVITE_SPENDS, {
2096
+ grantKey,
2097
+ deviceId
2098
+ });
2099
+ const own = await snap.get(DEVICES, { id: deviceId });
2100
+ const live = own && !own.revoked;
2101
+ const expired = !!grant.expiresAt && Date.now() > grant.expiresAt;
2102
+ if (expired && (!spent || grant.revokedAt)) {
2103
+ throw new Error(INVITE_GRANT_EXPIRED);
2104
+ }
2105
+ if (grant.revokedAt || !issuer || issuer.revoked) {
2106
+ throw new Error(INVITE_GRANT_REVOKED);
2107
+ }
2108
+ if (spent && !live) {
2109
+ throw new Error(INVITE_GRANT_EXHAUSTED);
2110
+ }
2111
+ if (spent) {
2112
+ return;
2113
+ }
2114
+ if (grant.maxUses && (grant.uses ?? 0) >= grant.maxUses) {
2115
+ throw new Error(INVITE_GRANT_EXHAUSTED);
2116
+ }
2117
+ if (memberId && (await belongsToAnotherMember(snap, own ?? null, memberId))) {
2118
+ throw new Error(DEVICE_OF_ANOTHER_MEMBER);
2119
+ }
2120
+ if (live) {
2121
+ throw new Error(MESH_ALREADY_JOINED);
2122
+ }
2123
+ const standing = memberId &&
2124
+ (await inviteStanding(snap, {
2125
+ device: own ?? null,
2126
+ memberId,
2127
+ grant,
2128
+ compute: mesh.compute
2129
+ }));
2130
+ if (standing === 'present') {
2131
+ throw new Error(MEMBER_ALREADY_IN_MESH);
2132
+ }
2133
+ if (standing === 'removed') {
2134
+ throw new Error(MEMBER_REMOVED_SINCE_INVITE);
2135
+ }
2136
+ }
2137
+ finally {
2138
+ await snap.close();
2139
+ }
2140
+ }
2141
+ async _refuseFromOwnCopy(invite, grantKey) {
2142
+ if (this._pooled(b4a.toHex(invite.baseKey)))
2143
+ return;
2144
+ const recorded = await this.local.readMeshSession(invite.baseKey);
2145
+ const archived = (await this.local.listArchivedMeshes()).find((row) => b4a.equals(row.key, invite.baseKey));
2146
+ const writerSeed = recorded?.writerSeed ?? archived?.writerSeed;
2147
+ if (!writerSeed) {
2148
+ return;
2149
+ }
2150
+ const copy = new Mesh(this.store, {
2151
+ seed: invite.seed,
2152
+ key: invite.baseKey,
2153
+ deviceId: this._requireDeviceKeyPair().publicKey,
2154
+ writerSeed,
2155
+ logger: this._log
2156
+ });
2157
+ try {
2158
+ await copy.ready();
2159
+ await this._refuseUnredeemable(copy, grantKey, null);
2160
+ }
2161
+ finally {
2162
+ await copy.close();
2163
+ }
2164
+ }
2165
+ async _openCandidateMesh(invite, session) {
2166
+ this._throwIfJoinCanceled();
2167
+ if (invite.memberInvite && invite.inviteNonce) {
2168
+ await this._refuseFromOwnCopy(invite, grantKeyPair(invite.inviteNonce).publicKey);
2169
+ }
2170
+ const candidate = new Mesh(this.store, {
2171
+ seed: session.seed,
2172
+ key: session.baseKey ?? null,
2173
+ compute: session.compute,
2174
+ deviceId: this._requireDeviceKeyPair().publicKey,
2175
+ writerSeed: session.writerSeed,
2176
+ logger: this._log,
2177
+ blindPeerKeys: this._resolveBlindPeerKeys(invite.blindPeers),
2178
+ blindPeeringOpts: this._blindPeeringOpts,
2179
+ bootFrom: invite.fastForward,
2180
+ wakeup: this._wakeup,
2181
+ attachmentUrl: (attachment) => this._linkAttachment(attachment, candidate),
2182
+ fileIndex: this._fileIndexFor(() => candidate)
2183
+ });
2184
+ this._candidateMesh = candidate;
2185
+ if (this._swarm) {
2186
+ this._swarm.join(candidate.discoveryKey, { server: true, client: true });
2187
+ }
2188
+ const onOpenCanceled = () => candidate.interruptBoot();
2189
+ this._cancelCandidateJoin = onOpenCanceled;
2190
+ const disarm = () => {
2191
+ if (this._cancelCandidateJoin === onOpenCanceled) {
2192
+ this._cancelCandidateJoin = null;
2193
+ }
2194
+ };
1810
2195
  try {
1811
2196
  await candidate.ready();
1812
2197
  }
1813
2198
  catch (error) {
1814
2199
  disarm();
1815
2200
  this._candidateMesh = null;
1816
- if (this._swarm)
2201
+ if (this._swarm) {
1817
2202
  await this._swarm.leave(candidate.discoveryKey).catch(noop);
2203
+ }
1818
2204
  await candidate.close().catch(noop);
1819
2205
  throw this._joinCancellation?.canceled ? new Error(MESH_JOIN_CANCELED) : error;
1820
2206
  }
1821
- if (this._swarm)
2207
+ if (this._swarm) {
1822
2208
  candidate.startBlindPeering(this._swarm.dht);
2209
+ }
1823
2210
  try {
1824
2211
  this._throwIfJoinCanceled();
1825
2212
  const member = invite.memberInvite
1826
- ? await this._joinBirthMember(candidate, this._deviceKeyPair.publicKey)
2213
+ ? await this._joinBirthMember(candidate, this._requireDeviceKeyPair().publicKey)
1827
2214
  : undefined;
1828
- const claim = member || !invite.memberId
1829
- ? undefined
1830
- : { memberId: invite.memberId, inviteNonce: invite.inviteNonce };
1831
- await candidate.appendBirthOp(this._deviceKeyPair, this._localDevice ?? undefined, member, claim);
2215
+ const invited = !member && invite.memberId && invite.inviteNonce;
2216
+ const grantSecret = invite.memberInvite ? invite.inviteNonce : undefined;
2217
+ if (grantSecret) {
2218
+ await this._refuseIfGrantUnusable(candidate, grantSecret, member?.member.id ?? null);
2219
+ }
2220
+ await candidate.appendBirthOp(this._requireDeviceKeyPair(), this._localDevice ?? undefined, {
2221
+ member,
2222
+ grantSecret,
2223
+ recovery: invite.recovery,
2224
+ vouched: Boolean(invited)
2225
+ });
1832
2226
  this._throwIfJoinCanceled();
1833
- if (!candidate.key.equals(invite.baseKey)) {
2227
+ if (!b4a.equals(candidate.key, invite.baseKey)) {
1834
2228
  throw new Error('Device is not permitted to join the invited mesh');
1835
2229
  }
1836
2230
  if ((await candidate.checkResumedRevocation()) === 'kicked') {
1837
2231
  throw new Error('Device is not permitted to join the invited mesh');
1838
2232
  }
2233
+ if (invite.recovery && (await this._isRemovedFrom(candidate))) {
2234
+ throw new Error(RECOVERY_DEVICE_REMOVED);
2235
+ }
1839
2236
  this._throwIfJoinCanceled();
1840
2237
  disarm();
1841
- await this._waitForCandidateWritable(candidate);
1842
- if (!candidate.writable)
2238
+ const inviter = invited
2239
+ ? this._requestInvitedAdmission(candidate, invite.memberId, invite.inviteNonce)
2240
+ : null;
2241
+ await this._waitForCandidateWritable(candidate, !invite.recovery).catch((error) => {
2242
+ throw inviter && !inviter.answered && error.message === GRANT_JOIN_TIMED_OUT
2243
+ ? new Error(INVITER_OFFLINE)
2244
+ : error;
2245
+ });
2246
+ if (!candidate.writable) {
1843
2247
  throw new Error('Device is not permitted to join the invited mesh');
2248
+ }
1844
2249
  this._throwIfJoinCanceled();
1845
2250
  return candidate;
1846
2251
  }
@@ -1852,18 +2257,71 @@ export class Core extends ReadyResource {
1852
2257
  disarm();
1853
2258
  }
1854
2259
  }
1855
- async _waitForCandidateWritable(candidate) {
2260
+ _requestInvitedAdmission(candidate, memberId, nonce) {
2261
+ const { publicKey: deviceId, secretKey } = this._requireDeviceKeyPair();
2262
+ const local = this._localDevice;
2263
+ if (!local) {
2264
+ throw new Error('local device read before the offline boot');
2265
+ }
2266
+ const joinedAt = Date.now();
2267
+ const request = {
2268
+ writerKey: candidate.localWriterKey,
2269
+ joinedAt,
2270
+ deviceSignature: candidate.signDeviceClaim(secretKey, deviceId, joinedAt),
2271
+ memberSignature: signMemberWriterClaim(secretKey, {
2272
+ meshPublicKey: candidate.publicKey,
2273
+ deviceId,
2274
+ writerKey: candidate.localWriterKey,
2275
+ joinedAt,
2276
+ memberId
2277
+ }),
2278
+ inviteToken: deviceInviteToken(nonce, deviceId),
2279
+ name: local.name,
2280
+ capabilityProfile: local.capabilityProfile,
2281
+ recommendedModelName: local.recommendedModelName
2282
+ };
2283
+ const state = { answered: false };
2284
+ const asking = () => this._candidateMesh === candidate && !candidate.writable && !this.closing;
2285
+ const ask = (inviter) => this._meshSeedHandoff.admit(inviter, candidate.key, request).then((admitted) => {
2286
+ state.answered = true;
2287
+ return admitted;
2288
+ }, (error) => {
2289
+ if (![HOST_UNREACHABLE, HOST_SILENT, SEED_REFUSED].includes(error.message)) {
2290
+ state.answered = true;
2291
+ }
2292
+ return false;
2293
+ });
2294
+ void (async () => {
2295
+ while (asking()) {
2296
+ for (const inviter of await this._liveSiblings(candidate, memberId)) {
2297
+ if (!asking() || (await ask(inviter)))
2298
+ return;
2299
+ }
2300
+ await Promise.race([after(INVITER_RETRY_MS), this._closeSignal]);
2301
+ }
2302
+ })().catch(noop);
2303
+ return state;
2304
+ }
2305
+ async _isRemovedFrom(mesh) {
2306
+ const device = await mesh.view
2307
+ .get(DEVICES, { id: this._requireDeviceKeyPair().publicKey })
2308
+ .catch(noop);
2309
+ return device ? isKickedRow(device) : false;
2310
+ }
2311
+ async _waitForCandidateWritable(candidate, bounded) {
1856
2312
  if (candidate.writable)
1857
2313
  return;
1858
2314
  await new Promise((resolve, reject) => {
1859
2315
  let offClose = noop;
1860
2316
  const cleanup = () => {
2317
+ clearTimeout(timer);
1861
2318
  candidate.autobee.off('writable', onWritable);
1862
2319
  candidate.autobee.off('interrupt', onInterrupt);
1863
2320
  candidate.off('kicked', onKicked);
1864
2321
  offClose();
1865
- if (this._cancelCandidateJoin === onCanceled)
2322
+ if (this._cancelCandidateJoin === onCanceled) {
1866
2323
  this._cancelCandidateJoin = null;
2324
+ }
1867
2325
  };
1868
2326
  const onWritable = () => {
1869
2327
  cleanup();
@@ -1881,6 +2339,12 @@ export class Core extends ReadyResource {
1881
2339
  cleanup();
1882
2340
  reject(new Error(MESH_JOIN_CANCELED));
1883
2341
  };
2342
+ const timer = bounded
2343
+ ? setTimeout(() => {
2344
+ cleanup();
2345
+ reject(new Error(GRANT_JOIN_TIMED_OUT));
2346
+ }, GRANT_WRITABLE_MS)
2347
+ : undefined;
1884
2348
  this._cancelCandidateJoin = onCanceled;
1885
2349
  candidate.autobee.on('writable', onWritable);
1886
2350
  candidate.autobee.on('interrupt', onInterrupt);
@@ -1891,8 +2355,9 @@ export class Core extends ReadyResource {
1891
2355
  _onMeshWritable(mesh) {
1892
2356
  if (!this._isPooled(mesh))
1893
2357
  return;
1894
- if (this._isAccount(mesh))
2358
+ if (this._isAccount(mesh)) {
1895
2359
  this._kicked = false;
2360
+ }
1896
2361
  this._notifyStatus();
1897
2362
  }
1898
2363
  _onMeshDead(mesh, err) {
@@ -1908,8 +2373,9 @@ export class Core extends ReadyResource {
1908
2373
  this._notifyStatus();
1909
2374
  }
1910
2375
  _onMeshStalled(mesh, err) {
1911
- if (this._isPooled(mesh))
2376
+ if (this._isPooled(mesh)) {
1912
2377
  this._withdrawFromMesh(mesh, err);
2378
+ }
1913
2379
  }
1914
2380
  _wireMesh(entry) {
1915
2381
  if (entry.handlers)
@@ -1925,14 +2391,21 @@ export class Core extends ReadyResource {
1925
2391
  mesh.on('unattested-device', () => void this._settleMembership(mesh));
1926
2392
  mesh.on('members-dirty', () => void this._revalidateLoans());
1927
2393
  mesh.on('members-dirty', () => {
1928
- if (this._isAccount(mesh))
1929
- void this._followAccountName(mesh);
2394
+ if (!this._isAccount(mesh))
2395
+ return;
2396
+ void this._followAccountName(mesh);
2397
+ void this._revokeInMeshes();
1930
2398
  });
1931
- mesh.on('rooms-dirty', () => void this._followJoinedRooms(mesh));
2399
+ mesh.on('meshes-dirty', (changed) => {
2400
+ if (changed || entry.meshesPending) {
2401
+ void this._followJoinedMeshes(mesh);
2402
+ }
2403
+ });
2404
+ mesh.on('mesh-kind', () => void this._refuseSealedReader(mesh));
1932
2405
  mesh.on('membership-tallied', () => this._notifyStatus());
1933
- mesh.on('membership', (own) => {
1934
- void this._recordMemberProof(mesh, own);
1935
- void this._followJoinedRooms(mesh);
2406
+ mesh.on('membership', (membership) => {
2407
+ void this._recordMemberProof(mesh, membership);
2408
+ void this._followJoinedMeshes(mesh);
1936
2409
  });
1937
2410
  mesh.autobee.on('writable', handlers.writable);
1938
2411
  mesh.autobee.on('error', handlers.dead);
@@ -1942,16 +2415,36 @@ export class Core extends ReadyResource {
1942
2415
  this._startEntryIndexing(entry);
1943
2416
  }
1944
2417
  async _adoptAccount(mesh) {
1945
- if (this._candidateMesh === mesh)
2418
+ if (this._candidateMesh === mesh) {
1946
2419
  this._candidateMesh = null;
1947
- await this.local.setAccountMesh(this._deviceKeyPair.publicKey, mesh.key);
2420
+ }
2421
+ await this.local.setAccountMesh(this._requireDeviceKeyPair().publicKey, mesh.key);
1948
2422
  this._wireMesh(this._poolEntry(mesh));
1949
2423
  this._accountId = this._meshIdOf(mesh);
1950
2424
  this._statusError = null;
1951
2425
  this._upgradeRequired = null;
1952
2426
  void this._closeConfigPeering().catch(noop);
1953
- if (mesh.writable)
2427
+ if (mesh.writable) {
1954
2428
  this._kicked = false;
2429
+ }
2430
+ this._notifyStatus();
2431
+ void this._refuseSealedReader(mesh);
2432
+ }
2433
+ async _refuseSealedReader(mesh) {
2434
+ if (!this._isAccount(mesh) || mesh.writable)
2435
+ return;
2436
+ const kind = await mesh.view.get(MESH_KINDS, { id: 'mesh' }).catch(noop);
2437
+ if (kind?.kind !== 'account') {
2438
+ return;
2439
+ }
2440
+ const own = await mesh.view.get(DEVICES, {
2441
+ id: this._requireDeviceKeyPair().publicKey
2442
+ });
2443
+ if (own) {
2444
+ return;
2445
+ }
2446
+ this._statusError = SEALED_ACCOUNT_READER;
2447
+ this._log?.error(['p2p', 'mesh'], SEALED_ACCOUNT_READER);
1955
2448
  this._notifyStatus();
1956
2449
  }
1957
2450
  _pooled(meshKey) {
@@ -1968,15 +2461,18 @@ export class Core extends ReadyResource {
1968
2461
  _poolEntry(mesh) {
1969
2462
  const key = this._meshIdOf(mesh);
1970
2463
  const existing = this._meshes.get(key);
1971
- if (existing?.mesh === mesh)
2464
+ if (existing?.mesh === mesh) {
1972
2465
  return existing;
2466
+ }
1973
2467
  const entry = {
1974
2468
  mesh,
1975
2469
  handlers: null,
1976
2470
  hostedAgents: null,
1977
2471
  processingFiles: null,
1978
2472
  vectorIndex: null,
1979
- memberLock: new ScopeLock({ debounce: true })
2473
+ memberLock: new ScopeLock({ debounce: true }),
2474
+ followLock: new ScopeLock({ debounce: true }),
2475
+ meshesPending: false
1980
2476
  };
1981
2477
  this._meshes.set(key, entry);
1982
2478
  return entry;
@@ -1986,11 +2482,13 @@ export class Core extends ReadyResource {
1986
2482
  if (b4a.toHex(mesh.blobs.core.key) === coreKey)
1987
2483
  return mesh;
1988
2484
  }
1989
- if (meshKey)
2485
+ if (meshKey) {
1990
2486
  return this._pooled(b4a.toHex(meshKey));
1991
- if (blockOffset === undefined)
2487
+ }
2488
+ if (blockOffset === undefined) {
1992
2489
  return null;
1993
- const indexed = await this.local.files.meshOf(Buffer.from(coreKey, 'hex'), blockOffset);
2490
+ }
2491
+ const indexed = await this.local.files.meshOf(b4a.from(coreKey, 'hex'), blockOffset);
1994
2492
  return indexed ? this._pooled(b4a.toHex(indexed)) : null;
1995
2493
  }
1996
2494
  _fileIndexFor(mesh) {
@@ -2001,31 +2499,36 @@ export class Core extends ReadyResource {
2001
2499
  refresh: (chunks) => this.local.files.refresh(known(chunks)),
2002
2500
  read: (reference) => {
2003
2501
  const file = referencedFile(reference, owner());
2004
- if (!file)
2502
+ if (!file) {
2005
2503
  return;
2504
+ }
2006
2505
  this.local.files
2007
2506
  .read(file)
2008
2507
  .catch((err) => this._log?.warn(['files'], 'recording a file read failed', err));
2009
2508
  },
2010
2509
  markCleared: async (blobId) => {
2011
2510
  const key = fileKeyOf(blobId, owner());
2012
- if (key)
2511
+ if (key) {
2013
2512
  await this.local.files.markCleared(key);
2513
+ }
2014
2514
  }
2015
2515
  };
2016
2516
  }
2017
2517
  async _indexMeshFiles(mesh) {
2018
2518
  try {
2019
2519
  await mesh.autobee.update();
2020
- if (await this.local.files.backfilled(mesh.key))
2520
+ if (await this.local.files.backfilled(mesh.key)) {
2021
2521
  return;
2522
+ }
2022
2523
  await backfillFileIndex(mesh);
2023
- if (!mesh.closing)
2524
+ if (!mesh.closing) {
2024
2525
  await this.local.files.markBackfilled(mesh.key);
2526
+ }
2025
2527
  }
2026
2528
  catch (err) {
2027
- if (!mesh.closing)
2529
+ if (!mesh.closing) {
2028
2530
  this._log?.warn(['files'], 'indexing the mesh files failed', err);
2531
+ }
2029
2532
  }
2030
2533
  }
2031
2534
  _servedFile(mesh, coreKey, blockOffset) {
@@ -2043,11 +2546,13 @@ export class Core extends ReadyResource {
2043
2546
  if (file.own && !includeOwn)
2044
2547
  continue;
2045
2548
  const mesh = this._pooled(b4a.toHex(file.meshKey));
2046
- if (!mesh)
2549
+ if (!mesh) {
2047
2550
  continue;
2551
+ }
2048
2552
  const done = await mesh.files.clear(file.blobId, file.attachmentId ?? file.blobId);
2049
- if (!done)
2553
+ if (!done) {
2050
2554
  continue;
2555
+ }
2051
2556
  await this.local.files.markCleared(file);
2052
2557
  cleared++;
2053
2558
  }
@@ -2055,8 +2560,9 @@ export class Core extends ReadyResource {
2055
2560
  }
2056
2561
  _startFileGc({ now = false } = {}) {
2057
2562
  const gc = this._fileGc;
2058
- if (!gc || this._fileGcTimer || this.suspended)
2563
+ if (!gc || this._fileGcTimer || this.suspended) {
2059
2564
  return;
2565
+ }
2060
2566
  const run = () => {
2061
2567
  if (this._fileGcRun || this.closing || this.suspended)
2062
2568
  return;
@@ -2068,12 +2574,14 @@ export class Core extends ReadyResource {
2068
2574
  };
2069
2575
  this._fileGcTimer = setInterval(run, gc.intervalMs ?? FILE_GC_INTERVAL_MS);
2070
2576
  unref(this._fileGcTimer);
2071
- if (now)
2577
+ if (now) {
2072
2578
  run();
2579
+ }
2073
2580
  }
2074
2581
  async _stopFileGc() {
2075
- if (this._fileGcTimer)
2582
+ if (this._fileGcTimer) {
2076
2583
  clearInterval(this._fileGcTimer);
2584
+ }
2077
2585
  this._fileGcTimer = null;
2078
2586
  await this._fileGcRun?.catch(noop);
2079
2587
  }
@@ -2095,10 +2603,12 @@ export class Core extends ReadyResource {
2095
2603
  this._meshes.delete(key);
2096
2604
  wasAccount = this._accountId === key;
2097
2605
  }
2098
- if (this._candidateMesh === mesh)
2606
+ if (this._candidateMesh === mesh) {
2099
2607
  this._candidateMesh = null;
2100
- if (wasAccount)
2608
+ }
2609
+ if (wasAccount) {
2101
2610
  this._notifyStatus();
2611
+ }
2102
2612
  }
2103
2613
  _unwireMesh(entry) {
2104
2614
  if (!entry.handlers)
@@ -2117,7 +2627,7 @@ export class Core extends ReadyResource {
2117
2627
  }
2118
2628
  _startMeshServices(entry) {
2119
2629
  const { mesh } = entry;
2120
- const deviceId = this._deviceKeyPair.publicKey;
2630
+ const deviceId = this._requireDeviceKeyPair().publicKey;
2121
2631
  mesh.on('notification', (event) => this.emit('notification', event));
2122
2632
  const built = rebuildChatOrder(mesh, this.local).catch((error) => this._log?.warn(['p2p', 'mesh'], 'building the chat order failed', error));
2123
2633
  mesh.chatOrderBuilt = built;
@@ -2132,7 +2642,7 @@ export class Core extends ReadyResource {
2132
2642
  void this.local
2133
2643
  .clearChatNotify(chatId)
2134
2644
  .catch((error) => this._log?.warn(['p2p', 'mesh'], 'chat-tombstone notification reclaim failed', error));
2135
- void removeChatAttachments(mesh, deviceId, chatId, deletedAt).catch((error) => this._log?.warn(['p2p', 'mesh'], 'chat-tombstone attachment reclaim failed', error));
2645
+ void removeChatAttachments(mesh, chatId, { deviceId, at: deletedAt }).catch((error) => this._log?.warn(['p2p', 'mesh'], 'chat-tombstone attachment reclaim failed', error));
2136
2646
  void removeChatKnowledge(mesh, chatId, deletedAt).catch((error) => this._log?.warn(['p2p', 'mesh'], 'chat-tombstone knowledge reclaim failed', error));
2137
2647
  void this._inferenceCalls
2138
2648
  ?.forget(chatId)
@@ -2143,8 +2653,9 @@ export class Core extends ReadyResource {
2143
2653
  if (!(await sweepLock.lock()))
2144
2654
  return;
2145
2655
  try {
2146
- if (!mesh.closing)
2656
+ if (!mesh.closing) {
2147
2657
  await mesh.files.sweepTombstones(deviceId);
2658
+ }
2148
2659
  }
2149
2660
  catch (error) {
2150
2661
  this._log?.warn(['p2p', 'mesh'], 'blob sweep failed', error);
@@ -2174,21 +2685,23 @@ export class Core extends ReadyResource {
2174
2685
  }
2175
2686
  async _discardCandidateMesh() {
2176
2687
  const candidate = this._candidateMesh;
2177
- if (!candidate)
2688
+ if (!candidate) {
2178
2689
  return;
2690
+ }
2179
2691
  this._candidateMesh = null;
2180
- if (this._swarm)
2692
+ if (this._swarm) {
2181
2693
  await this._swarm.leave(candidate.discoveryKey).catch(noop);
2694
+ }
2182
2695
  await candidate.close().catch(noop);
2183
2696
  }
2184
2697
  async _departureHasAudience(mesh) {
2185
2698
  if (!mesh.writable)
2186
2699
  return false;
2187
- const deviceId = this._deviceKeyPair.publicKey;
2700
+ const deviceId = this._requireDeviceKeyPair().publicKey;
2188
2701
  const snap = mesh.view.snapshot();
2189
2702
  try {
2190
- for await (const device of snap.find('@qvac/devices')) {
2191
- if (!device.revoked && !device.id.equals(deviceId))
2703
+ for await (const device of snap.find(DEVICES)) {
2704
+ if (!device.revoked && !b4a.equals(device.id, deviceId))
2192
2705
  return true;
2193
2706
  }
2194
2707
  return false;
@@ -2199,22 +2712,24 @@ export class Core extends ReadyResource {
2199
2712
  }
2200
2713
  async _announceDeparture(mesh = this._accountMesh(), strict = false) {
2201
2714
  if (!mesh?.writable) {
2202
- if (strict)
2715
+ if (strict) {
2203
2716
  throw new Error('Mesh departure requires a writable source');
2717
+ }
2204
2718
  return;
2205
2719
  }
2206
2720
  try {
2207
2721
  await mesh.dispatch('remove-writer', {
2208
2722
  writerKey: mesh.localWriterKey,
2209
- deviceId: this._deviceKeyPair.publicKey,
2723
+ deviceId: this._requireDeviceKeyPair().publicKey,
2210
2724
  revokedAt: Date.now()
2211
2725
  });
2212
2726
  await mesh.autobee.update();
2213
2727
  }
2214
2728
  catch (error) {
2215
2729
  this._log?.warn(['p2p', 'mesh'], 'writer departure announcement failed', error);
2216
- if (strict)
2730
+ if (strict) {
2217
2731
  throw error;
2732
+ }
2218
2733
  }
2219
2734
  }
2220
2735
  async leaveMesh(meshId) {
@@ -2222,15 +2737,18 @@ export class Core extends ReadyResource {
2222
2737
  return;
2223
2738
  if (!this.opened)
2224
2739
  await this.ready();
2225
- if (this._leaving === meshId)
2740
+ if (this._leaving === meshId) {
2226
2741
  return;
2227
- if (this._leaving || this._minting)
2742
+ }
2743
+ if (this._leaving || this._minting) {
2228
2744
  throw new Error('Mesh transition already in progress');
2745
+ }
2229
2746
  const departing = await this._openPooledMesh(meshId);
2230
- const others = (await this.local.listMeshes()).filter((row) => !row.key.equals(departing.key));
2747
+ const others = (await this.local.listMeshes()).filter((row) => !b4a.equals(row.key, departing.key));
2231
2748
  const leavingAccount = await this._isStoredAccount(departing);
2232
- if (others.length > 0 && leavingAccount)
2749
+ if (others.length > 0 && leavingAccount) {
2233
2750
  throw new Error(LEAVE_HOME_REFUSED);
2751
+ }
2234
2752
  this._leaving = meshId;
2235
2753
  this._notifyStatus();
2236
2754
  try {
@@ -2238,7 +2756,7 @@ export class Core extends ReadyResource {
2238
2756
  await this.local.recordDeparture(departing.key, { creator: departing.minted });
2239
2757
  }
2240
2758
  await this._announceDeparture(departing);
2241
- await this._releaseJoinedRoom(departing.key);
2759
+ await this._releaseJoinedMesh(departing.key);
2242
2760
  await this._archiveMembership(departing);
2243
2761
  if (!leavingAccount) {
2244
2762
  await this._retirePooledMesh(departing);
@@ -2246,10 +2764,11 @@ export class Core extends ReadyResource {
2246
2764
  return;
2247
2765
  }
2248
2766
  const landed = this._waitForMeshChange();
2249
- this._requestFreshMesh().catch(() => { });
2767
+ this._requestFreshMesh().catch(noop);
2250
2768
  const error = await landed;
2251
- if (error)
2769
+ if (error) {
2252
2770
  throw error;
2771
+ }
2253
2772
  }
2254
2773
  finally {
2255
2774
  this._leaving = null;
@@ -2258,17 +2777,18 @@ export class Core extends ReadyResource {
2258
2777
  }
2259
2778
  async _isStoredAccount(mesh) {
2260
2779
  const key = await this._storedAccountKey();
2261
- return key !== undefined && key.equals(mesh.key);
2780
+ return key !== undefined && b4a.equals(key, mesh.key);
2262
2781
  }
2263
2782
  async _storedAccountKey() {
2264
- return (await this.local.accountMesh(this._deviceKeyPair.publicKey))?.key;
2783
+ return (await this.local.accountMesh(this._requireDeviceKeyPair().publicKey))?.key;
2265
2784
  }
2266
2785
  listMeshes() {
2267
2786
  if (this._listing)
2268
2787
  return this._listing;
2269
2788
  const listing = this._readMeshList().finally(() => {
2270
- if (this._listing === listing)
2789
+ if (this._listing === listing) {
2271
2790
  this._listing = null;
2791
+ }
2272
2792
  });
2273
2793
  this._listing = listing;
2274
2794
  return listing;
@@ -2279,8 +2799,10 @@ export class Core extends ReadyResource {
2279
2799
  const accountKey = await this._storedAccountKey();
2280
2800
  const rows = await this.local.listMeshes();
2281
2801
  const registry = accountKey ? this._pooled(b4a.toHex(accountKey)) : null;
2282
- const rooms = registry ? await this._ownRooms(registry) : new Map();
2283
- return { meshes: rows.map((row) => this._meshEntry(row, accountKey, rooms)) };
2802
+ const meshes = registry ? await this._ownMeshes(registry) : new Map();
2803
+ return {
2804
+ meshes: await Promise.all(rows.map((row) => this._meshEntry(row, accountKey, meshes)))
2805
+ };
2284
2806
  }
2285
2807
  async listArchivedMeshes() {
2286
2808
  if (!this.opened)
@@ -2309,16 +2831,18 @@ export class Core extends ReadyResource {
2309
2831
  await this.ready();
2310
2832
  await this._meshTransitionLock.lock();
2311
2833
  try {
2312
- if (this.closing)
2834
+ if (this.closing) {
2313
2835
  throw new Error('Core is closing');
2836
+ }
2314
2837
  const row = await this._archivedRow(meshId);
2315
2838
  if (row.migratedAt) {
2316
2839
  const none = { chats: 0, agents: 0, knowledge: 0 };
2317
2840
  return { meshId, migrated: false, migratedAt: row.migratedAt, ...none };
2318
2841
  }
2319
2842
  const account = await this._writableAccount();
2320
- if (!account)
2843
+ if (!account) {
2321
2844
  throw new Error(NO_WRITABLE_ACCOUNT);
2845
+ }
2322
2846
  const counts = await this._withArchivedMesh(row, (mesh) => migrateContents(mesh, account));
2323
2847
  const migratedAt = Date.now();
2324
2848
  await this.local.markMeshMigrated(row.key, migratedAt);
@@ -2330,83 +2854,97 @@ export class Core extends ReadyResource {
2330
2854
  }
2331
2855
  async _archivedRow(meshId) {
2332
2856
  const key = this._meshKeyOf(meshId);
2333
- const row = (await this.local.listArchivedMeshes()).find((row) => row.key.equals(key));
2334
- if (!row)
2857
+ const row = (await this.local.listArchivedMeshes()).find((row) => b4a.equals(row.key, key));
2858
+ if (!row) {
2335
2859
  throw new Error(`${NO_SUCH_MESH}: ${meshId}`);
2336
- if (!row.wasHome)
2860
+ }
2861
+ if (!row.wasHome) {
2337
2862
  throw new Error(`${NOT_AN_ARCHIVED_ACCOUNT}: ${meshId}`);
2863
+ }
2338
2864
  return row;
2339
2865
  }
2340
2866
  _withArchivedMesh(row, fn) {
2341
2867
  const pooled = this._pooled(b4a.toHex(row.key));
2342
- if (pooled)
2868
+ if (pooled) {
2343
2869
  return fn(pooled);
2344
- return withArchivedMesh(this.store, row, { storage: this.storage, deviceId: this._deviceKeyPair.publicKey, logger: this._log }, fn);
2870
+ }
2871
+ return withArchivedMesh(row, {
2872
+ store: this.store,
2873
+ storage: this.storage,
2874
+ deviceId: this._requireDeviceKeyPair().publicKey,
2875
+ logger: this._log
2876
+ }, fn);
2345
2877
  }
2346
- async _ownRooms(registry) {
2347
- const rooms = new Map();
2878
+ async _ownMeshes(registry) {
2879
+ const meshes = new Map();
2348
2880
  const ours = registry.ourMemberId;
2349
- if (!ours)
2350
- return rooms;
2351
- for await (const room of registry.view.find(JOINED_MESHES)) {
2352
- if (!room.leftAt && room.memberId.equals(ours))
2353
- rooms.set(b4a.toHex(room.meshKey), room);
2881
+ if (!ours) {
2882
+ return meshes;
2883
+ }
2884
+ for await (const joined of registry.view.find(JOINED_MESHES)) {
2885
+ if (!joined.leftAt && b4a.equals(joined.memberId, ours)) {
2886
+ meshes.set(b4a.toHex(joined.meshKey), joined);
2887
+ }
2354
2888
  }
2355
- return rooms;
2889
+ return meshes;
2356
2890
  }
2357
- async _isOwnRoomIn(registry, meshKey) {
2891
+ async _isOwnMeshIn(registry, meshKey) {
2358
2892
  const ours = registry.ourMemberId;
2359
- if (!ours)
2893
+ if (!ours) {
2360
2894
  return false;
2361
- const room = await registry.view.get(JOINED_MESHES, { meshKey });
2362
- return Boolean(room) && !room.leftAt && room.memberId.equals(ours);
2895
+ }
2896
+ const joined = await registry.view.get(JOINED_MESHES, { meshKey });
2897
+ return !!joined && !joined.leftAt && b4a.equals(joined.memberId, ours);
2363
2898
  }
2364
2899
  async setMeshLabel(meshId, label) {
2365
2900
  if (!this.opened)
2366
2901
  await this.ready();
2367
2902
  const meshKey = this._meshKeyOf(meshId);
2368
2903
  const registry = await this._writableAccount();
2369
- if (!registry)
2370
- throw new Error(ROOM_WITHOUT_ACCOUNT);
2904
+ if (!registry) {
2905
+ throw new Error(MESH_WITHOUT_ACCOUNT);
2906
+ }
2371
2907
  const ours = registry.ourMemberId;
2372
- const room = await registry.view.get(JOINED_MESHES, { meshKey });
2373
- if (!room?.memberId.equals(ours))
2908
+ const joined = await registry.view.get(JOINED_MESHES, { meshKey });
2909
+ if (!ours || !joined || !b4a.equals(joined.memberId, ours)) {
2374
2910
  throw new Error(`${NO_SUCH_MESH}: ${meshId}`);
2911
+ }
2375
2912
  await registry.dispatch('put-joined-mesh', {
2376
2913
  room: {
2377
2914
  meshKey,
2378
2915
  memberId: ours,
2379
- joinedAt: room.joinedAt,
2380
- leftAt: room.leftAt,
2916
+ joinedAt: joined.joinedAt,
2917
+ leftAt: joined.leftAt,
2381
2918
  label,
2382
- labeledAt: Math.max(Date.now(), (room.labeledAt ?? 0) + 1),
2383
- shared: room.shared,
2384
- sharedAt: room.sharedAt
2919
+ labeledAt: Math.max(Date.now(), (joined.labeledAt ?? 0) + 1),
2920
+ shared: joined.shared,
2921
+ sharedAt: joined.sharedAt
2385
2922
  }
2386
2923
  });
2387
2924
  this._notifyStatus();
2388
2925
  }
2389
- async createRoom({ shared = false, compute = false } = {}) {
2926
+ async createMesh({ shared = false, compute = false } = {}) {
2390
2927
  if (!this.opened)
2391
2928
  await this.ready();
2392
2929
  await this._meshTransitionLock.lock();
2393
2930
  try {
2394
- return await this._mintRoom(shared, undefined, compute);
2931
+ return await this._mintMesh({ shared, compute });
2395
2932
  }
2396
2933
  finally {
2397
2934
  this._meshTransitionLock.unlock();
2398
2935
  }
2399
2936
  }
2400
- async sharedRoom() {
2937
+ async sharedMesh() {
2401
2938
  if (!this.opened)
2402
2939
  await this.ready();
2403
2940
  await this._meshTransitionLock.lock();
2404
2941
  try {
2405
2942
  const registry = await this._writableAccount();
2406
- if (!registry)
2407
- throw new Error(ROOM_WITHOUT_ACCOUNT);
2408
- const resolved = await this._resolveSharedRoom(registry);
2409
- return resolved ?? { meshId: await this._mintRoom(true, registry) };
2943
+ if (!registry) {
2944
+ throw new Error(MESH_WITHOUT_ACCOUNT);
2945
+ }
2946
+ const resolved = await this._resolveSharedMesh(registry);
2947
+ return resolved ?? { meshId: await this._mintMesh({ shared: true, registry }) };
2410
2948
  }
2411
2949
  finally {
2412
2950
  this._meshTransitionLock.unlock();
@@ -2414,19 +2952,21 @@ export class Core extends ReadyResource {
2414
2952
  }
2415
2953
  async _occupancyNotice(meshId) {
2416
2954
  const mesh = this._pooled(meshId);
2417
- if (!mesh)
2955
+ if (!mesh) {
2418
2956
  return undefined;
2419
- if (!mesh.ourMemberId)
2957
+ }
2958
+ if (!mesh.ourMemberId) {
2420
2959
  await mesh.refreshOurMember();
2960
+ }
2421
2961
  const ours = mesh.ourMemberId;
2422
2962
  const snap = mesh.view.snapshot();
2423
2963
  try {
2424
- for await (const member of snap.find('@qvac/members')) {
2425
- if (!ours || !member.id.equals(ours))
2426
- return ROOM_NOT_EMPTY;
2964
+ for await (const member of snap.find(MEMBERS)) {
2965
+ if (!ours || !b4a.equals(member.id, ours))
2966
+ return MESH_NOT_EMPTY;
2427
2967
  }
2428
- for await (const _chunk of snap.find('@qvac/chunks', { limit: 1 })) {
2429
- return ROOM_NOT_EMPTY;
2968
+ for await (const _chunk of snap.find(CHUNKS, { limit: 1 })) {
2969
+ return MESH_NOT_EMPTY;
2430
2970
  }
2431
2971
  return undefined;
2432
2972
  }
@@ -2434,61 +2974,76 @@ export class Core extends ReadyResource {
2434
2974
  await snap.close();
2435
2975
  }
2436
2976
  }
2437
- async _resolveSharedRoom(registry) {
2438
- const marked = [...(await this._ownRooms(registry)).values()].filter((room) => room.shared);
2439
- if (marked.length === 0)
2977
+ async _resolveSharedMesh(registry) {
2978
+ const marked = [...(await this._ownMeshes(registry)).values()].filter((joined) => joined.shared);
2979
+ if (marked.length === 0) {
2440
2980
  return null;
2441
- marked.sort((a, b) => a.joinedAt - b.joinedAt || Buffer.compare(a.meshKey, b.meshKey));
2981
+ }
2982
+ marked.sort((a, b) => a.joinedAt - b.joinedAt || b4a.compare(a.meshKey, b.meshKey));
2442
2983
  const [winner, ...losers] = marked;
2443
- for (const loser of losers)
2444
- await this._unmarkSharedRoom(registry, loser);
2445
- if (losers.length > 0)
2984
+ for (const loser of losers) {
2985
+ await this._unmarkSharedMesh(registry, loser);
2986
+ }
2987
+ if (losers.length > 0) {
2446
2988
  this._notifyStatus();
2989
+ }
2447
2990
  return { meshId: b4a.toHex(winner.meshKey), notice: unmarkedNotice(losers) };
2448
2991
  }
2449
- async _unmarkSharedRoom(registry, room) {
2992
+ async _unmarkSharedMesh(registry, joined) {
2450
2993
  await registry.dispatch('put-joined-mesh', {
2451
2994
  room: {
2452
- meshKey: room.meshKey,
2453
- memberId: room.memberId,
2454
- joinedAt: room.joinedAt,
2455
- label: room.label,
2456
- labeledAt: room.labeledAt,
2995
+ meshKey: joined.meshKey,
2996
+ memberId: joined.memberId,
2997
+ joinedAt: joined.joinedAt,
2998
+ label: joined.label,
2999
+ labeledAt: joined.labeledAt,
2457
3000
  shared: false,
2458
- sharedAt: Math.max(Date.now(), (room.sharedAt ?? 0) + 1)
3001
+ sharedAt: Math.max(Date.now(), (joined.sharedAt ?? 0) + 1)
2459
3002
  }
2460
3003
  });
2461
3004
  }
2462
- async _mintRoom(shared, resolved, compute = false) {
2463
- if (this.closing)
3005
+ async _mintMesh(opts) {
3006
+ const { shared, compute = false } = opts;
3007
+ if (this.closing) {
2464
3008
  throw new Error('Core is closing');
2465
- if (this._blockedByMinVersion())
3009
+ }
3010
+ if (this._blockedByMinVersion()) {
2466
3011
  throw new Error(MESH_BELOW_FLOOR);
2467
- if (this._leaving || this._minting)
3012
+ }
3013
+ if (this._leaving || this._minting) {
2468
3014
  throw new Error('Mesh transition already in progress');
2469
- const registry = resolved ?? (await this._writableAccount());
2470
- if (!registry)
2471
- throw new Error(ROOM_WITHOUT_ACCOUNT);
2472
- const mesh = await this._openMesh({ new: true, room: true, compute });
3015
+ }
3016
+ const registry = opts.registry ?? (await this._writableAccount());
3017
+ if (!registry) {
3018
+ throw new Error(MESH_WITHOUT_ACCOUNT);
3019
+ }
3020
+ if (!registry.ourMemberId) {
3021
+ throw new Error(ACCOUNT_MEMBER_UNKNOWN);
3022
+ }
3023
+ const mesh = await this._openMesh({ new: true, sharing: true, compute });
2473
3024
  this._wireMesh(this._poolEntry(mesh));
2474
3025
  this._bringMeshOnline(mesh, { new: true });
2475
3026
  try {
2476
- await this._registerRoom(mesh.key, shared, registry);
3027
+ await mesh.refreshOurMember();
3028
+ if (!mesh.ourMemberId) {
3029
+ throw new Error(MESH_WITHOUT_MEMBER);
3030
+ }
3031
+ await this._registerMesh(mesh.key, { shared, registry });
2477
3032
  }
2478
3033
  catch (error) {
2479
- await this._discardRoom(mesh);
3034
+ await this._discardMesh(mesh);
2480
3035
  throw error;
2481
3036
  }
2482
3037
  this._notifyStatus();
2483
3038
  return this._meshIdOf(mesh);
2484
3039
  }
2485
- async _discardRoom(mesh) {
3040
+ async _discardMesh(mesh) {
2486
3041
  try {
2487
3042
  await this.local.archiveMesh(mesh.key);
2488
3043
  await this._retirePooledMesh(mesh);
2489
3044
  }
2490
3045
  catch (error) {
2491
- this._log?.error(['p2p', 'mesh'], 'an unregistered room was left behind', error);
3046
+ this._log?.error(['p2p', 'mesh'], 'an unregistered mesh was left behind', error);
2492
3047
  }
2493
3048
  }
2494
3049
  async openMesh(meshId) {
@@ -2499,13 +3054,15 @@ export class Core extends ReadyResource {
2499
3054
  await this.ready();
2500
3055
  await this._meshTransitionLock.lock();
2501
3056
  try {
2502
- if (meshId === this._accountId)
3057
+ if (meshId === this._accountId) {
2503
3058
  throw new Error('The account mesh cannot be closed');
3059
+ }
2504
3060
  const key = this._meshKeyOf(meshId);
2505
3061
  const mesh = this._pooled(meshId) ?? (await this._opening.get(meshId)?.catch(noop)) ?? null;
2506
3062
  if (!mesh) {
2507
- if (!(await this.local.readMeshSession(key)))
3063
+ if (!(await this.local.readMeshSession(key))) {
2508
3064
  throw new Error(`${NO_SUCH_MESH}: ${meshId}`);
3065
+ }
2509
3066
  return;
2510
3067
  }
2511
3068
  await this._retirePooledMesh(mesh);
@@ -2518,33 +3075,45 @@ export class Core extends ReadyResource {
2518
3075
  async _openPooledMesh(meshId) {
2519
3076
  if (!this.opened)
2520
3077
  await this.ready();
2521
- if (this.closing)
3078
+ if (this.closing) {
2522
3079
  throw new Error('Core is closing');
2523
- if (this._blockedByMinVersion())
3080
+ }
3081
+ if (this._blockedByMinVersion()) {
2524
3082
  throw new Error(MESH_BELOW_FLOOR);
3083
+ }
2525
3084
  const pooled = this._pooled(meshId);
2526
- if (pooled)
3085
+ if (pooled) {
2527
3086
  return pooled;
3087
+ }
2528
3088
  const retiring = this._retiring.get(meshId);
2529
3089
  if (retiring) {
2530
3090
  await retiring.catch(noop);
2531
3091
  return this._openPooledMesh(meshId);
2532
3092
  }
2533
3093
  const inflight = this._opening.get(meshId);
2534
- if (inflight)
3094
+ if (inflight) {
2535
3095
  return inflight;
3096
+ }
2536
3097
  const opening = this._openRecordedMesh(meshId).finally(() => {
2537
- if (this._opening.get(meshId) === opening)
3098
+ if (this._opening.get(meshId) === opening) {
2538
3099
  this._opening.delete(meshId);
3100
+ }
2539
3101
  });
2540
3102
  this._opening.set(meshId, opening);
2541
3103
  return opening;
2542
3104
  }
2543
3105
  async _openRecordedMesh(meshId) {
2544
- const session = await this.local.readMeshSession(this._meshKeyOf(meshId));
2545
- if (!session)
3106
+ if (this._debugBeforeMeshOpen) {
3107
+ await this._debugBeforeMeshOpen(meshId);
3108
+ }
3109
+ const key = this._meshKeyOf(meshId);
3110
+ const session = await this.local.readMeshSession(key);
3111
+ if (!session) {
2546
3112
  throw new Error(`${NO_SUCH_MESH}: ${meshId}`);
2547
- const mesh = await this._openMeshSession(session);
3113
+ }
3114
+ const stored = await this._storedAccountKey();
3115
+ const sharing = !stored || !b4a.equals(stored, key);
3116
+ const mesh = await this._openMeshSession(session, { sharing });
2548
3117
  const halted = mesh.interrupted;
2549
3118
  if (halted) {
2550
3119
  this._withdrawFromMesh(mesh, halted);
@@ -2553,29 +3122,59 @@ export class Core extends ReadyResource {
2553
3122
  this._wireMesh(this._poolEntry(mesh));
2554
3123
  this._bringMeshOnline(mesh);
2555
3124
  this._notifyStatus();
3125
+ this._debugOnMeshOpened?.(mesh, meshId);
2556
3126
  return mesh;
2557
3127
  }
2558
- _meshEntry(row, accountKey, rooms) {
3128
+ async _meshEntry(row, accountKey, meshes) {
2559
3129
  const meshId = b4a.toHex(row.key);
2560
3130
  const mesh = this._pooled(meshId);
2561
- const account = !!accountKey?.equals(row.key);
2562
- const room = rooms.get(meshId);
3131
+ const account = !!accountKey && b4a.equals(accountKey, row.key);
3132
+ const joined = meshes.get(meshId);
3133
+ const state = this._meshEntryState(mesh, account);
3134
+ const admission = state === 'joining' ? await this._admission(mesh) : {};
2563
3135
  return {
2564
3136
  meshId,
2565
- state: this._meshEntryState(mesh, account),
3137
+ state,
2566
3138
  writable: mesh?.writable ?? false,
2567
3139
  open: mesh !== null,
2568
3140
  account,
2569
- label: room?.label || undefined,
3141
+ label: joined?.label || undefined,
2570
3142
  members: mesh?.membership.members ?? 0,
2571
- shared: room?.shared ?? false,
2572
- sharedAt: room?.shared ? room.sharedAt : undefined,
2573
- compute: row.compute ?? false
3143
+ shared: joined?.shared ?? false,
3144
+ sharedAt: joined?.shared ? joined.sharedAt : undefined,
3145
+ compute: row.compute ?? false,
3146
+ reason: admission.reason,
3147
+ awaitingFrom: admission.awaitingFrom
3148
+ };
3149
+ }
3150
+ async _admission(mesh) {
3151
+ if (!mesh || mesh.writable)
3152
+ return {};
3153
+ const ours = mesh.localWriterKey;
3154
+ const admitters = [];
3155
+ try {
3156
+ for await (const device of mesh.view.find(DEVICES)) {
3157
+ if (device.revoked || (device.writerKey && b4a.equals(device.writerKey, ours))) {
3158
+ continue;
3159
+ }
3160
+ admitters.push(device.name);
3161
+ if (admitters.length > 1) {
3162
+ break;
3163
+ }
3164
+ }
3165
+ }
3166
+ catch {
3167
+ return { reason: AWAITING_ADMISSION };
3168
+ }
3169
+ return {
3170
+ reason: AWAITING_ADMISSION,
3171
+ awaitingFrom: admitters.length === 1 ? admitters[0] : undefined
2574
3172
  };
2575
3173
  }
2576
3174
  _meshEntryState(mesh, account) {
2577
- if (account)
3175
+ if (account) {
2578
3176
  return this._statusState();
3177
+ }
2579
3178
  if (!mesh)
2580
3179
  return 'idle';
2581
3180
  return mesh.writable ? 'joined' : 'joining';
@@ -2583,20 +3182,115 @@ export class Core extends ReadyResource {
2583
3182
  _meshKeyOf(meshId) {
2584
3183
  if (!MESH_ID.test(meshId))
2585
3184
  throw new Error(`${NO_SUCH_MESH}: ${meshId}`);
2586
- return Buffer.from(meshId, 'hex');
3185
+ return b4a.from(meshId, 'hex');
2587
3186
  }
2588
3187
  async removeDeviceWriter(writerKey, deviceId, mesh) {
2589
3188
  const target = mesh ?? (await this._awaitMesh());
2590
- if (!target)
3189
+ if (!target) {
2591
3190
  throw new Error('this device holds no account mesh');
3191
+ }
2592
3192
  await target.dispatch('remove-writer', { writerKey, deviceId, revokedAt: Date.now() });
3193
+ await target.autobee.update();
3194
+ if (target === this._accountMesh()) {
3195
+ this._sweepUnknownEverywhere = true;
3196
+ }
3197
+ await this._revokeInMeshes();
3198
+ }
3199
+ _revokeInMeshes() {
3200
+ if (this._revokingInMeshes) {
3201
+ this._revokeInMeshesAgain = true;
3202
+ return this._revokingInMeshes;
3203
+ }
3204
+ this._revokingInMeshes = (async () => {
3205
+ do {
3206
+ this._revokeInMeshesAgain = false;
3207
+ await this._revokeInMeshesOnce();
3208
+ } while (this._revokeInMeshesAgain);
3209
+ })().finally(() => {
3210
+ this._revokingInMeshes = null;
3211
+ });
3212
+ return this._revokingInMeshes;
3213
+ }
3214
+ async _sweepEveryOwnMesh(account, ours) {
3215
+ for await (const joined of account.view.find(JOINED_MESHES)) {
3216
+ if (b4a.equals(joined.memberId, ours) && !joined.leftAt) {
3217
+ this._sweepUnknownIn.add(b4a.toHex(joined.meshKey));
3218
+ }
3219
+ }
3220
+ }
3221
+ async _revokeStaleRows(account, mesh, { self, ours, unknownToo }) {
3222
+ const rows = [];
3223
+ for await (const row of mesh.view.find(DEVICES)) {
3224
+ rows.push(row);
3225
+ }
3226
+ for (const row of rows) {
3227
+ if (!row.writerKey || row.revoked || b4a.equals(row.id, self)) {
3228
+ continue;
3229
+ }
3230
+ const member = row.memberId ?? row.claimedMemberId;
3231
+ if (member && !b4a.equals(member, ours)) {
3232
+ continue;
3233
+ }
3234
+ const device = await account.view.get(DEVICES, { id: row.id });
3235
+ if (device && !device.revoked) {
3236
+ continue;
3237
+ }
3238
+ if (!member &&
3239
+ device?.writerKey &&
3240
+ device.revokedBy &&
3241
+ b4a.equals(device.revokedBy, device.writerKey)) {
3242
+ continue;
3243
+ }
3244
+ if (!device && (!member || !unknownToo)) {
3245
+ continue;
3246
+ }
3247
+ await mesh.dispatch('remove-writer', {
3248
+ writerKey: row.writerKey,
3249
+ deviceId: row.id,
3250
+ revokedAt: device ? device.revokedAt : Date.now()
3251
+ });
3252
+ }
3253
+ }
3254
+ async _revokeInMeshesOnce() {
3255
+ try {
3256
+ const account = this._accountMesh();
3257
+ if (!account?.ourMemberId) {
3258
+ return;
3259
+ }
3260
+ if (this._sweepUnknownEverywhere) {
3261
+ this._sweepUnknownEverywhere = false;
3262
+ await this._sweepEveryOwnMesh(account, account.ourMemberId);
3263
+ }
3264
+ const self = this._requireDeviceKeyPair().publicKey;
3265
+ for (const { mesh } of [...this._meshes.values()]) {
3266
+ if (mesh === account || !mesh.writable)
3267
+ continue;
3268
+ if (!(await this._isOwnMeshIn(account, mesh.key)))
3269
+ continue;
3270
+ if (!mesh.ourMemberId) {
3271
+ await mesh.refreshOurMember();
3272
+ }
3273
+ if (!mesh.ourMemberId) {
3274
+ continue;
3275
+ }
3276
+ const meshId = b4a.toHex(mesh.key);
3277
+ const unknownToo = this._sweepUnknownIn.has(meshId);
3278
+ await this._revokeStaleRows(account, mesh, { self, ours: mesh.ourMemberId, unknownToo });
3279
+ this._sweepUnknownIn.delete(meshId);
3280
+ }
3281
+ }
3282
+ catch (error) {
3283
+ this._log?.warn(['p2p', 'mesh'], 'revoking an account-revoked device in a shared mesh failed', error);
3284
+ }
2593
3285
  }
2594
3286
  async renameLocalDevice(name) {
2595
3287
  const publicKey = this.devicePublicKey;
2596
- if (publicKey)
3288
+ if (publicKey) {
2597
3289
  await this.local.renameDevice(publicKey, name);
2598
- if (this._localDevice)
3290
+ }
3291
+ if (this._localDevice) {
2599
3292
  this._localDevice = { ...this._localDevice, name };
3293
+ }
2600
3294
  }
2601
3295
  async account() {
2602
3296
  if (!this.opened)
@@ -2610,25 +3304,32 @@ export class Core extends ReadyResource {
2610
3304
  }
2611
3305
  async displayName() {
2612
3306
  const identity = await this.local.readIdentity();
2613
- if (!identity)
3307
+ if (!identity) {
2614
3308
  return null;
3309
+ }
2615
3310
  return identity.displayName ?? (await this._accountMemberName(identity.publicKey));
2616
3311
  }
2617
3312
  async _accountMemberName(identityPublicKey) {
2618
3313
  const key = await this._storedAccountKey();
2619
3314
  const mesh = key ? this._pooled(b4a.toHex(key)) : null;
2620
- if (!mesh)
3315
+ if (!mesh) {
2621
3316
  return null;
3317
+ }
2622
3318
  const ours = mesh.ourMemberId;
2623
- if (!ours || ours.equals(identityPublicKey))
3319
+ if (!ours || b4a.equals(ours, identityPublicKey)) {
2624
3320
  return null;
2625
- const member = await mesh.view.get('@qvac/members', { id: ours });
3321
+ }
3322
+ const member = await mesh.view.get(MEMBERS, { id: ours });
2626
3323
  return member?.name ?? null;
2627
3324
  }
2628
3325
  async saveDeviceProfileLocal(capabilityProfile, recommendedModelName, platform) {
2629
3326
  const publicKey = this.devicePublicKey;
2630
3327
  if (publicKey) {
2631
- await this.local.saveDeviceProfile(publicKey, capabilityProfile, recommendedModelName, platform);
3328
+ await this.local.saveDeviceProfile(publicKey, {
3329
+ capabilityProfile,
3330
+ recommendedModelName,
3331
+ platform
3332
+ });
2632
3333
  }
2633
3334
  if (this._localDevice) {
2634
3335
  this._localDevice = {
@@ -2642,49 +3343,79 @@ export class Core extends ReadyResource {
2642
3343
  async waitForWritable() {
2643
3344
  if (this.closing)
2644
3345
  return;
2645
- await this.ready();
3346
+ if (!this.opened)
3347
+ await this.ready();
2646
3348
  const mesh = await this._awaitMesh();
2647
- if (this.closing || !mesh)
3349
+ if (this.closing || !mesh) {
2648
3350
  return;
3351
+ }
2649
3352
  await Promise.race([mesh.waitForWritable(), this._closeSignal]);
2650
3353
  }
2651
- async _assertRoomIsHere(meshId) {
3354
+ async _assertMeshIsHere(meshId) {
2652
3355
  const meshKey = this._meshKeyOf(meshId);
2653
- if (await this.local.readMeshSession(meshKey))
3356
+ if (await this.local.readMeshSession(meshKey)) {
2654
3357
  return;
3358
+ }
2655
3359
  const registry = await this._writableAccount();
2656
- if (registry && (await this._isOwnRoomIn(registry, meshKey))) {
2657
- throw new Error(ROOM_HELD_BY_SIBLING);
3360
+ if (registry && (await this._isOwnMeshIn(registry, meshKey))) {
3361
+ throw new Error(MESH_HELD_BY_SIBLING);
2658
3362
  }
2659
3363
  }
2660
3364
  async getMeshInvite(opts = {}) {
2661
- if (opts.memberInvite && opts.meshId)
2662
- await this._assertRoomIsHere(opts.meshId);
2663
- if (this.closing)
3365
+ if (opts.memberInvite && opts.meshId) {
3366
+ await this._assertMeshIsHere(opts.meshId);
3367
+ }
3368
+ if (this.closing) {
2664
3369
  return null;
2665
- if (!this.opened)
3370
+ }
3371
+ if (!this.opened) {
2666
3372
  await this.ready();
3373
+ }
2667
3374
  const accountKey = opts.memberInvite ? null : await this._storedAccountKey();
2668
3375
  const target = opts.meshId ?? (accountKey ? b4a.toHex(accountKey) : null);
2669
3376
  const mesh = target ? await this._openPooledMesh(target) : await this._awaitMesh();
2670
- if (!mesh)
3377
+ if (!mesh) {
2671
3378
  return null;
3379
+ }
2672
3380
  const registry = await this._writableAccount();
2673
- if (!registry?.ourMemberId)
3381
+ if (!registry?.ourMemberId) {
2674
3382
  throw new Error(INVITE_ACCOUNT_UNREADABLE);
2675
- const room = await this._isOwnRoomIn(registry, mesh.key);
3383
+ }
3384
+ const isOwnMesh = await this._isOwnMeshIn(registry, mesh.key);
2676
3385
  if (opts.memberInvite) {
2677
- if (!room)
3386
+ if (!isOwnMesh) {
2678
3387
  throw new Error(MEMBER_INVITE_HOME_REFUSED);
3388
+ }
2679
3389
  }
2680
3390
  else {
2681
- if (room)
2682
- throw new Error(DEVICE_INVITE_ROOM_REFUSED);
3391
+ if (isOwnMesh) {
3392
+ throw new Error(DEVICE_INVITE_MESH_REFUSED);
3393
+ }
2683
3394
  const key = await this._storedAccountKey();
2684
- if (!key)
3395
+ if (!key) {
2685
3396
  throw new Error(INVITE_ACCOUNT_UNREADABLE);
2686
- if (!key.equals(mesh.key))
2687
- throw new Error(DEVICE_INVITE_ROOM_REFUSED);
3397
+ }
3398
+ if (!b4a.equals(key, mesh.key)) {
3399
+ throw new Error(DEVICE_INVITE_MESH_REFUSED);
3400
+ }
3401
+ }
3402
+ let grantSecret;
3403
+ if (opts.memberInvite) {
3404
+ grantSecret = crypto.randomBytes(32);
3405
+ const now = Date.now();
3406
+ const terms = { expiresAt: now + GRANT_DEFAULT_TTL_MS, maxUses: GRANT_DEFAULT_MAX_USES };
3407
+ const refusal = inviteGrantTermsRefusal(terms, now);
3408
+ if (refusal) {
3409
+ throw new Error(refusal);
3410
+ }
3411
+ await mesh.dispatch('put-mesh-invite-grant', {
3412
+ grant: {
3413
+ grantKey: grantKeyPair(grantSecret).publicKey,
3414
+ kind: 'member',
3415
+ ...terms,
3416
+ updatedAt: now
3417
+ }
3418
+ });
2688
3419
  }
2689
3420
  const auto = mesh.autobee;
2690
3421
  const info = await auto.system.getInfo();
@@ -2693,11 +3424,14 @@ export class Core extends ReadyResource {
2693
3424
  ? this._swarm.dht.toArray({ limit: INVITE_DHT_NODES_LIMIT })
2694
3425
  : [];
2695
3426
  const memberId = opts.memberInvite ? undefined : (mesh.ourMemberId ?? undefined);
3427
+ const inviterName = memberId
3428
+ ? ((await mesh.view.get(MEMBERS, { id: memberId }))?.name ?? undefined)
3429
+ : undefined;
2696
3430
  const snap = mesh.view.snapshot();
2697
3431
  let blindPeerRows;
2698
3432
  try {
2699
3433
  blindPeerRows = await snap
2700
- .find('@qvac/mesh-blind-peers', { limit: INVITE_BLIND_PEERS_LIMIT })
3434
+ .find(MESH_BLIND_PEERS, { limit: INVITE_BLIND_PEERS_LIMIT })
2701
3435
  .toArray();
2702
3436
  }
2703
3437
  finally {
@@ -2713,10 +3447,18 @@ export class Core extends ReadyResource {
2713
3447
  : this._resolveBlindPeerKeys().slice(0, INVITE_BLIND_PEERS_LIMIT),
2714
3448
  memberInvite: opts.memberInvite ?? false,
2715
3449
  memberId,
2716
- inviteNonce: memberId ? await this._deviceInvites.issue() : undefined,
2717
- compute: mesh.compute
3450
+ inviteNonce: grantSecret ?? (memberId ? await this._deviceInvites.issue() : undefined),
3451
+ compute: mesh.compute,
3452
+ inviterName
2718
3453
  };
2719
3454
  }
3455
+ previewMeshInvite(invite) {
3456
+ const decoded = decodeMeshInvite(invite);
3457
+ if (!decoded) {
3458
+ throw new Error('Invalid mesh invite');
3459
+ }
3460
+ return { memberInvite: decoded.memberInvite ?? false, inviterName: decoded.inviterName };
3461
+ }
2720
3462
  async _closeSwarm() {
2721
3463
  this._wakeup.destroy();
2722
3464
  this._meshSeedHandoff.destroy();
@@ -2724,12 +3466,14 @@ export class Core extends ReadyResource {
2724
3466
  this._secretHandoff.destroy();
2725
3467
  this._skillOverlayHandoff.destroy();
2726
3468
  this._inferenceCallsHandoff.destroy();
2727
- if (!this._swarm)
3469
+ if (!this._swarm) {
2728
3470
  return;
3471
+ }
2729
3472
  const swarm = this._swarm;
2730
3473
  this._swarm = null;
2731
- for (const conn of swarm.connections)
3474
+ for (const conn of swarm.connections) {
2732
3475
  conn.destroy?.();
3476
+ }
2733
3477
  await swarm.destroy();
2734
3478
  }
2735
3479
  async pushSkillSecret(request) {
@@ -2737,26 +3481,31 @@ export class Core extends ReadyResource {
2737
3481
  await this.ready();
2738
3482
  const mesh = this._accountMesh();
2739
3483
  const deviceId = this.devicePublicKey;
2740
- if (!mesh || !deviceId)
3484
+ if (!mesh || !deviceId) {
2741
3485
  throw new Error(NOT_THE_HOST);
3486
+ }
2742
3487
  const agent = await getAgent(mesh, request.agentId);
2743
- if (!agent)
3488
+ if (!agent) {
2744
3489
  throw new Error(NO_SUCH_AGENT);
2745
- if (!agent.providerDeviceId)
3490
+ }
3491
+ if (!agent.providerDeviceId) {
2746
3492
  throw new Error(NOT_THE_HOST);
2747
- if (agent.providerDeviceId.equals(deviceId)) {
3493
+ }
3494
+ if (b4a.equals(agent.providerDeviceId, deviceId)) {
2748
3495
  return this._storeHandedOffSecret(request, deviceId);
2749
3496
  }
2750
- const host = await mesh.view.get('@qvac/devices', { id: agent.providerDeviceId });
2751
- if (!host || host.revoked)
3497
+ const host = await mesh.view.get(DEVICES, { id: agent.providerDeviceId });
3498
+ if (!host || host.revoked) {
2752
3499
  throw new Error(HOST_REVOKED);
3500
+ }
2753
3501
  return this._secretHandoff.send(agent.providerDeviceId, request);
2754
3502
  }
2755
3503
  async _storeHandedOffSecret(request, fromDeviceId) {
2756
3504
  const mesh = this._accountMesh();
2757
3505
  const deviceId = this.devicePublicKey;
2758
- if (!mesh || !deviceId)
3506
+ if (!mesh || !deviceId) {
2759
3507
  throw new Error(NOT_THE_HOST);
3508
+ }
2760
3509
  const receive = createSkillSecretReceiver({
2761
3510
  mesh,
2762
3511
  local: this.local,
@@ -2766,98 +3515,305 @@ export class Core extends ReadyResource {
2766
3515
  });
2767
3516
  return receive(request, fromDeviceId);
2768
3517
  }
2769
- async _followJoinedRooms(memberMesh) {
3518
+ async _followJoinedMeshes(memberMesh) {
2770
3519
  if (this.closing || !this._isPooled(memberMesh))
2771
3520
  return;
3521
+ const entry = this._meshes.get(this._meshIdOf(memberMesh));
3522
+ if (entry?.mesh !== memberMesh) {
3523
+ return;
3524
+ }
3525
+ if (!memberMesh.ourMemberId) {
3526
+ await memberMesh.refreshOurMember();
3527
+ }
2772
3528
  const ours = memberMesh.ourMemberId;
2773
- if (!ours)
3529
+ if (!ours) {
3530
+ entry.meshesPending = false;
3531
+ return;
3532
+ }
3533
+ if (!(await entry.followLock.lock())) {
2774
3534
  return;
2775
- for await (const room of memberMesh.view.find(JOINED_MESHES)) {
3535
+ }
3536
+ try {
3537
+ entry.meshesPending = await this._followMeshRows(memberMesh, ours);
3538
+ }
3539
+ finally {
3540
+ entry.followLock.unlock();
3541
+ }
3542
+ }
3543
+ async _followMeshRows(memberMesh, ours) {
3544
+ let pending = false;
3545
+ for await (const joined of memberMesh.view.find(JOINED_MESHES)) {
2776
3546
  if (this.closing || !this._isPooled(memberMesh))
2777
- return;
2778
- if (!room.memberId.equals(ours))
3547
+ return pending;
3548
+ if (!b4a.equals(joined.memberId, ours))
2779
3549
  continue;
2780
- const meshId = b4a.toHex(room.meshKey);
2781
- if (this._following.has(meshId))
3550
+ const meshId = b4a.toHex(joined.meshKey);
3551
+ if (this._following.has(meshId)) {
2782
3552
  continue;
3553
+ }
2783
3554
  const held = this._pooled(meshId);
2784
- this._following.add(meshId);
2785
- try {
2786
- if (room.leftAt) {
2787
- if (held)
2788
- await this._retireLeftRoom(held);
2789
- else
2790
- await this._archiveLeftRoomRow(room.meshKey);
2791
- continue;
3555
+ const failed = await this._trackFollow(meshId, async () => {
3556
+ if (joined.leftAt) {
3557
+ if (held) {
3558
+ await this._retireLeftMesh(held);
3559
+ }
3560
+ else {
3561
+ await this._archiveLeftMeshRow(joined.meshKey);
3562
+ }
3563
+ return;
2792
3564
  }
2793
- if (held)
2794
- continue;
2795
- if (await this.local.readMeshSession(room.meshKey))
2796
- continue;
2797
- await this._openFollowedRoom(memberMesh, room.meshKey, ours);
2798
- }
2799
- catch (error) {
2800
- this._log?.warn(['p2p', 'mesh'], 'following a joined room failed', error);
3565
+ if (held) {
3566
+ await this._requestMeshAdmission(memberMesh, held, ours);
3567
+ return;
3568
+ }
3569
+ if (await this.local.readMeshSession(joined.meshKey)) {
3570
+ if (this._upgradeRequired !== 'halt' &&
3571
+ (await this.local.awaitsAdmission(joined.meshKey))) {
3572
+ await this._requestMeshAdmission(memberMesh, await this._openPooledMesh(meshId), ours);
3573
+ }
3574
+ return;
3575
+ }
3576
+ await this._openFollowedMesh(memberMesh, joined.meshKey, ours);
3577
+ });
3578
+ if (failed && !joined.leftAt) {
3579
+ pending = true;
2801
3580
  }
2802
- finally {
3581
+ }
3582
+ return pending;
3583
+ }
3584
+ async _trackFollow(meshId, work) {
3585
+ let failed = false;
3586
+ const pass = work().catch((error) => {
3587
+ failed = true;
3588
+ this._log?.warn(['p2p', 'mesh'], 'following a joined mesh failed', error);
3589
+ });
3590
+ this._following.set(meshId, pass);
3591
+ try {
3592
+ await pass;
3593
+ }
3594
+ finally {
3595
+ if (this._following.get(meshId) === pass) {
2803
3596
  this._following.delete(meshId);
2804
3597
  }
2805
3598
  }
3599
+ return failed;
2806
3600
  }
2807
- async _retireLeftRoom(room) {
3601
+ async _retireLeftMesh(mesh) {
2808
3602
  if (this._leaving || this._minting)
2809
3603
  return;
2810
3604
  try {
2811
- if (await this._departureHasAudience(room)) {
2812
- await this.local.recordDeparture(room.key, { creator: room.minted });
2813
- }
2814
- await this._announceDeparture(room);
2815
- if (this._isAccount(room))
2816
- await this._replaceRevokedAccount(room);
2817
- else
2818
- await this._departRevokedMesh(room);
3605
+ if (await this._departureHasAudience(mesh)) {
3606
+ await this.local.recordDeparture(mesh.key, { creator: mesh.minted });
3607
+ }
3608
+ await this._announceDeparture(mesh);
3609
+ if (this._isAccount(mesh)) {
3610
+ await this._replaceRevokedAccount(mesh);
3611
+ }
3612
+ else {
3613
+ await this._departRevokedMesh(mesh);
3614
+ }
2819
3615
  this._departures?.flush();
2820
3616
  }
2821
3617
  catch (error) {
2822
- this._log?.warn(['p2p', 'mesh'], 'retiring a room the member left failed', error);
3618
+ this._log?.warn(['p2p', 'mesh'], 'retiring a mesh the member left failed', error);
2823
3619
  }
2824
3620
  }
2825
- async _archiveLeftRoomRow(meshKey) {
3621
+ async _archiveLeftMeshRow(meshKey) {
2826
3622
  if (!(await this.local.readMeshSession(meshKey)))
2827
3623
  return;
2828
3624
  await this.local.archiveMesh(meshKey);
2829
3625
  this._notifyStatus();
2830
3626
  }
2831
- async _openFollowedRoom(memberMesh, meshKey, ours) {
2832
- const seed = await this._requestRoomSeed(memberMesh, meshKey, ours);
2833
- if (!seed)
3627
+ async _openOwnMesh(invite) {
3628
+ const meshKey = invite.baseKey;
3629
+ const meshId = b4a.toHex(meshKey);
3630
+ if (!invite.inviteNonce) {
3631
+ return false;
3632
+ }
3633
+ const grantKey = grantKeyPair(invite.inviteNonce).publicKey;
3634
+ if (await this.local.readMeshSession(meshKey)) {
3635
+ return this._adoptOwnMesh(await this._openPooledMesh(meshId), grantKey);
3636
+ }
3637
+ const registry = await this._accountMesh();
3638
+ const ours = registry?.ourMemberId;
3639
+ if (!registry || !ours || !(await this._isOwnMeshIn(registry, meshKey))) {
3640
+ return false;
3641
+ }
3642
+ if (this._blockedByMinVersion()) {
3643
+ throw new Error(MESH_BELOW_FLOOR);
3644
+ }
3645
+ this._throwIfJoinCanceled();
3646
+ await this._openFollowedMesh(registry, meshKey, ours).catch((error) => {
3647
+ this._log?.warn(['p2p', 'mesh'], 'opening a mesh of ours through a sibling failed', error);
3648
+ });
3649
+ if (this.closing) {
3650
+ throw new Error('Core is closing');
3651
+ }
3652
+ this._throwIfJoinCanceled();
3653
+ const mesh = this._pooled(meshId);
3654
+ return mesh ? this._adoptOwnMesh(mesh, grantKey) : false;
3655
+ }
3656
+ async _adoptOwnMesh(mesh, grantKey) {
3657
+ const id = this._requireDeviceKeyPair().publicKey;
3658
+ const ours = this._accountMesh()?.ourMemberId ?? null;
3659
+ await this._awaitGrantRow(mesh, grantKey);
3660
+ let refused = false;
3661
+ const settled = await this._untilDeadline(async () => {
3662
+ const own = await mesh.view.get(DEVICES, { id });
3663
+ if (own && !own.revoked && own.writerKey && b4a.equals(own.writerKey, mesh.localWriterKey)) {
3664
+ return true;
3665
+ }
3666
+ refused = await this._refusedInMesh(mesh, grantKey, ours);
3667
+ return refused;
3668
+ });
3669
+ if (refused) {
3670
+ const own = await mesh.view.get(DEVICES, { id });
3671
+ await this._refuseUnredeemable(mesh, grantKey, own?.memberId ?? mesh.ourMemberId);
3672
+ await this._retirePooledMesh(mesh);
3673
+ await this.local.archiveMesh(mesh.key);
3674
+ return false;
3675
+ }
3676
+ if (!settled) {
3677
+ throw new Error(MESH_ADMISSION_PENDING);
3678
+ }
3679
+ return true;
3680
+ }
3681
+ async _refusedInMesh(mesh, grantKey, ours) {
3682
+ await mesh.autobee.update();
3683
+ const status = await syncStatusSnapshot(mesh);
3684
+ if (!status.devices?.length || status.state !== 'synced') {
3685
+ return false;
3686
+ }
3687
+ const self = this._requireDeviceKeyPair().publicKey;
3688
+ const own = await mesh.view.get(DEVICES, { id: self });
3689
+ if (own?.revoked &&
3690
+ !(own.revokedBy && b4a.equals(own.revokedBy, own.writerKey ?? b4a.alloc(0)))) {
3691
+ return true;
3692
+ }
3693
+ if (!ours) {
3694
+ return false;
3695
+ }
3696
+ const grant = await mesh.view.get(MESH_INVITE_GRANTS, { grantKey });
3697
+ if (grant && (await memberStanding(mesh.view, ours, grant)) === 'removed') {
3698
+ return true;
3699
+ }
3700
+ for await (const device of mesh.view.find(DEVICES)) {
3701
+ if (!device.revoked &&
3702
+ device.memberId &&
3703
+ b4a.equals(device.memberId, ours) &&
3704
+ !b4a.equals(device.id, self)) {
3705
+ return false;
3706
+ }
3707
+ }
3708
+ return true;
3709
+ }
3710
+ async _openFollowedMesh(memberMesh, meshKey, ours) {
3711
+ if (this._blockedByMinVersion())
3712
+ return;
3713
+ const seed = await this._requestMeshSeed(memberMesh, meshKey, ours);
3714
+ if (!seed || this.closing) {
2834
3715
  return;
2835
- if (this.closing || this._blockedByMinVersion())
3716
+ }
3717
+ const moving = this._joinCancellation ? this._joinCancellation.account : this._minting;
3718
+ if (moving || !this._isAccount(memberMesh)) {
2836
3719
  return;
3720
+ }
2837
3721
  const session = this.local.createCandidateSession(seed, meshKey);
2838
- await this.local.recordMesh(this._deviceKeyPair.publicKey, meshKey, session);
2839
- await this._openPooledMesh(b4a.toHex(meshKey));
3722
+ await this.local.recordMesh(meshKey, session, {
3723
+ deviceId: this._requireDeviceKeyPair().publicKey
3724
+ });
3725
+ await this.local.markAwaitingAdmission(meshKey, { awaitingAdmission: true });
3726
+ let mesh;
3727
+ try {
3728
+ mesh = await this._openPooledMesh(b4a.toHex(meshKey));
3729
+ }
3730
+ catch (error) {
3731
+ if (this._upgradeRequired !== 'halt') {
3732
+ await this.local.archiveMesh(meshKey).catch(noop);
3733
+ }
3734
+ throw error;
3735
+ }
3736
+ await this._requestMeshAdmission(memberMesh, mesh, ours);
2840
3737
  }
2841
- async _requestRoomSeed(memberMesh, meshKey, ours) {
2842
- const self = this._deviceKeyPair?.publicKey;
2843
- for await (const device of memberMesh.view.find('@qvac/devices')) {
3738
+ async _requestMeshSeed(memberMesh, meshKey, ours) {
3739
+ let unanswered = null;
3740
+ for (const sibling of await this._liveSiblings(memberMesh, ours)) {
2844
3741
  if (this.closing)
2845
3742
  return null;
2846
- if (device.revoked || !device.memberId?.equals(ours))
2847
- continue;
2848
- if (self && device.id.equals(self))
2849
- continue;
2850
- const seed = await this._meshSeedHandoff.request(device.id, meshKey).catch(noop);
2851
- if (seed)
3743
+ const seed = await this._meshSeedHandoff.request(sibling, meshKey).catch((error) => {
3744
+ this._log?.warn(['p2p', 'mesh'], 'a sibling did not hand over a mesh seed', error);
3745
+ if (UNANSWERED_SEED_REQUESTS.has(error.message)) {
3746
+ unanswered = error;
3747
+ }
3748
+ });
3749
+ if (seed) {
2852
3750
  return seed;
3751
+ }
3752
+ }
3753
+ if (unanswered) {
3754
+ throw unanswered;
2853
3755
  }
2854
3756
  return null;
2855
3757
  }
3758
+ async _requestMeshAdmission(memberMesh, mesh, ours) {
3759
+ if (mesh.writable) {
3760
+ return this.local.markAwaitingAdmission(mesh.key, { awaitingAdmission: false });
3761
+ }
3762
+ const { publicKey: deviceId, secretKey } = this._requireDeviceKeyPair();
3763
+ const own = await mesh.view.get(DEVICES, { id: deviceId });
3764
+ if (own && isKickedRow(own)) {
3765
+ return this.local.markAwaitingAdmission(mesh.key, { awaitingAdmission: false });
3766
+ }
3767
+ const binding = {
3768
+ meshPublicKey: mesh.publicKey,
3769
+ deviceId,
3770
+ writerKey: mesh.localWriterKey,
3771
+ joinedAt: Date.now()
3772
+ };
3773
+ const claim = {
3774
+ writerKey: binding.writerKey,
3775
+ joinedAt: binding.joinedAt,
3776
+ deviceSignature: signWriterClaim(secretKey, binding),
3777
+ memberSignature: signMemberWriterClaim(secretKey, { ...binding, memberId: ours })
3778
+ };
3779
+ const known = await mesh.bornKind();
3780
+ for (const sibling of known === null ? [] : await this._liveSiblings(memberMesh, ours)) {
3781
+ if (this.closing)
3782
+ return;
3783
+ if (mesh.writable)
3784
+ break;
3785
+ if (!(await this._meshSeedHandoff.admit(sibling, mesh.key, claim).catch(noop))) {
3786
+ continue;
3787
+ }
3788
+ await mesh.waitForWritable(ACCOUNT_WRITABLE_MS);
3789
+ }
3790
+ if (!mesh.writable && (await mesh.waitForGenesis(ACCOUNT_WRITABLE_MS)) === null) {
3791
+ await mesh.appendBirthOp(this._requireDeviceKeyPair(), this._localDevice ?? undefined);
3792
+ await mesh.waitForWritable(ACCOUNT_WRITABLE_MS);
3793
+ }
3794
+ if (mesh.writable) {
3795
+ await this.local.markAwaitingAdmission(mesh.key, { awaitingAdmission: false });
3796
+ }
3797
+ }
3798
+ async _liveSiblings(memberMesh, ours) {
3799
+ const self = this._deviceKeyPair?.publicKey;
3800
+ const siblings = [];
3801
+ for await (const device of memberMesh.view.find(DEVICES)) {
3802
+ if (device.revoked || !(device.memberId && b4a.equals(device.memberId, ours))) {
3803
+ continue;
3804
+ }
3805
+ if (self && b4a.equals(device.id, self))
3806
+ continue;
3807
+ siblings.push(device.id);
3808
+ }
3809
+ return siblings;
3810
+ }
2856
3811
  registerLoanableHarness(serve) {
2857
3812
  this._serveLoanedHarness = serve;
2858
3813
  return () => {
2859
- if (this._serveLoanedHarness === serve)
3814
+ if (this._serveLoanedHarness === serve) {
2860
3815
  this._serveLoanedHarness = null;
3816
+ }
2861
3817
  };
2862
3818
  }
2863
3819
  borrowHarness(deviceId) {
@@ -2865,9 +3821,10 @@ export class Core extends ReadyResource {
2865
3821
  }
2866
3822
  async _lendHarness(fromDeviceId) {
2867
3823
  const serve = this._serveLoanedHarness;
2868
- if (!serve)
3824
+ if (!serve) {
2869
3825
  return null;
2870
- const asker = Buffer.from(fromDeviceId);
3826
+ }
3827
+ const asker = b4a.from(fromDeviceId);
2871
3828
  if (!(await this._sharesComputeMesh(asker))) {
2872
3829
  this._log?.warn(['p2p', 'mesh'], 'loan refused: no compute mesh shared with that device');
2873
3830
  return null;
@@ -2877,7 +3834,7 @@ export class Core extends ReadyResource {
2877
3834
  return theirs;
2878
3835
  }
2879
3836
  _revalidateLoans() {
2880
- return this._harnessLoan.revalidate((device) => this._sharesComputeMesh(Buffer.from(device)));
3837
+ return this._harnessLoan.revalidate((device) => this._sharesComputeMesh(b4a.from(device)));
2881
3838
  }
2882
3839
  async _computeLender() {
2883
3840
  const self = this.devicePublicKey ? b4a.toHex(this.devicePublicKey) : undefined;
@@ -2885,10 +3842,11 @@ export class Core extends ReadyResource {
2885
3842
  for (const entry of this._meshes.values()) {
2886
3843
  if (!entry.mesh.compute)
2887
3844
  continue;
2888
- for await (const device of entry.mesh.view.find('@qvac/devices')) {
3845
+ for await (const device of entry.mesh.view.find(DEVICES)) {
2889
3846
  const id = b4a.toHex(device.id);
2890
- if (device.revoked || id === self)
3847
+ if (device.revoked || id === self) {
2891
3848
  continue;
3849
+ }
2892
3850
  lenders.set(id, device.id);
2893
3851
  }
2894
3852
  }
@@ -2899,60 +3857,188 @@ export class Core extends ReadyResource {
2899
3857
  for (const entry of this._meshes.values()) {
2900
3858
  if (!entry.mesh.compute)
2901
3859
  continue;
2902
- const device = await entry.mesh.view
2903
- .get('@qvac/devices', { id: deviceId })
2904
- .catch(noop);
2905
- if (device && !device.revoked)
3860
+ const device = await entry.mesh.view.get(DEVICES, { id: deviceId }).catch(noop);
3861
+ if (device && !device.revoked) {
2906
3862
  return true;
3863
+ }
2907
3864
  }
2908
3865
  return false;
2909
3866
  }
2910
3867
  async _serveMeshSeed(request, fromDeviceId) {
2911
- const asker = Buffer.from(fromDeviceId);
2912
- if (!(await this._isOwnMemberDevice(asker))) {
3868
+ const asker = b4a.from(fromDeviceId);
3869
+ if ('writerKey' in request) {
3870
+ return request.inviteToken
3871
+ ? this._admitInvitedDevice(request, asker)
3872
+ : this._admitIntoMesh(request, asker);
3873
+ }
3874
+ const standing = await this._askerStanding(asker);
3875
+ if (standing === 'unseen') {
3876
+ throw new Error(SEED_ASKER_UNSEEN);
3877
+ }
3878
+ if (standing === 'refused') {
2913
3879
  this._log?.warn(['p2p', 'mesh'], 'seed request refused: not a device of this member');
2914
3880
  return null;
2915
3881
  }
2916
- if (!(await this._isJoinedRoomKey(request.meshKey))) {
2917
- this._log?.warn(['p2p', 'mesh'], 'seed request refused: not a room this member joined');
3882
+ if (!(await this._isJoinedMeshKey(request.meshKey))) {
3883
+ this._log?.warn(['p2p', 'mesh'], 'seed request refused: not a mesh this member joined');
3884
+ return null;
3885
+ }
3886
+ const mesh = this._pooled(b4a.toHex(request.meshKey));
3887
+ const row = mesh ? await mesh.view.get(DEVICES, { id: asker }) : null;
3888
+ if (row?.revoked) {
3889
+ this._log?.warn(['p2p', 'mesh'], 'seed request refused: removed from this mesh');
3890
+ return null;
3891
+ }
3892
+ const session = await this.local.readMeshSession(request.meshKey);
3893
+ return session?.seed ? { seed: session.seed } : null;
3894
+ }
3895
+ async _admitInvitedDevice(request, asker) {
3896
+ const account = await this._accountMesh();
3897
+ if (!(account?.key && b4a.equals(account?.key, request.meshKey))) {
3898
+ this._log?.warn(['p2p', 'mesh'], "device invite refused: not this device's account");
3899
+ return null;
3900
+ }
3901
+ const context = { deviceKeyPair: this._requireDeviceKeyPair(), log: this._log };
3902
+ const admitted = await admitInvitedDevice(account, context, {
3903
+ invites: this._deviceInvites,
3904
+ deviceId: asker,
3905
+ request
3906
+ });
3907
+ if (admitted) {
3908
+ return { admitted: true };
3909
+ }
3910
+ if (request.inviteToken && (await this._deviceInvites.spent(request.inviteToken, asker))) {
3911
+ throw new Error(DEVICE_INVITE_SPENT);
3912
+ }
3913
+ return null;
3914
+ }
3915
+ async _admitIntoMesh(request, asker) {
3916
+ if (this._meshTransitionLock.locked)
3917
+ return null;
3918
+ await this._meshTransitionLock.lock();
3919
+ try {
3920
+ return await this._admitIntoMeshLocked(request, asker);
3921
+ }
3922
+ finally {
3923
+ this._meshTransitionLock.unlock();
3924
+ }
3925
+ }
3926
+ async _admitIntoMeshLocked(request, asker) {
3927
+ if (this._leaving || this._minting)
3928
+ return null;
3929
+ const account = await this._accountMesh();
3930
+ const ours = account?.ourMemberId;
3931
+ const row = ours ? await account.view.get(DEVICES, { id: asker }) : null;
3932
+ if (!ours ||
3933
+ !row ||
3934
+ row.revoked ||
3935
+ !(row.memberId && b4a.equals(row.memberId, ours)) ||
3936
+ (await this._askerStanding(asker)) !== 'ours') {
3937
+ this._log?.warn(['p2p', 'mesh'], 'admission refused: not a live device of this member');
3938
+ return null;
3939
+ }
3940
+ if (!(await this._isJoinedMeshKey(request.meshKey))) {
3941
+ this._log?.warn(['p2p', 'mesh'], 'admission refused: not a mesh this member joined');
2918
3942
  return null;
2919
3943
  }
2920
3944
  const session = await this.local.readMeshSession(request.meshKey);
2921
- return session?.seed ?? null;
3945
+ if (!session?.seed) {
3946
+ return null;
3947
+ }
3948
+ const writerKey = request.writerKey;
3949
+ const joinedAt = request.joinedAt ?? 0;
3950
+ const claim = {
3951
+ meshPublicKey: meshPublicKeyFromSeed(session.seed),
3952
+ deviceId: asker,
3953
+ writerKey,
3954
+ joinedAt
3955
+ };
3956
+ if (!verifyWriterClaim(request.deviceSignature, claim) ||
3957
+ !verifyMemberWriterClaim(request.memberSignature, { ...claim, memberId: ours })) {
3958
+ this._log?.warn(['p2p', 'mesh'], 'admission refused: the asker did not sign its claim');
3959
+ return null;
3960
+ }
3961
+ const mesh = await this._openPooledMesh(b4a.toHex(request.meshKey));
3962
+ await mesh.autobee.update();
3963
+ if (!mesh.writable) {
3964
+ return null;
3965
+ }
3966
+ if ((await mesh.bornKind()) !== 'shared') {
3967
+ this._log?.warn(['p2p', 'mesh'], 'admission refused: a sibling joins this mesh by its seed');
3968
+ return null;
3969
+ }
3970
+ const self = await mesh.view.get(DEVICES, {
3971
+ id: this._requireDeviceKeyPair().publicKey
3972
+ });
3973
+ if (!(self?.memberId && b4a.equals(self.memberId, ours)) ||
3974
+ self.revoked ||
3975
+ !(self.writerKey && b4a.equals(self.writerKey, mesh.localWriterKey))) {
3976
+ this._log?.warn(['p2p', 'mesh'], 'admission refused: this device is not linked in the mesh');
3977
+ return null;
3978
+ }
3979
+ const current = await mesh.view.get(DEVICES, { id: asker });
3980
+ if (current && isKickedRow(current)) {
3981
+ this._log?.warn(['p2p', 'mesh'], 'admission refused: removed from this mesh');
3982
+ return null;
3983
+ }
3984
+ if (current && !current.revoked) {
3985
+ return current.writerKey && b4a.equals(current.writerKey, writerKey)
3986
+ ? { admitted: true }
3987
+ : null;
3988
+ }
3989
+ await mesh.dispatch('vouched-join', {
3990
+ signature: mesh.sign(writerKey),
3991
+ deviceId: asker,
3992
+ device: claimableDevice({
3993
+ id: asker,
3994
+ joinedAt,
3995
+ name: row.name,
3996
+ capabilityProfile: row.capabilityProfile,
3997
+ recommendedModelName: row.recommendedModelName
3998
+ }),
3999
+ deviceSignature: request.deviceSignature,
4000
+ writerKey,
4001
+ memberProof: row.memberProof,
4002
+ memberSignature: request.memberSignature
4003
+ });
4004
+ return { admitted: true };
2922
4005
  }
2923
- async _isJoinedRoomKey(meshKey) {
4006
+ async _isJoinedMeshKey(meshKey) {
2924
4007
  for (const entry of this._meshes.values()) {
2925
4008
  const ours = entry.mesh.ourMemberId;
2926
- if (!ours)
4009
+ if (!ours) {
2927
4010
  continue;
4011
+ }
2928
4012
  const row = await entry.mesh.view.get(JOINED_MESHES, { meshKey }).catch(noop);
2929
- if (row?.memberId.equals(ours) && !row.leftAt)
4013
+ if (row?.memberId && b4a.equals(row.memberId, ours) && !row.leftAt) {
2930
4014
  return true;
4015
+ }
2931
4016
  }
2932
4017
  return false;
2933
4018
  }
2934
- async _isOwnMemberDevice(deviceId) {
2935
- let ourDevice = false;
2936
- for (const entry of this._meshes.values()) {
2937
- const ours = entry.mesh.ourMemberId;
2938
- if (!ours)
2939
- continue;
2940
- const device = await entry.mesh.view
2941
- .get('@qvac/devices', { id: deviceId })
2942
- .catch(noop);
2943
- if (!device)
2944
- continue;
2945
- if (device.revoked)
2946
- return false;
2947
- if (device.memberId?.equals(ours))
2948
- ourDevice = true;
4019
+ async _askerStanding(deviceId) {
4020
+ const account = this._accountMesh();
4021
+ const ours = account?.ourMemberId;
4022
+ if (!account || !ours) {
4023
+ return 'unseen';
4024
+ }
4025
+ const device = await account.view.get(DEVICES, { id: deviceId });
4026
+ if (!device) {
4027
+ return 'unseen';
2949
4028
  }
2950
- return ourDevice;
4029
+ if (device.revoked) {
4030
+ return 'refused';
4031
+ }
4032
+ if (!device.memberId) {
4033
+ return 'unseen';
4034
+ }
4035
+ return b4a.equals(device.memberId, ours) ? 'ours' : 'refused';
2951
4036
  }
2952
4037
  async _skillOverlayOp(agentId, op) {
2953
4038
  const host = await this._resolveAgentHost(agentId);
2954
- if (!host)
4039
+ if (!host) {
2955
4040
  return this._runLocalSkillOverlayOp(op);
4041
+ }
2956
4042
  return this._skillOverlayHandoff.send(host, { ...op, agentId });
2957
4043
  }
2958
4044
  async _resolveAgentHost(agentId, mesh = this._accountMesh()) {
@@ -2961,18 +4047,23 @@ export class Core extends ReadyResource {
2961
4047
  if (!this.opened)
2962
4048
  await this.ready();
2963
4049
  const deviceId = this.devicePublicKey;
2964
- if (!mesh || !deviceId)
4050
+ if (!mesh || !deviceId) {
2965
4051
  throw new Error(NOT_THE_HOST);
4052
+ }
2966
4053
  const agent = await getAgent(mesh, agentId);
2967
- if (!agent)
4054
+ if (!agent) {
2968
4055
  throw new Error(NO_SUCH_AGENT);
2969
- if (!agent.providerDeviceId)
4056
+ }
4057
+ if (!agent.providerDeviceId) {
2970
4058
  throw new Error(NOT_THE_HOST);
2971
- if (agent.providerDeviceId.equals(deviceId))
4059
+ }
4060
+ if (b4a.equals(agent.providerDeviceId, deviceId)) {
2972
4061
  return null;
2973
- const host = await mesh.view.get('@qvac/devices', { id: agent.providerDeviceId });
2974
- if (!host || host.revoked)
4062
+ }
4063
+ const host = await mesh.view.get(DEVICES, { id: agent.providerDeviceId });
4064
+ if (!host || host.revoked) {
2975
4065
  throw new Error(HOST_REVOKED);
4066
+ }
2976
4067
  return agent.providerDeviceId;
2977
4068
  }
2978
4069
  async _listInferenceCalls(meshId, chatId) {
@@ -2981,8 +4072,9 @@ export class Core extends ReadyResource {
2981
4072
  const own = store?.list(chatId) ?? { calls: [], truncated: false };
2982
4073
  const local = own.calls;
2983
4074
  const chat = await getChat(mesh, chatId);
2984
- if (!chat)
4075
+ if (!chat) {
2985
4076
  return own;
4077
+ }
2986
4078
  const host = await this._resolveAgentHost(chat.agentId, mesh).catch((err) => {
2987
4079
  if (local.length === 0)
2988
4080
  throw err;
@@ -2993,8 +4085,9 @@ export class Core extends ReadyResource {
2993
4085
  return null;
2994
4086
  });
2995
4087
  if (!host) {
2996
- if (!store)
4088
+ if (!store) {
2997
4089
  throw new Error(NO_RECORD_STORE);
4090
+ }
2998
4091
  return own;
2999
4092
  }
3000
4093
  const answer = await this._inferenceCallsHandoff.send(host, { chatId });
@@ -3006,18 +4099,21 @@ export class Core extends ReadyResource {
3006
4099
  }
3007
4100
  _toInferenceEntry(entry) {
3008
4101
  const call = entry.call;
3009
- if (typeof call !== 'object' || call === null)
4102
+ if (!isRecord(call)) {
3010
4103
  return [];
3011
- return [{ runId: entry.runId, at: entry.at, call: call }];
4104
+ }
4105
+ return [{ runId: entry.runId, at: entry.at, call }];
3012
4106
  }
3013
4107
  async _serveInferenceCalls(request, fromDeviceId) {
3014
4108
  const mesh = (await this._meshHoldingChat(request.chatId)) ?? this._accountMesh();
3015
4109
  const deviceId = this.devicePublicKey;
3016
- if (!mesh || !deviceId)
4110
+ if (!mesh || !deviceId) {
3017
4111
  throw new Error(NOT_THE_HOST);
4112
+ }
3018
4113
  const store = this._inferenceCalls;
3019
- if (!store)
4114
+ if (!store) {
3020
4115
  throw new Error(NO_RECORD_STORE);
4116
+ }
3021
4117
  const receive = createInferenceCallsReceiver({
3022
4118
  mesh,
3023
4119
  deviceId,
@@ -3026,16 +4122,18 @@ export class Core extends ReadyResource {
3026
4122
  return receive(request, fromDeviceId);
3027
4123
  }
3028
4124
  async _meshHoldingChat(chatId) {
3029
- for (const { mesh } of this._meshes.values())
4125
+ for (const { mesh } of this._meshes.values()) {
3030
4126
  if (await getChat(mesh, chatId))
3031
4127
  return mesh;
4128
+ }
3032
4129
  return null;
3033
4130
  }
3034
4131
  async _serveSkillOverlayOp(op, fromDeviceId) {
3035
4132
  const mesh = this._accountMesh();
3036
4133
  const deviceId = this.devicePublicKey;
3037
- if (!mesh || !deviceId)
4134
+ if (!mesh || !deviceId) {
3038
4135
  throw new Error(NOT_THE_HOST);
4136
+ }
3039
4137
  const receive = createSkillOverlayReceiver({
3040
4138
  mesh,
3041
4139
  deviceId,
@@ -3070,25 +4168,31 @@ export class Core extends ReadyResource {
3070
4168
  }
3071
4169
  async _setupFields(skillName) {
3072
4170
  const skills = await this._hostSkills();
3073
- if (skills.length === 0)
4171
+ if (skills.length === 0) {
3074
4172
  return null;
4173
+ }
3075
4174
  const skill = skills.find((entry) => entry.name === skillName);
3076
- if (!skill)
4175
+ if (!skill) {
3077
4176
  return new Map();
4177
+ }
3078
4178
  const fields = new Map();
3079
4179
  for (const slot of skill.credentials ?? []) {
3080
- for (const key of slot.split('|'))
4180
+ for (const key of slot.split('|')) {
3081
4181
  fields.set(key, true);
4182
+ }
3082
4183
  }
3083
4184
  const foreign = credentialKeysOwnedElsewhere(skills, skillName);
3084
4185
  for (const route of skill.setup?.routes ?? []) {
3085
- if (route.credentialKey)
4186
+ if (route.credentialKey) {
3086
4187
  fields.set(route.credentialKey, true);
4188
+ }
3087
4189
  const stateKey = route.oauth?.stateKey;
3088
- if (stateKey && !foreign.has(stateKey))
4190
+ if (stateKey && !foreign.has(stateKey)) {
3089
4191
  fields.set(stateKey, true);
3090
- for (const field of route.fields ?? [])
4192
+ }
4193
+ for (const field of route.fields ?? []) {
3091
4194
  fields.set(field.key, field.secret === true);
4195
+ }
3092
4196
  }
3093
4197
  return fields;
3094
4198
  }
@@ -3125,12 +4229,12 @@ export class Core extends ReadyResource {
3125
4229
  this._inferenceCallsHandoff.addStream(conn);
3126
4230
  for (const entry of this._meshes.values()) {
3127
4231
  entry.hostedAgents?.kick();
3128
- if (entry.mesh.ourMemberId)
3129
- void this._followJoinedRooms(entry.mesh);
4232
+ void this._followJoinedMeshes(entry.mesh);
3130
4233
  }
3131
4234
  this.rootCorestore.replicate(conn);
3132
- for (const entry of this._meshes.values())
4235
+ for (const entry of this._meshes.values()) {
3133
4236
  entry.mesh.files.reconnect();
4237
+ }
3134
4238
  }
3135
4239
  _trackPeerConnection(conn) {
3136
4240
  this._peers.add(conn);
@@ -3165,17 +4269,18 @@ export class Core extends ReadyResource {
3165
4269
  acknowledgeKicked: () => this.acknowledgeKicked(),
3166
4270
  join: (invite) => this.joinMesh(invite),
3167
4271
  cancelJoin: () => this.cancelMeshJoin(),
4272
+ preview: (invite) => this.previewMeshInvite(invite),
3168
4273
  invite: async (member, meshId) => {
3169
4274
  if (!member) {
3170
4275
  const device = await this.getMeshInvite({ meshId });
3171
4276
  return { invite: device ? encodeMeshInvite(device) : undefined };
3172
4277
  }
3173
- const room = meshId ? { meshId } : await this.sharedRoom();
3174
- const invite = await this.getMeshInvite({ memberInvite: true, meshId: room.meshId });
3175
- const notices = [room.notice, await this._occupancyNotice(room.meshId)];
4278
+ const target = meshId ? { meshId } : await this.sharedMesh();
4279
+ const invite = await this.getMeshInvite({ memberInvite: true, meshId: target.meshId });
4280
+ const notices = [target.notice, await this._occupancyNotice(target.meshId)];
3176
4281
  return {
3177
4282
  invite: invite ? encodeMeshInvite(invite) : undefined,
3178
- meshId: room.meshId,
4283
+ meshId: target.meshId,
3179
4284
  notice: notices.filter(Boolean).join('\n') || undefined
3180
4285
  };
3181
4286
  },
@@ -3184,7 +4289,7 @@ export class Core extends ReadyResource {
3184
4289
  open: (meshId) => this.openMesh(meshId),
3185
4290
  close: (meshId) => this.closeMesh(meshId),
3186
4291
  label: (meshId, label) => this.setMeshLabel(meshId, label),
3187
- createRoom: (opts) => this.createRoom(opts),
4292
+ createMesh: (opts) => this.createMesh(opts),
3188
4293
  listArchived: () => this.listArchivedMeshes(),
3189
4294
  archivedContents: (meshId) => this.archivedMeshContents(meshId),
3190
4295
  migrateArchived: (meshId) => this.migrateArchivedMesh(meshId),
@@ -3198,13 +4303,16 @@ export class Core extends ReadyResource {
3198
4303
  const listeners = new Set();
3199
4304
  let timer = null;
3200
4305
  return {
4306
+ sampled: true,
3201
4307
  watch: (listener) => {
3202
4308
  listeners.add(listener);
3203
- if (timer)
4309
+ if (timer) {
3204
4310
  return;
4311
+ }
3205
4312
  timer = setInterval(() => {
3206
- for (const fn of listeners)
4313
+ for (const fn of listeners) {
3207
4314
  fn();
4315
+ }
3208
4316
  }, DIAGNOSTICS_SAMPLE_MS);
3209
4317
  unref(timer);
3210
4318
  },
@@ -3219,7 +4327,7 @@ export class Core extends ReadyResource {
3219
4327
  };
3220
4328
  }
3221
4329
  _networkSnapshot() {
3222
- const dht = this._swarm ? this._swarm.dht : null;
4330
+ const dht = this._swarm?.dht ?? null;
3223
4331
  return {
3224
4332
  state: this._networkState(dht),
3225
4333
  peerCount: this.peerDeviceIds.length
@@ -3234,8 +4342,9 @@ export class Core extends ReadyResource {
3234
4342
  }
3235
4343
  _logSource() {
3236
4344
  const log = this._log;
3237
- if (!log)
4345
+ if (!log) {
3238
4346
  return null;
4347
+ }
3239
4348
  return {
3240
4349
  backfill: () => log.backfill(),
3241
4350
  subscribe: (listener) => log.subscribe(listener),
@@ -3257,46 +4366,60 @@ export class Core extends ReadyResource {
3257
4366
  this._diagnosticsProviders.add(provider);
3258
4367
  return () => void this._diagnosticsProviders.delete(provider);
3259
4368
  }
4369
+ registerModelResidency(residency) {
4370
+ this._modelResidency = residency;
4371
+ return () => {
4372
+ if (this._modelResidency === residency) {
4373
+ this._modelResidency = null;
4374
+ }
4375
+ };
4376
+ }
3260
4377
  registerInferenceCalls(source) {
3261
4378
  this._inferenceCalls = source;
3262
4379
  return () => {
3263
- if (this._inferenceCalls === source)
4380
+ if (this._inferenceCalls === source) {
3264
4381
  this._inferenceCalls = null;
4382
+ }
3265
4383
  };
3266
4384
  }
3267
4385
  registerListModels(hook) {
3268
4386
  this._listModels = hook;
3269
4387
  return () => {
3270
- if (this._listModels === hook)
4388
+ if (this._listModels === hook) {
3271
4389
  this._listModels = null;
4390
+ }
3272
4391
  };
3273
4392
  }
3274
4393
  registerDeleteModel(hook) {
3275
4394
  this._deleteModel = hook;
3276
4395
  return () => {
3277
- if (this._deleteModel === hook)
4396
+ if (this._deleteModel === hook) {
3278
4397
  this._deleteModel = null;
4398
+ }
3279
4399
  };
3280
4400
  }
3281
4401
  registerClearKvCache(hook) {
3282
4402
  this._clearKvCache = hook;
3283
4403
  return () => {
3284
- if (this._clearKvCache === hook)
4404
+ if (this._clearKvCache === hook) {
3285
4405
  this._clearKvCache = null;
4406
+ }
3286
4407
  };
3287
4408
  }
3288
4409
  registerDeleteChatKvCache(hook) {
3289
4410
  this._deleteChatKvCache = hook;
3290
4411
  return () => {
3291
- if (this._deleteChatKvCache === hook)
4412
+ if (this._deleteChatKvCache === hook) {
3292
4413
  this._deleteChatKvCache = null;
4414
+ }
3293
4415
  };
3294
4416
  }
3295
4417
  registerCompactChat(hook) {
3296
4418
  this._compactChat = hook;
3297
4419
  return () => {
3298
- if (this._compactChat === hook)
4420
+ if (this._compactChat === hook) {
3299
4421
  this._compactChat = null;
4422
+ }
3300
4423
  };
3301
4424
  }
3302
4425
  registerModelCatalogWatch(hook) {
@@ -3306,8 +4429,9 @@ export class Core extends ReadyResource {
3306
4429
  if (this._modelCatalogWatch !== hook)
3307
4430
  return;
3308
4431
  this._modelCatalogWatch = null;
3309
- if (!this.closing)
4432
+ if (!this.closing) {
3310
4433
  this._resetModelCatalogWatchSource();
4434
+ }
3311
4435
  };
3312
4436
  }
3313
4437
  async *_watchModelCatalog() {
@@ -3320,15 +4444,17 @@ export class Core extends ReadyResource {
3320
4444
  return;
3321
4445
  }
3322
4446
  const watch = this._modelCatalogWatch;
3323
- if (!watch)
4447
+ if (!watch) {
3324
4448
  continue;
4449
+ }
3325
4450
  yield* watch();
3326
4451
  return;
3327
4452
  }
3328
4453
  }
3329
4454
  _openModelCatalogWatchSource() {
3330
- if (!this._modelCatalogWatch || !this._modelCatalogWatchSource.enter())
4455
+ if (!this._modelCatalogWatch || !this._modelCatalogWatchSource.enter()) {
3331
4456
  return;
4457
+ }
3332
4458
  this._modelCatalogWatchSource.exit();
3333
4459
  }
3334
4460
  _resetModelCatalogWatchSource() {
@@ -3338,30 +4464,34 @@ export class Core extends ReadyResource {
3338
4464
  registerRetryModelDownload(hook) {
3339
4465
  this._retryModelDownload = hook;
3340
4466
  return () => {
3341
- if (this._retryModelDownload === hook)
4467
+ if (this._retryModelDownload === hook) {
3342
4468
  this._retryModelDownload = null;
4469
+ }
3343
4470
  };
3344
4471
  }
3345
4472
  registerSkills(hook) {
3346
4473
  this._skills = hook;
3347
4474
  return () => {
3348
- if (this._skills === hook)
4475
+ if (this._skills === hook) {
3349
4476
  this._skills = null;
4477
+ }
3350
4478
  };
3351
4479
  }
3352
4480
  registerSkillCatalog(hook) {
3353
4481
  this._skillCatalog = hook;
3354
4482
  this._openCatalogHooks();
3355
4483
  return () => {
3356
- if (this._skillCatalog === hook)
4484
+ if (this._skillCatalog === hook) {
3357
4485
  this._skillCatalog = null;
4486
+ }
3358
4487
  };
3359
4488
  }
3360
4489
  registerSkillManagement(hooks) {
3361
4490
  this._skillManagement = hooks;
3362
4491
  return () => {
3363
- if (this._skillManagement === hooks)
4492
+ if (this._skillManagement === hooks) {
3364
4493
  this._skillManagement = null;
4494
+ }
3365
4495
  };
3366
4496
  }
3367
4497
  async _waitForCatalogHooks() {
@@ -3383,8 +4513,9 @@ export class Core extends ReadyResource {
3383
4513
  this._tools = hook;
3384
4514
  this._openCatalogHooks();
3385
4515
  return () => {
3386
- if (this._tools === hook)
4516
+ if (this._tools === hook) {
3387
4517
  this._tools = null;
4518
+ }
3388
4519
  };
3389
4520
  }
3390
4521
  registerEmbedder(embedder, extractors) {
@@ -3402,8 +4533,9 @@ export class Core extends ReadyResource {
3402
4533
  async _reconcileIndexing() {
3403
4534
  await this._indexingLock.lock();
3404
4535
  try {
3405
- if (this.closing)
4536
+ if (this.closing) {
3406
4537
  return;
4538
+ }
3407
4539
  if (this._indexedEmbedder && this._indexedEmbedder !== this._embedder) {
3408
4540
  await this._stopIndexing();
3409
4541
  }
@@ -3414,8 +4546,9 @@ export class Core extends ReadyResource {
3414
4546
  }
3415
4547
  }
3416
4548
  _startIndexing() {
3417
- for (const entry of this._meshes.values())
4549
+ for (const entry of this._meshes.values()) {
3418
4550
  this._startEntryIndexing(entry);
4551
+ }
3419
4552
  }
3420
4553
  _startEntryIndexing(entry) {
3421
4554
  if (!this._embedder || entry.processingFiles)
@@ -3437,41 +4570,64 @@ export class Core extends ReadyResource {
3437
4570
  }
3438
4571
  async _stopIndexing() {
3439
4572
  this._indexedEmbedder = null;
3440
- for (const entry of this._meshes.values())
4573
+ for (const entry of this._meshes.values()) {
3441
4574
  await this._stopEntryIndexing(entry);
4575
+ }
3442
4576
  }
3443
4577
  registerTranscribe(hook) {
3444
4578
  this._transcribe = hook;
3445
4579
  return () => {
3446
- if (this._transcribe === hook)
4580
+ if (this._transcribe === hook) {
3447
4581
  this._transcribe = null;
4582
+ }
4583
+ };
4584
+ }
4585
+ registerDetectLanguage(hook) {
4586
+ this._detectLanguage = hook;
4587
+ return () => {
4588
+ if (this._detectLanguage === hook) {
4589
+ this._detectLanguage = null;
4590
+ }
4591
+ };
4592
+ }
4593
+ registerPreviewModelSource(hook) {
4594
+ this._previewModelSource = hook;
4595
+ return () => {
4596
+ if (this._previewModelSource === hook) {
4597
+ this._previewModelSource = null;
4598
+ }
3448
4599
  };
3449
4600
  }
3450
4601
  registerSpeak(hook) {
3451
4602
  this._speak = hook;
3452
4603
  return () => {
3453
- if (this._speak === hook)
4604
+ if (this._speak === hook) {
3454
4605
  this._speak = null;
4606
+ }
3455
4607
  };
3456
4608
  }
3457
4609
  registerSpeakStream(hook) {
3458
4610
  this._speakStream = hook;
3459
4611
  return () => {
3460
- if (this._speakStream === hook)
4612
+ if (this._speakStream === hook) {
3461
4613
  this._speakStream = null;
4614
+ }
3462
4615
  };
3463
4616
  }
3464
4617
  _diagnosticsSource() {
3465
4618
  const listeners = new Set();
3466
4619
  let timer = null;
3467
4620
  return {
4621
+ sampled: true,
3468
4622
  watch: (listener) => {
3469
4623
  listeners.add(listener);
3470
- if (timer)
4624
+ if (timer) {
3471
4625
  return;
4626
+ }
3472
4627
  timer = setInterval(() => {
3473
- for (const fn of listeners)
4628
+ for (const fn of listeners) {
3474
4629
  fn();
4630
+ }
3475
4631
  }, DIAGNOSTICS_SAMPLE_MS);
3476
4632
  unref(timer);
3477
4633
  },
@@ -3484,8 +4640,9 @@ export class Core extends ReadyResource {
3484
4640
  },
3485
4641
  snapshot: () => {
3486
4642
  const merged = { ...this._diagnostics() };
3487
- for (const provider of this._diagnosticsProviders)
4643
+ for (const provider of this._diagnosticsProviders) {
3488
4644
  Object.assign(merged, provider());
4645
+ }
3489
4646
  return merged;
3490
4647
  }
3491
4648
  };
@@ -3502,7 +4659,7 @@ export class Core extends ReadyResource {
3502
4659
  _diagnostics() {
3503
4660
  const mesh = this._accountMesh();
3504
4661
  const swarm = this._swarm;
3505
- const dht = swarm ? swarm.dht : null;
4662
+ const dht = swarm?.dht ?? null;
3506
4663
  const system = this._systemInfo?.snapshot() ?? { cpu: null, gpu: null };
3507
4664
  const publicKey = this.devicePublicKey ? b4a.toHex(this.devicePublicKey) : undefined;
3508
4665
  const device = this._localDevice;
@@ -3573,21 +4730,26 @@ export class Core extends ReadyResource {
3573
4730
  return 'error';
3574
4731
  if (this.closing || this._leaving)
3575
4732
  return 'leaving';
3576
- if (this._kicked)
4733
+ if (this._kicked) {
3577
4734
  return 'kicked';
3578
- if (this._upgradeRequired)
4735
+ }
4736
+ if (this._upgradeRequired) {
3579
4737
  return 'needs-upgrade';
3580
- if (this._minting)
4738
+ }
4739
+ if (this._minting) {
3581
4740
  return 'joining';
4741
+ }
3582
4742
  const account = this._accountMesh();
3583
- if (account)
4743
+ if (account) {
3584
4744
  return account.writable ? 'joined' : 'joining';
4745
+ }
3585
4746
  return 'idle';
3586
4747
  }
3587
4748
  _notifyStatus() {
3588
4749
  this._listing = null;
3589
- for (const listener of [...this._statusListeners])
4750
+ for (const listener of [...this._statusListeners]) {
3590
4751
  listener();
4752
+ }
3591
4753
  }
3592
4754
  }
3593
4755
  function after(ms) {
@@ -3596,8 +4758,8 @@ function after(ms) {
3596
4758
  function unmarkedNotice(losers) {
3597
4759
  if (losers.length === 0)
3598
4760
  return undefined;
3599
- const ids = losers.map((room) => b4a.toHex(room.meshKey).slice(0, 8)).join(', ');
3600
- return `another device of yours opened a shared room at the same moment, so ${ids} is an ordinary room now`;
4761
+ const ids = losers.map((mesh) => b4a.toHex(mesh.meshKey).slice(0, 8)).join(', ');
4762
+ return `another device of yours opened a shared mesh at the same moment, so ${ids} is an ordinary mesh now`;
3601
4763
  }
3602
4764
  function noop() { }
3603
4765
  async function closeConfigReader(reader) {
@@ -3609,26 +4771,34 @@ async function closeConfigReader(reader) {
3609
4771
  async function recordedBlockIsLocal(core) {
3610
4772
  await raceResource(core, core.ready(), 'config core');
3611
4773
  const length = Number((await raceResource(core, core.getUserData('hyperconf'), 'config core')) || '0');
3612
- if (length <= 0)
4774
+ if (length <= 0) {
3613
4775
  return true;
4776
+ }
3614
4777
  return raceResource(core, core.has(length - 1), 'config core');
3615
4778
  }
3616
4779
  function statusErrorMessage(context, err) {
3617
- const detail = err instanceof Error ? err.message : err ? String(err) : '';
4780
+ const detail = errorDetail(err);
3618
4781
  return detail ? `${context}: ${detail}` : context;
3619
4782
  }
4783
+ function errorDetail(err) {
4784
+ if (err instanceof Error)
4785
+ return err.message;
4786
+ return err ? String(err) : '';
4787
+ }
3620
4788
  function credentialKeysOwnedElsewhere(skills, skillName) {
3621
4789
  const keys = new Set();
3622
4790
  for (const entry of skills) {
3623
4791
  if (entry.name === skillName)
3624
4792
  continue;
3625
4793
  for (const slot of entry.credentials ?? []) {
3626
- for (const key of slot.split('|'))
4794
+ for (const key of slot.split('|')) {
3627
4795
  keys.add(key);
4796
+ }
3628
4797
  }
3629
4798
  for (const route of entry.setup?.routes ?? []) {
3630
- if (route.credentialKey)
4799
+ if (route.credentialKey) {
3631
4800
  keys.add(route.credentialKey);
4801
+ }
3632
4802
  }
3633
4803
  }
3634
4804
  return keys;