@qvac/core 0.6.7 → 0.7.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 (116) hide show
  1. package/CHANGELOG.md +145 -1
  2. package/README.md +2 -0
  3. package/dist-lib/lib/api/app-config.d.ts +3 -1
  4. package/dist-lib/lib/api/app-config.js +15 -4
  5. package/dist-lib/lib/assistant/fake-models.d.ts +22 -0
  6. package/dist-lib/lib/assistant/fake-models.js +112 -0
  7. package/dist-lib/lib/assistant/harness.d.ts +10 -0
  8. package/dist-lib/lib/assistant/harness.js +26 -0
  9. package/dist-lib/lib/assistant/history.d.ts +5 -1
  10. package/dist-lib/lib/assistant/history.js +14 -2
  11. package/dist-lib/lib/assistant-tree.d.ts +4 -0
  12. package/dist-lib/lib/assistant-tree.js +45 -7
  13. package/dist-lib/lib/assistant.d.ts +15 -2
  14. package/dist-lib/lib/assistant.js +175 -41
  15. package/dist-lib/lib/constants.d.ts +6 -0
  16. package/dist-lib/lib/constants.js +6 -0
  17. package/dist-lib/lib/core/chat-activity.d.ts +1 -1
  18. package/dist-lib/lib/core/chat-activity.js +3 -0
  19. package/dist-lib/lib/core/collections.d.ts +1 -0
  20. package/dist-lib/lib/core/collections.js +1 -0
  21. package/dist-lib/lib/core/contract/compute.d.ts +1 -1
  22. package/dist-lib/lib/core/contract/compute.js +2 -1
  23. package/dist-lib/lib/core/contract/index.js +6 -1
  24. package/dist-lib/lib/core/contract/invites.d.ts +1 -11
  25. package/dist-lib/lib/core/contract/invites.js +3 -3
  26. package/dist-lib/lib/core/contract/mesh-seeds.d.ts +2 -0
  27. package/dist-lib/lib/core/contract/mesh-seeds.js +26 -0
  28. package/dist-lib/lib/core/contract/open-join.d.ts +2 -0
  29. package/dist-lib/lib/core/contract/open-join.js +57 -0
  30. package/dist-lib/lib/core/departures.d.ts +3 -0
  31. package/dist-lib/lib/core/departures.js +44 -1
  32. package/dist-lib/lib/core/identity.d.ts +1 -1
  33. package/dist-lib/lib/core/identity.js +6 -4
  34. package/dist-lib/lib/core/invite.d.ts +2 -0
  35. package/dist-lib/lib/core/invite.js +6 -2
  36. package/dist-lib/lib/core/membership.d.ts +1 -12
  37. package/dist-lib/lib/core/membership.js +1 -94
  38. package/dist-lib/lib/core/mesh.d.ts +8 -13
  39. package/dist-lib/lib/core/mesh.js +41 -87
  40. package/dist-lib/lib/core/sync/index.js +2 -16
  41. package/dist-lib/lib/core.d.ts +30 -49
  42. package/dist-lib/lib/core.js +341 -868
  43. package/dist-lib/lib/diagnostics.d.ts +7 -0
  44. package/dist-lib/lib/diagnostics.js +22 -0
  45. package/dist-lib/lib/doctor/checks.d.ts +15 -0
  46. package/dist-lib/lib/doctor/checks.js +269 -0
  47. package/dist-lib/lib/doctor/redact.d.ts +4 -0
  48. package/dist-lib/lib/doctor/redact.js +31 -0
  49. package/dist-lib/lib/doctor/render.d.ts +8 -0
  50. package/dist-lib/lib/doctor/render.js +83 -0
  51. package/dist-lib/lib/doctor/tree.d.ts +5 -0
  52. package/dist-lib/lib/doctor/tree.js +167 -0
  53. package/dist-lib/lib/downloads-allowed-pusher.d.ts +10 -0
  54. package/dist-lib/lib/downloads-allowed-pusher.js +37 -0
  55. package/dist-lib/lib/guards.d.ts +1 -0
  56. package/dist-lib/lib/guards.js +4 -0
  57. package/dist-lib/lib/inference-calls.js +1 -5
  58. package/dist-lib/lib/kv-cache-reclaim.d.ts +2 -1
  59. package/dist-lib/lib/kv-cache-reclaim.js +24 -0
  60. package/dist-lib/lib/mesh-scoped-engine.js +1 -0
  61. package/dist-lib/lib/model-download-status.d.ts +1 -1
  62. package/dist-lib/lib/model-download.d.ts +9 -1
  63. package/dist-lib/lib/model-download.js +48 -3
  64. package/dist-lib/lib/model-memory-cap.d.ts +29 -0
  65. package/dist-lib/lib/model-memory-cap.js +69 -0
  66. package/dist-lib/lib/models-watch.d.ts +1 -1
  67. package/dist-lib/lib/models-watch.js +4 -4
  68. package/dist-lib/lib/oauth/flow.js +1 -1
  69. package/dist-lib/lib/oauth/loopback.js +16 -2
  70. package/dist-lib/lib/oauth/redirect-types.d.ts +1 -0
  71. package/dist-lib/lib/run-replay.d.ts +26 -0
  72. package/dist-lib/lib/run-replay.js +107 -0
  73. package/dist-lib/schema/config.d.ts +1 -1
  74. package/dist-lib/schema/config.js +1 -1
  75. package/dist-lib/schema/content.js +9 -1
  76. package/dist-lib/schema/engine.js +30 -5
  77. package/dist-lib/schema/local.js +3 -2
  78. package/dist-lib/schema/qvac.js +18 -1
  79. package/dist-lib/spec/bind.js +3 -0
  80. package/dist-lib/spec/calls.js +1 -0
  81. package/dist-lib/spec/capabilities.d.ts +2 -0
  82. package/dist-lib/spec/config/hyperconf/index.js +1 -1
  83. package/dist-lib/spec/hrpc/hrpc.json +13 -0
  84. package/dist-lib/spec/hrpc/index.js +15 -3
  85. package/dist-lib/spec/hrpc/messages.js +646 -557
  86. package/dist-lib/spec/hyperschema/index.js +646 -557
  87. package/dist-lib/spec/hyperschema/schema.json +80 -0
  88. package/dist-lib/spec/hyperschema/types.d.ts +20 -3
  89. package/dist-lib/spec/local/hyperdb/messages.js +22 -10
  90. package/dist-lib/spec/local/hyperschema/index.js +16 -7
  91. package/dist-lib/spec/local/hyperschema/schema.json +10 -1
  92. package/dist-lib/spec/local/hyperschema/types.d.ts +3 -2
  93. package/dist-lib/spec/mesh/hyperdb/db.json +16 -1
  94. package/dist-lib/spec/mesh/hyperdb/index.js +71 -2
  95. package/dist-lib/spec/mesh/hyperdb/messages.js +477 -240
  96. package/dist-lib/spec/mesh/hyperdispatch/dispatch.json +13 -1
  97. package/dist-lib/spec/mesh/hyperdispatch/index.js +35 -1
  98. package/dist-lib/spec/mesh/hyperdispatch/messages.js +180 -7
  99. package/dist-lib/spec/mesh/hyperschema/index.js +180 -7
  100. package/dist-lib/spec/mesh/hyperschema/schema.json +98 -1
  101. package/dist-lib/spec/mesh/hyperschema/types.d.ts +26 -2
  102. package/package.json +8 -16
  103. package/tui/README.md +7 -1
  104. package/tui/app.mjs +245 -11
  105. package/tui/boot.mjs +1 -0
  106. package/tui/index.mjs +1 -0
  107. package/tui/lib/render.mjs +25 -1
  108. package/worker/assistant-sidecar.mjs +5 -2
  109. package/dist-lib/lib/core/device-invites.d.ts +0 -11
  110. package/dist-lib/lib/core/device-invites.js +0 -63
  111. package/dist-lib/lib/core/grant-expiry.d.ts +0 -11
  112. package/dist-lib/lib/core/grant-expiry.js +0 -66
  113. package/dist-lib/lib/core/mesh-seed-handoff.d.ts +0 -27
  114. package/dist-lib/lib/core/mesh-seed-handoff.js +0 -53
  115. package/dist-lib/lib/oauth/loopback.stub.d.ts +0 -3
  116. package/dist-lib/lib/oauth/loopback.stub.js +0 -6
@@ -13,6 +13,7 @@ import ReadyResource from 'ready-resource';
13
13
  import ScopeLock from 'scope-lock';
14
14
  import { isAndroid } from 'which-runtime';
15
15
  import { createApi } from './api/index.js';
16
+ import { writeAutoDownloadModels } from './api/app-config.js';
16
17
  import { NO_SUCH_MESH, requireMesh } from './api/current-mesh.js';
17
18
  import { ChatMoves } from './core/chat-move.js';
18
19
  import { asEncoded, watchModels } from './models-watch.js';
@@ -24,9 +25,6 @@ import { createFsDriveHost } from './core/fs-drives.js';
24
25
  import { sweepDriveStaging } from './fs-drive-bridge.js';
25
26
  import { decodeMeshInvite, encodeMeshInvite } from './core/invite.js';
26
27
  import { fileKeyOf, knownFile, referencedFile } from './core/files/local-index.js';
27
- import { grantKeyPair, inviteGrantTermsRefusal } from './core/invite-grants.js';
28
- import { belongsToAnotherMember, inviteStanding, memberStanding, removedBy } from './core/contract/invites.js';
29
- import { syncStatusSnapshot } from './core/sync-status.js';
30
28
  import { openLocalStore } from './core/local/index.js';
31
29
  import { MAX_MESH_NAME_CHARS, meshNameWithinBounds } from '../schema/qvac.js';
32
30
  import { getAgent } from './core/agent.js';
@@ -34,27 +32,22 @@ import { countContents, migrateContents, withArchivedMesh } from './core/archive
34
32
  import { HostedAgents } from './core/hosted-agents.js';
35
33
  import { HarnessLoan } from './core/harness-loan.js';
36
34
  import { duplexPair } from '@qvac/harness/transport';
37
- import { signMemberWriterClaim, signWriterClaim, verifyMemberWriterClaim, verifyWriterClaim } from './core/device-attestation.js';
38
- import { HOST_SILENT, HOST_UNREACHABLE } from './core/handoff-channel.js';
39
- import { MeshSeedHandoff, SEED_REFUSED, ADMISSION_DEFERRED, SEED_ASKER_UNSEEN } from './core/mesh-seed-handoff.js';
40
35
  import { SecretHandoff } from './core/secret-handoff.js';
41
36
  import { InferenceCallsHandoff } from './core/inference-calls-handoff.js';
42
37
  import { createInferenceCallsReceiver, NO_RECORD_STORE } from './core/inference-calls-receiver.js';
43
38
  import { SkillOverlayHandoff } from './core/skill-overlay-handoff.js';
44
39
  import { createSkillOverlayReceiver } from './core/skill-overlay-receiver.js';
45
40
  import { createSkillSecretReceiver, HOST_REVOKED, NO_SUCH_AGENT, NOT_THE_HOST } from './core/skill-secrets.js';
46
- import { attestMemberClaim, claimAttestation, deviceInviteToken, openIdentity } from './core/identity.js';
41
+ import { attestDeviceProof, attestMemberClaim, claimAttestation, delegationFits, openIdentity } from './core/identity.js';
47
42
  import { openRecoveryCore, publishRecovery, readRecovery, recoveryKeys } from './core/account-recovery.js';
48
- import { admitInvitedDevice, attestUnattestedDevices, claimOwnMembership, legacyNameStamp, namedAt, renameFoundedMember, sealAccount } from './core/membership.js';
49
- import { DEVICE_INVITE_SPENT, openDeviceInvites } from './core/device-invites.js';
43
+ import { claimOwnMembership, legacyNameStamp, namedAt, renameFoundedMember } from './core/membership.js';
50
44
  import { runMigrations } from './core/migrations/index.js';
51
45
  import { backfillFileIndex } from './core/migrations/file-index.js';
52
46
  import { advertiseDeviceVersion, retractInventory } from './core/devices.js';
53
47
  import { OtaConfigReader, configCoreFor, resolveConfigChannel, vendoredMinSupportedVersion } from './core/ota-config.js';
54
48
  import { updateRequired } from './core/min-version.js';
55
49
  import { PendingDepartures } from './core/departures.js';
56
- import { isKickedRow } from './core/helpers/index.js';
57
- import { Mesh, claimableDevice, meshPublicKeyFromSeed } from './core/mesh.js';
50
+ import { Mesh } from './core/mesh.js';
58
51
  import { raceResource } from './race-resource.js';
59
52
  import { createSystemInfoSampler } from './core/system-info.js';
60
53
  import { setLogger } from './logger.js';
@@ -63,19 +56,19 @@ import { openLocalSpec } from './spec-loader.js';
63
56
  import { unref } from './unref.js';
64
57
  import { local } from '../spec/index.js';
65
58
  import { isRecord } from './guards.js';
66
- import { CHUNKS, DEVICES, JOINED_MESHES, MEMBERS, MESH_BLIND_PEERS, MESH_INVITE_GRANTS, MESH_INVITE_SPENDS, MESH_KINDS } from './core/collections.js';
59
+ import { CHUNKS, DEVICES, JOINED_MESHES, MEMBERS, MESH_BLIND_PEERS, MESH_SEEDS } from './core/collections.js';
60
+ import { isOwnRevokedRow } from './core/helpers/index.js';
67
61
  const QvacState = local.getEnum('@local/qvac-state');
68
62
  const top = new Top();
69
63
  const FILE_GC_INTERVAL_MS = 24 * 60 * 60 * 1000;
70
64
  const SWARM_KEYPAIR_NAME = 'qvac-swarm-keypair';
71
65
  const QVAC_CORE_NAMESPACE = 'qvac-core';
72
66
  const MESH_JOIN_CANCELED = 'Mesh join canceled';
73
- const GRANT_JOIN_TIMED_OUT = 'Join did not complete in time - the invite may already be spent, expired or revoked';
74
67
  const MESH_ID = /^[0-9a-f]{64}$/;
75
68
  const MESH_BELOW_FLOOR = 'Build is below the mesh floor';
76
69
  const MESH_WITHOUT_ACCOUNT = 'Recording a mesh needs the account mesh';
77
70
  export const ACCOUNT_MEMBER_UNKNOWN = 'This device is not part of its account yet';
78
- export const AWAITING_ADMISSION = 'awaiting-admission';
71
+ export const DEVICE_UNKNOWN = 'This device has no device details: pass `device` when creating Core';
79
72
  const MESH_WITHOUT_MEMBER = 'A mesh needs this device to belong to its account member';
80
73
  const NO_WRITABLE_ACCOUNT = 'The account mesh is not writable';
81
74
  const NOT_AN_ARCHIVED_ACCOUNT = 'Not an account this device left';
@@ -83,35 +76,18 @@ const NO_ACCOUNT_TO_RECOVER = 'This device has no account to make recoverable';
83
76
  const PHRASE_NOT_OURS = 'The phrase does not derive the identity this device holds';
84
77
  const PHRASE_NOT_A_MEMBER = "The phrase names no member of this account, so it could not recover it: publish from a device holding the account's phrase";
85
78
  const NO_RECOVERY_RECORD = 'No recovery record was found for this phrase';
86
- const RECOVERY_DEVICE_REMOVED = 'This device was removed from the account, so it cannot recover it: wipe it and recover as a new device';
87
79
  const RECOVERY_WAIT_MS = 30_000;
88
80
  export const MEMBER_INVITE_HOME_REFUSED = 'An account mesh cannot be invited into';
89
81
  export const DEVICE_INVITE_MESH_REFUSED = 'Only an account mesh can take a device invite';
90
82
  export const MESH_NAME_ACCOUNT_REFUSED = 'An account mesh has no shared name';
91
83
  export const INVITE_ACCOUNT_UNREADABLE = 'This device cannot reach its account to check';
84
+ export const DEVICE_INVITE_CHAIN_TOO_LONG = 'This device cannot invite another one: invite from another of your devices, or recover from your phrase';
92
85
  export const MESH_HELD_BY_SIBLING = 'Another of your devices holds this mesh: bring that device online, or invite from it instead';
93
- export const INVITE_GRANT_REVOKED = 'This invite was revoked';
94
- export const MESH_ALREADY_JOINED = 'This device is already in this mesh';
95
- export const MESH_ADMISSION_PENDING = 'This mesh has not admitted this device yet: try again in a moment';
96
- export const MEMBER_ALREADY_IN_MESH = 'Another of your devices is already in this mesh: join through it once it is online';
97
- export const DEVICE_OF_ANOTHER_MEMBER = 'This device belongs to another member in this mesh';
98
- export const MEMBER_REMOVED_SINCE_INVITE = 'You were removed from this mesh after this invite was made: ask for a new one';
99
- export const INVITE_GRANT_EXPIRED = 'This invite has expired';
100
- export const INVITE_GRANT_EXHAUSTED = 'This invite has already been used';
101
- export const SEALED_ACCOUNT_READER = 'This account admits no device by its seed alone: pair this device with a device invite';
102
- export const INVITER_OFFLINE = 'The device that made this invite is not online: bring it online and try again';
86
+ const MESH_DIED = 'the local database died';
103
87
  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';
104
- const UNANSWERED_SEED_REQUESTS = new Set([HOST_SILENT, SEED_ASKER_UNSEEN]);
105
88
  const INVITE_DHT_NODES_LIMIT = 3;
106
89
  const INVITE_BLIND_PEERS_LIMIT = 3;
107
- const GRANT_DEFAULT_MAX_USES = 1;
108
- const GRANT_DEFAULT_TTL_MS = 48 * 60 * 60 * 1000;
109
- const GRANT_VISIBLE_MS = 10_000;
110
90
  const DIAGNOSTICS_SAMPLE_MS = 2000;
111
- const ACCOUNT_WRITABLE_MS = 15_000;
112
- const GRANT_WRITABLE_MS = 60_000;
113
- const INVITER_RETRY_MS = 1_000;
114
- const ADMISSION_RETRIES = 60;
115
91
  export class Core extends ReadyResource {
116
92
  _storagePath;
117
93
  store;
@@ -121,7 +97,6 @@ export class Core extends ReadyResource {
121
97
  _ownsSwarm;
122
98
  _ownsWakeup;
123
99
  local;
124
- _deviceInvites;
125
100
  state;
126
101
  _transport;
127
102
  _apiLifecycle;
@@ -141,15 +116,14 @@ export class Core extends ReadyResource {
141
116
  _blindPeerKeys;
142
117
  _blindPeeringOpts;
143
118
  _fileGc;
119
+ _autoDownloadModels;
144
120
  _fileGcTimer = null;
145
121
  _fileGcRun = null;
146
122
  _meshSeed;
147
123
  _meshKey;
148
124
  _additionalNodes;
149
- _grantWritableMs;
150
- _accountWritableMs;
151
- _grantVisibleMs;
152
125
  _listModels;
126
+ _modelMemory = null;
153
127
  _deleteModel;
154
128
  _clearKvCache;
155
129
  _deleteChatKvCache;
@@ -203,12 +177,9 @@ export class Core extends ReadyResource {
203
177
  _fsDrives = null;
204
178
  _blobServer = null;
205
179
  _wakeup;
206
- _meshSeedHandoff;
207
180
  _harnessLoan;
208
181
  _serveLoanedHarness = null;
209
182
  _following = new Map();
210
- _admissionRetries = new Map();
211
- _admissionRetryPending = new Set();
212
183
  _revokingInMeshes = null;
213
184
  _revokeInMeshesAgain = false;
214
185
  _sweepUnknownEverywhere = false;
@@ -217,6 +188,7 @@ export class Core extends ReadyResource {
217
188
  _skillOverlayHandoff;
218
189
  _inferenceCallsHandoff;
219
190
  _minting;
191
+ _backfill = Promise.resolve();
220
192
  _leaving;
221
193
  _kicked;
222
194
  _kickedPending;
@@ -231,7 +203,7 @@ export class Core extends ReadyResource {
231
203
  _systemInfo;
232
204
  _statusError;
233
205
  _upgradeRequired;
234
- constructor(transport, { storagePath, store = undefined, swarm = undefined, wakeup = undefined, 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, grantWritableMs = GRANT_WRITABLE_MS, accountWritableMs = ACCOUNT_WRITABLE_MS, grantVisibleMs = GRANT_VISIBLE_MS }) {
206
+ constructor(transport, { storagePath, store = undefined, swarm = undefined, wakeup = undefined, logger = null, spec = openLocalSpec, bootstrapNodes = undefined, device = undefined, app = undefined, minSupportedVersion = undefined, otaConfigCore = undefined, blindPeerKeys = undefined, blindPeeringOpts = undefined, fileGc = null, autoDownloadModels = undefined, 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 }) {
235
207
  super();
236
208
  this._transport = transport;
237
209
  this._apiLifecycle = apiLifecycle ?? {
@@ -257,7 +229,6 @@ export class Core extends ReadyResource {
257
229
  this.rootCorestore = store ?? new Corestore(this.storage, { globalCache: new Rache() });
258
230
  this.store = this.rootCorestore.namespace(QVAC_CORE_NAMESPACE);
259
231
  this.local = openLocalStore(this.storage);
260
- this._deviceInvites = openDeviceInvites(this.local);
261
232
  this.state = QvacState.RESUME;
262
233
  this._spec = spec;
263
234
  this._bootstrapNodes = bootstrapNodes;
@@ -274,12 +245,10 @@ export class Core extends ReadyResource {
274
245
  this._blindPeerKeys = blindPeerKeys;
275
246
  this._blindPeeringOpts = blindPeeringOpts;
276
247
  this._fileGc = fileGc;
248
+ this._autoDownloadModels = autoDownloadModels;
277
249
  this._meshSeed = meshSeed;
278
250
  this._meshKey = meshKey;
279
251
  this._additionalNodes = additionalNodes;
280
- this._grantWritableMs = grantWritableMs;
281
- this._accountWritableMs = accountWritableMs;
282
- this._grantVisibleMs = grantVisibleMs;
283
252
  this._listModels = listModels ?? null;
284
253
  this._deleteModel = deleteModel ?? null;
285
254
  this._clearKvCache = clearKvCache ?? null;
@@ -336,9 +305,6 @@ export class Core extends ReadyResource {
336
305
  this._skillOverlayHandoff = new SkillOverlayHandoff({
337
306
  onrequest: (op, from) => this._serveSkillOverlayOp(op, from)
338
307
  });
339
- this._meshSeedHandoff = new MeshSeedHandoff({
340
- onrequest: (request, from) => this._serveMeshSeed(request, from)
341
- });
342
308
  this._harnessLoan = new HarnessLoan({ onborrow: (from) => this._lendHarness(from) });
343
309
  this._inferenceCallsHandoff = new InferenceCallsHandoff({
344
310
  onrequest: (request, from) => this._serveInferenceCalls(request, from)
@@ -395,10 +361,14 @@ export class Core extends ReadyResource {
395
361
  this._swarm?.keyPair ?? (await this.store.createKeyPair(SWARM_KEYPAIR_NAME));
396
362
  this._identityPublicKey = (await this.local.readIdentity())?.publicKey ?? null;
397
363
  this._localDevice = await this.local.ensureDevice(this._deviceKeyPair.publicKey, this._device);
364
+ if (this._autoDownloadModels !== undefined) {
365
+ await writeAutoDownloadModels(this.local, this._autoDownloadModels);
366
+ }
398
367
  const swarm = this._openSwarm(this._deviceKeyPair);
399
368
  this._departures = new PendingDepartures(this.store, this.local, {
400
369
  swarm,
401
370
  isPooled: (key) => this._pooled(b4a.toHex(key)) !== null,
371
+ deviceId: () => this._deviceKeyPair?.publicKey ?? null,
402
372
  logger: this._log,
403
373
  blindPeerKeys: this._resolveBlindPeerKeys(),
404
374
  blindPeeringOpts: this._blindPeeringOpts,
@@ -445,7 +415,7 @@ export class Core extends ReadyResource {
445
415
  computeLender: () => this._computeLender(),
446
416
  pushSkillSecret: (request) => this.pushSkillSecret(request),
447
417
  listModels: this._hostsModelSource || this._listModels
448
- ? async (request) => ({ models: (await this._readModels(request)) ?? [] })
418
+ ? async (request) => (await this._readModelList(request)) ?? { models: [] }
449
419
  : null,
450
420
  deleteModel: this._hostsModelSource || this._deleteModel
451
421
  ? (options) => this._deleteModel?.(options) ??
@@ -478,7 +448,7 @@ export class Core extends ReadyResource {
478
448
  ? () => this._watchModelCatalog()
479
449
  : null,
480
450
  modelsWatch: this._hostsModelSource || this._modelCatalogWatch
481
- ? (request) => watchModels(() => this._modelCatalogRevisions(), () => this._readModels(request))
451
+ ? (request) => watchModels(() => this._modelCatalogRevisions(), () => this._readModelList(request))
482
452
  : null,
483
453
  retryModelDownload: this._hostsModelSource || this._retryModelDownload
484
454
  ? ({ name }) => this._retryModelDownload?.(name) ??
@@ -1076,31 +1046,61 @@ export class Core extends ReadyResource {
1076
1046
  });
1077
1047
  try {
1078
1048
  await mesh.ready();
1079
- await raceResource(mesh.autobee, (async () => {
1080
- const birth = sharing
1081
- ? await this._accountBirthMember(mesh, session)
1082
- : await this._mintBirthMember(mesh, deviceId, session);
1083
- await mesh.appendBirthOp(this._requireDeviceKeyPair(), this._localDevice ?? undefined, {
1084
- member: birth?.member,
1085
- sharing
1086
- });
1049
+ if (session.baseKey && mesh.localLength === 0) {
1050
+ this._requireLocalDevice();
1087
1051
  await this.local.recordMesh(mesh.key, session, { deviceId, account });
1088
- if (account && birth?.mnemonic) {
1089
- await this._publishRecovery(birth.mnemonic, {
1090
- meshKey: mesh.key,
1091
- seed: session.seed,
1092
- createdAt: Date.now()
1093
- });
1094
- }
1095
- })(), 'mesh');
1052
+ void this._appendJoinLater(mesh, () => this._knownBirthMember(mesh, deviceId), sharing);
1053
+ }
1054
+ else {
1055
+ await this._appendOwnBirth(mesh, session, { deviceId, account, sharing });
1056
+ }
1096
1057
  }
1097
1058
  catch (err) {
1059
+ if (mesh.opened && mesh.interrupted && !this._upgradeRequired) {
1060
+ this._setUpgradeRequired('halt');
1061
+ }
1098
1062
  await mesh.close().catch(noop);
1099
1063
  throw err;
1100
1064
  }
1101
1065
  this._poolEntry(mesh);
1102
1066
  return mesh;
1103
1067
  }
1068
+ async _appendOwnBirth(mesh, session, { deviceId, account, sharing }) {
1069
+ await raceResource(mesh.autobee, (async () => {
1070
+ const birth = sharing
1071
+ ? await this._accountBirthMember(mesh, session)
1072
+ : await this._mintBirthMember(mesh, deviceId, session);
1073
+ await mesh.appendBirthOp(this._requireDeviceKeyPair(), this._localDevice ?? undefined, {
1074
+ member: birth?.member,
1075
+ sharing
1076
+ });
1077
+ await this.local.recordMesh(mesh.key, session, { deviceId, account });
1078
+ if (account && birth?.mnemonic) {
1079
+ await this._publishRecovery(birth.mnemonic, {
1080
+ meshKey: mesh.key,
1081
+ seed: session.seed,
1082
+ createdAt: Date.now()
1083
+ });
1084
+ }
1085
+ })(), 'mesh');
1086
+ }
1087
+ _requireLocalDevice() {
1088
+ if (!this._localDevice)
1089
+ throw new Error(DEVICE_UNKNOWN);
1090
+ return this._localDevice;
1091
+ }
1092
+ _appendJoinLater(mesh, member, sharing = false) {
1093
+ const birth = async () => ({ member: (await member()) ?? undefined, sharing });
1094
+ const appended = mesh.appendBirthOp(this._requireDeviceKeyPair(), this._localDevice ?? undefined, birth);
1095
+ return appended.catch((err) => {
1096
+ if (this.closing || mesh.closing)
1097
+ return;
1098
+ if (mesh.interrupted && !this._upgradeRequired) {
1099
+ this._setUpgradeRequired('halt');
1100
+ }
1101
+ this._log?.warn(['p2p', 'mesh'], 'appending the join failed', err);
1102
+ });
1103
+ }
1104
1104
  async _accountBirthMember(mesh, session) {
1105
1105
  if (!this._localDevice || session.baseKey || mesh.localLength > 0) {
1106
1106
  return undefined;
@@ -1213,6 +1213,7 @@ export class Core extends ReadyResource {
1213
1213
  }
1214
1214
  async recoverAccount(mnemonic, { timeout = RECOVERY_WAIT_MS } = {}) {
1215
1215
  await this._awaitMesh();
1216
+ this._requireLocalDevice();
1216
1217
  const identity = await openIdentity(mnemonic);
1217
1218
  const keys = recoveryKeys(identity);
1218
1219
  const core = openRecoveryCore(this.store, keys);
@@ -1236,7 +1237,8 @@ export class Core extends ReadyResource {
1236
1237
  ownsTransition = true;
1237
1238
  this._minting = true;
1238
1239
  this._notifyStatus();
1239
- await this._recoverAccount(identity, record);
1240
+ const joined = await this._joinRecoveredAccount(identity, record);
1241
+ await this._rerootRecovered(identity, record, joined);
1240
1242
  await this._markRecoverable(record, core);
1241
1243
  await this._adoptRecoveryCore(core, keys.coreKeyPair.publicKey);
1242
1244
  }
@@ -1253,21 +1255,24 @@ export class Core extends ReadyResource {
1253
1255
  this._departures?.flush();
1254
1256
  }
1255
1257
  }
1256
- async _recoverAccount(identity, record) {
1258
+ async _joinRecoveredAccount(identity, record) {
1257
1259
  const deviceId = this._requireDeviceKeyPair().publicKey;
1258
1260
  const proof = await identity.bootstrap(deviceId);
1259
1261
  const meshId = b4a.toHex(record.meshKey);
1260
1262
  await this._opening.get(meshId)?.catch(noop);
1261
1263
  const pooled = this._pooled(meshId);
1262
- const recovery = pooled?.writable ? undefined : { memberId: identity.identityPublicKey, proof };
1263
1264
  if (pooled?.writable) {
1264
1265
  if (!this._isAccount(pooled)) {
1265
1266
  await this._adoptAccount(pooled);
1266
1267
  }
1268
+ return { proof, recovered: false };
1267
1269
  }
1268
- else {
1269
- await this._joinMesh({ seed: record.seed, baseKey: record.meshKey, fastForward: null, recovery }, pooled);
1270
- }
1270
+ const recovery = { memberId: identity.identityPublicKey, proof };
1271
+ await this._joinMesh({ seed: record.seed, baseKey: record.meshKey, fastForward: null, recovery }, pooled);
1272
+ return { proof, recovered: true };
1273
+ }
1274
+ async _rerootRecovered(identity, record, { proof, recovered }) {
1275
+ const deviceId = this._requireDeviceKeyPair().publicKey;
1271
1276
  const mesh = this._accountMesh();
1272
1277
  if (!mesh?.key || !b4a.equals(mesh.key, record.meshKey)) {
1273
1278
  throw new Error('the recovered account did not adopt');
@@ -1283,7 +1288,7 @@ export class Core extends ReadyResource {
1283
1288
  createdAt: now
1284
1289
  });
1285
1290
  this._identityPublicKey = identity.identityPublicKey;
1286
- if (recovery) {
1291
+ if (recovered) {
1287
1292
  return;
1288
1293
  }
1289
1294
  await mesh.dispatch('attest-member-device', {
@@ -1337,23 +1342,12 @@ export class Core extends ReadyResource {
1337
1342
  if (!local || mesh.localLength > 0) {
1338
1343
  return undefined;
1339
1344
  }
1340
- const now = Date.now();
1341
- const attestation = claimAttestation(mesh.publicKey, deviceId, mesh.localWriterKey);
1342
- const known = await this._knownMember(mesh);
1345
+ const known = await this._knownBirthMember(mesh, deviceId);
1343
1346
  if (known) {
1344
- const identity = await this.local.readIdentity();
1345
- const name = identity?.displayName;
1346
- const ours = identity && name && namedAt(identity) >= known.updatedAt;
1347
- return {
1348
- member: {
1349
- id: known.id,
1350
- name: ours ? name : known.name,
1351
- joinedAt: now,
1352
- updatedAt: ours ? namedAt(identity) : known.updatedAt
1353
- },
1354
- proof: await attestMemberClaim(attestation, this._requireDeviceKeyPair(), known.proof)
1355
- };
1347
+ return known;
1356
1348
  }
1349
+ const now = Date.now();
1350
+ const attestation = claimAttestation(mesh.publicKey, deviceId, mesh.localWriterKey);
1357
1351
  const { identity, mnemonic } = await this.local.ensureIdentity(deviceId, now);
1358
1352
  this._identityPublicKey = identity.publicKey;
1359
1353
  this._holdIdentityPhrase(mnemonic);
@@ -1368,6 +1362,46 @@ export class Core extends ReadyResource {
1368
1362
  proof
1369
1363
  };
1370
1364
  }
1365
+ async _knownBirthMember(mesh, deviceId) {
1366
+ if (!this._localDevice || mesh.localLength > 0)
1367
+ return null;
1368
+ const known = await this._knownMember(mesh);
1369
+ if (!known) {
1370
+ return null;
1371
+ }
1372
+ const identity = await this.local.readIdentity();
1373
+ const name = identity?.displayName;
1374
+ const ours = identity && name && namedAt(identity) >= known.updatedAt;
1375
+ const attestation = claimAttestation(mesh.publicKey, deviceId, mesh.localWriterKey);
1376
+ return {
1377
+ member: {
1378
+ id: known.id,
1379
+ name: ours ? name : known.name,
1380
+ joinedAt: Date.now(),
1381
+ updatedAt: ours ? namedAt(identity) : known.updatedAt
1382
+ },
1383
+ proof: await attestMemberClaim(attestation, this._requireDeviceKeyPair(), known.proof)
1384
+ };
1385
+ }
1386
+ async _recoveryBirthMember(mesh, recovery) {
1387
+ const deviceKeyPair = this._requireDeviceKeyPair();
1388
+ const attestation = claimAttestation(mesh.publicKey, deviceKeyPair.publicKey, mesh.localWriterKey);
1389
+ await this.local.recordMemberProof({
1390
+ meshKey: mesh.key,
1391
+ memberId: recovery.memberId,
1392
+ proof: recovery.proof,
1393
+ attestedAt: 0
1394
+ });
1395
+ return {
1396
+ member: {
1397
+ id: recovery.memberId,
1398
+ name: this._localDevice?.name ?? '',
1399
+ joinedAt: Date.now(),
1400
+ updatedAt: 0
1401
+ },
1402
+ proof: await attestMemberClaim(attestation, deviceKeyPair, recovery.proof)
1403
+ };
1404
+ }
1371
1405
  _holdIdentityPhrase(mnemonic) {
1372
1406
  if (!mnemonic)
1373
1407
  return;
@@ -1516,8 +1550,9 @@ export class Core extends ReadyResource {
1516
1550
  });
1517
1551
  }
1518
1552
  await this._claimOwnMembership(mesh, context);
1519
- await attestUnattestedDevices(mesh, context, this._deviceInvites);
1520
- await this._sealAccount(mesh);
1553
+ await this._backfillMeshSeeds(mesh).catch((err) => {
1554
+ this._log?.warn(['p2p', 'mesh'], 'backfilling mesh seeds failed', err);
1555
+ });
1521
1556
  await this._renameFoundedMember(mesh, context);
1522
1557
  await this._revokeInMeshes();
1523
1558
  }
@@ -1528,12 +1563,6 @@ export class Core extends ReadyResource {
1528
1563
  entry.memberLock.unlock();
1529
1564
  }
1530
1565
  }
1531
- async _sealAccount(mesh) {
1532
- if ((this._meshSeed && b4a.equals(this._meshSeed, mesh.seed)) || !this._isAccount(mesh)) {
1533
- return;
1534
- }
1535
- await sealAccount(mesh, { deviceKeyPair: this._requireDeviceKeyPair(), log: this._log });
1536
- }
1537
1566
  async _renameFoundedMember(mesh, context) {
1538
1567
  let identity = await this.local.readIdentity();
1539
1568
  if (!identity) {
@@ -1603,7 +1632,16 @@ export class Core extends ReadyResource {
1603
1632
  };
1604
1633
  }
1605
1634
  }
1606
- return null;
1635
+ return this._recordedMember();
1636
+ }
1637
+ async _recordedMember() {
1638
+ const account = await this._storedAccountKey();
1639
+ const link = account ? await this.local.readMemberProof(account) : null;
1640
+ if (!link) {
1641
+ return null;
1642
+ }
1643
+ const name = (await this.local.readIdentity())?.displayName ?? '';
1644
+ return { id: link.memberId, name, updatedAt: 0, proof: link.proof };
1607
1645
  }
1608
1646
  _migrationContext() {
1609
1647
  const local = this._localDevice;
@@ -1814,6 +1852,7 @@ export class Core extends ReadyResource {
1814
1852
  throw new Error('Invalid mesh invite');
1815
1853
  }
1816
1854
  await this._awaitMesh();
1855
+ this._requireLocalDevice();
1817
1856
  await this._meshTransitionLock.lock();
1818
1857
  let ownsTransition = false;
1819
1858
  try {
@@ -1856,15 +1895,10 @@ export class Core extends ReadyResource {
1856
1895
  throw new Error(MESH_JOIN_CANCELED);
1857
1896
  }
1858
1897
  async _joinMesh(invite, retire = null) {
1859
- const cancellation = {
1860
- canceled: false,
1861
- accepting: true,
1862
- deadline: Date.now() + this._grantVisibleMs,
1863
- account: !invite.memberInvite
1864
- };
1898
+ const cancellation = { canceled: false, accepting: true, account: !invite.memberInvite };
1865
1899
  this._joinCancellation = cancellation;
1866
1900
  try {
1867
- if (invite.memberInvite && invite.inviteNonce) {
1901
+ if (invite.memberInvite) {
1868
1902
  await this._joinMeshInvite(invite);
1869
1903
  }
1870
1904
  else if (await this._reopenOwnAccount(invite)) {
@@ -1881,7 +1915,7 @@ export class Core extends ReadyResource {
1881
1915
  }
1882
1916
  }
1883
1917
  async _reopenOwnAccount(invite) {
1884
- if (invite.recovery || !invite.memberId || !invite.inviteNonce)
1918
+ if (invite.recovery || !invite.memberId)
1885
1919
  return false;
1886
1920
  const stored = await this._storedAccountKey();
1887
1921
  if (!stored || !b4a.equals(stored, invite.baseKey)) {
@@ -1891,12 +1925,7 @@ export class Core extends ReadyResource {
1891
1925
  return false;
1892
1926
  }
1893
1927
  const account = await this._openPooledMesh(b4a.toHex(invite.baseKey));
1894
- const own = await account.view.get(DEVICES, {
1895
- id: this._requireDeviceKeyPair().publicKey
1896
- });
1897
- if (!own ||
1898
- own.revoked ||
1899
- !(own.writerKey && b4a.equals(own.writerKey, account.localWriterKey))) {
1928
+ if (!(await this._keepsWriter(account))) {
1900
1929
  return false;
1901
1930
  }
1902
1931
  if (!this._isAccount(account)) {
@@ -1929,7 +1958,7 @@ export class Core extends ReadyResource {
1929
1958
  const meshId = b4a.toHex(invite.baseKey);
1930
1959
  await this._following.get(meshId);
1931
1960
  const joining = (async () => {
1932
- if (!(await this._openOwnMesh(invite))) {
1961
+ if (!(await this._reopenRecordedMesh(invite))) {
1933
1962
  await this._claimJoin(invite, this._pooled(meshId));
1934
1963
  }
1935
1964
  })();
@@ -1944,6 +1973,22 @@ export class Core extends ReadyResource {
1944
1973
  }
1945
1974
  }
1946
1975
  }
1976
+ async _reopenRecordedMesh(invite) {
1977
+ if (!(await this.local.readMeshSession(invite.baseKey)))
1978
+ return false;
1979
+ return this._keepsWriter(await this._openPooledMesh(b4a.toHex(invite.baseKey)));
1980
+ }
1981
+ async _keepsWriter(mesh) {
1982
+ if (mesh.writable)
1983
+ return true;
1984
+ if (await mesh.ownWriterRefused()) {
1985
+ return false;
1986
+ }
1987
+ const own = await mesh.view.get(DEVICES, {
1988
+ id: this._requireDeviceKeyPair().publicKey
1989
+ });
1990
+ return !(own && isOwnRevokedRow(mesh, own));
1991
+ }
1947
1992
  async _runJoinMesh(invite, claim) {
1948
1993
  const deviceId = this._requireDeviceKeyPair().publicKey;
1949
1994
  const source = this._accountMesh();
@@ -1982,32 +2027,44 @@ export class Core extends ReadyResource {
1982
2027
  this._joinCancellation.accepting = false;
1983
2028
  }
1984
2029
  try {
1985
- if (source && !invite.memberInvite && (await this._departureHasAudience(source))) {
1986
- await this.local.recordDeparture(source.key, { creator: source.minted });
1987
- }
1988
2030
  await this.local.recordMesh(candidate.key, session, { deviceId });
1989
2031
  }
1990
2032
  catch (error) {
1991
2033
  await this._discardCandidateMesh();
1992
2034
  throw error;
1993
2035
  }
1994
- return this._landJoinedMesh(invite, candidate, { source, deviceId });
2036
+ const member = await this._candidateBirthMember(candidate, invite);
2037
+ const appended = this._appendJoinLater(candidate, async () => member);
2038
+ return this._landJoinedMesh(candidate, {
2039
+ source,
2040
+ deviceId,
2041
+ memberInvite: !!invite.memberInvite,
2042
+ appended
2043
+ });
1995
2044
  }
1996
- async _landJoinedMesh(invite, candidate, { source, deviceId }) {
1997
- if (!invite.memberInvite) {
2045
+ async _landJoinedMesh(candidate, { source, deviceId, memberInvite, appended }) {
2046
+ if (!memberInvite) {
1998
2047
  await this._departOldAccount(candidate.key, source);
1999
2048
  }
2000
2049
  if (this._blockedByMinVersion()) {
2001
- if (!invite.memberInvite) {
2050
+ if (!memberInvite) {
2002
2051
  await this.local.setAccountMesh(deviceId, candidate.key);
2003
2052
  }
2004
- await this._retireMesh(candidate).catch((err) => this._log?.warn(['p2p', 'mesh'], 'withholding the joined mesh failed', err));
2053
+ void appended
2054
+ .then(() => this._retireMesh(candidate))
2055
+ .catch((err) => this._log?.warn(['p2p', 'mesh'], 'withholding the joined mesh failed', err));
2005
2056
  return null;
2006
2057
  }
2007
- if (invite.memberInvite || candidate.compute) {
2058
+ if (memberInvite || candidate.compute) {
2008
2059
  this._candidateMesh = null;
2060
+ if (!candidate.writable) {
2061
+ await this.local.markAwaitingAdmission(candidate.key, { awaitingAdmission: true });
2062
+ }
2009
2063
  this._wireMesh(this._poolEntry(candidate));
2010
2064
  this._bringMeshOnline(candidate);
2065
+ if (candidate.writable) {
2066
+ await this.local.markAwaitingAdmission(candidate.key, { awaitingAdmission: false });
2067
+ }
2011
2068
  this._notifyStatus();
2012
2069
  }
2013
2070
  else {
@@ -2017,7 +2074,7 @@ export class Core extends ReadyResource {
2017
2074
  void this._advertiseDeviceProfile(candidate, deviceId);
2018
2075
  void candidate.refreshOurMember().catch(noop);
2019
2076
  void this._settleMembership(candidate, { migrate: true });
2020
- if (invite.memberInvite && !candidate.compute) {
2077
+ if (memberInvite && !candidate.compute) {
2021
2078
  void this._recordJoinedMesh(candidate.key);
2022
2079
  }
2023
2080
  this.emit('mesh-changed', candidate);
@@ -2030,9 +2087,6 @@ export class Core extends ReadyResource {
2030
2087
  }
2031
2088
  const rows = (await this.local.listMeshes()).filter((row) => !b4a.equals(row.key, joined));
2032
2089
  const meshes = rows.filter((row) => !(account && b4a.equals(account, row.key)));
2033
- if (account) {
2034
- await this._writableAccount();
2035
- }
2036
2090
  for (const mesh of meshes) {
2037
2091
  await this._departIfPooled(mesh.key, 'mesh');
2038
2092
  }
@@ -2051,16 +2105,7 @@ export class Core extends ReadyResource {
2051
2105
  return;
2052
2106
  }
2053
2107
  try {
2054
- await Promise.race([
2055
- mesh.waitForWritable(),
2056
- this._closeSignal,
2057
- after(this._accountWritableMs)
2058
- ]);
2059
- if (!mesh.writable) {
2060
- this._log?.warn(['p2p', 'mesh'], `the old ${kind} never went writable, so its writer was not revoked`, { meshId });
2061
- return;
2062
- }
2063
- await this._announceDeparture(mesh);
2108
+ await this._recordDeparture(mesh);
2064
2109
  await this._retirePooledMesh(mesh);
2065
2110
  }
2066
2111
  catch (error) {
@@ -2078,17 +2123,70 @@ export class Core extends ReadyResource {
2078
2123
  async _registerMesh(meshKey, opts) {
2079
2124
  const { shared } = opts;
2080
2125
  const registry = opts.registry ?? (await this._writableAccount());
2081
- if (!registry) {
2082
- throw new Error(MESH_WITHOUT_ACCOUNT);
2083
- }
2084
- const ours = registry.ourMemberId;
2085
- if (!ours) {
2086
- throw new Error(ACCOUNT_MEMBER_UNKNOWN);
2126
+ const ours = registry?.ourMemberId;
2127
+ if (!registry || !ours) {
2128
+ return;
2087
2129
  }
2088
2130
  const now = Date.now();
2089
2131
  await registry.dispatch('put-joined-mesh', {
2090
2132
  room: { meshKey, memberId: ours, joinedAt: now, shared, sharedAt: shared ? now : 0 }
2091
2133
  });
2134
+ await this._backfillMeshSeeds(registry).catch((err) => {
2135
+ this._log?.warn(['p2p', 'mesh'], 'writing the mesh seed failed; writable or settle retries', err);
2136
+ });
2137
+ }
2138
+ async _backfillMeshSeeds(account, { register = true } = {}) {
2139
+ if (!this._isAccount(account))
2140
+ return;
2141
+ const pass = this._backfill.then(() => this._writeMeshSeeds(account, register));
2142
+ this._backfill = pass.catch(noop);
2143
+ await pass;
2144
+ }
2145
+ async _writeMeshSeeds(account, register) {
2146
+ const ours = account.ourMemberId;
2147
+ if (!ours || !this._isAccount(account) || !account.writable) {
2148
+ return;
2149
+ }
2150
+ const batch = account.batch();
2151
+ const registered = register
2152
+ ? await this._registerRecordedMeshes(account, ours, batch)
2153
+ : new Set();
2154
+ for (const { mesh } of this._meshes.values()) {
2155
+ if (await this._seedRowDue(account, mesh, { ours, registered })) {
2156
+ batch.dispatch('put-mesh-seed', { meshKey: mesh.key, seed: mesh.seed });
2157
+ }
2158
+ }
2159
+ await batch.flush();
2160
+ }
2161
+ async _registerRecordedMeshes(account, ours, batch) {
2162
+ const registered = new Set();
2163
+ const now = Date.now();
2164
+ for (const row of await this.local.listMeshes()) {
2165
+ if (b4a.equals(row.key, account.key) || row.compute)
2166
+ continue;
2167
+ const held = await account.view.get(JOINED_MESHES, { meshKey: row.key });
2168
+ if (held) {
2169
+ continue;
2170
+ }
2171
+ batch.dispatch('put-joined-mesh', {
2172
+ room: { meshKey: row.key, memberId: ours, joinedAt: now, shared: false, sharedAt: 0 }
2173
+ });
2174
+ registered.add(b4a.toHex(row.key));
2175
+ }
2176
+ return registered;
2177
+ }
2178
+ async _seedRowDue(account, mesh, { ours, registered }) {
2179
+ if (!mesh.writable || mesh === account || mesh.compute)
2180
+ return false;
2181
+ if (registered.has(this._meshIdOf(mesh))) {
2182
+ return true;
2183
+ }
2184
+ const joined = await account.view.get(JOINED_MESHES, { meshKey: mesh.key });
2185
+ if (!joined?.memberId || !b4a.equals(joined.memberId, ours) || joined.leftAt) {
2186
+ return false;
2187
+ }
2188
+ const held = await account.view.get(MESH_SEEDS, { meshKey: mesh.key });
2189
+ return !held || !b4a.equals(held.seed, mesh.seed);
2092
2190
  }
2093
2191
  async _releaseJoinedMesh(meshKey, registry) {
2094
2192
  try {
@@ -2118,13 +2216,6 @@ export class Core extends ReadyResource {
2118
2216
  const key = await this._storedAccountKey();
2119
2217
  const held = key ? this._pooled(b4a.toHex(key)) : null;
2120
2218
  const mesh = key ? await this._openPooledMesh(b4a.toHex(key)).catch(noop) : null;
2121
- if (mesh && !mesh.writable) {
2122
- await Promise.race([
2123
- mesh.waitForWritable(),
2124
- this._closeSignal,
2125
- after(this._accountWritableMs)
2126
- ]);
2127
- }
2128
2219
  if (mesh && !mesh.ourMemberId) {
2129
2220
  await mesh.refreshOurMember();
2130
2221
  }
@@ -2137,114 +2228,8 @@ export class Core extends ReadyResource {
2137
2228
  }
2138
2229
  return mesh;
2139
2230
  }
2140
- async _awaitGrantRow(mesh, grantKey) {
2141
- await this._untilDeadline(async () => Boolean(await mesh.view.get(MESH_INVITE_GRANTS, { grantKey })));
2142
- }
2143
- async _untilDeadline(done) {
2144
- const deadline = this._joinCancellation?.deadline ?? Date.now();
2145
- for (;;) {
2146
- if (await done())
2147
- return true;
2148
- if (Date.now() >= deadline)
2149
- return false;
2150
- this._throwIfJoinCanceled();
2151
- await after(250);
2152
- }
2153
- }
2154
- async _refuseIfGrantUnusable(candidate, grantSecret, memberId) {
2155
- const grantKey = grantKeyPair(grantSecret).publicKey;
2156
- await this._awaitGrantRow(candidate, grantKey);
2157
- await this._untilDeadline(async () => {
2158
- await candidate.autobee.update();
2159
- const status = await syncStatusSnapshot(candidate);
2160
- return !!status.devices?.length && status.state === 'synced';
2161
- });
2162
- await this._refuseUnredeemable(candidate, grantKey, memberId);
2163
- }
2164
- async _refuseUnredeemable(mesh, grantKey, memberId) {
2165
- const deviceId = this._requireDeviceKeyPair().publicKey;
2166
- const snap = mesh.view.snapshot();
2167
- try {
2168
- const grant = await snap.get(MESH_INVITE_GRANTS, { grantKey });
2169
- if (!grant) {
2170
- return;
2171
- }
2172
- const issuer = grant.issuerDeviceId && (await snap.get(DEVICES, { id: grant.issuerDeviceId }));
2173
- const spent = await snap.get(MESH_INVITE_SPENDS, {
2174
- grantKey,
2175
- deviceId
2176
- });
2177
- const own = await snap.get(DEVICES, { id: deviceId });
2178
- const live = own && !own.revoked;
2179
- const expired = !!grant.expiresAt && Date.now() > grant.expiresAt;
2180
- if (expired && (!spent || grant.revokedAt)) {
2181
- throw new Error(INVITE_GRANT_EXPIRED);
2182
- }
2183
- if (grant.revokedAt || !issuer || issuer.revoked) {
2184
- throw new Error(INVITE_GRANT_REVOKED);
2185
- }
2186
- if (spent && !live) {
2187
- throw new Error(INVITE_GRANT_EXHAUSTED);
2188
- }
2189
- if (spent) {
2190
- return;
2191
- }
2192
- if (grant.maxUses && (grant.uses ?? 0) >= grant.maxUses) {
2193
- throw new Error(INVITE_GRANT_EXHAUSTED);
2194
- }
2195
- if (memberId && (await belongsToAnotherMember(snap, own ?? null, memberId))) {
2196
- throw new Error(DEVICE_OF_ANOTHER_MEMBER);
2197
- }
2198
- if (live) {
2199
- throw new Error(MESH_ALREADY_JOINED);
2200
- }
2201
- const standing = memberId &&
2202
- (await inviteStanding(snap, {
2203
- device: own ?? null,
2204
- memberId,
2205
- grant,
2206
- compute: mesh.compute
2207
- }));
2208
- if (standing === 'present') {
2209
- throw new Error(MEMBER_ALREADY_IN_MESH);
2210
- }
2211
- if (standing === 'removed') {
2212
- throw new Error(MEMBER_REMOVED_SINCE_INVITE);
2213
- }
2214
- }
2215
- finally {
2216
- await snap.close();
2217
- }
2218
- }
2219
- async _refuseFromOwnCopy(invite, grantKey) {
2220
- if (this._pooled(b4a.toHex(invite.baseKey)))
2221
- return;
2222
- const recorded = await this.local.readMeshSession(invite.baseKey);
2223
- const archived = (await this.local.listArchivedMeshes()).find((row) => b4a.equals(row.key, invite.baseKey));
2224
- const writerSeed = recorded?.writerSeed ?? archived?.writerSeed;
2225
- if (!writerSeed) {
2226
- return;
2227
- }
2228
- const copy = new Mesh(this.store, {
2229
- seed: invite.seed,
2230
- key: invite.baseKey,
2231
- deviceId: this._requireDeviceKeyPair().publicKey,
2232
- writerSeed,
2233
- logger: this._log
2234
- });
2235
- try {
2236
- await copy.ready();
2237
- await this._refuseUnredeemable(copy, grantKey, null);
2238
- }
2239
- finally {
2240
- await copy.close();
2241
- }
2242
- }
2243
2231
  async _openCandidateMesh(invite, session) {
2244
2232
  this._throwIfJoinCanceled();
2245
- if (invite.memberInvite && invite.inviteNonce) {
2246
- await this._refuseFromOwnCopy(invite, grantKeyPair(invite.inviteNonce).publicKey);
2247
- }
2248
2233
  const candidate = new Mesh(this.store, {
2249
2234
  seed: session.seed,
2250
2235
  key: session.baseKey ?? null,
@@ -2286,21 +2271,6 @@ export class Core extends ReadyResource {
2286
2271
  candidate.startBlindPeering(this._swarm.dht);
2287
2272
  }
2288
2273
  try {
2289
- this._throwIfJoinCanceled();
2290
- const member = invite.memberInvite
2291
- ? await this._joinBirthMember(candidate, this._requireDeviceKeyPair().publicKey)
2292
- : undefined;
2293
- const invited = !member && invite.memberId && invite.inviteNonce;
2294
- const grantSecret = invite.memberInvite ? invite.inviteNonce : undefined;
2295
- if (grantSecret) {
2296
- await this._refuseIfGrantUnusable(candidate, grantSecret, member?.member.id ?? null);
2297
- }
2298
- await candidate.appendBirthOp(this._requireDeviceKeyPair(), this._localDevice ?? undefined, {
2299
- member,
2300
- grantSecret,
2301
- recovery: invite.recovery,
2302
- vouched: Boolean(invited)
2303
- });
2304
2274
  this._throwIfJoinCanceled();
2305
2275
  if (!b4a.equals(candidate.key, invite.baseKey)) {
2306
2276
  throw new Error('Device is not permitted to join the invited mesh');
@@ -2308,22 +2278,6 @@ export class Core extends ReadyResource {
2308
2278
  if ((await candidate.checkResumedRevocation()) === 'kicked') {
2309
2279
  throw new Error('Device is not permitted to join the invited mesh');
2310
2280
  }
2311
- if (invite.recovery && (await this._isRemovedFrom(candidate))) {
2312
- throw new Error(RECOVERY_DEVICE_REMOVED);
2313
- }
2314
- this._throwIfJoinCanceled();
2315
- disarm();
2316
- const inviter = invited
2317
- ? this._requestInvitedAdmission(candidate, invite.memberId, invite.inviteNonce)
2318
- : null;
2319
- await this._waitForCandidateWritable(candidate, !invite.recovery).catch((error) => {
2320
- throw inviter && !inviter.answered && error.message === GRANT_JOIN_TIMED_OUT
2321
- ? new Error(INVITER_OFFLINE)
2322
- : error;
2323
- });
2324
- if (!candidate.writable) {
2325
- throw new Error('Device is not permitted to join the invited mesh');
2326
- }
2327
2281
  this._throwIfJoinCanceled();
2328
2282
  return candidate;
2329
2283
  }
@@ -2335,104 +2289,43 @@ export class Core extends ReadyResource {
2335
2289
  disarm();
2336
2290
  }
2337
2291
  }
2338
- _requestInvitedAdmission(candidate, memberId, nonce) {
2339
- const { publicKey: deviceId, secretKey } = this._requireDeviceKeyPair();
2340
- const local = this._localDevice;
2341
- if (!local) {
2342
- throw new Error('local device read before the offline boot');
2292
+ async _candidateBirthMember(candidate, invite) {
2293
+ const deviceId = this._requireDeviceKeyPair().publicKey;
2294
+ if (invite.recovery) {
2295
+ return this._recoveryBirthMember(candidate, invite.recovery);
2296
+ }
2297
+ const { deviceSeed, deviceProof, memberId } = invite;
2298
+ if (deviceSeed && deviceProof && memberId) {
2299
+ return this._delegatedBirthMember(candidate, {
2300
+ deviceSeed,
2301
+ deviceProof,
2302
+ memberId,
2303
+ name: invite.inviterName ?? ''
2304
+ });
2343
2305
  }
2344
- const joinedAt = Date.now();
2345
- const request = {
2346
- writerKey: candidate.localWriterKey,
2347
- joinedAt,
2348
- deviceSignature: candidate.signDeviceClaim(secretKey, deviceId, joinedAt),
2349
- memberSignature: signMemberWriterClaim(secretKey, {
2350
- meshPublicKey: candidate.publicKey,
2351
- deviceId,
2352
- writerKey: candidate.localWriterKey,
2353
- joinedAt,
2354
- memberId
2355
- }),
2356
- inviteToken: deviceInviteToken(nonce, deviceId),
2357
- name: local.name,
2358
- capabilityProfile: local.capabilityProfile,
2359
- recommendedModelName: local.recommendedModelName
2360
- };
2361
- const state = { answered: false };
2362
- const asking = () => this._candidateMesh === candidate && !candidate.writable && !this.closing;
2363
- const ask = (inviter) => this._meshSeedHandoff.admit(inviter, candidate.key, request).then((admitted) => {
2364
- state.answered = true;
2365
- return admitted;
2366
- }, (error) => {
2367
- if (![HOST_UNREACHABLE, HOST_SILENT, SEED_REFUSED].includes(error.message)) {
2368
- state.answered = true;
2369
- }
2370
- return false;
2371
- });
2372
- void (async () => {
2373
- while (asking()) {
2374
- for (const inviter of await this._liveSiblings(candidate, memberId)) {
2375
- if (!asking() || (await ask(inviter)))
2376
- return;
2377
- }
2378
- await Promise.race([after(INVITER_RETRY_MS), this._closeSignal]);
2379
- }
2380
- })().catch(noop);
2381
- return state;
2306
+ return invite.memberInvite ? this._joinBirthMember(candidate, deviceId) : undefined;
2382
2307
  }
2383
- async _isRemovedFrom(mesh) {
2384
- const device = await mesh.view
2385
- .get(DEVICES, { id: this._requireDeviceKeyPair().publicKey })
2386
- .catch(noop);
2387
- return device ? isKickedRow(device) : false;
2308
+ async _delegatedBirthMember(mesh, { deviceSeed, deviceProof, memberId, name }) {
2309
+ const keyPair = this._requireDeviceKeyPair();
2310
+ const proof = await attestDeviceProof(keyPair.publicKey, crypto.keyPair(deviceSeed), deviceProof);
2311
+ const attestation = claimAttestation(mesh.publicKey, keyPair.publicKey, mesh.localWriterKey);
2312
+ await this.local.recordMemberProof({ meshKey: mesh.key, memberId, proof, attestedAt: 0 });
2313
+ return {
2314
+ member: { id: memberId, name, joinedAt: Date.now(), updatedAt: 0 },
2315
+ proof: await attestMemberClaim(attestation, keyPair, proof)
2316
+ };
2388
2317
  }
2389
- async _waitForCandidateWritable(candidate, bounded) {
2390
- if (candidate.writable)
2391
- return;
2392
- await new Promise((resolve, reject) => {
2393
- let offClose = noop;
2394
- const cleanup = () => {
2395
- clearTimeout(timer);
2396
- candidate.autobee.off('writable', onWritable);
2397
- candidate.autobee.off('interrupt', onInterrupt);
2398
- candidate.off('kicked', onKicked);
2399
- offClose();
2400
- if (this._cancelCandidateJoin === onCanceled) {
2401
- this._cancelCandidateJoin = null;
2402
- }
2403
- };
2404
- const onWritable = () => {
2405
- cleanup();
2406
- resolve();
2407
- };
2408
- const onKicked = () => {
2409
- cleanup();
2410
- reject(new Error('Device is not permitted to join the invited mesh'));
2411
- };
2412
- const onInterrupt = (reason) => {
2413
- cleanup();
2414
- reject(reason instanceof Error ? reason : new Error('Apply interrupted'));
2415
- };
2416
- const onCanceled = () => {
2417
- cleanup();
2418
- reject(new Error(MESH_JOIN_CANCELED));
2419
- };
2420
- const timer = bounded
2421
- ? setTimeout(() => {
2422
- cleanup();
2423
- reject(new Error(GRANT_JOIN_TIMED_OUT));
2424
- }, this._grantWritableMs)
2425
- : undefined;
2426
- this._cancelCandidateJoin = onCanceled;
2427
- candidate.autobee.on('writable', onWritable);
2428
- candidate.autobee.on('interrupt', onInterrupt);
2429
- candidate.on('kicked', onKicked);
2430
- offClose = this._onClose(onCanceled);
2431
- });
2318
+ _onMeshSeedDue(mesh) {
2319
+ const account = this._accountMesh();
2320
+ if (account) {
2321
+ void this._backfillMeshSeeds(account, { register: mesh === account }).catch(noop);
2322
+ }
2432
2323
  }
2433
2324
  _onMeshWritable(mesh) {
2434
2325
  if (!this._isPooled(mesh))
2435
2326
  return;
2327
+ void this.local.markAwaitingAdmission(mesh.key, { awaitingAdmission: false }).catch(noop);
2328
+ this._onMeshSeedDue(mesh);
2436
2329
  if (this._isAccount(mesh)) {
2437
2330
  this._kicked = false;
2438
2331
  }
@@ -2443,7 +2336,7 @@ export class Core extends ReadyResource {
2443
2336
  return;
2444
2337
  this._log?.error(['p2p', 'mesh'], 'mesh autobee died - retiring it', err);
2445
2338
  if (this._isAccount(mesh)) {
2446
- this._statusError = statusErrorMessage('the local database died', err);
2339
+ this._statusError = statusErrorMessage(MESH_DIED, err);
2447
2340
  }
2448
2341
  this._retirePooledMesh(mesh).catch((retireErr) => {
2449
2342
  this._log?.warn(['p2p', 'mesh'], 'retiring the dead mesh failed', retireErr);
@@ -2467,6 +2360,9 @@ export class Core extends ReadyResource {
2467
2360
  entry.handlers = handlers;
2468
2361
  mesh.on('kicked', () => this._onKicked(mesh));
2469
2362
  mesh.on('unattested-device', () => void this._settleMembership(mesh));
2363
+ if (mesh.writable) {
2364
+ this._onMeshSeedDue(mesh);
2365
+ }
2470
2366
  mesh.on('members-dirty', () => void this._revalidateLoans());
2471
2367
  mesh.on('members-dirty', () => {
2472
2368
  if (!this._isAccount(mesh))
@@ -2479,7 +2375,6 @@ export class Core extends ReadyResource {
2479
2375
  void this._followJoinedMeshes(mesh);
2480
2376
  }
2481
2377
  });
2482
- mesh.on('mesh-kind', () => void this._refuseSealedReader(mesh));
2483
2378
  mesh.on('membership-tallied', () => this._notifyStatus());
2484
2379
  mesh.on('mesh-named', () => this._notifyStatus());
2485
2380
  mesh.on('membership', (membership) => {
@@ -2507,24 +2402,6 @@ export class Core extends ReadyResource {
2507
2402
  this._kicked = false;
2508
2403
  }
2509
2404
  this._notifyStatus();
2510
- void this._refuseSealedReader(mesh);
2511
- }
2512
- async _refuseSealedReader(mesh) {
2513
- if (!this._isAccount(mesh) || mesh.writable)
2514
- return;
2515
- const kind = await mesh.view.get(MESH_KINDS, { id: 'mesh' }).catch(noop);
2516
- if (kind?.kind !== 'account') {
2517
- return;
2518
- }
2519
- const own = await mesh.view.get(DEVICES, {
2520
- id: this._requireDeviceKeyPair().publicKey
2521
- });
2522
- if (own) {
2523
- return;
2524
- }
2525
- this._statusError = SEALED_ACCOUNT_READER;
2526
- this._log?.error(['p2p', 'mesh'], SEALED_ACCOUNT_READER);
2527
- this._notifyStatus();
2528
2405
  }
2529
2406
  _pooled(meshKey) {
2530
2407
  if (meshKey === null)
@@ -2797,6 +2674,13 @@ export class Core extends ReadyResource {
2797
2674
  }
2798
2675
  await candidate.close().catch(noop);
2799
2676
  }
2677
+ async _recordDeparture(mesh) {
2678
+ const pending = !mesh.writable && (mesh.localLength > 0 || mesh.joining);
2679
+ if (pending || (await this._departureHasAudience(mesh))) {
2680
+ await this.local.recordDeparture(mesh.key, { creator: mesh.minted });
2681
+ }
2682
+ await this._announceDeparture(mesh);
2683
+ }
2800
2684
  async _departureHasAudience(mesh) {
2801
2685
  if (!mesh.writable)
2802
2686
  return false;
@@ -2859,10 +2743,7 @@ export class Core extends ReadyResource {
2859
2743
  return;
2860
2744
  }
2861
2745
  }
2862
- if (await this._departureHasAudience(departing)) {
2863
- await this.local.recordDeparture(departing.key, { creator: departing.minted });
2864
- }
2865
- await this._announceDeparture(departing);
2746
+ await this._recordDeparture(departing);
2866
2747
  await this._releaseJoinedMesh(departing.key);
2867
2748
  await this._archiveMembership(departing);
2868
2749
  if (!leavingAccount) {
@@ -2885,13 +2766,7 @@ export class Core extends ReadyResource {
2885
2766
  async _departOnLogout(key) {
2886
2767
  try {
2887
2768
  const mesh = await this._openPooledMesh(b4a.toHex(key));
2888
- if (!(await this.local.awaitsAdmission(key))) {
2889
- await mesh.waitForWritable(this._accountWritableMs);
2890
- }
2891
- if (await this._departureHasAudience(mesh)) {
2892
- await this.local.recordDeparture(mesh.key, { creator: mesh.minted });
2893
- }
2894
- await this._announceDeparture(mesh);
2769
+ await this._recordDeparture(mesh);
2895
2770
  await this._archiveMembership(mesh);
2896
2771
  await this._retirePooledMesh(mesh);
2897
2772
  }
@@ -3159,10 +3034,10 @@ export class Core extends ReadyResource {
3159
3034
  throw new Error('Mesh transition already in progress');
3160
3035
  }
3161
3036
  const registry = opts.registry ?? (await this._writableAccount());
3162
- if (!registry) {
3037
+ if (shared && !registry) {
3163
3038
  throw new Error(MESH_WITHOUT_ACCOUNT);
3164
3039
  }
3165
- if (!registry.ourMemberId) {
3040
+ if (registry && !registry.ourMemberId) {
3166
3041
  throw new Error(ACCOUNT_MEMBER_UNKNOWN);
3167
3042
  }
3168
3043
  const mesh = await this._openMesh({ new: true, sharing: true, compute });
@@ -3173,7 +3048,9 @@ export class Core extends ReadyResource {
3173
3048
  if (!mesh.ourMemberId) {
3174
3049
  throw new Error(MESH_WITHOUT_MEMBER);
3175
3050
  }
3176
- await this._registerMesh(mesh.key, { shared, registry });
3051
+ if (registry) {
3052
+ await this._registerMesh(mesh.key, { shared, registry });
3053
+ }
3177
3054
  }
3178
3055
  catch (error) {
3179
3056
  await this._discardMesh(mesh);
@@ -3265,7 +3142,13 @@ export class Core extends ReadyResource {
3265
3142
  throw halted;
3266
3143
  }
3267
3144
  this._wireMesh(this._poolEntry(mesh));
3145
+ if (this._isAccount(mesh) && this._statusError?.startsWith(MESH_DIED)) {
3146
+ this._statusError = null;
3147
+ }
3268
3148
  this._bringMeshOnline(mesh);
3149
+ if (mesh.writable) {
3150
+ void this.local.markAwaitingAdmission(mesh.key, { awaitingAdmission: false }).catch(noop);
3151
+ }
3269
3152
  this._notifyStatus();
3270
3153
  this._debugOnMeshOpened?.(mesh, meshId);
3271
3154
  return mesh;
@@ -3276,7 +3159,6 @@ export class Core extends ReadyResource {
3276
3159
  const account = !!accountKey && b4a.equals(accountKey, row.key);
3277
3160
  const joined = meshes.get(meshId);
3278
3161
  const state = this._meshEntryState(mesh, account);
3279
- const admission = state === 'joining' ? await this._admission(mesh) : {};
3280
3162
  return {
3281
3163
  meshId,
3282
3164
  state,
@@ -3288,33 +3170,7 @@ export class Core extends ReadyResource {
3288
3170
  members: mesh?.membership.members ?? 0,
3289
3171
  shared: joined?.shared ?? false,
3290
3172
  sharedAt: joined?.shared ? joined.sharedAt : undefined,
3291
- compute: row.compute ?? false,
3292
- reason: admission.reason,
3293
- awaitingFrom: admission.awaitingFrom
3294
- };
3295
- }
3296
- async _admission(mesh) {
3297
- if (!mesh || mesh.writable)
3298
- return {};
3299
- const ours = mesh.localWriterKey;
3300
- const admitters = [];
3301
- try {
3302
- for await (const device of mesh.view.find(DEVICES)) {
3303
- if (device.revoked || (device.writerKey && b4a.equals(device.writerKey, ours))) {
3304
- continue;
3305
- }
3306
- admitters.push(device.name);
3307
- if (admitters.length > 1) {
3308
- break;
3309
- }
3310
- }
3311
- }
3312
- catch {
3313
- return { reason: AWAITING_ADMISSION };
3314
- }
3315
- return {
3316
- reason: AWAITING_ADMISSION,
3317
- awaitingFrom: admitters.length === 1 ? admitters[0] : undefined
3173
+ compute: row.compute ?? false
3318
3174
  };
3319
3175
  }
3320
3176
  _meshEntryState(mesh, account) {
@@ -3547,24 +3403,6 @@ export class Core extends ReadyResource {
3547
3403
  throw new Error(DEVICE_INVITE_MESH_REFUSED);
3548
3404
  }
3549
3405
  }
3550
- let grantSecret;
3551
- if (opts.memberInvite) {
3552
- grantSecret = crypto.randomBytes(32);
3553
- const now = Date.now();
3554
- const terms = { expiresAt: now + GRANT_DEFAULT_TTL_MS, maxUses: GRANT_DEFAULT_MAX_USES };
3555
- const refusal = inviteGrantTermsRefusal(terms, now);
3556
- if (refusal) {
3557
- throw new Error(refusal);
3558
- }
3559
- await mesh.dispatch('put-mesh-invite-grant', {
3560
- grant: {
3561
- grantKey: grantKeyPair(grantSecret).publicKey,
3562
- kind: 'member',
3563
- ...terms,
3564
- updatedAt: now
3565
- }
3566
- });
3567
- }
3568
3406
  const auto = mesh.autobee;
3569
3407
  const info = await auto.system.getInfo();
3570
3408
  const head = info && info.view.length > 0 ? await auto.trusted.mostRecentTrusted(auto.view, null) : null;
@@ -3572,6 +3410,7 @@ export class Core extends ReadyResource {
3572
3410
  ? this._swarm.dht.toArray({ limit: INVITE_DHT_NODES_LIMIT })
3573
3411
  : [];
3574
3412
  const memberId = opts.memberInvite ? undefined : (mesh.ourMemberId ?? undefined);
3413
+ const delegation = memberId ? await this._delegatePairing(mesh) : null;
3575
3414
  const inviterName = memberId
3576
3415
  ? ((await mesh.view.get(MEMBERS, { id: memberId }))?.name ?? undefined)
3577
3416
  : undefined;
@@ -3595,11 +3434,26 @@ export class Core extends ReadyResource {
3595
3434
  : this._resolveBlindPeerKeys().slice(0, INVITE_BLIND_PEERS_LIMIT),
3596
3435
  memberInvite: opts.memberInvite ?? false,
3597
3436
  memberId,
3598
- inviteNonce: grantSecret ?? (memberId ? await this._deviceInvites.issue() : undefined),
3599
3437
  compute: mesh.compute,
3600
- inviterName
3438
+ inviterName,
3439
+ deviceSeed: delegation?.deviceSeed,
3440
+ deviceProof: delegation?.deviceProof
3601
3441
  };
3602
3442
  }
3443
+ async _delegatePairing(account) {
3444
+ const keyPair = this._requireDeviceKeyPair();
3445
+ const own = await account.view.get(DEVICES, { id: keyPair.publicKey });
3446
+ if (!own?.memberProof) {
3447
+ return null;
3448
+ }
3449
+ const deviceSeed = crypto.randomBytes(32);
3450
+ const delegate = crypto.keyPair(deviceSeed);
3451
+ const deviceProof = await attestDeviceProof(delegate.publicKey, keyPair, own.memberProof);
3452
+ if (!(await delegationFits(deviceProof, delegate))) {
3453
+ throw new Error(DEVICE_INVITE_CHAIN_TOO_LONG);
3454
+ }
3455
+ return { deviceSeed, deviceProof };
3456
+ }
3603
3457
  previewMeshInvite(invite) {
3604
3458
  const decoded = decodeMeshInvite(invite);
3605
3459
  if (!decoded) {
@@ -3611,7 +3465,6 @@ export class Core extends ReadyResource {
3611
3465
  if (this._ownsWakeup) {
3612
3466
  this._wakeup.destroy();
3613
3467
  }
3614
- this._meshSeedHandoff.destroy();
3615
3468
  this._harnessLoan.destroy();
3616
3469
  this._secretHandoff.destroy();
3617
3470
  this._skillOverlayHandoff.destroy();
@@ -3725,17 +3578,16 @@ export class Core extends ReadyResource {
3725
3578
  return;
3726
3579
  }
3727
3580
  if (held) {
3728
- await this._requestMeshAdmission(memberMesh, held, ours);
3729
3581
  return;
3730
3582
  }
3731
3583
  if (await this.local.readMeshSession(joined.meshKey)) {
3732
3584
  if (this._upgradeRequired !== 'halt' &&
3733
3585
  (await this.local.awaitsAdmission(joined.meshKey))) {
3734
- await this._requestMeshAdmission(memberMesh, await this._openPooledMesh(meshId), ours);
3586
+ await this._openPooledMesh(meshId);
3735
3587
  }
3736
3588
  return;
3737
3589
  }
3738
- await this._openFollowedMesh(memberMesh, joined.meshKey, ours);
3590
+ await this._openFollowedMesh(memberMesh, joined);
3739
3591
  });
3740
3592
  if (failed && !joined.leftAt) {
3741
3593
  pending = true;
@@ -3764,10 +3616,7 @@ export class Core extends ReadyResource {
3764
3616
  if (this._leaving || this._minting)
3765
3617
  return;
3766
3618
  try {
3767
- if (await this._departureHasAudience(mesh)) {
3768
- await this.local.recordDeparture(mesh.key, { creator: mesh.minted });
3769
- }
3770
- await this._announceDeparture(mesh);
3619
+ await this._recordDeparture(mesh);
3771
3620
  if (this._isAccount(mesh)) {
3772
3621
  await this._replaceRevokedAccount(mesh);
3773
3622
  }
@@ -3786,226 +3635,26 @@ export class Core extends ReadyResource {
3786
3635
  await this.local.archiveMesh(meshKey);
3787
3636
  this._notifyStatus();
3788
3637
  }
3789
- async _openOwnMesh(invite) {
3790
- const meshKey = invite.baseKey;
3791
- const meshId = b4a.toHex(meshKey);
3792
- if (!invite.inviteNonce) {
3793
- return false;
3794
- }
3795
- const grantKey = grantKeyPair(invite.inviteNonce).publicKey;
3796
- if (await this.local.readMeshSession(meshKey)) {
3797
- return this._adoptOwnMesh(await this._openPooledMesh(meshId), grantKey);
3798
- }
3799
- const registry = await this._accountMesh();
3800
- const ours = registry?.ourMemberId;
3801
- if (!registry || !ours || !(await this._isOwnMeshIn(registry, meshKey))) {
3802
- return false;
3803
- }
3804
- if (this._blockedByMinVersion()) {
3805
- throw new Error(MESH_BELOW_FLOOR);
3806
- }
3807
- this._throwIfJoinCanceled();
3808
- await this._openFollowedMesh(registry, meshKey, ours).catch((error) => {
3809
- this._log?.warn(['p2p', 'mesh'], 'opening a mesh of ours through a sibling failed', error);
3810
- });
3811
- if (this.closing) {
3812
- throw new Error('Core is closing');
3813
- }
3814
- this._throwIfJoinCanceled();
3815
- const mesh = this._pooled(meshId);
3816
- return mesh ? this._adoptOwnMesh(mesh, grantKey) : false;
3817
- }
3818
- async _adoptOwnMesh(mesh, grantKey) {
3819
- const id = this._requireDeviceKeyPair().publicKey;
3820
- const ours = this._accountMesh()?.ourMemberId ?? null;
3821
- await this._awaitGrantRow(mesh, grantKey);
3822
- let refused = false;
3823
- const settled = await this._untilDeadline(async () => {
3824
- const own = await mesh.view.get(DEVICES, { id });
3825
- if (own && !own.revoked && own.writerKey && b4a.equals(own.writerKey, mesh.localWriterKey)) {
3826
- return true;
3827
- }
3828
- refused = await this._refusedInMesh(mesh, grantKey, ours);
3829
- return refused;
3830
- });
3831
- if (refused) {
3832
- const own = await mesh.view.get(DEVICES, { id });
3833
- await this._refuseUnredeemable(mesh, grantKey, own?.memberId ?? mesh.ourMemberId);
3834
- await this._retirePooledMesh(mesh);
3835
- await this.local.archiveMesh(mesh.key);
3836
- return false;
3837
- }
3838
- if (!settled) {
3839
- throw new Error(MESH_ADMISSION_PENDING);
3840
- }
3841
- return true;
3842
- }
3843
- async _refusedInMesh(mesh, grantKey, ours) {
3844
- await mesh.autobee.update();
3845
- const status = await syncStatusSnapshot(mesh);
3846
- if (!status.devices?.length || status.state !== 'synced') {
3847
- return false;
3848
- }
3849
- const self = this._requireDeviceKeyPair().publicKey;
3850
- const own = await mesh.view.get(DEVICES, { id: self });
3851
- if (own?.revoked &&
3852
- !(own.revokedBy && b4a.equals(own.revokedBy, own.writerKey ?? b4a.alloc(0)))) {
3853
- return true;
3854
- }
3855
- if (!ours) {
3856
- return false;
3857
- }
3858
- const grant = await mesh.view.get(MESH_INVITE_GRANTS, { grantKey });
3859
- if (grant && (await memberStanding(mesh.view, ours, grant)) === 'removed') {
3860
- return true;
3861
- }
3862
- for await (const device of mesh.view.find(DEVICES)) {
3863
- if (!device.revoked &&
3864
- device.memberId &&
3865
- b4a.equals(device.memberId, ours) &&
3866
- !b4a.equals(device.id, self)) {
3867
- return false;
3868
- }
3869
- }
3870
- return true;
3871
- }
3872
- async _openFollowedMesh(memberMesh, meshKey, ours) {
3873
- if (this._blockedByMinVersion())
3874
- return;
3875
- const seed = await this._requestMeshSeed(memberMesh, meshKey, ours);
3876
- if (!seed || this.closing) {
3638
+ async _openFollowedMesh(memberMesh, joined) {
3639
+ if (this._blockedByMinVersion() || this._upgradeRequired || !this._mayFollow(memberMesh)) {
3877
3640
  return;
3878
3641
  }
3879
- const moving = this._joinCancellation ? this._joinCancellation.account : this._minting;
3880
- const leaving = this._leaving === this._meshIdOf(memberMesh);
3881
- if (moving || leaving || !this._isAccount(memberMesh)) {
3642
+ const { meshKey } = joined;
3643
+ const held = await memberMesh.view.get(MESH_SEEDS, { meshKey });
3644
+ if (!held || this.closing) {
3882
3645
  return;
3883
3646
  }
3884
- const session = this.local.createCandidateSession(seed, meshKey);
3647
+ const session = this.local.createCandidateSession(held.seed, meshKey);
3885
3648
  await this.local.recordMesh(meshKey, session, {
3886
3649
  deviceId: this._requireDeviceKeyPair().publicKey
3887
3650
  });
3888
3651
  await this.local.markAwaitingAdmission(meshKey, { awaitingAdmission: true });
3889
- let mesh;
3890
- try {
3891
- mesh = await this._openPooledMesh(b4a.toHex(meshKey));
3892
- }
3893
- catch (error) {
3894
- if (this._upgradeRequired !== 'halt') {
3895
- await this.local.archiveMesh(meshKey).catch(noop);
3896
- }
3897
- throw error;
3898
- }
3899
- await this._requestMeshAdmission(memberMesh, mesh, ours);
3900
- }
3901
- async _requestMeshSeed(memberMesh, meshKey, ours) {
3902
- let unanswered = null;
3903
- for (const sibling of await this._liveSiblings(memberMesh, ours)) {
3904
- if (this.closing)
3905
- return null;
3906
- const seed = await this._meshSeedHandoff.request(sibling, meshKey).catch((error) => {
3907
- this._log?.warn(['p2p', 'mesh'], 'a sibling did not hand over a mesh seed', error);
3908
- if (UNANSWERED_SEED_REQUESTS.has(error.message)) {
3909
- unanswered = error;
3910
- }
3911
- });
3912
- if (seed) {
3913
- return seed;
3914
- }
3915
- }
3916
- if (unanswered) {
3917
- throw unanswered;
3918
- }
3919
- return null;
3652
+ await this._openPooledMesh(b4a.toHex(meshKey));
3920
3653
  }
3921
- async _requestMeshAdmission(memberMesh, mesh, ours) {
3922
- if (mesh.writable) {
3923
- return this.local.markAwaitingAdmission(mesh.key, { awaitingAdmission: false });
3924
- }
3925
- const { publicKey: deviceId, secretKey } = this._requireDeviceKeyPair();
3926
- const own = await mesh.view.get(DEVICES, { id: deviceId });
3927
- if (own && (await this._removedFor(mesh, own))) {
3928
- return this.local.markAwaitingAdmission(mesh.key, { awaitingAdmission: false });
3929
- }
3930
- const binding = {
3931
- meshPublicKey: mesh.publicKey,
3932
- deviceId,
3933
- writerKey: mesh.localWriterKey,
3934
- joinedAt: Date.now()
3935
- };
3936
- const claim = {
3937
- writerKey: binding.writerKey,
3938
- joinedAt: binding.joinedAt,
3939
- deviceSignature: signWriterClaim(secretKey, binding),
3940
- memberSignature: signMemberWriterClaim(secretKey, { ...binding, memberId: ours })
3941
- };
3942
- const known = await mesh.bornKind();
3943
- const deferred = known !== null && (await this._askSiblingsToAdmit(memberMesh, mesh, { ours, claim }));
3944
- if (this.closing) {
3945
- return;
3946
- }
3947
- if (!mesh.writable && (await mesh.waitForGenesis(this._accountWritableMs)) === null) {
3948
- await mesh.appendBirthOp(this._requireDeviceKeyPair(), this._localDevice ?? undefined);
3949
- await mesh.waitForWritable(this._accountWritableMs);
3950
- }
3951
- const meshId = this._meshIdOf(mesh);
3952
- if (deferred && !mesh.writable) {
3953
- this._retryAdmission(memberMesh, meshId);
3954
- return;
3955
- }
3956
- this._admissionRetries.delete(meshId);
3957
- if (mesh.writable) {
3958
- await this.local.markAwaitingAdmission(mesh.key, { awaitingAdmission: false });
3959
- }
3960
- }
3961
- async _askSiblingsToAdmit(memberMesh, mesh, { ours, claim }) {
3962
- let deferred = false;
3963
- for (const sibling of await this._liveSiblings(memberMesh, ours)) {
3964
- if (this.closing || mesh.writable)
3965
- break;
3966
- const admitted = await this._meshSeedHandoff
3967
- .admit(sibling, mesh.key, claim)
3968
- .catch((error) => {
3969
- deferred ||= error.message === ADMISSION_DEFERRED;
3970
- return false;
3971
- });
3972
- if (admitted) {
3973
- await mesh.waitForWritable(this._accountWritableMs);
3974
- }
3975
- }
3976
- return deferred && !mesh.writable;
3977
- }
3978
- _retryAdmission(memberMesh, meshId) {
3979
- const tries = this._admissionRetries.get(meshId) ?? 0;
3980
- if (tries >= ADMISSION_RETRIES) {
3981
- return;
3982
- }
3983
- this._admissionRetries.set(meshId, tries + 1);
3984
- const memberId = this._meshIdOf(memberMesh);
3985
- if (this._admissionRetryPending.has(memberId)) {
3986
- return;
3987
- }
3988
- this._admissionRetryPending.add(memberId);
3989
- Promise.race([after(INVITER_RETRY_MS), this._closeSignal])
3990
- .then(() => {
3991
- this._admissionRetryPending.delete(memberId);
3992
- const current = this.closing ? null : this._pooled(memberId);
3993
- return current ? this._followJoinedMeshes(current) : undefined;
3994
- })
3995
- .catch(noop);
3996
- }
3997
- async _liveSiblings(memberMesh, ours) {
3998
- const self = this._deviceKeyPair?.publicKey;
3999
- const siblings = [];
4000
- for await (const device of memberMesh.view.find(DEVICES)) {
4001
- if (device.revoked || !(device.memberId && b4a.equals(device.memberId, ours))) {
4002
- continue;
4003
- }
4004
- if (self && b4a.equals(device.id, self))
4005
- continue;
4006
- siblings.push(device.id);
4007
- }
4008
- return siblings;
3654
+ _mayFollow(memberMesh) {
3655
+ const moving = this._joinCancellation ? this._joinCancellation.account : this._minting;
3656
+ const leaving = this._leaving === this._meshIdOf(memberMesh);
3657
+ return !this.closing && !moving && !leaving && this._isAccount(memberMesh);
4009
3658
  }
4010
3659
  registerLoanableHarness(serve) {
4011
3660
  this._serveLoanedHarness = serve;
@@ -4063,193 +3712,6 @@ export class Core extends ReadyResource {
4063
3712
  }
4064
3713
  return false;
4065
3714
  }
4066
- async _serveMeshSeed(request, fromDeviceId) {
4067
- const asker = b4a.from(fromDeviceId);
4068
- if ('writerKey' in request) {
4069
- return request.inviteToken
4070
- ? this._admitInvitedDevice(request, asker)
4071
- : this._admitIntoMesh(request, asker);
4072
- }
4073
- const standing = await this._askerStanding(asker);
4074
- if (standing === 'unseen') {
4075
- throw new Error(SEED_ASKER_UNSEEN);
4076
- }
4077
- if (standing === 'refused') {
4078
- this._log?.warn(['p2p', 'mesh'], 'seed request refused: not a device of this member');
4079
- return null;
4080
- }
4081
- if (!(await this._isJoinedMeshKey(request.meshKey))) {
4082
- this._log?.warn(['p2p', 'mesh'], 'seed request refused: not a mesh this member joined');
4083
- return null;
4084
- }
4085
- const mesh = this._pooled(b4a.toHex(request.meshKey));
4086
- const row = mesh ? await mesh.view.get(DEVICES, { id: asker }) : null;
4087
- if (mesh && row && (await this._removedFor(mesh, row))) {
4088
- this._log?.warn(['p2p', 'mesh'], 'seed request refused: removed from this mesh');
4089
- return null;
4090
- }
4091
- const session = await this.local.readMeshSession(request.meshKey);
4092
- return session?.seed ? { seed: session.seed } : null;
4093
- }
4094
- async _admitInvitedDevice(request, asker) {
4095
- const account = await this._accountMesh();
4096
- if (!(account?.key && b4a.equals(account?.key, request.meshKey))) {
4097
- this._log?.warn(['p2p', 'mesh'], "device invite refused: not this device's account");
4098
- return null;
4099
- }
4100
- const context = { deviceKeyPair: this._requireDeviceKeyPair(), log: this._log };
4101
- const admitted = await admitInvitedDevice(account, context, {
4102
- invites: this._deviceInvites,
4103
- deviceId: asker,
4104
- request
4105
- });
4106
- if (admitted) {
4107
- return { admitted: true };
4108
- }
4109
- if (request.inviteToken && (await this._deviceInvites.spent(request.inviteToken, asker))) {
4110
- throw new Error(DEVICE_INVITE_SPENT);
4111
- }
4112
- return null;
4113
- }
4114
- async _admitIntoMesh(request, asker) {
4115
- if (this._meshTransitionLock.locked) {
4116
- throw new Error(ADMISSION_DEFERRED);
4117
- }
4118
- await this._meshTransitionLock.lock();
4119
- try {
4120
- return await this._admitIntoMeshLocked(request, asker);
4121
- }
4122
- finally {
4123
- this._meshTransitionLock.unlock();
4124
- }
4125
- }
4126
- async _admitIntoMeshLocked(request, asker) {
4127
- if (this._leaving)
4128
- return null;
4129
- if (this._minting) {
4130
- throw new Error(ADMISSION_DEFERRED);
4131
- }
4132
- const account = await this._accountMesh();
4133
- const ours = account?.ourMemberId;
4134
- const row = ours ? await account.view.get(DEVICES, { id: asker }) : null;
4135
- if (!ours ||
4136
- !row ||
4137
- row.revoked ||
4138
- !(row.memberId && b4a.equals(row.memberId, ours)) ||
4139
- (await this._askerStanding(asker)) !== 'ours') {
4140
- this._log?.warn(['p2p', 'mesh'], 'admission refused: not a live device of this member');
4141
- return null;
4142
- }
4143
- if (!(await this._isJoinedMeshKey(request.meshKey))) {
4144
- this._log?.warn(['p2p', 'mesh'], 'admission refused: not a mesh this member joined');
4145
- return null;
4146
- }
4147
- const session = await this.local.readMeshSession(request.meshKey);
4148
- if (!session?.seed) {
4149
- return null;
4150
- }
4151
- const writerKey = request.writerKey;
4152
- const joinedAt = request.joinedAt ?? 0;
4153
- const claim = {
4154
- meshPublicKey: meshPublicKeyFromSeed(session.seed),
4155
- deviceId: asker,
4156
- writerKey,
4157
- joinedAt
4158
- };
4159
- if (!verifyWriterClaim(request.deviceSignature, claim) ||
4160
- !verifyMemberWriterClaim(request.memberSignature, { ...claim, memberId: ours })) {
4161
- this._log?.warn(['p2p', 'mesh'], 'admission refused: the asker did not sign its claim');
4162
- return null;
4163
- }
4164
- const mesh = await this._openPooledMesh(b4a.toHex(request.meshKey));
4165
- await mesh.autobee.update();
4166
- if (!mesh.writable) {
4167
- throw new Error(ADMISSION_DEFERRED);
4168
- }
4169
- if ((await mesh.bornKind()) !== 'shared') {
4170
- this._log?.warn(['p2p', 'mesh'], 'admission refused: a sibling joins this mesh by its seed');
4171
- return null;
4172
- }
4173
- const self = await mesh.view.get(DEVICES, {
4174
- id: this._requireDeviceKeyPair().publicKey
4175
- });
4176
- if (!(self?.memberId && b4a.equals(self.memberId, ours)) ||
4177
- self.revoked ||
4178
- !(self.writerKey && b4a.equals(self.writerKey, mesh.localWriterKey))) {
4179
- this._log?.warn(['p2p', 'mesh'], 'admission refused: this device is not linked in the mesh');
4180
- return null;
4181
- }
4182
- const current = await mesh.view.get(DEVICES, { id: asker });
4183
- if (current && (await this._removedFor(mesh, current))) {
4184
- this._log?.warn(['p2p', 'mesh'], 'admission refused: removed from this mesh');
4185
- return null;
4186
- }
4187
- if (current && !current.revoked) {
4188
- if (current.writerKey && b4a.equals(current.writerKey, writerKey)) {
4189
- return { admitted: true };
4190
- }
4191
- if (!(row.joinedAt > current.joinedAt)) {
4192
- throw new Error(ADMISSION_DEFERRED);
4193
- }
4194
- }
4195
- await mesh.dispatch('vouched-join', {
4196
- signature: mesh.sign(writerKey),
4197
- deviceId: asker,
4198
- device: claimableDevice({
4199
- id: asker,
4200
- joinedAt,
4201
- name: row.name,
4202
- capabilityProfile: row.capabilityProfile,
4203
- recommendedModelName: row.recommendedModelName
4204
- }),
4205
- deviceSignature: request.deviceSignature,
4206
- writerKey,
4207
- memberProof: row.memberProof,
4208
- memberSignature: request.memberSignature
4209
- });
4210
- return { admitted: true };
4211
- }
4212
- async _isJoinedMeshKey(meshKey) {
4213
- for (const entry of this._meshes.values()) {
4214
- const ours = entry.mesh.ourMemberId;
4215
- if (!ours) {
4216
- continue;
4217
- }
4218
- const row = await entry.mesh.view.get(JOINED_MESHES, { meshKey }).catch(noop);
4219
- if (row?.memberId && b4a.equals(row.memberId, ours) && !row.leftAt) {
4220
- return true;
4221
- }
4222
- }
4223
- return false;
4224
- }
4225
- async _removedFor(mesh, row) {
4226
- if (!row.revoked)
4227
- return false;
4228
- const by = await removedBy(mesh.view, row);
4229
- if (by !== 'own-member') {
4230
- return by === 'another-member';
4231
- }
4232
- const paired = await this._accountMesh()?.view.get(DEVICES, { id: row.id });
4233
- return !(paired && !paired.revoked && row.revokedAt && paired.joinedAt > row.revokedAt);
4234
- }
4235
- async _askerStanding(deviceId) {
4236
- const account = this._accountMesh();
4237
- const ours = account?.ourMemberId;
4238
- if (!account || !ours) {
4239
- return 'unseen';
4240
- }
4241
- const device = await account.view.get(DEVICES, { id: deviceId });
4242
- if (!device) {
4243
- return 'unseen';
4244
- }
4245
- if (device.revoked) {
4246
- return 'refused';
4247
- }
4248
- if (!device.memberId) {
4249
- return 'unseen';
4250
- }
4251
- return b4a.equals(device.memberId, ours) ? 'ours' : 'refused';
4252
- }
4253
3715
  async _skillOverlayOp(agentId, op) {
4254
3716
  const host = await this._resolveAgentHost(agentId);
4255
3717
  if (!host) {
@@ -4446,7 +3908,6 @@ export class Core extends ReadyResource {
4446
3908
  });
4447
3909
  this._secretHandoff.addStream(conn);
4448
3910
  this._skillOverlayHandoff.addStream(conn);
4449
- this._meshSeedHandoff.addStream(conn);
4450
3911
  this._harnessLoan.addStream(conn);
4451
3912
  this._inferenceCallsHandoff.addStream(conn);
4452
3913
  if (this._ownsSwarm) {
@@ -4630,6 +4091,14 @@ export class Core extends ReadyResource {
4630
4091
  }
4631
4092
  };
4632
4093
  }
4094
+ registerModelMemory(hook) {
4095
+ this._modelMemory = hook;
4096
+ return () => {
4097
+ if (this._modelMemory === hook) {
4098
+ this._modelMemory = null;
4099
+ }
4100
+ };
4101
+ }
4633
4102
  registerDeleteModel(hook) {
4634
4103
  this._deleteModel = hook;
4635
4104
  return () => {
@@ -4696,6 +4165,13 @@ export class Core extends ReadyResource {
4696
4165
  }
4697
4166
  return null;
4698
4167
  }
4168
+ async _readModelList(request) {
4169
+ const models = await this._readModels(request);
4170
+ if (!models) {
4171
+ return null;
4172
+ }
4173
+ return { models, memory: (await this._modelMemory?.()) ?? undefined };
4174
+ }
4699
4175
  async _readModels({ excludeCustom, ...options }) {
4700
4176
  const list = await this._listModels?.(options);
4701
4177
  if (!list) {
@@ -5005,9 +4481,6 @@ export class Core extends ReadyResource {
5005
4481
  }
5006
4482
  }
5007
4483
  }
5008
- function after(ms) {
5009
- return new Promise((resolve) => unref(setTimeout(resolve, ms)));
5010
- }
5011
4484
  function unmarkedNotice(losers) {
5012
4485
  if (losers.length === 0)
5013
4486
  return undefined;