@qvac/core 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (383) hide show
  1. package/CHANGELOG.md +75 -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 +30 -11
  58. package/dist-lib/lib/assistant.js +824 -378
  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 +42 -28
  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 +69 -0
  95. package/dist-lib/lib/core/collections.js +69 -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.js +1 -1
  103. package/dist-lib/lib/core/contract/chunks.js +10 -9
  104. package/dist-lib/lib/core/contract/compute.js +2 -1
  105. package/dist-lib/lib/core/contract/devices.js +6 -5
  106. package/dist-lib/lib/core/contract/grant-order.js +5 -6
  107. package/dist-lib/lib/core/contract/index.js +4 -2
  108. package/dist-lib/lib/core/contract/indexing.js +3 -3
  109. package/dist-lib/lib/core/contract/invites.d.ts +8 -3
  110. package/dist-lib/lib/core/contract/invites.js +52 -26
  111. package/dist-lib/lib/core/contract/joined-meshes.js +3 -3
  112. package/dist-lib/lib/core/contract/knowledge.js +5 -5
  113. package/dist-lib/lib/core/contract/members.d.ts +13 -2
  114. package/dist-lib/lib/core/contract/members.js +46 -25
  115. package/dist-lib/lib/core/contract/mesh-kind.js +9 -8
  116. package/dist-lib/lib/core/contract/seal.js +1 -1
  117. package/dist-lib/lib/core/contract/seed-defaults.js +1 -3
  118. package/dist-lib/lib/core/contract/tool-activity.js +5 -5
  119. package/dist-lib/lib/core/contract/tool-configs.js +1 -2
  120. package/dist-lib/lib/core/contract/writers.d.ts +6 -1
  121. package/dist-lib/lib/core/contract/writers.js +55 -34
  122. package/dist-lib/lib/core/departures.js +16 -8
  123. package/dist-lib/lib/core/device-invites.js +3 -2
  124. package/dist-lib/lib/core/devices.js +6 -3
  125. package/dist-lib/lib/core/document-attachment.d.ts +20 -11
  126. package/dist-lib/lib/core/document-attachment.js +10 -5
  127. package/dist-lib/lib/core/files/attachments.d.ts +2 -5
  128. package/dist-lib/lib/core/files/attachments.js +6 -3
  129. package/dist-lib/lib/core/files/index.d.ts +44 -52
  130. package/dist-lib/lib/core/files/index.js +142 -93
  131. package/dist-lib/lib/core/files/knowledge.d.ts +2 -5
  132. package/dist-lib/lib/core/files/local-index.js +9 -5
  133. package/dist-lib/lib/core/files/preview/image.d.ts +0 -1
  134. package/dist-lib/lib/core/files/preview/image.js +9 -6
  135. package/dist-lib/lib/core/files/preview/index.d.ts +8 -11
  136. package/dist-lib/lib/core/files/preview/index.js +20 -15
  137. package/dist-lib/lib/core/files/processing/claims.d.ts +6 -5
  138. package/dist-lib/lib/core/files/processing/claims.js +16 -8
  139. package/dist-lib/lib/core/files/processing/document.d.ts +21 -50
  140. package/dist-lib/lib/core/files/processing/index.d.ts +18 -13
  141. package/dist-lib/lib/core/files/processing/index.js +65 -37
  142. package/dist-lib/lib/core/files/processing/ownership.d.ts +8 -1
  143. package/dist-lib/lib/core/files/processing/ownership.js +1 -1
  144. package/dist-lib/lib/core/files/processing/protocol.d.ts +19 -19
  145. package/dist-lib/lib/core/files/processing/protocol.js +5 -5
  146. package/dist-lib/lib/core/files/processing/settle.d.ts +10 -7
  147. package/dist-lib/lib/core/files/processing/settle.js +22 -11
  148. package/dist-lib/lib/core/files/processing/source.js +14 -8
  149. package/dist-lib/lib/core/files/processing/state.d.ts +13 -11
  150. package/dist-lib/lib/core/files/processing/state.js +19 -12
  151. package/dist-lib/lib/core/files/rag/build.d.ts +2 -2
  152. package/dist-lib/lib/core/files/rag/build.js +2 -1
  153. package/dist-lib/lib/core/files/rag/document-types.d.ts +4 -6
  154. package/dist-lib/lib/core/files/rag/index.d.ts +10 -13
  155. package/dist-lib/lib/core/files/rag/index.js +3 -2
  156. package/dist-lib/lib/core/files/rag/load.d.ts +10 -9
  157. package/dist-lib/lib/core/files/rag/load.js +26 -13
  158. package/dist-lib/lib/core/files/rag/policy.js +2 -1
  159. package/dist-lib/lib/core/files/rag/produce.js +33 -19
  160. package/dist-lib/lib/core/files/rag/retrieval/full-text.d.ts +5 -3
  161. package/dist-lib/lib/core/files/rag/retrieval/full-text.js +30 -10
  162. package/dist-lib/lib/core/files/records/chunks.js +4 -2
  163. package/dist-lib/lib/core/files/records/knowledge.d.ts +10 -11
  164. package/dist-lib/lib/core/files/records/knowledge.js +9 -8
  165. package/dist-lib/lib/core/files/records/linkage.js +6 -3
  166. package/dist-lib/lib/core/files/records/output.d.ts +5 -4
  167. package/dist-lib/lib/core/files/records/output.js +8 -4
  168. package/dist-lib/lib/core/files/records/reclaim.js +41 -25
  169. package/dist-lib/lib/core/files/records/routing.d.ts +4 -6
  170. package/dist-lib/lib/core/files/records/routing.js +15 -8
  171. package/dist-lib/lib/core/files/records/source.d.ts +5 -4
  172. package/dist-lib/lib/core/files/records/source.js +20 -14
  173. package/dist-lib/lib/core/files/records/sweep.js +1 -3
  174. package/dist-lib/lib/core/files/store/blob.d.ts +10 -10
  175. package/dist-lib/lib/core/files/store/blob.js +25 -19
  176. package/dist-lib/lib/core/files/store/index.d.ts +1 -6
  177. package/dist-lib/lib/core/files/store/index.js +4 -4
  178. package/dist-lib/lib/core/files/store/inline.d.ts +2 -2
  179. package/dist-lib/lib/core/files/store/inline.js +6 -3
  180. package/dist-lib/lib/core/files/store/reference.d.ts +6 -9
  181. package/dist-lib/lib/core/files/store/reference.js +25 -17
  182. package/dist-lib/lib/core/files/store/server.d.ts +7 -6
  183. package/dist-lib/lib/core/files/store/server.js +22 -11
  184. package/dist-lib/lib/core/files/store/sweep.js +13 -7
  185. package/dist-lib/lib/core/files/upload-input.d.ts +4 -12
  186. package/dist-lib/lib/core/files/upload-input.js +10 -5
  187. package/dist-lib/lib/core/files/upload.d.ts +27 -24
  188. package/dist-lib/lib/core/files/upload.js +74 -51
  189. package/dist-lib/lib/core/fs-drives.js +4 -2
  190. package/dist-lib/lib/core/grant-expiry.js +12 -7
  191. package/dist-lib/lib/core/handoff-channel.js +27 -13
  192. package/dist-lib/lib/core/harness-loan.js +35 -17
  193. package/dist-lib/lib/core/helpers/index.js +6 -2
  194. package/dist-lib/lib/core/hosted-agents.js +19 -12
  195. package/dist-lib/lib/core/id.js +1 -1
  196. package/dist-lib/lib/core/identity.js +6 -3
  197. package/dist-lib/lib/core/image/cache-sweep.d.ts +12 -10
  198. package/dist-lib/lib/core/image/cache-sweep.js +11 -6
  199. package/dist-lib/lib/core/image/normalize.d.ts +6 -0
  200. package/dist-lib/lib/core/image/normalize.js +12 -2
  201. package/dist-lib/lib/core/image/sniff.js +42 -21
  202. package/dist-lib/lib/core/inference-calls-receiver.js +7 -4
  203. package/dist-lib/lib/core/invite-grants.js +4 -2
  204. package/dist-lib/lib/core/invite.js +2 -1
  205. package/dist-lib/lib/core/local/files.js +20 -19
  206. package/dist-lib/lib/core/local/index.d.ts +69 -46
  207. package/dist-lib/lib/core/local/index.js +146 -129
  208. package/dist-lib/lib/core/membership.d.ts +12 -2
  209. package/dist-lib/lib/core/membership.js +55 -33
  210. package/dist-lib/lib/core/mesh-seed-handoff.js +7 -1
  211. package/dist-lib/lib/core/mesh.d.ts +37 -27
  212. package/dist-lib/lib/core/mesh.js +131 -73
  213. package/dist-lib/lib/core/migrations/agent-catalog.js +3 -2
  214. package/dist-lib/lib/core/migrations/agent-indexes.js +3 -3
  215. package/dist-lib/lib/core/migrations/file-index.js +7 -4
  216. package/dist-lib/lib/core/migrations/index.d.ts +4 -3
  217. package/dist-lib/lib/core/migrations/membership.js +9 -4
  218. package/dist-lib/lib/core/migrations/seal.js +3 -2
  219. package/dist-lib/lib/core/min-version.js +4 -2
  220. package/dist-lib/lib/core/next-frame.d.ts +5 -4
  221. package/dist-lib/lib/core/next-frame.js +6 -3
  222. package/dist-lib/lib/core/notification.d.ts +5 -1
  223. package/dist-lib/lib/core/notification.js +89 -77
  224. package/dist-lib/lib/core/ota-config.js +2 -1
  225. package/dist-lib/lib/core/pdf/rasterize.d.ts +18 -0
  226. package/dist-lib/lib/core/pdf/rasterize.js +57 -0
  227. package/dist-lib/lib/core/prompt-history.js +4 -2
  228. package/dist-lib/lib/core/range.d.ts +4 -4
  229. package/dist-lib/lib/core/range.js +12 -6
  230. package/dist-lib/lib/core/rank.d.ts +5 -4
  231. package/dist-lib/lib/core/rank.js +2 -1
  232. package/dist-lib/lib/core/send.d.ts +4 -4
  233. package/dist-lib/lib/core/send.js +6 -3
  234. package/dist-lib/lib/core/skill-overlay-receiver.js +7 -4
  235. package/dist-lib/lib/core/skill-secrets.js +16 -9
  236. package/dist-lib/lib/core/sync/chunks.js +2 -1
  237. package/dist-lib/lib/core/sync/devices.js +3 -1
  238. package/dist-lib/lib/core/sync/files.d.ts +2 -4
  239. package/dist-lib/lib/core/sync/files.js +28 -20
  240. package/dist-lib/lib/core/sync/index.d.ts +2 -5
  241. package/dist-lib/lib/core/sync/index.js +20 -15
  242. package/dist-lib/lib/core/sync-status.js +10 -7
  243. package/dist-lib/lib/core/system-info.js +4 -2
  244. package/dist-lib/lib/core/tool-activity.d.ts +4 -3
  245. package/dist-lib/lib/core/tool-activity.js +1 -1
  246. package/dist-lib/lib/core/tool-configs.js +12 -7
  247. package/dist-lib/lib/core.d.ts +38 -26
  248. package/dist-lib/lib/core.js +987 -539
  249. package/dist-lib/lib/credential-pusher.d.ts +12 -17
  250. package/dist-lib/lib/credential-pusher.js +61 -42
  251. package/dist-lib/lib/custom-model-pusher.d.ts +7 -3
  252. package/dist-lib/lib/custom-model-pusher.js +15 -7
  253. package/dist-lib/lib/custom-model-task.d.ts +1 -0
  254. package/dist-lib/lib/custom-model-task.js +12 -0
  255. package/dist-lib/lib/deadline.js +4 -2
  256. package/dist-lib/lib/diagnostics.d.ts +1 -5
  257. package/dist-lib/lib/frame-readable.d.ts +3 -0
  258. package/dist-lib/lib/frame-readable.js +3 -0
  259. package/dist-lib/lib/fs-drive-bridge.js +24 -14
  260. package/dist-lib/lib/fs-grants.js +13 -8
  261. package/dist-lib/lib/guards.d.ts +3 -0
  262. package/dist-lib/lib/guards.js +9 -0
  263. package/dist-lib/lib/inference-calls.d.ts +28 -23
  264. package/dist-lib/lib/inference-calls.js +25 -13
  265. package/dist-lib/lib/integrations/mcp-providers.d.ts +2 -2
  266. package/dist-lib/lib/integrations/setup-routes.d.ts +2 -2
  267. package/dist-lib/lib/knowledge-search.d.ts +6 -5
  268. package/dist-lib/lib/knowledge-search.js +26 -18
  269. package/dist-lib/lib/kv-cache-reclaim.js +4 -2
  270. package/dist-lib/lib/kv-cache.js +8 -4
  271. package/dist-lib/lib/legacy-core-domain.d.ts +42 -42
  272. package/dist-lib/lib/log-buffer.js +2 -1
  273. package/dist-lib/lib/log.js +25 -15
  274. package/dist-lib/lib/mesh-scoped-engine.js +12 -4
  275. package/dist-lib/lib/model-catalog-revision.js +6 -3
  276. package/dist-lib/lib/model-clamp.js +6 -3
  277. package/dist-lib/lib/model-context.d.ts +8 -3
  278. package/dist-lib/lib/model-context.js +13 -5
  279. package/dist-lib/lib/model-download-status.js +4 -2
  280. package/dist-lib/lib/model-download.d.ts +12 -4
  281. package/dist-lib/lib/model-download.js +200 -103
  282. package/dist-lib/lib/model-idle-pusher.d.ts +2 -2
  283. package/dist-lib/lib/model-idle-pusher.js +3 -4
  284. package/dist-lib/lib/oauth/browser-connect.d.ts +10 -8
  285. package/dist-lib/lib/oauth/browser-connect.js +33 -20
  286. package/dist-lib/lib/oauth/client.d.ts +2 -2
  287. package/dist-lib/lib/oauth/flow-core.js +23 -9
  288. package/dist-lib/lib/oauth/flow.d.ts +1 -3
  289. package/dist-lib/lib/oauth/flow.js +9 -5
  290. package/dist-lib/lib/oauth/keys.d.ts +4 -4
  291. package/dist-lib/lib/oauth/keys.js +18 -12
  292. package/dist-lib/lib/oauth/loopback.d.ts +2 -2
  293. package/dist-lib/lib/oauth/loopback.js +147 -107
  294. package/dist-lib/lib/oauth/loopback.stub.d.ts +2 -2
  295. package/dist-lib/lib/oauth/loopback.stub.js +1 -1
  296. package/dist-lib/lib/oauth/pkce.d.ts +4 -2
  297. package/dist-lib/lib/oauth/pkce.js +10 -0
  298. package/dist-lib/lib/oauth/providers.js +5 -5
  299. package/dist-lib/lib/oauth/redirect-types.d.ts +12 -7
  300. package/dist-lib/lib/oauth/register.js +3 -2
  301. package/dist-lib/lib/oauth/registry.d.ts +2 -2
  302. package/dist-lib/lib/oauth/registry.js +2 -1
  303. package/dist-lib/lib/oauth/resolve.d.ts +30 -10
  304. package/dist-lib/lib/oauth/resolve.js +12 -6
  305. package/dist-lib/lib/oauth/token-exchange-core.d.ts +12 -4
  306. package/dist-lib/lib/oauth/token-exchange-core.js +1 -1
  307. package/dist-lib/lib/oauth/types.d.ts +12 -12
  308. package/dist-lib/lib/oauth.d.ts +4 -5
  309. package/dist-lib/lib/oauth.js +2 -3
  310. package/dist-lib/lib/reconnecting-watch.d.ts +1 -1
  311. package/dist-lib/lib/reconnecting-watch.js +6 -6
  312. package/dist-lib/lib/retry-budget.js +6 -3
  313. package/dist-lib/lib/run-notices.d.ts +1 -0
  314. package/dist-lib/lib/run-notices.js +5 -2
  315. package/dist-lib/lib/run-transcript.d.ts +2 -4
  316. package/dist-lib/lib/run-transcript.js +4 -2
  317. package/dist-lib/lib/skill-readiness.js +4 -2
  318. package/dist-lib/lib/skill-types.d.ts +16 -16
  319. package/dist-lib/lib/suspend-lifecycle.d.ts +4 -4
  320. package/dist-lib/lib/suspend-lifecycle.js +10 -5
  321. package/dist-lib/lib/task.js +22 -12
  322. package/dist-lib/lib/unref.d.ts +3 -2
  323. package/dist-lib/lib/unref.js +2 -1
  324. package/dist-lib/lib/wav-duration.js +10 -5
  325. package/dist-lib/lib/write-queue.d.ts +5 -4
  326. package/dist-lib/lib/write-queue.js +2 -1
  327. package/dist-lib/schema/build.js +10 -6
  328. package/dist-lib/schema/config.d.ts +2 -3
  329. package/dist-lib/schema/content.d.ts +17 -2
  330. package/dist-lib/schema/content.js +2 -1
  331. package/dist-lib/schema/engine.d.ts +3 -2
  332. package/dist-lib/schema/engine.js +95 -6
  333. package/dist-lib/schema/field-order.js +22 -11
  334. package/dist-lib/schema/indexes.d.ts +22 -0
  335. package/dist-lib/schema/{helpers.js → indexes.js} +14 -57
  336. package/dist-lib/schema/local.d.ts +3 -2
  337. package/dist-lib/schema/local.js +7 -2
  338. package/dist-lib/schema/media-kind.d.ts +8 -0
  339. package/dist-lib/schema/media-kind.js +52 -0
  340. package/dist-lib/schema/qvac.d.ts +12 -9
  341. package/dist-lib/schema/qvac.js +8 -4
  342. package/dist-lib/spec/bind.js +12 -0
  343. package/dist-lib/spec/calls.js +4 -0
  344. package/dist-lib/spec/capabilities.d.ts +12 -4
  345. package/dist-lib/spec/hrpc/hrpc.json +54 -2
  346. package/dist-lib/spec/hrpc/index.js +53 -5
  347. package/dist-lib/spec/hrpc/messages.js +783 -494
  348. package/dist-lib/spec/hyperschema/index.js +783 -494
  349. package/dist-lib/spec/hyperschema/schema.json +247 -1
  350. package/dist-lib/spec/hyperschema/types.d.ts +69 -1
  351. package/dist-lib/spec/local/hyperdb/index.js +1 -1
  352. package/dist-lib/spec/local/hyperdb/messages.js +82 -14
  353. package/dist-lib/spec/local/hyperschema/index.js +42 -8
  354. package/dist-lib/spec/local/hyperschema/schema.json +27 -1
  355. package/dist-lib/spec/local/hyperschema/types.d.ts +6 -1
  356. package/dist-lib/spec/mesh/hyperdb/index.js +1 -1
  357. package/package.json +7 -3
  358. package/tui/app.mjs +2424 -941
  359. package/tui/boot.mjs +17 -46
  360. package/tui/index.mjs +10 -5
  361. package/tui/lib/boot-timing.mjs +8 -8
  362. package/tui/lib/busy-words.mjs +21 -22
  363. package/tui/lib/export.mjs +100 -32
  364. package/tui/lib/knowledge-command.mjs +64 -19
  365. package/tui/lib/knowledge-import.mjs +52 -18
  366. package/tui/lib/render.mjs +65 -33
  367. package/tui/lib/save-file.mjs +30 -13
  368. package/tui/lib/select.mjs +23 -5
  369. package/tui/lib/selection.mjs +6 -4
  370. package/tui/lib/setup.mjs +11 -19
  371. package/tui/lib/sidebar.mjs +23 -13
  372. package/tui/lib/splash.mjs +6 -7
  373. package/tui/lib/upload-frames.mjs +1 -2
  374. package/tui/lib/usage.mjs +13 -9
  375. package/tui/lib/wrap.mjs +35 -6
  376. package/tui/main.mjs +54 -78
  377. package/worker/assistant-sidecar.mjs +5 -10
  378. package/worker/stow-entry.mjs +7 -4
  379. package/dist-lib/lib/custom-model-source.d.ts +0 -15
  380. package/dist-lib/lib/custom-model-source.js +0 -46
  381. package/dist-lib/lib/oauth/common.d.ts +0 -38
  382. package/dist-lib/lib/oauth/common.js +0 -34
  383. 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,36 @@ 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);
2513
+ }
2316
2514
  }
2317
2515
  };
2318
2516
  }
2319
2517
  async _indexMeshFiles(mesh) {
2320
2518
  try {
2321
2519
  await mesh.autobee.update();
2322
- if (await this.local.files.backfilled(mesh.key))
2520
+ if (await this.local.files.backfilled(mesh.key)) {
2323
2521
  return;
2522
+ }
2324
2523
  await backfillFileIndex(mesh);
2325
- if (!mesh.closing)
2524
+ if (!mesh.closing) {
2326
2525
  await this.local.files.markBackfilled(mesh.key);
2526
+ }
2327
2527
  }
2328
2528
  catch (err) {
2329
- if (!mesh.closing)
2529
+ if (!mesh.closing) {
2330
2530
  this._log?.warn(['files'], 'indexing the mesh files failed', err);
2531
+ }
2331
2532
  }
2332
2533
  }
2333
2534
  _servedFile(mesh, coreKey, blockOffset) {
@@ -2345,11 +2546,13 @@ export class Core extends ReadyResource {
2345
2546
  if (file.own && !includeOwn)
2346
2547
  continue;
2347
2548
  const mesh = this._pooled(b4a.toHex(file.meshKey));
2348
- if (!mesh)
2549
+ if (!mesh) {
2349
2550
  continue;
2551
+ }
2350
2552
  const done = await mesh.files.clear(file.blobId, file.attachmentId ?? file.blobId);
2351
- if (!done)
2553
+ if (!done) {
2352
2554
  continue;
2555
+ }
2353
2556
  await this.local.files.markCleared(file);
2354
2557
  cleared++;
2355
2558
  }
@@ -2357,8 +2560,9 @@ export class Core extends ReadyResource {
2357
2560
  }
2358
2561
  _startFileGc({ now = false } = {}) {
2359
2562
  const gc = this._fileGc;
2360
- if (!gc || this._fileGcTimer || this.suspended)
2563
+ if (!gc || this._fileGcTimer || this.suspended) {
2361
2564
  return;
2565
+ }
2362
2566
  const run = () => {
2363
2567
  if (this._fileGcRun || this.closing || this.suspended)
2364
2568
  return;
@@ -2370,12 +2574,14 @@ export class Core extends ReadyResource {
2370
2574
  };
2371
2575
  this._fileGcTimer = setInterval(run, gc.intervalMs ?? FILE_GC_INTERVAL_MS);
2372
2576
  unref(this._fileGcTimer);
2373
- if (now)
2577
+ if (now) {
2374
2578
  run();
2579
+ }
2375
2580
  }
2376
2581
  async _stopFileGc() {
2377
- if (this._fileGcTimer)
2582
+ if (this._fileGcTimer) {
2378
2583
  clearInterval(this._fileGcTimer);
2584
+ }
2379
2585
  this._fileGcTimer = null;
2380
2586
  await this._fileGcRun?.catch(noop);
2381
2587
  }
@@ -2397,10 +2603,12 @@ export class Core extends ReadyResource {
2397
2603
  this._meshes.delete(key);
2398
2604
  wasAccount = this._accountId === key;
2399
2605
  }
2400
- if (this._candidateMesh === mesh)
2606
+ if (this._candidateMesh === mesh) {
2401
2607
  this._candidateMesh = null;
2402
- if (wasAccount)
2608
+ }
2609
+ if (wasAccount) {
2403
2610
  this._notifyStatus();
2611
+ }
2404
2612
  }
2405
2613
  _unwireMesh(entry) {
2406
2614
  if (!entry.handlers)
@@ -2419,7 +2627,7 @@ export class Core extends ReadyResource {
2419
2627
  }
2420
2628
  _startMeshServices(entry) {
2421
2629
  const { mesh } = entry;
2422
- const deviceId = this._deviceKeyPair.publicKey;
2630
+ const deviceId = this._requireDeviceKeyPair().publicKey;
2423
2631
  mesh.on('notification', (event) => this.emit('notification', event));
2424
2632
  const built = rebuildChatOrder(mesh, this.local).catch((error) => this._log?.warn(['p2p', 'mesh'], 'building the chat order failed', error));
2425
2633
  mesh.chatOrderBuilt = built;
@@ -2434,7 +2642,7 @@ export class Core extends ReadyResource {
2434
2642
  void this.local
2435
2643
  .clearChatNotify(chatId)
2436
2644
  .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));
2645
+ void removeChatAttachments(mesh, chatId, { deviceId, at: deletedAt }).catch((error) => this._log?.warn(['p2p', 'mesh'], 'chat-tombstone attachment reclaim failed', error));
2438
2646
  void removeChatKnowledge(mesh, chatId, deletedAt).catch((error) => this._log?.warn(['p2p', 'mesh'], 'chat-tombstone knowledge reclaim failed', error));
2439
2647
  void this._inferenceCalls
2440
2648
  ?.forget(chatId)
@@ -2445,8 +2653,9 @@ export class Core extends ReadyResource {
2445
2653
  if (!(await sweepLock.lock()))
2446
2654
  return;
2447
2655
  try {
2448
- if (!mesh.closing)
2656
+ if (!mesh.closing) {
2449
2657
  await mesh.files.sweepTombstones(deviceId);
2658
+ }
2450
2659
  }
2451
2660
  catch (error) {
2452
2661
  this._log?.warn(['p2p', 'mesh'], 'blob sweep failed', error);
@@ -2476,21 +2685,23 @@ export class Core extends ReadyResource {
2476
2685
  }
2477
2686
  async _discardCandidateMesh() {
2478
2687
  const candidate = this._candidateMesh;
2479
- if (!candidate)
2688
+ if (!candidate) {
2480
2689
  return;
2690
+ }
2481
2691
  this._candidateMesh = null;
2482
- if (this._swarm)
2692
+ if (this._swarm) {
2483
2693
  await this._swarm.leave(candidate.discoveryKey).catch(noop);
2694
+ }
2484
2695
  await candidate.close().catch(noop);
2485
2696
  }
2486
2697
  async _departureHasAudience(mesh) {
2487
2698
  if (!mesh.writable)
2488
2699
  return false;
2489
- const deviceId = this._deviceKeyPair.publicKey;
2700
+ const deviceId = this._requireDeviceKeyPair().publicKey;
2490
2701
  const snap = mesh.view.snapshot();
2491
2702
  try {
2492
- for await (const device of snap.find('@qvac/devices')) {
2493
- if (!device.revoked && !device.id.equals(deviceId))
2703
+ for await (const device of snap.find(DEVICES)) {
2704
+ if (!device.revoked && !b4a.equals(device.id, deviceId))
2494
2705
  return true;
2495
2706
  }
2496
2707
  return false;
@@ -2501,22 +2712,24 @@ export class Core extends ReadyResource {
2501
2712
  }
2502
2713
  async _announceDeparture(mesh = this._accountMesh(), strict = false) {
2503
2714
  if (!mesh?.writable) {
2504
- if (strict)
2715
+ if (strict) {
2505
2716
  throw new Error('Mesh departure requires a writable source');
2717
+ }
2506
2718
  return;
2507
2719
  }
2508
2720
  try {
2509
2721
  await mesh.dispatch('remove-writer', {
2510
2722
  writerKey: mesh.localWriterKey,
2511
- deviceId: this._deviceKeyPair.publicKey,
2723
+ deviceId: this._requireDeviceKeyPair().publicKey,
2512
2724
  revokedAt: Date.now()
2513
2725
  });
2514
2726
  await mesh.autobee.update();
2515
2727
  }
2516
2728
  catch (error) {
2517
2729
  this._log?.warn(['p2p', 'mesh'], 'writer departure announcement failed', error);
2518
- if (strict)
2730
+ if (strict) {
2519
2731
  throw error;
2732
+ }
2520
2733
  }
2521
2734
  }
2522
2735
  async leaveMesh(meshId) {
@@ -2524,15 +2737,18 @@ export class Core extends ReadyResource {
2524
2737
  return;
2525
2738
  if (!this.opened)
2526
2739
  await this.ready();
2527
- if (this._leaving === meshId)
2740
+ if (this._leaving === meshId) {
2528
2741
  return;
2529
- if (this._leaving || this._minting)
2742
+ }
2743
+ if (this._leaving || this._minting) {
2530
2744
  throw new Error('Mesh transition already in progress');
2745
+ }
2531
2746
  const departing = await this._openPooledMesh(meshId);
2532
- const others = (await this.local.listMeshes()).filter((row) => !row.key.equals(departing.key));
2747
+ const others = (await this.local.listMeshes()).filter((row) => !b4a.equals(row.key, departing.key));
2533
2748
  const leavingAccount = await this._isStoredAccount(departing);
2534
- if (others.length > 0 && leavingAccount)
2749
+ if (others.length > 0 && leavingAccount) {
2535
2750
  throw new Error(LEAVE_HOME_REFUSED);
2751
+ }
2536
2752
  this._leaving = meshId;
2537
2753
  this._notifyStatus();
2538
2754
  try {
@@ -2548,10 +2764,11 @@ export class Core extends ReadyResource {
2548
2764
  return;
2549
2765
  }
2550
2766
  const landed = this._waitForMeshChange();
2551
- this._requestFreshMesh().catch(() => { });
2767
+ this._requestFreshMesh().catch(noop);
2552
2768
  const error = await landed;
2553
- if (error)
2769
+ if (error) {
2554
2770
  throw error;
2771
+ }
2555
2772
  }
2556
2773
  finally {
2557
2774
  this._leaving = null;
@@ -2560,17 +2777,18 @@ export class Core extends ReadyResource {
2560
2777
  }
2561
2778
  async _isStoredAccount(mesh) {
2562
2779
  const key = await this._storedAccountKey();
2563
- return key !== undefined && key.equals(mesh.key);
2780
+ return key !== undefined && b4a.equals(key, mesh.key);
2564
2781
  }
2565
2782
  async _storedAccountKey() {
2566
- return (await this.local.accountMesh(this._deviceKeyPair.publicKey))?.key;
2783
+ return (await this.local.accountMesh(this._requireDeviceKeyPair().publicKey))?.key;
2567
2784
  }
2568
2785
  listMeshes() {
2569
2786
  if (this._listing)
2570
2787
  return this._listing;
2571
2788
  const listing = this._readMeshList().finally(() => {
2572
- if (this._listing === listing)
2789
+ if (this._listing === listing) {
2573
2790
  this._listing = null;
2791
+ }
2574
2792
  });
2575
2793
  this._listing = listing;
2576
2794
  return listing;
@@ -2613,16 +2831,18 @@ export class Core extends ReadyResource {
2613
2831
  await this.ready();
2614
2832
  await this._meshTransitionLock.lock();
2615
2833
  try {
2616
- if (this.closing)
2834
+ if (this.closing) {
2617
2835
  throw new Error('Core is closing');
2836
+ }
2618
2837
  const row = await this._archivedRow(meshId);
2619
2838
  if (row.migratedAt) {
2620
2839
  const none = { chats: 0, agents: 0, knowledge: 0 };
2621
2840
  return { meshId, migrated: false, migratedAt: row.migratedAt, ...none };
2622
2841
  }
2623
2842
  const account = await this._writableAccount();
2624
- if (!account)
2843
+ if (!account) {
2625
2844
  throw new Error(NO_WRITABLE_ACCOUNT);
2845
+ }
2626
2846
  const counts = await this._withArchivedMesh(row, (mesh) => migrateContents(mesh, account));
2627
2847
  const migratedAt = Date.now();
2628
2848
  await this.local.markMeshMigrated(row.key, migratedAt);
@@ -2634,26 +2854,35 @@ export class Core extends ReadyResource {
2634
2854
  }
2635
2855
  async _archivedRow(meshId) {
2636
2856
  const key = this._meshKeyOf(meshId);
2637
- const row = (await this.local.listArchivedMeshes()).find((row) => row.key.equals(key));
2638
- if (!row)
2857
+ const row = (await this.local.listArchivedMeshes()).find((row) => b4a.equals(row.key, key));
2858
+ if (!row) {
2639
2859
  throw new Error(`${NO_SUCH_MESH}: ${meshId}`);
2640
- if (!row.wasHome)
2860
+ }
2861
+ if (!row.wasHome) {
2641
2862
  throw new Error(`${NOT_AN_ARCHIVED_ACCOUNT}: ${meshId}`);
2863
+ }
2642
2864
  return row;
2643
2865
  }
2644
2866
  _withArchivedMesh(row, fn) {
2645
2867
  const pooled = this._pooled(b4a.toHex(row.key));
2646
- if (pooled)
2868
+ if (pooled) {
2647
2869
  return fn(pooled);
2648
- return withArchivedMesh(this.store, row, { storage: this.storage, deviceId: this._deviceKeyPair.publicKey, logger: this._log }, fn);
2870
+ }
2871
+ return withArchivedMesh(row, {
2872
+ store: this.store,
2873
+ storage: this.storage,
2874
+ deviceId: this._requireDeviceKeyPair().publicKey,
2875
+ logger: this._log
2876
+ }, fn);
2649
2877
  }
2650
2878
  async _ownMeshes(registry) {
2651
2879
  const meshes = new Map();
2652
2880
  const ours = registry.ourMemberId;
2653
- if (!ours)
2881
+ if (!ours) {
2654
2882
  return meshes;
2883
+ }
2655
2884
  for await (const joined of registry.view.find(JOINED_MESHES)) {
2656
- if (!joined.leftAt && joined.memberId.equals(ours)) {
2885
+ if (!joined.leftAt && b4a.equals(joined.memberId, ours)) {
2657
2886
  meshes.set(b4a.toHex(joined.meshKey), joined);
2658
2887
  }
2659
2888
  }
@@ -2661,22 +2890,25 @@ export class Core extends ReadyResource {
2661
2890
  }
2662
2891
  async _isOwnMeshIn(registry, meshKey) {
2663
2892
  const ours = registry.ourMemberId;
2664
- if (!ours)
2893
+ if (!ours) {
2665
2894
  return false;
2895
+ }
2666
2896
  const joined = await registry.view.get(JOINED_MESHES, { meshKey });
2667
- return Boolean(joined) && !joined.leftAt && joined.memberId.equals(ours);
2897
+ return !!joined && !joined.leftAt && b4a.equals(joined.memberId, ours);
2668
2898
  }
2669
2899
  async setMeshLabel(meshId, label) {
2670
2900
  if (!this.opened)
2671
2901
  await this.ready();
2672
2902
  const meshKey = this._meshKeyOf(meshId);
2673
2903
  const registry = await this._writableAccount();
2674
- if (!registry)
2904
+ if (!registry) {
2675
2905
  throw new Error(MESH_WITHOUT_ACCOUNT);
2906
+ }
2676
2907
  const ours = registry.ourMemberId;
2677
2908
  const joined = await registry.view.get(JOINED_MESHES, { meshKey });
2678
- if (!joined?.memberId.equals(ours))
2909
+ if (!ours || !joined || !b4a.equals(joined.memberId, ours)) {
2679
2910
  throw new Error(`${NO_SUCH_MESH}: ${meshId}`);
2911
+ }
2680
2912
  await registry.dispatch('put-joined-mesh', {
2681
2913
  room: {
2682
2914
  meshKey,
@@ -2696,7 +2928,7 @@ export class Core extends ReadyResource {
2696
2928
  await this.ready();
2697
2929
  await this._meshTransitionLock.lock();
2698
2930
  try {
2699
- return await this._mintMesh(shared, undefined, compute);
2931
+ return await this._mintMesh({ shared, compute });
2700
2932
  }
2701
2933
  finally {
2702
2934
  this._meshTransitionLock.unlock();
@@ -2708,10 +2940,11 @@ export class Core extends ReadyResource {
2708
2940
  await this._meshTransitionLock.lock();
2709
2941
  try {
2710
2942
  const registry = await this._writableAccount();
2711
- if (!registry)
2943
+ if (!registry) {
2712
2944
  throw new Error(MESH_WITHOUT_ACCOUNT);
2945
+ }
2713
2946
  const resolved = await this._resolveSharedMesh(registry);
2714
- return resolved ?? { meshId: await this._mintMesh(true, registry) };
2947
+ return resolved ?? { meshId: await this._mintMesh({ shared: true, registry }) };
2715
2948
  }
2716
2949
  finally {
2717
2950
  this._meshTransitionLock.unlock();
@@ -2719,18 +2952,20 @@ export class Core extends ReadyResource {
2719
2952
  }
2720
2953
  async _occupancyNotice(meshId) {
2721
2954
  const mesh = this._pooled(meshId);
2722
- if (!mesh)
2955
+ if (!mesh) {
2723
2956
  return undefined;
2724
- if (!mesh.ourMemberId)
2957
+ }
2958
+ if (!mesh.ourMemberId) {
2725
2959
  await mesh.refreshOurMember();
2960
+ }
2726
2961
  const ours = mesh.ourMemberId;
2727
2962
  const snap = mesh.view.snapshot();
2728
2963
  try {
2729
- for await (const member of snap.find('@qvac/members')) {
2730
- if (!ours || !member.id.equals(ours))
2964
+ for await (const member of snap.find(MEMBERS)) {
2965
+ if (!ours || !b4a.equals(member.id, ours))
2731
2966
  return MESH_NOT_EMPTY;
2732
2967
  }
2733
- for await (const _chunk of snap.find('@qvac/chunks', { limit: 1 })) {
2968
+ for await (const _chunk of snap.find(CHUNKS, { limit: 1 })) {
2734
2969
  return MESH_NOT_EMPTY;
2735
2970
  }
2736
2971
  return undefined;
@@ -2741,14 +2976,17 @@ export class Core extends ReadyResource {
2741
2976
  }
2742
2977
  async _resolveSharedMesh(registry) {
2743
2978
  const marked = [...(await this._ownMeshes(registry)).values()].filter((joined) => joined.shared);
2744
- if (marked.length === 0)
2979
+ if (marked.length === 0) {
2745
2980
  return null;
2746
- marked.sort((a, b) => a.joinedAt - b.joinedAt || Buffer.compare(a.meshKey, b.meshKey));
2981
+ }
2982
+ marked.sort((a, b) => a.joinedAt - b.joinedAt || b4a.compare(a.meshKey, b.meshKey));
2747
2983
  const [winner, ...losers] = marked;
2748
- for (const loser of losers)
2984
+ for (const loser of losers) {
2749
2985
  await this._unmarkSharedMesh(registry, loser);
2750
- if (losers.length > 0)
2986
+ }
2987
+ if (losers.length > 0) {
2751
2988
  this._notifyStatus();
2989
+ }
2752
2990
  return { meshId: b4a.toHex(winner.meshKey), notice: unmarkedNotice(losers) };
2753
2991
  }
2754
2992
  async _unmarkSharedMesh(registry, joined) {
@@ -2764,26 +3002,33 @@ export class Core extends ReadyResource {
2764
3002
  }
2765
3003
  });
2766
3004
  }
2767
- async _mintMesh(shared, resolved, compute = false) {
2768
- if (this.closing)
3005
+ async _mintMesh(opts) {
3006
+ const { shared, compute = false } = opts;
3007
+ if (this.closing) {
2769
3008
  throw new Error('Core is closing');
2770
- if (this._blockedByMinVersion())
3009
+ }
3010
+ if (this._blockedByMinVersion()) {
2771
3011
  throw new Error(MESH_BELOW_FLOOR);
2772
- if (this._leaving || this._minting)
3012
+ }
3013
+ if (this._leaving || this._minting) {
2773
3014
  throw new Error('Mesh transition already in progress');
2774
- const registry = resolved ?? (await this._writableAccount());
2775
- if (!registry)
3015
+ }
3016
+ const registry = opts.registry ?? (await this._writableAccount());
3017
+ if (!registry) {
2776
3018
  throw new Error(MESH_WITHOUT_ACCOUNT);
2777
- if (!registry.ourMemberId)
3019
+ }
3020
+ if (!registry.ourMemberId) {
2778
3021
  throw new Error(ACCOUNT_MEMBER_UNKNOWN);
3022
+ }
2779
3023
  const mesh = await this._openMesh({ new: true, sharing: true, compute });
2780
3024
  this._wireMesh(this._poolEntry(mesh));
2781
3025
  this._bringMeshOnline(mesh, { new: true });
2782
3026
  try {
2783
3027
  await mesh.refreshOurMember();
2784
- if (!mesh.ourMemberId)
3028
+ if (!mesh.ourMemberId) {
2785
3029
  throw new Error(MESH_WITHOUT_MEMBER);
2786
- await this._registerMesh(mesh.key, shared, registry);
3030
+ }
3031
+ await this._registerMesh(mesh.key, { shared, registry });
2787
3032
  }
2788
3033
  catch (error) {
2789
3034
  await this._discardMesh(mesh);
@@ -2809,13 +3054,15 @@ export class Core extends ReadyResource {
2809
3054
  await this.ready();
2810
3055
  await this._meshTransitionLock.lock();
2811
3056
  try {
2812
- if (meshId === this._accountId)
3057
+ if (meshId === this._accountId) {
2813
3058
  throw new Error('The account mesh cannot be closed');
3059
+ }
2814
3060
  const key = this._meshKeyOf(meshId);
2815
3061
  const mesh = this._pooled(meshId) ?? (await this._opening.get(meshId)?.catch(noop)) ?? null;
2816
3062
  if (!mesh) {
2817
- if (!(await this.local.readMeshSession(key)))
3063
+ if (!(await this.local.readMeshSession(key))) {
2818
3064
  throw new Error(`${NO_SUCH_MESH}: ${meshId}`);
3065
+ }
2819
3066
  return;
2820
3067
  }
2821
3068
  await this._retirePooledMesh(mesh);
@@ -2828,36 +3075,44 @@ export class Core extends ReadyResource {
2828
3075
  async _openPooledMesh(meshId) {
2829
3076
  if (!this.opened)
2830
3077
  await this.ready();
2831
- if (this.closing)
3078
+ if (this.closing) {
2832
3079
  throw new Error('Core is closing');
2833
- if (this._blockedByMinVersion())
3080
+ }
3081
+ if (this._blockedByMinVersion()) {
2834
3082
  throw new Error(MESH_BELOW_FLOOR);
3083
+ }
2835
3084
  const pooled = this._pooled(meshId);
2836
- if (pooled)
3085
+ if (pooled) {
2837
3086
  return pooled;
3087
+ }
2838
3088
  const retiring = this._retiring.get(meshId);
2839
3089
  if (retiring) {
2840
3090
  await retiring.catch(noop);
2841
3091
  return this._openPooledMesh(meshId);
2842
3092
  }
2843
3093
  const inflight = this._opening.get(meshId);
2844
- if (inflight)
3094
+ if (inflight) {
2845
3095
  return inflight;
3096
+ }
2846
3097
  const opening = this._openRecordedMesh(meshId).finally(() => {
2847
- if (this._opening.get(meshId) === opening)
3098
+ if (this._opening.get(meshId) === opening) {
2848
3099
  this._opening.delete(meshId);
3100
+ }
2849
3101
  });
2850
3102
  this._opening.set(meshId, opening);
2851
3103
  return opening;
2852
3104
  }
2853
3105
  async _openRecordedMesh(meshId) {
2854
- if (this._debugBeforeMeshOpen)
3106
+ if (this._debugBeforeMeshOpen) {
2855
3107
  await this._debugBeforeMeshOpen(meshId);
3108
+ }
2856
3109
  const key = this._meshKeyOf(meshId);
2857
3110
  const session = await this.local.readMeshSession(key);
2858
- if (!session)
3111
+ if (!session) {
2859
3112
  throw new Error(`${NO_SUCH_MESH}: ${meshId}`);
2860
- const sharing = !(await this._storedAccountKey())?.equals(key);
3113
+ }
3114
+ const stored = await this._storedAccountKey();
3115
+ const sharing = !stored || !b4a.equals(stored, key);
2861
3116
  const mesh = await this._openMeshSession(session, { sharing });
2862
3117
  const halted = mesh.interrupted;
2863
3118
  if (halted) {
@@ -2873,9 +3128,10 @@ export class Core extends ReadyResource {
2873
3128
  async _meshEntry(row, accountKey, meshes) {
2874
3129
  const meshId = b4a.toHex(row.key);
2875
3130
  const mesh = this._pooled(meshId);
2876
- const account = !!accountKey?.equals(row.key);
3131
+ const account = !!accountKey && b4a.equals(accountKey, row.key);
2877
3132
  const joined = meshes.get(meshId);
2878
3133
  const state = this._meshEntryState(mesh, account);
3134
+ const admission = state === 'joining' ? await this._admission(mesh) : {};
2879
3135
  return {
2880
3136
  meshId,
2881
3137
  state,
@@ -2887,7 +3143,8 @@ export class Core extends ReadyResource {
2887
3143
  shared: joined?.shared ?? false,
2888
3144
  sharedAt: joined?.shared ? joined.sharedAt : undefined,
2889
3145
  compute: row.compute ?? false,
2890
- ...(state === 'joining' ? await this._admission(mesh) : {})
3146
+ reason: admission.reason,
3147
+ awaitingFrom: admission.awaitingFrom
2891
3148
  };
2892
3149
  }
2893
3150
  async _admission(mesh) {
@@ -2896,12 +3153,14 @@ export class Core extends ReadyResource {
2896
3153
  const ours = mesh.localWriterKey;
2897
3154
  const admitters = [];
2898
3155
  try {
2899
- for await (const device of mesh.view.find('@qvac/devices')) {
2900
- if (device.revoked || device.writerKey?.equals(ours))
3156
+ for await (const device of mesh.view.find(DEVICES)) {
3157
+ if (device.revoked || (device.writerKey && b4a.equals(device.writerKey, ours))) {
2901
3158
  continue;
3159
+ }
2902
3160
  admitters.push(device.name);
2903
- if (admitters.length > 1)
3161
+ if (admitters.length > 1) {
2904
3162
  break;
3163
+ }
2905
3164
  }
2906
3165
  }
2907
3166
  catch {
@@ -2913,8 +3172,9 @@ export class Core extends ReadyResource {
2913
3172
  };
2914
3173
  }
2915
3174
  _meshEntryState(mesh, account) {
2916
- if (account)
3175
+ if (account) {
2917
3176
  return this._statusState();
3177
+ }
2918
3178
  if (!mesh)
2919
3179
  return 'idle';
2920
3180
  return mesh.writable ? 'joined' : 'joining';
@@ -2922,16 +3182,18 @@ export class Core extends ReadyResource {
2922
3182
  _meshKeyOf(meshId) {
2923
3183
  if (!MESH_ID.test(meshId))
2924
3184
  throw new Error(`${NO_SUCH_MESH}: ${meshId}`);
2925
- return Buffer.from(meshId, 'hex');
3185
+ return b4a.from(meshId, 'hex');
2926
3186
  }
2927
3187
  async removeDeviceWriter(writerKey, deviceId, mesh) {
2928
3188
  const target = mesh ?? (await this._awaitMesh());
2929
- if (!target)
3189
+ if (!target) {
2930
3190
  throw new Error('this device holds no account mesh');
3191
+ }
2931
3192
  await target.dispatch('remove-writer', { writerKey, deviceId, revokedAt: Date.now() });
2932
3193
  await target.autobee.update();
2933
- if (target === this._accountMesh())
3194
+ if (target === this._accountMesh()) {
2934
3195
  this._sweepUnknownEverywhere = true;
3196
+ }
2935
3197
  await this._revokeInMeshes();
2936
3198
  }
2937
3199
  _revokeInMeshes() {
@@ -2949,53 +3211,71 @@ export class Core extends ReadyResource {
2949
3211
  });
2950
3212
  return this._revokingInMeshes;
2951
3213
  }
3214
+ async _sweepEveryOwnMesh(account, ours) {
3215
+ for await (const joined of account.view.find(JOINED_MESHES)) {
3216
+ if (b4a.equals(joined.memberId, ours) && !joined.leftAt) {
3217
+ this._sweepUnknownIn.add(b4a.toHex(joined.meshKey));
3218
+ }
3219
+ }
3220
+ }
3221
+ async _revokeStaleRows(account, mesh, { self, ours, unknownToo }) {
3222
+ const rows = [];
3223
+ for await (const row of mesh.view.find(DEVICES)) {
3224
+ rows.push(row);
3225
+ }
3226
+ for (const row of rows) {
3227
+ if (!row.writerKey || row.revoked || b4a.equals(row.id, self)) {
3228
+ continue;
3229
+ }
3230
+ const member = row.memberId ?? row.claimedMemberId;
3231
+ if (member && !b4a.equals(member, ours)) {
3232
+ continue;
3233
+ }
3234
+ const device = await account.view.get(DEVICES, { id: row.id });
3235
+ if (device && !device.revoked) {
3236
+ continue;
3237
+ }
3238
+ if (!member &&
3239
+ device?.writerKey &&
3240
+ device.revokedBy &&
3241
+ b4a.equals(device.revokedBy, device.writerKey)) {
3242
+ continue;
3243
+ }
3244
+ if (!device && (!member || !unknownToo)) {
3245
+ continue;
3246
+ }
3247
+ await mesh.dispatch('remove-writer', {
3248
+ writerKey: row.writerKey,
3249
+ deviceId: row.id,
3250
+ revokedAt: device ? device.revokedAt : Date.now()
3251
+ });
3252
+ }
3253
+ }
2952
3254
  async _revokeInMeshesOnce() {
2953
3255
  try {
2954
3256
  const account = this._accountMesh();
2955
- if (!account?.ourMemberId)
3257
+ if (!account?.ourMemberId) {
2956
3258
  return;
3259
+ }
2957
3260
  if (this._sweepUnknownEverywhere) {
2958
3261
  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
- }
3262
+ await this._sweepEveryOwnMesh(account, account.ourMemberId);
2964
3263
  }
2965
- const self = this._deviceKeyPair.publicKey;
3264
+ const self = this._requireDeviceKeyPair().publicKey;
2966
3265
  for (const { mesh } of [...this._meshes.values()]) {
2967
3266
  if (mesh === account || !mesh.writable)
2968
3267
  continue;
2969
3268
  if (!(await this._isOwnMeshIn(account, mesh.key)))
2970
3269
  continue;
2971
- if (!mesh.ourMemberId)
3270
+ if (!mesh.ourMemberId) {
2972
3271
  await mesh.refreshOurMember();
2973
- if (!mesh.ourMemberId)
3272
+ }
3273
+ if (!mesh.ourMemberId) {
2974
3274
  continue;
3275
+ }
2975
3276
  const meshId = b4a.toHex(mesh.key);
2976
3277
  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
- }
3278
+ await this._revokeStaleRows(account, mesh, { self, ours: mesh.ourMemberId, unknownToo });
2999
3279
  this._sweepUnknownIn.delete(meshId);
3000
3280
  }
3001
3281
  }
@@ -3005,10 +3285,12 @@ export class Core extends ReadyResource {
3005
3285
  }
3006
3286
  async renameLocalDevice(name) {
3007
3287
  const publicKey = this.devicePublicKey;
3008
- if (publicKey)
3288
+ if (publicKey) {
3009
3289
  await this.local.renameDevice(publicKey, name);
3010
- if (this._localDevice)
3290
+ }
3291
+ if (this._localDevice) {
3011
3292
  this._localDevice = { ...this._localDevice, name };
3293
+ }
3012
3294
  }
3013
3295
  async account() {
3014
3296
  if (!this.opened)
@@ -3022,25 +3304,32 @@ export class Core extends ReadyResource {
3022
3304
  }
3023
3305
  async displayName() {
3024
3306
  const identity = await this.local.readIdentity();
3025
- if (!identity)
3307
+ if (!identity) {
3026
3308
  return null;
3309
+ }
3027
3310
  return identity.displayName ?? (await this._accountMemberName(identity.publicKey));
3028
3311
  }
3029
3312
  async _accountMemberName(identityPublicKey) {
3030
3313
  const key = await this._storedAccountKey();
3031
3314
  const mesh = key ? this._pooled(b4a.toHex(key)) : null;
3032
- if (!mesh)
3315
+ if (!mesh) {
3033
3316
  return null;
3317
+ }
3034
3318
  const ours = mesh.ourMemberId;
3035
- if (!ours || ours.equals(identityPublicKey))
3319
+ if (!ours || b4a.equals(ours, identityPublicKey)) {
3036
3320
  return null;
3037
- const member = await mesh.view.get('@qvac/members', { id: ours });
3321
+ }
3322
+ const member = await mesh.view.get(MEMBERS, { id: ours });
3038
3323
  return member?.name ?? null;
3039
3324
  }
3040
3325
  async saveDeviceProfileLocal(capabilityProfile, recommendedModelName, platform) {
3041
3326
  const publicKey = this.devicePublicKey;
3042
3327
  if (publicKey) {
3043
- await this.local.saveDeviceProfile(publicKey, capabilityProfile, recommendedModelName, platform);
3328
+ await this.local.saveDeviceProfile(publicKey, {
3329
+ capabilityProfile,
3330
+ recommendedModelName,
3331
+ platform
3332
+ });
3044
3333
  }
3045
3334
  if (this._localDevice) {
3046
3335
  this._localDevice = {
@@ -3054,49 +3343,61 @@ export class Core extends ReadyResource {
3054
3343
  async waitForWritable() {
3055
3344
  if (this.closing)
3056
3345
  return;
3057
- await this.ready();
3346
+ if (!this.opened)
3347
+ await this.ready();
3058
3348
  const mesh = await this._awaitMesh();
3059
- if (this.closing || !mesh)
3349
+ if (this.closing || !mesh) {
3060
3350
  return;
3351
+ }
3061
3352
  await Promise.race([mesh.waitForWritable(), this._closeSignal]);
3062
3353
  }
3063
3354
  async _assertMeshIsHere(meshId) {
3064
3355
  const meshKey = this._meshKeyOf(meshId);
3065
- if (await this.local.readMeshSession(meshKey))
3356
+ if (await this.local.readMeshSession(meshKey)) {
3066
3357
  return;
3358
+ }
3067
3359
  const registry = await this._writableAccount();
3068
3360
  if (registry && (await this._isOwnMeshIn(registry, meshKey))) {
3069
3361
  throw new Error(MESH_HELD_BY_SIBLING);
3070
3362
  }
3071
3363
  }
3072
3364
  async getMeshInvite(opts = {}) {
3073
- if (opts.memberInvite && opts.meshId)
3365
+ if (opts.memberInvite && opts.meshId) {
3074
3366
  await this._assertMeshIsHere(opts.meshId);
3075
- if (this.closing)
3367
+ }
3368
+ if (this.closing) {
3076
3369
  return null;
3077
- if (!this.opened)
3370
+ }
3371
+ if (!this.opened) {
3078
3372
  await this.ready();
3373
+ }
3079
3374
  const accountKey = opts.memberInvite ? null : await this._storedAccountKey();
3080
3375
  const target = opts.meshId ?? (accountKey ? b4a.toHex(accountKey) : null);
3081
3376
  const mesh = target ? await this._openPooledMesh(target) : await this._awaitMesh();
3082
- if (!mesh)
3377
+ if (!mesh) {
3083
3378
  return null;
3379
+ }
3084
3380
  const registry = await this._writableAccount();
3085
- if (!registry?.ourMemberId)
3381
+ if (!registry?.ourMemberId) {
3086
3382
  throw new Error(INVITE_ACCOUNT_UNREADABLE);
3383
+ }
3087
3384
  const isOwnMesh = await this._isOwnMeshIn(registry, mesh.key);
3088
3385
  if (opts.memberInvite) {
3089
- if (!isOwnMesh)
3386
+ if (!isOwnMesh) {
3090
3387
  throw new Error(MEMBER_INVITE_HOME_REFUSED);
3388
+ }
3091
3389
  }
3092
3390
  else {
3093
- if (isOwnMesh)
3391
+ if (isOwnMesh) {
3094
3392
  throw new Error(DEVICE_INVITE_MESH_REFUSED);
3393
+ }
3095
3394
  const key = await this._storedAccountKey();
3096
- if (!key)
3395
+ if (!key) {
3097
3396
  throw new Error(INVITE_ACCOUNT_UNREADABLE);
3098
- if (!key.equals(mesh.key))
3397
+ }
3398
+ if (!b4a.equals(key, mesh.key)) {
3099
3399
  throw new Error(DEVICE_INVITE_MESH_REFUSED);
3400
+ }
3100
3401
  }
3101
3402
  let grantSecret;
3102
3403
  if (opts.memberInvite) {
@@ -3104,8 +3405,9 @@ export class Core extends ReadyResource {
3104
3405
  const now = Date.now();
3105
3406
  const terms = { expiresAt: now + GRANT_DEFAULT_TTL_MS, maxUses: GRANT_DEFAULT_MAX_USES };
3106
3407
  const refusal = inviteGrantTermsRefusal(terms, now);
3107
- if (refusal)
3408
+ if (refusal) {
3108
3409
  throw new Error(refusal);
3410
+ }
3109
3411
  await mesh.dispatch('put-mesh-invite-grant', {
3110
3412
  grant: {
3111
3413
  grantKey: grantKeyPair(grantSecret).publicKey,
@@ -3123,13 +3425,13 @@ export class Core extends ReadyResource {
3123
3425
  : [];
3124
3426
  const memberId = opts.memberInvite ? undefined : (mesh.ourMemberId ?? undefined);
3125
3427
  const inviterName = memberId
3126
- ? ((await mesh.view.get('@qvac/members', { id: memberId }))?.name ?? undefined)
3428
+ ? ((await mesh.view.get(MEMBERS, { id: memberId }))?.name ?? undefined)
3127
3429
  : undefined;
3128
3430
  const snap = mesh.view.snapshot();
3129
3431
  let blindPeerRows;
3130
3432
  try {
3131
3433
  blindPeerRows = await snap
3132
- .find('@qvac/mesh-blind-peers', { limit: INVITE_BLIND_PEERS_LIMIT })
3434
+ .find(MESH_BLIND_PEERS, { limit: INVITE_BLIND_PEERS_LIMIT })
3133
3435
  .toArray();
3134
3436
  }
3135
3437
  finally {
@@ -3152,8 +3454,9 @@ export class Core extends ReadyResource {
3152
3454
  }
3153
3455
  previewMeshInvite(invite) {
3154
3456
  const decoded = decodeMeshInvite(invite);
3155
- if (!decoded)
3457
+ if (!decoded) {
3156
3458
  throw new Error('Invalid mesh invite');
3459
+ }
3157
3460
  return { memberInvite: decoded.memberInvite ?? false, inviterName: decoded.inviterName };
3158
3461
  }
3159
3462
  async _closeSwarm() {
@@ -3163,12 +3466,14 @@ export class Core extends ReadyResource {
3163
3466
  this._secretHandoff.destroy();
3164
3467
  this._skillOverlayHandoff.destroy();
3165
3468
  this._inferenceCallsHandoff.destroy();
3166
- if (!this._swarm)
3469
+ if (!this._swarm) {
3167
3470
  return;
3471
+ }
3168
3472
  const swarm = this._swarm;
3169
3473
  this._swarm = null;
3170
- for (const conn of swarm.connections)
3474
+ for (const conn of swarm.connections) {
3171
3475
  conn.destroy?.();
3476
+ }
3172
3477
  await swarm.destroy();
3173
3478
  }
3174
3479
  async pushSkillSecret(request) {
@@ -3176,26 +3481,31 @@ export class Core extends ReadyResource {
3176
3481
  await this.ready();
3177
3482
  const mesh = this._accountMesh();
3178
3483
  const deviceId = this.devicePublicKey;
3179
- if (!mesh || !deviceId)
3484
+ if (!mesh || !deviceId) {
3180
3485
  throw new Error(NOT_THE_HOST);
3486
+ }
3181
3487
  const agent = await getAgent(mesh, request.agentId);
3182
- if (!agent)
3488
+ if (!agent) {
3183
3489
  throw new Error(NO_SUCH_AGENT);
3184
- if (!agent.providerDeviceId)
3490
+ }
3491
+ if (!agent.providerDeviceId) {
3185
3492
  throw new Error(NOT_THE_HOST);
3186
- if (agent.providerDeviceId.equals(deviceId)) {
3493
+ }
3494
+ if (b4a.equals(agent.providerDeviceId, deviceId)) {
3187
3495
  return this._storeHandedOffSecret(request, deviceId);
3188
3496
  }
3189
- const host = await mesh.view.get('@qvac/devices', { id: agent.providerDeviceId });
3190
- if (!host || host.revoked)
3497
+ const host = await mesh.view.get(DEVICES, { id: agent.providerDeviceId });
3498
+ if (!host || host.revoked) {
3191
3499
  throw new Error(HOST_REVOKED);
3500
+ }
3192
3501
  return this._secretHandoff.send(agent.providerDeviceId, request);
3193
3502
  }
3194
3503
  async _storeHandedOffSecret(request, fromDeviceId) {
3195
3504
  const mesh = this._accountMesh();
3196
3505
  const deviceId = this.devicePublicKey;
3197
- if (!mesh || !deviceId)
3506
+ if (!mesh || !deviceId) {
3198
3507
  throw new Error(NOT_THE_HOST);
3508
+ }
3199
3509
  const receive = createSkillSecretReceiver({
3200
3510
  mesh,
3201
3511
  local: this.local,
@@ -3209,17 +3519,20 @@ export class Core extends ReadyResource {
3209
3519
  if (this.closing || !this._isPooled(memberMesh))
3210
3520
  return;
3211
3521
  const entry = this._meshes.get(this._meshIdOf(memberMesh));
3212
- if (entry?.mesh !== memberMesh)
3522
+ if (entry?.mesh !== memberMesh) {
3213
3523
  return;
3214
- if (!memberMesh.ourMemberId)
3524
+ }
3525
+ if (!memberMesh.ourMemberId) {
3215
3526
  await memberMesh.refreshOurMember();
3527
+ }
3216
3528
  const ours = memberMesh.ourMemberId;
3217
3529
  if (!ours) {
3218
3530
  entry.meshesPending = false;
3219
3531
  return;
3220
3532
  }
3221
- if (!(await entry.followLock.lock()))
3533
+ if (!(await entry.followLock.lock())) {
3222
3534
  return;
3535
+ }
3223
3536
  try {
3224
3537
  entry.meshesPending = await this._followMeshRows(memberMesh, ours);
3225
3538
  }
@@ -3232,18 +3545,21 @@ export class Core extends ReadyResource {
3232
3545
  for await (const joined of memberMesh.view.find(JOINED_MESHES)) {
3233
3546
  if (this.closing || !this._isPooled(memberMesh))
3234
3547
  return pending;
3235
- if (!joined.memberId.equals(ours))
3548
+ if (!b4a.equals(joined.memberId, ours))
3236
3549
  continue;
3237
3550
  const meshId = b4a.toHex(joined.meshKey);
3238
- if (this._following.has(meshId))
3551
+ if (this._following.has(meshId)) {
3239
3552
  continue;
3553
+ }
3240
3554
  const held = this._pooled(meshId);
3241
3555
  const failed = await this._trackFollow(meshId, async () => {
3242
3556
  if (joined.leftAt) {
3243
- if (held)
3557
+ if (held) {
3244
3558
  await this._retireLeftMesh(held);
3245
- else
3559
+ }
3560
+ else {
3246
3561
  await this._archiveLeftMeshRow(joined.meshKey);
3562
+ }
3247
3563
  return;
3248
3564
  }
3249
3565
  if (held) {
@@ -3259,8 +3575,9 @@ export class Core extends ReadyResource {
3259
3575
  }
3260
3576
  await this._openFollowedMesh(memberMesh, joined.meshKey, ours);
3261
3577
  });
3262
- if (failed && !joined.leftAt)
3578
+ if (failed && !joined.leftAt) {
3263
3579
  pending = true;
3580
+ }
3264
3581
  }
3265
3582
  return pending;
3266
3583
  }
@@ -3275,8 +3592,9 @@ export class Core extends ReadyResource {
3275
3592
  await pass;
3276
3593
  }
3277
3594
  finally {
3278
- if (this._following.get(meshId) === pass)
3595
+ if (this._following.get(meshId) === pass) {
3279
3596
  this._following.delete(meshId);
3597
+ }
3280
3598
  }
3281
3599
  return failed;
3282
3600
  }
@@ -3288,10 +3606,12 @@ export class Core extends ReadyResource {
3288
3606
  await this.local.recordDeparture(mesh.key, { creator: mesh.minted });
3289
3607
  }
3290
3608
  await this._announceDeparture(mesh);
3291
- if (this._isAccount(mesh))
3609
+ if (this._isAccount(mesh)) {
3292
3610
  await this._replaceRevokedAccount(mesh);
3293
- else
3611
+ }
3612
+ else {
3294
3613
  await this._departRevokedMesh(mesh);
3614
+ }
3295
3615
  this._departures?.flush();
3296
3616
  }
3297
3617
  catch (error) {
@@ -3306,66 +3626,84 @@ export class Core extends ReadyResource {
3306
3626
  }
3307
3627
  async _openOwnMesh(invite) {
3308
3628
  const meshKey = invite.baseKey;
3309
- const meshId = meshKey.toString('hex');
3629
+ const meshId = b4a.toHex(meshKey);
3630
+ if (!invite.inviteNonce) {
3631
+ return false;
3632
+ }
3310
3633
  const grantKey = grantKeyPair(invite.inviteNonce).publicKey;
3311
3634
  if (await this.local.readMeshSession(meshKey)) {
3312
3635
  return this._adoptOwnMesh(await this._openPooledMesh(meshId), grantKey);
3313
3636
  }
3314
3637
  const registry = await this._accountMesh();
3315
- if (!registry || !(await this._isOwnMeshIn(registry, meshKey)))
3638
+ const ours = registry?.ourMemberId;
3639
+ if (!registry || !ours || !(await this._isOwnMeshIn(registry, meshKey))) {
3316
3640
  return false;
3317
- if (this._blockedByMinVersion())
3641
+ }
3642
+ if (this._blockedByMinVersion()) {
3318
3643
  throw new Error(MESH_BELOW_FLOOR);
3644
+ }
3319
3645
  this._throwIfJoinCanceled();
3320
- await this._openFollowedMesh(registry, meshKey, registry.ourMemberId).catch((error) => {
3646
+ await this._openFollowedMesh(registry, meshKey, ours).catch((error) => {
3321
3647
  this._log?.warn(['p2p', 'mesh'], 'opening a mesh of ours through a sibling failed', error);
3322
3648
  });
3323
- if (this.closing)
3649
+ if (this.closing) {
3324
3650
  throw new Error('Core is closing');
3651
+ }
3325
3652
  this._throwIfJoinCanceled();
3326
3653
  const mesh = this._pooled(meshId);
3327
3654
  return mesh ? this._adoptOwnMesh(mesh, grantKey) : false;
3328
3655
  }
3329
3656
  async _adoptOwnMesh(mesh, grantKey) {
3330
- const id = this._deviceKeyPair.publicKey;
3657
+ const id = this._requireDeviceKeyPair().publicKey;
3331
3658
  const ours = this._accountMesh()?.ourMemberId ?? null;
3332
3659
  await this._awaitGrantRow(mesh, grantKey);
3333
3660
  let refused = false;
3334
3661
  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))
3662
+ const own = await mesh.view.get(DEVICES, { id });
3663
+ if (own && !own.revoked && own.writerKey && b4a.equals(own.writerKey, mesh.localWriterKey)) {
3337
3664
  return true;
3665
+ }
3338
3666
  refused = await this._refusedInMesh(mesh, grantKey, ours);
3339
3667
  return refused;
3340
3668
  });
3341
3669
  if (refused) {
3342
- const own = await mesh.view.get('@qvac/devices', { id });
3670
+ const own = await mesh.view.get(DEVICES, { id });
3343
3671
  await this._refuseUnredeemable(mesh, grantKey, own?.memberId ?? mesh.ourMemberId);
3344
3672
  await this._retirePooledMesh(mesh);
3345
3673
  await this.local.archiveMesh(mesh.key);
3346
3674
  return false;
3347
3675
  }
3348
- if (!settled)
3676
+ if (!settled) {
3349
3677
  throw new Error(MESH_ADMISSION_PENDING);
3678
+ }
3350
3679
  return true;
3351
3680
  }
3352
3681
  async _refusedInMesh(mesh, grantKey, ours) {
3353
3682
  await mesh.autobee.update();
3354
3683
  const status = await syncStatusSnapshot(mesh);
3355
- if (!status.devices?.length || status.state !== 'synced')
3684
+ if (!status.devices?.length || status.state !== 'synced') {
3356
3685
  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)))
3686
+ }
3687
+ const self = this._requireDeviceKeyPair().publicKey;
3688
+ const own = await mesh.view.get(DEVICES, { id: self });
3689
+ if (own?.revoked &&
3690
+ !(own.revokedBy && b4a.equals(own.revokedBy, own.writerKey ?? b4a.alloc(0)))) {
3360
3691
  return true;
3361
- if (!ours)
3692
+ }
3693
+ if (!ours) {
3362
3694
  return false;
3363
- const grant = await mesh.view.get('@qvac/mesh-invite-grants', { grantKey });
3364
- if (grant && (await memberStanding(mesh.view, ours, grant)) === 'removed')
3695
+ }
3696
+ const grant = await mesh.view.get(MESH_INVITE_GRANTS, { grantKey });
3697
+ if (grant && (await memberStanding(mesh.view, ours, grant)) === 'removed') {
3365
3698
  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))
3699
+ }
3700
+ for await (const device of mesh.view.find(DEVICES)) {
3701
+ if (!device.revoked &&
3702
+ device.memberId &&
3703
+ b4a.equals(device.memberId, ours) &&
3704
+ !b4a.equals(device.id, self)) {
3368
3705
  return false;
3706
+ }
3369
3707
  }
3370
3708
  return true;
3371
3709
  }
@@ -3373,21 +3711,26 @@ export class Core extends ReadyResource {
3373
3711
  if (this._blockedByMinVersion())
3374
3712
  return;
3375
3713
  const seed = await this._requestMeshSeed(memberMesh, meshKey, ours);
3376
- if (!seed || this.closing)
3714
+ if (!seed || this.closing) {
3377
3715
  return;
3716
+ }
3378
3717
  const moving = this._joinCancellation ? this._joinCancellation.account : this._minting;
3379
- if (moving || !this._isAccount(memberMesh))
3718
+ if (moving || !this._isAccount(memberMesh)) {
3380
3719
  return;
3720
+ }
3381
3721
  const session = this.local.createCandidateSession(seed, meshKey);
3382
- await this.local.recordMesh(this._deviceKeyPair.publicKey, meshKey, session);
3383
- await this.local.markAwaitingAdmission(meshKey, true);
3722
+ await this.local.recordMesh(meshKey, session, {
3723
+ deviceId: this._requireDeviceKeyPair().publicKey
3724
+ });
3725
+ await this.local.markAwaitingAdmission(meshKey, { awaitingAdmission: true });
3384
3726
  let mesh;
3385
3727
  try {
3386
3728
  mesh = await this._openPooledMesh(b4a.toHex(meshKey));
3387
3729
  }
3388
3730
  catch (error) {
3389
- if (this._upgradeRequired !== 'halt')
3731
+ if (this._upgradeRequired !== 'halt') {
3390
3732
  await this.local.archiveMesh(meshKey).catch(noop);
3733
+ }
3391
3734
  throw error;
3392
3735
  }
3393
3736
  await this._requestMeshAdmission(memberMesh, mesh, ours);
@@ -3399,23 +3742,28 @@ export class Core extends ReadyResource {
3399
3742
  return null;
3400
3743
  const seed = await this._meshSeedHandoff.request(sibling, meshKey).catch((error) => {
3401
3744
  this._log?.warn(['p2p', 'mesh'], 'a sibling did not hand over a mesh seed', error);
3402
- if (UNANSWERED_SEED_REQUESTS.has(error.message))
3745
+ if (UNANSWERED_SEED_REQUESTS.has(error.message)) {
3403
3746
  unanswered = error;
3747
+ }
3404
3748
  });
3405
- if (seed)
3749
+ if (seed) {
3406
3750
  return seed;
3751
+ }
3407
3752
  }
3408
- if (unanswered)
3753
+ if (unanswered) {
3409
3754
  throw unanswered;
3755
+ }
3410
3756
  return null;
3411
3757
  }
3412
3758
  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);
3759
+ if (mesh.writable) {
3760
+ return this.local.markAwaitingAdmission(mesh.key, { awaitingAdmission: false });
3761
+ }
3762
+ const { publicKey: deviceId, secretKey } = this._requireDeviceKeyPair();
3763
+ const own = await mesh.view.get(DEVICES, { id: deviceId });
3764
+ if (own && isKickedRow(own)) {
3765
+ return this.local.markAwaitingAdmission(mesh.key, { awaitingAdmission: false });
3766
+ }
3419
3767
  const binding = {
3420
3768
  meshPublicKey: mesh.publicKey,
3421
3769
  deviceId,
@@ -3434,24 +3782,27 @@ export class Core extends ReadyResource {
3434
3782
  return;
3435
3783
  if (mesh.writable)
3436
3784
  break;
3437
- if (!(await this._meshSeedHandoff.admit(sibling, mesh.key, claim).catch(noop)))
3785
+ if (!(await this._meshSeedHandoff.admit(sibling, mesh.key, claim).catch(noop))) {
3438
3786
  continue;
3787
+ }
3439
3788
  await mesh.waitForWritable(ACCOUNT_WRITABLE_MS);
3440
3789
  }
3441
3790
  if (!mesh.writable && (await mesh.waitForGenesis(ACCOUNT_WRITABLE_MS)) === null) {
3442
- await mesh.appendBirthOp(this._deviceKeyPair, this._localDevice ?? undefined);
3791
+ await mesh.appendBirthOp(this._requireDeviceKeyPair(), this._localDevice ?? undefined);
3443
3792
  await mesh.waitForWritable(ACCOUNT_WRITABLE_MS);
3444
3793
  }
3445
- if (mesh.writable)
3446
- await this.local.markAwaitingAdmission(mesh.key, false);
3794
+ if (mesh.writable) {
3795
+ await this.local.markAwaitingAdmission(mesh.key, { awaitingAdmission: false });
3796
+ }
3447
3797
  }
3448
3798
  async _liveSiblings(memberMesh, ours) {
3449
3799
  const self = this._deviceKeyPair?.publicKey;
3450
3800
  const siblings = [];
3451
- for await (const device of memberMesh.view.find('@qvac/devices')) {
3452
- if (device.revoked || !device.memberId?.equals(ours))
3801
+ for await (const device of memberMesh.view.find(DEVICES)) {
3802
+ if (device.revoked || !(device.memberId && b4a.equals(device.memberId, ours))) {
3453
3803
  continue;
3454
- if (self && device.id.equals(self))
3804
+ }
3805
+ if (self && b4a.equals(device.id, self))
3455
3806
  continue;
3456
3807
  siblings.push(device.id);
3457
3808
  }
@@ -3460,8 +3811,9 @@ export class Core extends ReadyResource {
3460
3811
  registerLoanableHarness(serve) {
3461
3812
  this._serveLoanedHarness = serve;
3462
3813
  return () => {
3463
- if (this._serveLoanedHarness === serve)
3814
+ if (this._serveLoanedHarness === serve) {
3464
3815
  this._serveLoanedHarness = null;
3816
+ }
3465
3817
  };
3466
3818
  }
3467
3819
  borrowHarness(deviceId) {
@@ -3469,9 +3821,10 @@ export class Core extends ReadyResource {
3469
3821
  }
3470
3822
  async _lendHarness(fromDeviceId) {
3471
3823
  const serve = this._serveLoanedHarness;
3472
- if (!serve)
3824
+ if (!serve) {
3473
3825
  return null;
3474
- const asker = Buffer.from(fromDeviceId);
3826
+ }
3827
+ const asker = b4a.from(fromDeviceId);
3475
3828
  if (!(await this._sharesComputeMesh(asker))) {
3476
3829
  this._log?.warn(['p2p', 'mesh'], 'loan refused: no compute mesh shared with that device');
3477
3830
  return null;
@@ -3481,7 +3834,7 @@ export class Core extends ReadyResource {
3481
3834
  return theirs;
3482
3835
  }
3483
3836
  _revalidateLoans() {
3484
- return this._harnessLoan.revalidate((device) => this._sharesComputeMesh(Buffer.from(device)));
3837
+ return this._harnessLoan.revalidate((device) => this._sharesComputeMesh(b4a.from(device)));
3485
3838
  }
3486
3839
  async _computeLender() {
3487
3840
  const self = this.devicePublicKey ? b4a.toHex(this.devicePublicKey) : undefined;
@@ -3489,10 +3842,11 @@ export class Core extends ReadyResource {
3489
3842
  for (const entry of this._meshes.values()) {
3490
3843
  if (!entry.mesh.compute)
3491
3844
  continue;
3492
- for await (const device of entry.mesh.view.find('@qvac/devices')) {
3845
+ for await (const device of entry.mesh.view.find(DEVICES)) {
3493
3846
  const id = b4a.toHex(device.id);
3494
- if (device.revoked || id === self)
3847
+ if (device.revoked || id === self) {
3495
3848
  continue;
3849
+ }
3496
3850
  lenders.set(id, device.id);
3497
3851
  }
3498
3852
  }
@@ -3503,24 +3857,24 @@ export class Core extends ReadyResource {
3503
3857
  for (const entry of this._meshes.values()) {
3504
3858
  if (!entry.mesh.compute)
3505
3859
  continue;
3506
- const device = await entry.mesh.view
3507
- .get('@qvac/devices', { id: deviceId })
3508
- .catch(noop);
3509
- if (device && !device.revoked)
3860
+ const device = await entry.mesh.view.get(DEVICES, { id: deviceId }).catch(noop);
3861
+ if (device && !device.revoked) {
3510
3862
  return true;
3863
+ }
3511
3864
  }
3512
3865
  return false;
3513
3866
  }
3514
3867
  async _serveMeshSeed(request, fromDeviceId) {
3515
- const asker = Buffer.from(fromDeviceId);
3868
+ const asker = b4a.from(fromDeviceId);
3516
3869
  if ('writerKey' in request) {
3517
3870
  return request.inviteToken
3518
3871
  ? this._admitInvitedDevice(request, asker)
3519
3872
  : this._admitIntoMesh(request, asker);
3520
3873
  }
3521
3874
  const standing = await this._askerStanding(asker);
3522
- if (standing === 'unseen')
3875
+ if (standing === 'unseen') {
3523
3876
  throw new Error(SEED_ASKER_UNSEEN);
3877
+ }
3524
3878
  if (standing === 'refused') {
3525
3879
  this._log?.warn(['p2p', 'mesh'], 'seed request refused: not a device of this member');
3526
3880
  return null;
@@ -3530,7 +3884,7 @@ export class Core extends ReadyResource {
3530
3884
  return null;
3531
3885
  }
3532
3886
  const mesh = this._pooled(b4a.toHex(request.meshKey));
3533
- const row = mesh ? await mesh.view.get('@qvac/devices', { id: asker }) : null;
3887
+ const row = mesh ? await mesh.view.get(DEVICES, { id: asker }) : null;
3534
3888
  if (row?.revoked) {
3535
3889
  this._log?.warn(['p2p', 'mesh'], 'seed request refused: removed from this mesh');
3536
3890
  return null;
@@ -3540,15 +3894,20 @@ export class Core extends ReadyResource {
3540
3894
  }
3541
3895
  async _admitInvitedDevice(request, asker) {
3542
3896
  const account = await this._accountMesh();
3543
- if (!account?.key.equals(request.meshKey)) {
3897
+ if (!(account?.key && b4a.equals(account?.key, request.meshKey))) {
3544
3898
  this._log?.warn(['p2p', 'mesh'], "device invite refused: not this device's account");
3545
3899
  return null;
3546
3900
  }
3547
- const context = { deviceKeyPair: this._deviceKeyPair, log: this._log };
3548
- const admitted = await admitInvitedDevice(account, context, this._deviceInvites, asker, request);
3549
- if (admitted)
3901
+ const context = { deviceKeyPair: this._requireDeviceKeyPair(), log: this._log };
3902
+ const admitted = await admitInvitedDevice(account, context, {
3903
+ invites: this._deviceInvites,
3904
+ deviceId: asker,
3905
+ request
3906
+ });
3907
+ if (admitted) {
3550
3908
  return { admitted: true };
3551
- if (await this._deviceInvites.spent(request.inviteToken, asker)) {
3909
+ }
3910
+ if (request.inviteToken && (await this._deviceInvites.spent(request.inviteToken, asker))) {
3552
3911
  throw new Error(DEVICE_INVITE_SPENT);
3553
3912
  }
3554
3913
  return null;
@@ -3569,10 +3928,11 @@ export class Core extends ReadyResource {
3569
3928
  return null;
3570
3929
  const account = await this._accountMesh();
3571
3930
  const ours = account?.ourMemberId;
3572
- const row = ours ? await account.view.get('@qvac/devices', { id: asker }) : null;
3573
- if (!row ||
3931
+ const row = ours ? await account.view.get(DEVICES, { id: asker }) : null;
3932
+ if (!ours ||
3933
+ !row ||
3574
3934
  row.revoked ||
3575
- !row.memberId?.equals(ours) ||
3935
+ !(row.memberId && b4a.equals(row.memberId, ours)) ||
3576
3936
  (await this._askerStanding(asker)) !== 'ours') {
3577
3937
  this._log?.warn(['p2p', 'mesh'], 'admission refused: not a live device of this member');
3578
3938
  return null;
@@ -3582,8 +3942,9 @@ export class Core extends ReadyResource {
3582
3942
  return null;
3583
3943
  }
3584
3944
  const session = await this.local.readMeshSession(request.meshKey);
3585
- if (!session?.seed)
3945
+ if (!session?.seed) {
3586
3946
  return null;
3947
+ }
3587
3948
  const writerKey = request.writerKey;
3588
3949
  const joinedAt = request.joinedAt ?? 0;
3589
3950
  const claim = {
@@ -3597,30 +3958,33 @@ export class Core extends ReadyResource {
3597
3958
  this._log?.warn(['p2p', 'mesh'], 'admission refused: the asker did not sign its claim');
3598
3959
  return null;
3599
3960
  }
3600
- const mesh = await this._openPooledMesh(request.meshKey.toString('hex'));
3961
+ const mesh = await this._openPooledMesh(b4a.toHex(request.meshKey));
3601
3962
  await mesh.autobee.update();
3602
- if (!mesh.writable)
3963
+ if (!mesh.writable) {
3603
3964
  return null;
3965
+ }
3604
3966
  if ((await mesh.bornKind()) !== 'shared') {
3605
3967
  this._log?.warn(['p2p', 'mesh'], 'admission refused: a sibling joins this mesh by its seed');
3606
3968
  return null;
3607
3969
  }
3608
- const self = await mesh.view.get('@qvac/devices', {
3609
- id: this._deviceKeyPair.publicKey
3970
+ const self = await mesh.view.get(DEVICES, {
3971
+ id: this._requireDeviceKeyPair().publicKey
3610
3972
  });
3611
- if (!self?.memberId?.equals(ours) ||
3973
+ if (!(self?.memberId && b4a.equals(self.memberId, ours)) ||
3612
3974
  self.revoked ||
3613
- !self.writerKey?.equals(mesh.localWriterKey)) {
3975
+ !(self.writerKey && b4a.equals(self.writerKey, mesh.localWriterKey))) {
3614
3976
  this._log?.warn(['p2p', 'mesh'], 'admission refused: this device is not linked in the mesh');
3615
3977
  return null;
3616
3978
  }
3617
- const current = await mesh.view.get('@qvac/devices', { id: asker });
3979
+ const current = await mesh.view.get(DEVICES, { id: asker });
3618
3980
  if (current && isKickedRow(current)) {
3619
3981
  this._log?.warn(['p2p', 'mesh'], 'admission refused: removed from this mesh');
3620
3982
  return null;
3621
3983
  }
3622
3984
  if (current && !current.revoked) {
3623
- return current.writerKey?.equals(writerKey) ? { admitted: true } : null;
3985
+ return current.writerKey && b4a.equals(current.writerKey, writerKey)
3986
+ ? { admitted: true }
3987
+ : null;
3624
3988
  }
3625
3989
  await mesh.dispatch('vouched-join', {
3626
3990
  signature: mesh.sign(writerKey),
@@ -3642,32 +4006,39 @@ export class Core extends ReadyResource {
3642
4006
  async _isJoinedMeshKey(meshKey) {
3643
4007
  for (const entry of this._meshes.values()) {
3644
4008
  const ours = entry.mesh.ourMemberId;
3645
- if (!ours)
4009
+ if (!ours) {
3646
4010
  continue;
4011
+ }
3647
4012
  const row = await entry.mesh.view.get(JOINED_MESHES, { meshKey }).catch(noop);
3648
- if (row?.memberId.equals(ours) && !row.leftAt)
4013
+ if (row?.memberId && b4a.equals(row.memberId, ours) && !row.leftAt) {
3649
4014
  return true;
4015
+ }
3650
4016
  }
3651
4017
  return false;
3652
4018
  }
3653
4019
  async _askerStanding(deviceId) {
3654
4020
  const account = this._accountMesh();
3655
4021
  const ours = account?.ourMemberId;
3656
- if (!account || !ours)
4022
+ if (!account || !ours) {
3657
4023
  return 'unseen';
3658
- const device = await account.view.get('@qvac/devices', { id: deviceId });
3659
- if (!device)
4024
+ }
4025
+ const device = await account.view.get(DEVICES, { id: deviceId });
4026
+ if (!device) {
3660
4027
  return 'unseen';
3661
- if (device.revoked)
4028
+ }
4029
+ if (device.revoked) {
3662
4030
  return 'refused';
3663
- if (!device.memberId)
4031
+ }
4032
+ if (!device.memberId) {
3664
4033
  return 'unseen';
3665
- return device.memberId.equals(ours) ? 'ours' : 'refused';
4034
+ }
4035
+ return b4a.equals(device.memberId, ours) ? 'ours' : 'refused';
3666
4036
  }
3667
4037
  async _skillOverlayOp(agentId, op) {
3668
4038
  const host = await this._resolveAgentHost(agentId);
3669
- if (!host)
4039
+ if (!host) {
3670
4040
  return this._runLocalSkillOverlayOp(op);
4041
+ }
3671
4042
  return this._skillOverlayHandoff.send(host, { ...op, agentId });
3672
4043
  }
3673
4044
  async _resolveAgentHost(agentId, mesh = this._accountMesh()) {
@@ -3676,18 +4047,23 @@ export class Core extends ReadyResource {
3676
4047
  if (!this.opened)
3677
4048
  await this.ready();
3678
4049
  const deviceId = this.devicePublicKey;
3679
- if (!mesh || !deviceId)
4050
+ if (!mesh || !deviceId) {
3680
4051
  throw new Error(NOT_THE_HOST);
4052
+ }
3681
4053
  const agent = await getAgent(mesh, agentId);
3682
- if (!agent)
4054
+ if (!agent) {
3683
4055
  throw new Error(NO_SUCH_AGENT);
3684
- if (!agent.providerDeviceId)
4056
+ }
4057
+ if (!agent.providerDeviceId) {
3685
4058
  throw new Error(NOT_THE_HOST);
3686
- if (agent.providerDeviceId.equals(deviceId))
4059
+ }
4060
+ if (b4a.equals(agent.providerDeviceId, deviceId)) {
3687
4061
  return null;
3688
- const host = await mesh.view.get('@qvac/devices', { id: agent.providerDeviceId });
3689
- if (!host || host.revoked)
4062
+ }
4063
+ const host = await mesh.view.get(DEVICES, { id: agent.providerDeviceId });
4064
+ if (!host || host.revoked) {
3690
4065
  throw new Error(HOST_REVOKED);
4066
+ }
3691
4067
  return agent.providerDeviceId;
3692
4068
  }
3693
4069
  async _listInferenceCalls(meshId, chatId) {
@@ -3696,8 +4072,9 @@ export class Core extends ReadyResource {
3696
4072
  const own = store?.list(chatId) ?? { calls: [], truncated: false };
3697
4073
  const local = own.calls;
3698
4074
  const chat = await getChat(mesh, chatId);
3699
- if (!chat)
4075
+ if (!chat) {
3700
4076
  return own;
4077
+ }
3701
4078
  const host = await this._resolveAgentHost(chat.agentId, mesh).catch((err) => {
3702
4079
  if (local.length === 0)
3703
4080
  throw err;
@@ -3708,8 +4085,9 @@ export class Core extends ReadyResource {
3708
4085
  return null;
3709
4086
  });
3710
4087
  if (!host) {
3711
- if (!store)
4088
+ if (!store) {
3712
4089
  throw new Error(NO_RECORD_STORE);
4090
+ }
3713
4091
  return own;
3714
4092
  }
3715
4093
  const answer = await this._inferenceCallsHandoff.send(host, { chatId });
@@ -3721,18 +4099,21 @@ export class Core extends ReadyResource {
3721
4099
  }
3722
4100
  _toInferenceEntry(entry) {
3723
4101
  const call = entry.call;
3724
- if (typeof call !== 'object' || call === null)
4102
+ if (!isRecord(call)) {
3725
4103
  return [];
3726
- return [{ runId: entry.runId, at: entry.at, call: call }];
4104
+ }
4105
+ return [{ runId: entry.runId, at: entry.at, call }];
3727
4106
  }
3728
4107
  async _serveInferenceCalls(request, fromDeviceId) {
3729
4108
  const mesh = (await this._meshHoldingChat(request.chatId)) ?? this._accountMesh();
3730
4109
  const deviceId = this.devicePublicKey;
3731
- if (!mesh || !deviceId)
4110
+ if (!mesh || !deviceId) {
3732
4111
  throw new Error(NOT_THE_HOST);
4112
+ }
3733
4113
  const store = this._inferenceCalls;
3734
- if (!store)
4114
+ if (!store) {
3735
4115
  throw new Error(NO_RECORD_STORE);
4116
+ }
3736
4117
  const receive = createInferenceCallsReceiver({
3737
4118
  mesh,
3738
4119
  deviceId,
@@ -3741,16 +4122,18 @@ export class Core extends ReadyResource {
3741
4122
  return receive(request, fromDeviceId);
3742
4123
  }
3743
4124
  async _meshHoldingChat(chatId) {
3744
- for (const { mesh } of this._meshes.values())
4125
+ for (const { mesh } of this._meshes.values()) {
3745
4126
  if (await getChat(mesh, chatId))
3746
4127
  return mesh;
4128
+ }
3747
4129
  return null;
3748
4130
  }
3749
4131
  async _serveSkillOverlayOp(op, fromDeviceId) {
3750
4132
  const mesh = this._accountMesh();
3751
4133
  const deviceId = this.devicePublicKey;
3752
- if (!mesh || !deviceId)
4134
+ if (!mesh || !deviceId) {
3753
4135
  throw new Error(NOT_THE_HOST);
4136
+ }
3754
4137
  const receive = createSkillOverlayReceiver({
3755
4138
  mesh,
3756
4139
  deviceId,
@@ -3785,25 +4168,31 @@ export class Core extends ReadyResource {
3785
4168
  }
3786
4169
  async _setupFields(skillName) {
3787
4170
  const skills = await this._hostSkills();
3788
- if (skills.length === 0)
4171
+ if (skills.length === 0) {
3789
4172
  return null;
4173
+ }
3790
4174
  const skill = skills.find((entry) => entry.name === skillName);
3791
- if (!skill)
4175
+ if (!skill) {
3792
4176
  return new Map();
4177
+ }
3793
4178
  const fields = new Map();
3794
4179
  for (const slot of skill.credentials ?? []) {
3795
- for (const key of slot.split('|'))
4180
+ for (const key of slot.split('|')) {
3796
4181
  fields.set(key, true);
4182
+ }
3797
4183
  }
3798
4184
  const foreign = credentialKeysOwnedElsewhere(skills, skillName);
3799
4185
  for (const route of skill.setup?.routes ?? []) {
3800
- if (route.credentialKey)
4186
+ if (route.credentialKey) {
3801
4187
  fields.set(route.credentialKey, true);
4188
+ }
3802
4189
  const stateKey = route.oauth?.stateKey;
3803
- if (stateKey && !foreign.has(stateKey))
4190
+ if (stateKey && !foreign.has(stateKey)) {
3804
4191
  fields.set(stateKey, true);
3805
- for (const field of route.fields ?? [])
4192
+ }
4193
+ for (const field of route.fields ?? []) {
3806
4194
  fields.set(field.key, field.secret === true);
4195
+ }
3807
4196
  }
3808
4197
  return fields;
3809
4198
  }
@@ -3843,8 +4232,9 @@ export class Core extends ReadyResource {
3843
4232
  void this._followJoinedMeshes(entry.mesh);
3844
4233
  }
3845
4234
  this.rootCorestore.replicate(conn);
3846
- for (const entry of this._meshes.values())
4235
+ for (const entry of this._meshes.values()) {
3847
4236
  entry.mesh.files.reconnect();
4237
+ }
3848
4238
  }
3849
4239
  _trackPeerConnection(conn) {
3850
4240
  this._peers.add(conn);
@@ -3913,13 +4303,16 @@ export class Core extends ReadyResource {
3913
4303
  const listeners = new Set();
3914
4304
  let timer = null;
3915
4305
  return {
4306
+ sampled: true,
3916
4307
  watch: (listener) => {
3917
4308
  listeners.add(listener);
3918
- if (timer)
4309
+ if (timer) {
3919
4310
  return;
4311
+ }
3920
4312
  timer = setInterval(() => {
3921
- for (const fn of listeners)
4313
+ for (const fn of listeners) {
3922
4314
  fn();
4315
+ }
3923
4316
  }, DIAGNOSTICS_SAMPLE_MS);
3924
4317
  unref(timer);
3925
4318
  },
@@ -3934,7 +4327,7 @@ export class Core extends ReadyResource {
3934
4327
  };
3935
4328
  }
3936
4329
  _networkSnapshot() {
3937
- const dht = this._swarm ? this._swarm.dht : null;
4330
+ const dht = this._swarm?.dht ?? null;
3938
4331
  return {
3939
4332
  state: this._networkState(dht),
3940
4333
  peerCount: this.peerDeviceIds.length
@@ -3949,8 +4342,9 @@ export class Core extends ReadyResource {
3949
4342
  }
3950
4343
  _logSource() {
3951
4344
  const log = this._log;
3952
- if (!log)
4345
+ if (!log) {
3953
4346
  return null;
4347
+ }
3954
4348
  return {
3955
4349
  backfill: () => log.backfill(),
3956
4350
  subscribe: (listener) => log.subscribe(listener),
@@ -3972,46 +4366,60 @@ export class Core extends ReadyResource {
3972
4366
  this._diagnosticsProviders.add(provider);
3973
4367
  return () => void this._diagnosticsProviders.delete(provider);
3974
4368
  }
4369
+ registerModelResidency(residency) {
4370
+ this._modelResidency = residency;
4371
+ return () => {
4372
+ if (this._modelResidency === residency) {
4373
+ this._modelResidency = null;
4374
+ }
4375
+ };
4376
+ }
3975
4377
  registerInferenceCalls(source) {
3976
4378
  this._inferenceCalls = source;
3977
4379
  return () => {
3978
- if (this._inferenceCalls === source)
4380
+ if (this._inferenceCalls === source) {
3979
4381
  this._inferenceCalls = null;
4382
+ }
3980
4383
  };
3981
4384
  }
3982
4385
  registerListModels(hook) {
3983
4386
  this._listModels = hook;
3984
4387
  return () => {
3985
- if (this._listModels === hook)
4388
+ if (this._listModels === hook) {
3986
4389
  this._listModels = null;
4390
+ }
3987
4391
  };
3988
4392
  }
3989
4393
  registerDeleteModel(hook) {
3990
4394
  this._deleteModel = hook;
3991
4395
  return () => {
3992
- if (this._deleteModel === hook)
4396
+ if (this._deleteModel === hook) {
3993
4397
  this._deleteModel = null;
4398
+ }
3994
4399
  };
3995
4400
  }
3996
4401
  registerClearKvCache(hook) {
3997
4402
  this._clearKvCache = hook;
3998
4403
  return () => {
3999
- if (this._clearKvCache === hook)
4404
+ if (this._clearKvCache === hook) {
4000
4405
  this._clearKvCache = null;
4406
+ }
4001
4407
  };
4002
4408
  }
4003
4409
  registerDeleteChatKvCache(hook) {
4004
4410
  this._deleteChatKvCache = hook;
4005
4411
  return () => {
4006
- if (this._deleteChatKvCache === hook)
4412
+ if (this._deleteChatKvCache === hook) {
4007
4413
  this._deleteChatKvCache = null;
4414
+ }
4008
4415
  };
4009
4416
  }
4010
4417
  registerCompactChat(hook) {
4011
4418
  this._compactChat = hook;
4012
4419
  return () => {
4013
- if (this._compactChat === hook)
4420
+ if (this._compactChat === hook) {
4014
4421
  this._compactChat = null;
4422
+ }
4015
4423
  };
4016
4424
  }
4017
4425
  registerModelCatalogWatch(hook) {
@@ -4021,8 +4429,9 @@ export class Core extends ReadyResource {
4021
4429
  if (this._modelCatalogWatch !== hook)
4022
4430
  return;
4023
4431
  this._modelCatalogWatch = null;
4024
- if (!this.closing)
4432
+ if (!this.closing) {
4025
4433
  this._resetModelCatalogWatchSource();
4434
+ }
4026
4435
  };
4027
4436
  }
4028
4437
  async *_watchModelCatalog() {
@@ -4035,15 +4444,17 @@ export class Core extends ReadyResource {
4035
4444
  return;
4036
4445
  }
4037
4446
  const watch = this._modelCatalogWatch;
4038
- if (!watch)
4447
+ if (!watch) {
4039
4448
  continue;
4449
+ }
4040
4450
  yield* watch();
4041
4451
  return;
4042
4452
  }
4043
4453
  }
4044
4454
  _openModelCatalogWatchSource() {
4045
- if (!this._modelCatalogWatch || !this._modelCatalogWatchSource.enter())
4455
+ if (!this._modelCatalogWatch || !this._modelCatalogWatchSource.enter()) {
4046
4456
  return;
4457
+ }
4047
4458
  this._modelCatalogWatchSource.exit();
4048
4459
  }
4049
4460
  _resetModelCatalogWatchSource() {
@@ -4053,30 +4464,34 @@ export class Core extends ReadyResource {
4053
4464
  registerRetryModelDownload(hook) {
4054
4465
  this._retryModelDownload = hook;
4055
4466
  return () => {
4056
- if (this._retryModelDownload === hook)
4467
+ if (this._retryModelDownload === hook) {
4057
4468
  this._retryModelDownload = null;
4469
+ }
4058
4470
  };
4059
4471
  }
4060
4472
  registerSkills(hook) {
4061
4473
  this._skills = hook;
4062
4474
  return () => {
4063
- if (this._skills === hook)
4475
+ if (this._skills === hook) {
4064
4476
  this._skills = null;
4477
+ }
4065
4478
  };
4066
4479
  }
4067
4480
  registerSkillCatalog(hook) {
4068
4481
  this._skillCatalog = hook;
4069
4482
  this._openCatalogHooks();
4070
4483
  return () => {
4071
- if (this._skillCatalog === hook)
4484
+ if (this._skillCatalog === hook) {
4072
4485
  this._skillCatalog = null;
4486
+ }
4073
4487
  };
4074
4488
  }
4075
4489
  registerSkillManagement(hooks) {
4076
4490
  this._skillManagement = hooks;
4077
4491
  return () => {
4078
- if (this._skillManagement === hooks)
4492
+ if (this._skillManagement === hooks) {
4079
4493
  this._skillManagement = null;
4494
+ }
4080
4495
  };
4081
4496
  }
4082
4497
  async _waitForCatalogHooks() {
@@ -4098,8 +4513,9 @@ export class Core extends ReadyResource {
4098
4513
  this._tools = hook;
4099
4514
  this._openCatalogHooks();
4100
4515
  return () => {
4101
- if (this._tools === hook)
4516
+ if (this._tools === hook) {
4102
4517
  this._tools = null;
4518
+ }
4103
4519
  };
4104
4520
  }
4105
4521
  registerEmbedder(embedder, extractors) {
@@ -4117,8 +4533,9 @@ export class Core extends ReadyResource {
4117
4533
  async _reconcileIndexing() {
4118
4534
  await this._indexingLock.lock();
4119
4535
  try {
4120
- if (this.closing)
4536
+ if (this.closing) {
4121
4537
  return;
4538
+ }
4122
4539
  if (this._indexedEmbedder && this._indexedEmbedder !== this._embedder) {
4123
4540
  await this._stopIndexing();
4124
4541
  }
@@ -4129,8 +4546,9 @@ export class Core extends ReadyResource {
4129
4546
  }
4130
4547
  }
4131
4548
  _startIndexing() {
4132
- for (const entry of this._meshes.values())
4549
+ for (const entry of this._meshes.values()) {
4133
4550
  this._startEntryIndexing(entry);
4551
+ }
4134
4552
  }
4135
4553
  _startEntryIndexing(entry) {
4136
4554
  if (!this._embedder || entry.processingFiles)
@@ -4152,48 +4570,64 @@ export class Core extends ReadyResource {
4152
4570
  }
4153
4571
  async _stopIndexing() {
4154
4572
  this._indexedEmbedder = null;
4155
- for (const entry of this._meshes.values())
4573
+ for (const entry of this._meshes.values()) {
4156
4574
  await this._stopEntryIndexing(entry);
4575
+ }
4157
4576
  }
4158
4577
  registerTranscribe(hook) {
4159
4578
  this._transcribe = hook;
4160
4579
  return () => {
4161
- if (this._transcribe === hook)
4580
+ if (this._transcribe === hook) {
4162
4581
  this._transcribe = null;
4582
+ }
4163
4583
  };
4164
4584
  }
4165
4585
  registerDetectLanguage(hook) {
4166
4586
  this._detectLanguage = hook;
4167
4587
  return () => {
4168
- if (this._detectLanguage === hook)
4588
+ if (this._detectLanguage === hook) {
4169
4589
  this._detectLanguage = null;
4590
+ }
4591
+ };
4592
+ }
4593
+ registerPreviewModelSource(hook) {
4594
+ this._previewModelSource = hook;
4595
+ return () => {
4596
+ if (this._previewModelSource === hook) {
4597
+ this._previewModelSource = null;
4598
+ }
4170
4599
  };
4171
4600
  }
4172
4601
  registerSpeak(hook) {
4173
4602
  this._speak = hook;
4174
4603
  return () => {
4175
- if (this._speak === hook)
4604
+ if (this._speak === hook) {
4176
4605
  this._speak = null;
4606
+ }
4177
4607
  };
4178
4608
  }
4179
4609
  registerSpeakStream(hook) {
4180
4610
  this._speakStream = hook;
4181
4611
  return () => {
4182
- if (this._speakStream === hook)
4612
+ if (this._speakStream === hook) {
4183
4613
  this._speakStream = null;
4614
+ }
4184
4615
  };
4185
4616
  }
4186
4617
  _diagnosticsSource() {
4187
4618
  const listeners = new Set();
4188
4619
  let timer = null;
4189
4620
  return {
4621
+ sampled: true,
4190
4622
  watch: (listener) => {
4191
4623
  listeners.add(listener);
4192
- if (timer)
4624
+ if (timer) {
4193
4625
  return;
4626
+ }
4194
4627
  timer = setInterval(() => {
4195
- for (const fn of listeners)
4628
+ for (const fn of listeners) {
4196
4629
  fn();
4630
+ }
4197
4631
  }, DIAGNOSTICS_SAMPLE_MS);
4198
4632
  unref(timer);
4199
4633
  },
@@ -4206,8 +4640,9 @@ export class Core extends ReadyResource {
4206
4640
  },
4207
4641
  snapshot: () => {
4208
4642
  const merged = { ...this._diagnostics() };
4209
- for (const provider of this._diagnosticsProviders)
4643
+ for (const provider of this._diagnosticsProviders) {
4210
4644
  Object.assign(merged, provider());
4645
+ }
4211
4646
  return merged;
4212
4647
  }
4213
4648
  };
@@ -4224,7 +4659,7 @@ export class Core extends ReadyResource {
4224
4659
  _diagnostics() {
4225
4660
  const mesh = this._accountMesh();
4226
4661
  const swarm = this._swarm;
4227
- const dht = swarm ? swarm.dht : null;
4662
+ const dht = swarm?.dht ?? null;
4228
4663
  const system = this._systemInfo?.snapshot() ?? { cpu: null, gpu: null };
4229
4664
  const publicKey = this.devicePublicKey ? b4a.toHex(this.devicePublicKey) : undefined;
4230
4665
  const device = this._localDevice;
@@ -4295,21 +4730,26 @@ export class Core extends ReadyResource {
4295
4730
  return 'error';
4296
4731
  if (this.closing || this._leaving)
4297
4732
  return 'leaving';
4298
- if (this._kicked)
4733
+ if (this._kicked) {
4299
4734
  return 'kicked';
4300
- if (this._upgradeRequired)
4735
+ }
4736
+ if (this._upgradeRequired) {
4301
4737
  return 'needs-upgrade';
4302
- if (this._minting)
4738
+ }
4739
+ if (this._minting) {
4303
4740
  return 'joining';
4741
+ }
4304
4742
  const account = this._accountMesh();
4305
- if (account)
4743
+ if (account) {
4306
4744
  return account.writable ? 'joined' : 'joining';
4745
+ }
4307
4746
  return 'idle';
4308
4747
  }
4309
4748
  _notifyStatus() {
4310
4749
  this._listing = null;
4311
- for (const listener of [...this._statusListeners])
4750
+ for (const listener of [...this._statusListeners]) {
4312
4751
  listener();
4752
+ }
4313
4753
  }
4314
4754
  }
4315
4755
  function after(ms) {
@@ -4331,26 +4771,34 @@ async function closeConfigReader(reader) {
4331
4771
  async function recordedBlockIsLocal(core) {
4332
4772
  await raceResource(core, core.ready(), 'config core');
4333
4773
  const length = Number((await raceResource(core, core.getUserData('hyperconf'), 'config core')) || '0');
4334
- if (length <= 0)
4774
+ if (length <= 0) {
4335
4775
  return true;
4776
+ }
4336
4777
  return raceResource(core, core.has(length - 1), 'config core');
4337
4778
  }
4338
4779
  function statusErrorMessage(context, err) {
4339
- const detail = err instanceof Error ? err.message : err ? String(err) : '';
4780
+ const detail = errorDetail(err);
4340
4781
  return detail ? `${context}: ${detail}` : context;
4341
4782
  }
4783
+ function errorDetail(err) {
4784
+ if (err instanceof Error)
4785
+ return err.message;
4786
+ return err ? String(err) : '';
4787
+ }
4342
4788
  function credentialKeysOwnedElsewhere(skills, skillName) {
4343
4789
  const keys = new Set();
4344
4790
  for (const entry of skills) {
4345
4791
  if (entry.name === skillName)
4346
4792
  continue;
4347
4793
  for (const slot of entry.credentials ?? []) {
4348
- for (const key of slot.split('|'))
4794
+ for (const key of slot.split('|')) {
4349
4795
  keys.add(key);
4796
+ }
4350
4797
  }
4351
4798
  for (const route of entry.setup?.routes ?? []) {
4352
- if (route.credentialKey)
4799
+ if (route.credentialKey) {
4353
4800
  keys.add(route.credentialKey);
4801
+ }
4354
4802
  }
4355
4803
  }
4356
4804
  return keys;