@qvac/core 0.5.0 → 0.6.1

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