maka-agent 0.2.0-dev.8.20260830 → 0.2.0-dev.9.20260831

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 (63) hide show
  1. package/dist/cli-core.js +11 -0
  2. package/dist/runtime-host-cli.js +44 -0
  3. package/dist/runtime-host-installed-update-activator.js +70 -33
  4. package/dist/runtime-host-installed-update-coordinator.js +11 -96
  5. package/dist/runtime-host-lifecycle-transaction.js +2 -0
  6. package/dist/runtime-host-local-handoff.js +169 -38
  7. package/dist/runtime-host-local-source-retirement.js +103 -0
  8. package/dist/runtime-host-local-target-activation.js +141 -0
  9. package/dist/runtime-host-peer-management-command.js +10 -4
  10. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  11. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  12. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  13. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  14. package/node_modules/@maka/core/dist/artifacts.js +23 -15
  15. package/node_modules/@maka/core/dist/durable-tool-result-projection.js +124 -0
  16. package/node_modules/@maka/core/dist/llm-connections.js +20 -0
  17. package/node_modules/@maka/core/dist/runtime-event.js +28 -3
  18. package/node_modules/@maka/core/dist/session-name.js +0 -1
  19. package/node_modules/@maka/core/package.json +1 -0
  20. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +95 -19
  21. package/node_modules/@maka/runtime/dist/conversation-copy.js +67 -0
  22. package/node_modules/@maka/runtime/dist/durable-tool-result-projection.js +390 -0
  23. package/node_modules/@maka/runtime/dist/model-history.js +12 -39
  24. package/node_modules/@maka/runtime/dist/recovery-resolver.js +18 -14
  25. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +20 -11
  26. package/node_modules/@maka/runtime/dist/session-manager.js +0 -170
  27. package/node_modules/@maka/runtime/dist/tool-runtime.js +118 -71
  28. package/node_modules/@maka/runtime/package.json +1 -0
  29. package/node_modules/@maka/runtime-host/dist/candidate-entry.js +6 -1
  30. package/node_modules/@maka/runtime-host/dist/candidate-launch-owner-guard.js +13 -0
  31. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +4 -1
  32. package/node_modules/@maka/runtime-host/dist/client/host-profile.js +27 -1
  33. package/node_modules/@maka/runtime-host/dist/client/index.js +1 -1
  34. package/node_modules/@maka/runtime-host/dist/client/launcher.js +8 -2
  35. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +11 -1
  36. package/node_modules/@maka/runtime-host/dist/peer-mesh/index.js +1 -1
  37. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +394 -113
  38. package/node_modules/@maka/runtime-host/dist/peer-mesh/store.js +90 -21
  39. package/node_modules/@maka/runtime-host/dist/protocol/index.js +8 -1
  40. package/node_modules/@maka/runtime-host/dist/protocol/oauth.js +60 -7
  41. package/node_modules/@maka/runtime-host/dist/protocol/usage-pricing.js +4 -0
  42. package/node_modules/@maka/runtime-host/dist/server/artifact-coordinator.js +2 -4
  43. package/node_modules/@maka/runtime-host/dist/server/candidate.js +3 -0
  44. package/node_modules/@maka/runtime-host/dist/server/client-capability-recovery.js +10 -7
  45. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +5 -1
  46. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +9 -1
  47. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +10 -0
  48. package/node_modules/@maka/runtime-host/dist/server/oauth-coordinator.js +91 -42
  49. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +10 -1
  50. package/node_modules/@maka/runtime-host/dist/server/usage-pricing-coordinator.js +45 -5
  51. package/node_modules/@maka/storage/dist/artifact-attachments.js +62 -11
  52. package/node_modules/@maka/storage/dist/artifact-store.js +11 -0
  53. package/node_modules/@maka/storage/dist/artifact-stores.js +4 -1
  54. package/node_modules/@maka/storage/dist/quiescent-session-snapshot.js +1154 -0
  55. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +36 -0
  56. package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +213 -46
  57. package/node_modules/@maka/storage/dist/runtime-policy/document-io.js +1 -1
  58. package/node_modules/@maka/storage/dist/runtime-policy/oauth-login-receipt-document.js +186 -0
  59. package/node_modules/@maka/storage/dist/runtime-policy/onboarding-transaction.js +120 -1
  60. package/node_modules/@maka/storage/dist/runtime-policy-stores.js +2 -1
  61. package/node_modules/@maka/storage/dist/session-bundle-ustar.js +12 -0
  62. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +5 -0
  63. package/package.json +1 -1
@@ -19,7 +19,7 @@
19
19
  import { setTimeout as delay } from 'node:timers/promises';
20
20
  import { canonicalPeerMeshRoster, canonicalPeerMeshRouteRecord, createPeerMeshInvitationSecret, validatePeerMeshInvitation, decodeSignedPeerMeshRoster, decodeSignedPeerMeshRouteRecord, generatePeerMeshAuthorityKeyPair, matchesPeerMeshInvitationSecret, PEER_MESH_MAX_MEMBERS, PEER_MESH_MAX_MESHES, PEER_MESH_MAX_INVITATION_RECORDS, PEER_MESH_MAX_PENDING_INVITATIONS, PEER_MESH_MAX_TRANSIT_ADDRESSES_PER_RELAY, PEER_MESH_MAX_TRANSIT_RELAY_ADDRESSES, peerMeshRouteRecordSigningBytes, peerMeshId, peerMeshInvitationSecretDigest, signPeerMeshRoster, } from './model.js';
21
21
  import { canonicalPeerMeshDisplayName } from './display-name.js';
22
- import { authorityKeys, openPeerMeshStateStore, } from './store.js';
22
+ import { authorityKeys, isActivePeerMeshMembership as isActiveMembership, isRetiredPeerMeshState as isRetired, openPeerMeshStateStore, } from './store.js';
23
23
  const CONTROL_FRAME_MAX_BYTES = 64 * 1024;
24
24
  const DEFAULT_INVITATION_TTL_MS = 15 * 60 * 1_000;
25
25
  const CONNECT_DEADLINE_MS = 30_000;
@@ -104,7 +104,7 @@ class PeerMeshNodeImpl {
104
104
  setMeshDisplayName(meshId, displayName) {
105
105
  return this.#admitMesh(async () => {
106
106
  const canonical = displayName === null ? undefined : canonicalPeerMeshDisplayName(displayName);
107
- await this.#store.mutate((current) => {
107
+ const announcement = await this.#store.mutate((current) => {
108
108
  const state = requireAuthority(current.meshes, meshId);
109
109
  if (state.roster.roster.closed)
110
110
  throw new Error('Peer Mesh is closed');
@@ -118,9 +118,14 @@ class PeerMeshNodeImpl {
118
118
  }), authorityKeys(state));
119
119
  return {
120
120
  state: { ...current, meshes: replaceMesh(current.meshes, { ...state, roster }) },
121
- result: undefined,
121
+ result: {
122
+ roster,
123
+ targets: rosterAnnouncementTargets(state.roster.roster.members, current.routes, this.#peer.identity().peerId),
124
+ },
122
125
  };
123
126
  });
127
+ if (announcement)
128
+ this.#scheduleRosterAnnouncement(announcement.roster, announcement.targets);
124
129
  const stored = this.#store.read();
125
130
  return peerMeshStatus(requireAuthority(stored.meshes, meshId), this.#peer.identity(), this.#endpointKind, stored.routes, this.#now());
126
131
  });
@@ -130,7 +135,7 @@ class PeerMeshNodeImpl {
130
135
  const identity = this.#peer.identity();
131
136
  const stored = this.#store.read();
132
137
  return Object.freeze(stored.meshes
133
- .filter((state) => isActiveMembership(state, identity.peerId))
138
+ .filter((state) => state.roster.roster.closed || isActiveMembership(state, identity.peerId))
134
139
  .map((state) => peerMeshStatus(state, identity, this.#endpointKind, stored.routes, this.#now())));
135
140
  }
136
141
  create() {
@@ -153,7 +158,7 @@ class PeerMeshNodeImpl {
153
158
  const signedRoute = await this.#signLocalRoute();
154
159
  const now = this.#now();
155
160
  await this.#store.mutate((current) => {
156
- assertMeshCapacity(current.meshes, identity.peerId);
161
+ assertMeshCapacity(current.meshes, identity.peerId, current.pendingJoins.length);
157
162
  const currentLocalRoute = current.routes
158
163
  .filter(({ route }) => route.peerId === identity.peerId)
159
164
  .sort((left, right) => right.route.sequence - left.route.sequence)[0];
@@ -225,88 +230,215 @@ class PeerMeshNodeImpl {
225
230
  join(invitationValue, signal) {
226
231
  return this.#admitMesh(async () => {
227
232
  const invitation = validatePeerMeshInvitation(invitationValue);
228
- if (invitation.expiresAt <= this.#now()) {
229
- throw new Error('Peer Mesh invitation has expired');
230
- }
231
233
  const current = this.#store.read();
232
234
  const existing = findMesh(current.meshes, invitation.meshId);
235
+ const pending = current.pendingJoins.find(({ invitation: candidate }) => candidate.meshId === invitation.meshId);
236
+ if (!pending && invitation.expiresAt <= this.#now()) {
237
+ throw new Error('Peer Mesh invitation has expired');
238
+ }
233
239
  const localPeerId = this.#peer.identity().peerId;
240
+ if (existing?.roster.roster.closed) {
241
+ throw new Error('Peer Mesh is closed');
242
+ }
234
243
  if (existing?.role === 'authority') {
235
244
  throw new Error('This peer already belongs to that Peer Mesh');
236
245
  }
237
- if (!existing)
238
- assertMeshCapacity(current.meshes, localPeerId);
246
+ assertRejoinSettled(existing, localPeerId);
247
+ if (pending && pending.invitation.secret !== invitation.secret) {
248
+ throw new Error('This Peer Mesh already has an unresolved join attempt');
249
+ }
250
+ if (pending?.phase === 'leave_pending') {
251
+ throw new Error('This Peer Mesh join is still being cancelled');
252
+ }
253
+ if (!existing && !pending) {
254
+ assertMeshCapacity(current.meshes, localPeerId, current.pendingJoins.length);
255
+ }
239
256
  const operationSignal = signal
240
257
  ? AbortSignal.any([signal, this.#lifetime.signal])
241
258
  : this.#lifetime.signal;
242
- const stream = await this.#peer.connectMeshControl({
243
- peerId: invitation.peerId,
244
- routeHints: invitation.routeHints,
245
- coordinationRelays: invitation.coordinationRelays,
246
- directDeadlineMs: CONNECT_DEADLINE_MS,
247
- }, operationSignal);
259
+ let stream;
260
+ let joinIntentAdmitted = pending !== undefined;
248
261
  try {
262
+ stream = await this.#peer.connectMeshControl({
263
+ peerId: invitation.peerId,
264
+ routeHints: invitation.routeHints,
265
+ coordinationRelays: invitation.coordinationRelays,
266
+ directDeadlineMs: CONNECT_DEADLINE_MS,
267
+ }, operationSignal);
249
268
  const localRoute = (await this.#refreshLocalRoute()) ?? (await this.#signLocalRoute());
250
- const request = {
251
- kind: 'redeem-invitation',
252
- meshId: invitation.meshId,
253
- secret: invitation.secret,
254
- route: localRoute,
255
- };
256
- const response = await exchangeControl(stream, request, decodeRedeemResponse, operationSignal);
257
- if (response.kind === 'invitation-rejected') {
258
- throw new Error(`Peer Mesh invitation was rejected: ${response.reason}`);
259
- }
260
- const roster = decodeSignedPeerMeshRoster(response.roster);
261
- const identity = this.#peer.identity();
262
- if (roster.roster.meshId !== invitation.meshId ||
263
- roster.authorityPublicKey !== invitation.authorityPublicKey ||
264
- !roster.roster.members.includes(identity.peerId)) {
265
- throw new Error('Peer Mesh authority returned an unrelated roster');
266
- }
267
- const routes = await this.#validateRoutes(response.routes, roster, this.#now());
268
- operationSignal.throwIfAborted();
269
269
  await this.#store.mutate((current) => {
270
270
  const existing = findMesh(current.meshes, invitation.meshId);
271
271
  if (existing?.role === 'authority') {
272
272
  throw new Error('This peer already belongs to that Peer Mesh');
273
273
  }
274
- const selectedRoster = existing ? selectRoster(existing.roster, roster) : roster;
275
- if (!selectedRoster.roster.members.includes(identity.peerId)) {
276
- throw new Error('Peer Mesh invitation did not establish an active membership');
274
+ assertRejoinSettled(existing, localPeerId);
275
+ const pending = current.pendingJoins.find(({ invitation: candidate }) => candidate.meshId === invitation.meshId);
276
+ if (pending && pending.invitation.secret !== invitation.secret) {
277
+ throw new Error('This Peer Mesh already has an unresolved join attempt');
277
278
  }
278
- const state = {
279
- role: 'replica',
280
- authority: {
281
- peerId: invitation.peerId,
282
- routeHints: invitation.routeHints,
283
- coordinationRelays: invitation.coordinationRelays,
284
- },
285
- roster: selectedRoster,
286
- };
287
- if (!existing)
288
- assertMeshCapacity(current.meshes, identity.peerId);
289
- const meshes = existing
290
- ? replaceMesh(current.meshes, state)
291
- : appendMesh(current.meshes, state, identity.peerId);
279
+ if (pending?.phase === 'leave_pending') {
280
+ throw new Error('This Peer Mesh join is still being cancelled');
281
+ }
282
+ if (!existing && !pending) {
283
+ assertMeshCapacity(current.meshes, localPeerId, current.pendingJoins.length);
284
+ }
285
+ const next = pending
286
+ ? { ...pending, invitation }
287
+ : { invitation, phase: 'prepared' };
292
288
  return {
293
289
  state: {
294
290
  ...current,
295
- meshes,
296
- routes: mergeRoutes(current.routes, [...routes, localRoute], this.#now()),
291
+ pendingJoins: pending
292
+ ? current.pendingJoins.map((candidate) => candidate === pending ? next : candidate)
293
+ : [...current.pendingJoins, next],
297
294
  },
298
295
  result: undefined,
299
296
  };
300
297
  });
301
- await this.#refreshLocalRoute();
302
- await this.#reconcileTransit();
303
- const stored = this.#store.read();
304
- return peerMeshStatus(findMesh(stored.meshes, invitation.meshId), identity, this.#endpointKind, stored.routes);
298
+ joinIntentAdmitted = true;
299
+ return await this.#redeemPendingJoin(invitation, localRoute, stream, operationSignal);
300
+ }
301
+ catch (error) {
302
+ if (signal?.aborted && joinIntentAdmitted) {
303
+ await this.#cancelPendingJoin(invitation.meshId);
304
+ await this.#reconcileTransit();
305
+ }
306
+ void this.reconcile().catch(() => undefined);
307
+ throw error;
305
308
  }
306
309
  finally {
307
- await stream.close().catch(() => undefined);
310
+ await stream?.close().catch(() => undefined);
311
+ }
312
+ });
313
+ }
314
+ async #redeemPendingJoin(invitation, localRoute, stream, signal) {
315
+ signal.throwIfAborted();
316
+ const dispatch = await this.#store.mutate((current) => {
317
+ const pending = current.pendingJoins.find(({ invitation: candidate }) => candidate.meshId === invitation.meshId && candidate.secret === invitation.secret);
318
+ if (!pending) {
319
+ return { state: current, result: false };
320
+ }
321
+ if (pending.phase !== 'prepared') {
322
+ return { state: current, result: true };
323
+ }
324
+ return {
325
+ state: {
326
+ ...current,
327
+ pendingJoins: current.pendingJoins.map((candidate) => candidate === pending ? { ...candidate, phase: 'outcome_unknown' } : candidate),
328
+ },
329
+ result: true,
330
+ };
331
+ });
332
+ if (!dispatch)
333
+ throw new Error('Peer Mesh join is no longer pending');
334
+ signal.throwIfAborted();
335
+ const response = await exchangeControl(stream, {
336
+ kind: 'redeem-invitation',
337
+ meshId: invitation.meshId,
338
+ secret: invitation.secret,
339
+ route: localRoute,
340
+ }, decodeRedeemResponse, signal);
341
+ if (response.kind === 'invitation-rejected') {
342
+ await this.#discardPendingJoin(invitation);
343
+ throw new Error(`Peer Mesh invitation was rejected: ${response.reason}`);
344
+ }
345
+ const roster = decodeSignedPeerMeshRoster(response.roster);
346
+ const identity = this.#peer.identity();
347
+ if (roster.roster.meshId !== invitation.meshId ||
348
+ roster.authorityPublicKey !== invitation.authorityPublicKey ||
349
+ !roster.roster.members.includes(identity.peerId)) {
350
+ throw new Error('Peer Mesh authority returned an unrelated roster');
351
+ }
352
+ const routes = await this.#validateRoutes(response.routes, roster, this.#now());
353
+ signal.throwIfAborted();
354
+ await this.#store.mutate((current) => {
355
+ const pending = current.pendingJoins.find(({ invitation: candidate }) => candidate.meshId === invitation.meshId && candidate.secret === invitation.secret);
356
+ const existing = findMesh(current.meshes, invitation.meshId);
357
+ if (!pending) {
358
+ if (!existing || existing.role === 'authority') {
359
+ throw new Error('Peer Mesh join is no longer pending');
360
+ }
361
+ return { state: current, result: undefined };
362
+ }
363
+ const selectedRoster = existing ? selectRoster(existing.roster, roster) : roster;
364
+ if (!selectedRoster.roster.members.includes(identity.peerId)) {
365
+ throw new Error('Peer Mesh invitation did not establish an active membership');
308
366
  }
367
+ const state = {
368
+ role: 'replica',
369
+ authority: {
370
+ peerId: invitation.peerId,
371
+ routeHints: invitation.routeHints,
372
+ coordinationRelays: invitation.coordinationRelays,
373
+ },
374
+ roster: selectedRoster,
375
+ desiredMembership: pending.phase === 'leave_pending' ? 'left' : 'active',
376
+ };
377
+ return {
378
+ state: {
379
+ ...current,
380
+ meshes: existing
381
+ ? replaceMesh(current.meshes, state)
382
+ : appendMesh(current.meshes, state, identity.peerId),
383
+ pendingJoins: current.pendingJoins.filter((candidate) => candidate !== pending),
384
+ routes: mergeRoutes(current.routes, [...routes, localRoute], this.#now()),
385
+ },
386
+ result: undefined,
387
+ };
309
388
  });
389
+ signal.throwIfAborted();
390
+ await this.#refreshLocalRoute();
391
+ signal.throwIfAborted();
392
+ await this.#reconcileTransit();
393
+ signal.throwIfAborted();
394
+ const stored = this.#store.read();
395
+ const state = findMesh(stored.meshes, invitation.meshId);
396
+ if (!state)
397
+ throw new Error('Peer Mesh join was not retained');
398
+ return peerMeshStatus(state, identity, this.#endpointKind, stored.routes, this.#now());
399
+ }
400
+ #discardPendingJoin(invitation) {
401
+ return this.#store.mutate((current) => ({
402
+ state: {
403
+ ...current,
404
+ pendingJoins: current.pendingJoins.filter(({ invitation: candidate }) => candidate.meshId !== invitation.meshId || candidate.secret !== invitation.secret),
405
+ },
406
+ result: undefined,
407
+ }));
408
+ }
409
+ #cancelPendingJoin(meshId) {
410
+ return this.#store.mutate((current) => {
411
+ const existing = findMesh(current.meshes, meshId);
412
+ return {
413
+ state: {
414
+ ...current,
415
+ meshes: existing?.role === 'replica'
416
+ ? replaceMesh(current.meshes, { ...existing, desiredMembership: 'left' })
417
+ : current.meshes,
418
+ pendingJoins: current.pendingJoins.flatMap((pending) => {
419
+ if (pending.invitation.meshId !== meshId)
420
+ return [pending];
421
+ return pending.phase === 'prepared' ? [] : [{ ...pending, phase: 'leave_pending' }];
422
+ }),
423
+ },
424
+ result: undefined,
425
+ };
426
+ });
427
+ }
428
+ async #resumePendingJoin(pending, signal) {
429
+ const stream = await this.#peer.connectMeshControl({
430
+ peerId: pending.invitation.peerId,
431
+ routeHints: pending.invitation.routeHints,
432
+ coordinationRelays: pending.invitation.coordinationRelays,
433
+ directDeadlineMs: CONNECT_DEADLINE_MS,
434
+ }, signal);
435
+ try {
436
+ const localRoute = (await this.#refreshLocalRoute()) ?? (await this.#signLocalRoute());
437
+ await this.#redeemPendingJoin(pending.invitation, localRoute, stream, signal);
438
+ }
439
+ finally {
440
+ await stream.close().catch(() => undefined);
441
+ }
310
442
  }
311
443
  remove(meshId, peerId) {
312
444
  if (this.#lifetime.signal.aborted)
@@ -324,31 +456,29 @@ class PeerMeshNodeImpl {
324
456
  }
325
457
  leave(meshId, signal) {
326
458
  return this.#admitMesh(async () => {
327
- const stored = this.#store.read();
328
- const state = findMesh(stored.meshes, meshId);
459
+ signal?.throwIfAborted();
329
460
  const localPeerId = this.#peer.identity().peerId;
330
- if (!state || !isActiveMembership(state, localPeerId)) {
331
- throw new Error('This peer does not belong to that Peer Mesh');
332
- }
333
- if (state.role === 'authority') {
334
- throw new Error('Close a Peer Mesh instead of leaving its authority');
335
- }
336
- const operationSignal = signal
337
- ? AbortSignal.any([signal, this.#lifetime.signal])
338
- : this.#lifetime.signal;
339
- const stream = await this.#peer.connectMeshControl({
340
- ...currentAuthorityTarget(state, stored.routes),
341
- directDeadlineMs: CONNECT_DEADLINE_MS,
342
- }, operationSignal);
343
- try {
344
- const response = await exchangeControl(stream, { kind: 'leave', meshId }, decodeLeaveResponse, operationSignal);
345
- if (response.kind === 'leave-rejected') {
346
- throw new Error('Peer Mesh authority rejected the leave request');
461
+ await this.#store.mutate((current) => {
462
+ const state = findMesh(current.meshes, meshId);
463
+ if (!state || !isActiveMembership(state, localPeerId)) {
464
+ throw new Error('This peer does not belong to that Peer Mesh');
465
+ }
466
+ if (state.role === 'authority') {
467
+ throw new Error('Close a Peer Mesh instead of leaving its authority');
347
468
  }
348
- await this.#applySync(meshId, response.roster, []);
469
+ return {
470
+ state: {
471
+ ...current,
472
+ meshes: replaceMesh(current.meshes, { ...state, desiredMembership: 'left' }),
473
+ },
474
+ result: undefined,
475
+ };
476
+ });
477
+ try {
478
+ await this.#reconcileTransit();
349
479
  }
350
480
  finally {
351
- await stream.close().catch(() => undefined);
481
+ void this.reconcile().catch(() => undefined);
352
482
  }
353
483
  });
354
484
  }
@@ -377,7 +507,7 @@ class PeerMeshNodeImpl {
377
507
  await this.#reconcileTransit();
378
508
  await this.#refreshLocalRoute();
379
509
  }
380
- catch {
510
+ finally {
381
511
  void this.reconcile().catch(() => undefined);
382
512
  }
383
513
  });
@@ -505,8 +635,10 @@ class PeerMeshNodeImpl {
505
635
  await this.#refreshLocalRoute();
506
636
  const identity = this.#peer.identity();
507
637
  const stored = this.#store.read();
508
- const memberships = stored.meshes.filter((state) => state.role === 'replica' && isActiveMembership(state, identity.peerId));
509
- const pending = [];
638
+ const memberships = stored.meshes.filter((state) => state.role === 'replica' &&
639
+ !state.roster.roster.closed &&
640
+ state.roster.roster.members.includes(identity.peerId));
641
+ const pending = stored.pendingJoins.map((join) => ({ kind: 'join', join }));
510
642
  const gossipCursor = this.#gossipCursor;
511
643
  this.#gossipCursor = (this.#gossipCursor + 1) % PEER_MESH_MAX_MEMBERS;
512
644
  const now = this.#now();
@@ -523,9 +655,12 @@ class PeerMeshNodeImpl {
523
655
  targets.push(gossipRoutes[(gossipCursor + index) % gossipRoutes.length]);
524
656
  }
525
657
  pending.push({
658
+ kind: 'membership',
526
659
  meshId: state.roster.roster.meshId,
527
660
  targets,
528
661
  authorityRouteExpired: authorityRoute !== undefined && authorityRoute.route.expiresAt <= now,
662
+ desiredMembership: state.desiredMembership,
663
+ roster: state.roster,
529
664
  });
530
665
  }
531
666
  if (pending.length === 0)
@@ -541,9 +676,17 @@ class PeerMeshNodeImpl {
541
676
  next += 1;
542
677
  if (offset >= pending.length)
543
678
  return;
544
- const { meshId, targets, authorityRouteExpired } = pending[(start + offset) % pending.length];
679
+ const operation = pending[(start + offset) % pending.length];
545
680
  try {
546
- await this.#syncTargets(meshId, targets, authorityRouteExpired, operationSignal);
681
+ if (operation.kind === 'join') {
682
+ await this.#resumePendingJoin(operation.join, operationSignal);
683
+ }
684
+ else if (operation.desiredMembership === 'left') {
685
+ await this.#notifyLeave(operation.meshId, operation.targets[0], operation.roster, operationSignal);
686
+ }
687
+ else {
688
+ await this.#syncTargets(operation.meshId, operation.targets, operation.authorityRouteExpired, operationSignal);
689
+ }
547
690
  }
548
691
  catch (error) {
549
692
  if (lifetimeSignal.aborted)
@@ -559,7 +702,20 @@ class PeerMeshNodeImpl {
559
702
  await this.#reconcileTransit();
560
703
  lifetimeSignal.throwIfAborted();
561
704
  if (failures.length > 0) {
562
- throw new AggregateError(failures, 'Peer Mesh synchronization did not reach every membership');
705
+ throw new AggregateError(failures, 'Peer Mesh reconciliation did not reach every pending intent');
706
+ }
707
+ }
708
+ async #notifyLeave(meshId, target, roster, signal) {
709
+ const stream = await this.#peer.connectMeshControl({ ...target, directDeadlineMs: CONNECT_DEADLINE_MS }, signal);
710
+ try {
711
+ const response = await exchangeControl(stream, { kind: 'leave', meshId, roster }, decodeLeaveResponse, signal);
712
+ if (response.kind === 'leave-rejected') {
713
+ throw new Error('Peer Mesh authority rejected the leave request');
714
+ }
715
+ await this.#applySync(meshId, response.roster, []);
716
+ }
717
+ finally {
718
+ await stream.close().catch(() => undefined);
563
719
  }
564
720
  }
565
721
  async #syncTargets(meshId, targets, authorityRouteExpired, signal) {
@@ -750,7 +906,7 @@ class PeerMeshNodeImpl {
750
906
  state: {
751
907
  ...current,
752
908
  meshes: replaceMesh(current.meshes, next),
753
- routes: nextRoster.roster.closed || !nextRoster.roster.members.includes(localPeerId)
909
+ routes: !isActiveMembership(next, localPeerId)
754
910
  ? current.routes
755
911
  : mergeRoutes(current.routes, routes, this.#now()),
756
912
  },
@@ -765,7 +921,7 @@ class PeerMeshNodeImpl {
765
921
  throw new Error('Peer Mesh node is closed');
766
922
  }
767
923
  async #updateAuthorityRoster(meshId, closedIsSuccess, update) {
768
- await this.#store.mutate((current) => {
924
+ const announcement = await this.#store.mutate((current) => {
769
925
  const state = requireAuthority(current.meshes, meshId);
770
926
  if (state.roster.roster.closed) {
771
927
  if (closedIsSuccess) {
@@ -796,14 +952,49 @@ class PeerMeshNodeImpl {
796
952
  };
797
953
  return {
798
954
  state: { ...current, meshes: replaceMesh(current.meshes, updated) },
799
- result: undefined,
955
+ result: {
956
+ roster,
957
+ targets: rosterAnnouncementTargets(state.roster.roster.members, current.routes, this.#peer.identity().peerId),
958
+ },
800
959
  };
801
960
  });
802
- await this.#refreshLocalRoute();
803
- await this.#reconcileTransit();
961
+ try {
962
+ await this.#reconcileTransit();
963
+ }
964
+ finally {
965
+ if (announcement) {
966
+ this.#scheduleRosterAnnouncement(announcement.roster, announcement.targets);
967
+ }
968
+ this.#scheduleMaintenance();
969
+ }
804
970
  const stored = this.#store.read();
805
971
  return peerMeshStatus(findMesh(stored.meshes, meshId), this.#peer.identity(), this.#endpointKind, stored.routes);
806
972
  }
973
+ #scheduleRosterAnnouncement(roster, targets) {
974
+ if (targets.length === 0 || this.#lifetime.signal.aborted)
975
+ return;
976
+ const signal = this.#lifetime.signal;
977
+ void Promise.allSettled(targets.map(async (target) => {
978
+ const stream = await this.#peer.connectMeshControl({ ...target, directDeadlineMs: CONNECT_DEADLINE_MS }, signal);
979
+ try {
980
+ const response = await exchangeControl(stream, {
981
+ kind: 'announce-roster',
982
+ meshId: roster.roster.meshId,
983
+ roster,
984
+ }, decodeAnnounceRosterResponse, signal);
985
+ if (response.kind === 'roster-rejected') {
986
+ throw new Error('Peer Mesh roster announcement was rejected');
987
+ }
988
+ }
989
+ finally {
990
+ await stream.close().catch(() => undefined);
991
+ }
992
+ }));
993
+ }
994
+ #scheduleMaintenance() {
995
+ void this.#refreshLocalRoute().catch(() => undefined);
996
+ void this.#reconcileTransit().catch(() => undefined);
997
+ }
807
998
  #acceptIncoming(stream) {
808
999
  let peerStreams = 0;
809
1000
  for (const active of this.#activeControlStreams) {
@@ -844,13 +1035,15 @@ class PeerMeshNodeImpl {
844
1035
  else if (request.kind === 'sync') {
845
1036
  response = await this.#sync(request, stream.peerId);
846
1037
  }
1038
+ else if (request.kind === 'leave') {
1039
+ response = await this.#leave(request, stream.peerId);
1040
+ }
847
1041
  else {
848
- response = await this.#leave(request.meshId, stream.peerId);
1042
+ response = await this.#observeRoster(request);
849
1043
  }
850
- await this.#refreshLocalRoute();
851
- await this.#reconcileTransit();
852
1044
  await writeFrame(stream, response);
853
1045
  await stream.close();
1046
+ this.#scheduleMaintenance();
854
1047
  }
855
1048
  catch {
856
1049
  stream.abort();
@@ -859,9 +1052,31 @@ class PeerMeshNodeImpl {
859
1052
  clearTimeout(deadline);
860
1053
  }
861
1054
  }
862
- #redeem(request, remotePeerId, remoteRoute) {
1055
+ async #observeRoster(request) {
1056
+ const response = await this.#store.mutate((current) => {
1057
+ const state = findMesh(current.meshes, request.meshId);
1058
+ if (!state || state.roster.authorityPublicKey !== request.roster.authorityPublicKey) {
1059
+ return {
1060
+ state: current,
1061
+ result: { kind: 'roster-rejected', reason: 'unknown' },
1062
+ };
1063
+ }
1064
+ const roster = selectRoster(state.roster, request.roster);
1065
+ return {
1066
+ state: {
1067
+ ...current,
1068
+ meshes: replaceMesh(current.meshes, { ...state, roster }),
1069
+ },
1070
+ result: { kind: 'roster-observed' },
1071
+ };
1072
+ });
1073
+ if (response.kind === 'roster-observed')
1074
+ await this.#reconcileTransit();
1075
+ return response;
1076
+ }
1077
+ async #redeem(request, remotePeerId, remoteRoute) {
863
1078
  const now = this.#now();
864
- return this.#store.mutate((current) => {
1079
+ const response = await this.#store.mutate((current) => {
865
1080
  const state = findMesh(current.meshes, request.meshId);
866
1081
  if (!state || state.role !== 'authority')
867
1082
  return { state: current, result: rejected('invalid') };
@@ -967,21 +1182,30 @@ class PeerMeshNodeImpl {
967
1182
  },
968
1183
  };
969
1184
  });
1185
+ if (response.kind === 'invitation-redeemed') {
1186
+ const stored = this.#store.read();
1187
+ const state = findMesh(stored.meshes, request.meshId);
1188
+ if (state) {
1189
+ this.#scheduleRosterAnnouncement(state.roster, rosterAnnouncementTargets(state.roster.roster.members, stored.routes, this.#peer.identity().peerId).filter(({ peerId }) => peerId !== remotePeerId));
1190
+ }
1191
+ }
1192
+ return response;
970
1193
  }
971
- #leave(meshId, remotePeerId) {
972
- return this.#store.mutate((current) => {
973
- const state = findMesh(current.meshes, meshId);
1194
+ async #leave(request, remotePeerId) {
1195
+ const response = await this.#store.mutate((current) => {
1196
+ const state = findMesh(current.meshes, request.meshId);
974
1197
  if (!state ||
975
1198
  state.role !== 'authority' ||
976
- state.roster.roster.closed ||
977
- (!state.roster.roster.members.includes(remotePeerId) &&
978
- !state.invitations.some((invitation) => invitation.status === 'redeemed' && invitation.peerId === remotePeerId))) {
1199
+ request.roster.roster.meshId !== request.meshId ||
1200
+ request.roster.authorityPublicKey !== state.roster.authorityPublicKey ||
1201
+ request.roster.roster.revision > state.roster.roster.revision ||
1202
+ !request.roster.roster.members.includes(remotePeerId)) {
979
1203
  return {
980
1204
  state: current,
981
1205
  result: { kind: 'leave-rejected', reason: 'unknown' },
982
1206
  };
983
1207
  }
984
- if (!state.roster.roster.members.includes(remotePeerId)) {
1208
+ if (state.roster.roster.closed || !state.roster.roster.members.includes(remotePeerId)) {
985
1209
  return {
986
1210
  state: current,
987
1211
  result: { kind: 'left', roster: state.roster },
@@ -1001,12 +1225,21 @@ class PeerMeshNodeImpl {
1001
1225
  result: { kind: 'left', roster },
1002
1226
  };
1003
1227
  });
1228
+ if (response.kind === 'left') {
1229
+ await this.#reconcileTransit();
1230
+ const stored = this.#store.read();
1231
+ const state = findMesh(stored.meshes, request.meshId);
1232
+ if (state) {
1233
+ this.#scheduleRosterAnnouncement(state.roster, rosterAnnouncementTargets(state.roster.roster.members, stored.routes, this.#peer.identity().peerId));
1234
+ }
1235
+ }
1236
+ return response;
1004
1237
  }
1005
1238
  async #sync(request, remotePeerId) {
1006
1239
  const remoteRoute = this.#validateRemoteRoute(request.route, remotePeerId);
1007
1240
  await this.#refreshLocalRoute();
1008
1241
  const incomingRoster = decodeSignedPeerMeshRoster(request.roster);
1009
- return this.#store.mutate((current) => {
1242
+ const response = await this.#store.mutate((current) => {
1010
1243
  const state = findMesh(current.meshes, request.meshId);
1011
1244
  if (!state || state.roster.authorityPublicKey !== incomingRoster.authorityPublicKey) {
1012
1245
  return {
@@ -1016,12 +1249,12 @@ class PeerMeshNodeImpl {
1016
1249
  }
1017
1250
  const roster = selectRoster(state.roster, incomingRoster);
1018
1251
  const localPeerId = this.#peer.identity().peerId;
1019
- const localMember = !roster.roster.closed && roster.roster.members.includes(localPeerId);
1020
- const remoteMember = !roster.roster.closed && roster.roster.members.includes(remotePeerId);
1021
1252
  const updated = {
1022
1253
  ...state,
1023
1254
  roster,
1024
1255
  };
1256
+ const localMember = isActiveMembership(updated, localPeerId);
1257
+ const remoteMember = !roster.roster.closed && roster.roster.members.includes(remotePeerId);
1025
1258
  const routes = localMember && remoteMember
1026
1259
  ? mergeRoutes(current.routes, [remoteRoute], this.#now())
1027
1260
  : current.routes;
@@ -1047,6 +1280,9 @@ class PeerMeshNodeImpl {
1047
1280
  },
1048
1281
  };
1049
1282
  });
1283
+ if (response.kind === 'sync-result')
1284
+ await this.#reconcileTransit();
1285
+ return response;
1050
1286
  }
1051
1287
  async #reconcileTransit() {
1052
1288
  const stored = this.#store.read();
@@ -1065,10 +1301,17 @@ class PeerMeshNodeImpl {
1065
1301
  })
1066
1302
  .sort((left, right) => left.route.peerId.localeCompare(right.route.peerId));
1067
1303
  const relayCandidates = transitRelayCandidates(eligibleRelays);
1304
+ const approvedRelayPeerIds = [
1305
+ ...new Set(stored.meshes
1306
+ .filter((mesh) => isActiveMembership(mesh, localPeerId))
1307
+ .flatMap((mesh) => mesh.roster.roster.members)
1308
+ .filter((peerId) => peerId !== localPeerId)),
1309
+ ].sort();
1068
1310
  await this.#peer.configureTransit({
1069
1311
  allowedPeerIds: selected
1070
1312
  ? selected.roster.roster.members.filter((peerId) => peerId !== localPeerId)
1071
1313
  : [],
1314
+ approvedRelayPeerIds,
1072
1315
  relayCandidates,
1073
1316
  });
1074
1317
  }
@@ -1154,6 +1397,16 @@ function currentAuthorityTarget(state, routes) {
1154
1397
  const learned = routes.find(({ route }) => route.peerId === state.authority.peerId)?.route;
1155
1398
  return learned ? mergeTargets(learned, state.authority) : state.authority;
1156
1399
  }
1400
+ function rosterAnnouncementTargets(memberPeerIds, routes, localPeerId) {
1401
+ const members = new Set(memberPeerIds);
1402
+ return Object.freeze(routes
1403
+ .filter(({ route }) => route.peerId !== localPeerId && members.has(route.peerId))
1404
+ .map(({ route }) => Object.freeze({
1405
+ peerId: route.peerId,
1406
+ routeHints: route.routeHints,
1407
+ coordinationRelays: route.coordinationRelays,
1408
+ })));
1409
+ }
1157
1410
  function requireAuthority(states, meshId) {
1158
1411
  const state = findMesh(states, meshId);
1159
1412
  if (!state || state.role !== 'authority')
@@ -1183,21 +1436,26 @@ function authorityTarget(identity) {
1183
1436
  coordinationRelays: identity.coordinationRelays,
1184
1437
  });
1185
1438
  }
1186
- function assertMeshCapacity(states, localPeerId) {
1187
- if (states.filter((state) => isActiveMembership(state, localPeerId)).length >= PEER_MESH_MAX_MESHES) {
1439
+ function assertMeshCapacity(states, localPeerId, pendingJoinCount = 0) {
1440
+ if (states.filter((state) => !isRetired(state, localPeerId)).length + pendingJoinCount >=
1441
+ PEER_MESH_MAX_MESHES) {
1188
1442
  throw new Error('This peer belongs to too many Peer Meshes');
1189
1443
  }
1190
1444
  }
1191
1445
  function appendMesh(states, state, localPeerId) {
1192
1446
  if (states.length < PEER_MESH_MAX_MESHES)
1193
1447
  return [...states, state];
1194
- const retired = states.findIndex((candidate) => !isActiveMembership(candidate, localPeerId));
1448
+ const retired = states.findIndex((candidate) => isRetired(candidate, localPeerId));
1195
1449
  if (retired < 0)
1196
1450
  throw new Error('This peer belongs to too many Peer Meshes');
1197
1451
  return [...states.slice(0, retired), ...states.slice(retired + 1), state];
1198
1452
  }
1199
- function isActiveMembership(state, localPeerId) {
1200
- return !state.roster.roster.closed && state.roster.roster.members.includes(localPeerId);
1453
+ function assertRejoinSettled(state, localPeerId) {
1454
+ if (state?.role === 'replica' &&
1455
+ state.desiredMembership === 'left' &&
1456
+ state.roster.roster.members.includes(localPeerId)) {
1457
+ throw new Error('This Peer Mesh leave is still being reconciled');
1458
+ }
1201
1459
  }
1202
1460
  function selectRoster(current, candidate) {
1203
1461
  if (current.roster.meshId !== candidate.roster.meshId ||
@@ -1330,8 +1588,19 @@ function decodeControlRequest(value) {
1330
1588
  knownRoutes: decodeRouteSequences(record.knownRoutes),
1331
1589
  };
1332
1590
  }
1333
- if (record.kind === 'leave' && hasExactKeys(record, ['kind', 'meshId'])) {
1334
- return { kind: 'leave', meshId: requiredString(record.meshId, 128) };
1591
+ if (record.kind === 'leave' && hasExactKeys(record, ['kind', 'meshId', 'roster'])) {
1592
+ return {
1593
+ kind: 'leave',
1594
+ meshId: requiredString(record.meshId, 128),
1595
+ roster: decodeSignedPeerMeshRoster(record.roster),
1596
+ };
1597
+ }
1598
+ if (record.kind === 'announce-roster' && hasExactKeys(record, ['kind', 'meshId', 'roster'])) {
1599
+ return {
1600
+ kind: 'announce-roster',
1601
+ meshId: requiredString(record.meshId, 128),
1602
+ roster: decodeSignedPeerMeshRoster(record.roster),
1603
+ };
1335
1604
  }
1336
1605
  throw new Error('Unsupported Peer Mesh control request');
1337
1606
  }
@@ -1385,6 +1654,18 @@ function decodeLeaveResponse(value) {
1385
1654
  }
1386
1655
  throw new Error('Invalid Peer Mesh leave response');
1387
1656
  }
1657
+ function decodeAnnounceRosterResponse(value) {
1658
+ const record = recordValue(value);
1659
+ if (record.kind === 'roster-observed' && hasExactKeys(record, ['kind'])) {
1660
+ return { kind: 'roster-observed' };
1661
+ }
1662
+ if (record.kind === 'roster-rejected' &&
1663
+ hasExactKeys(record, ['kind', 'reason']) &&
1664
+ record.reason === 'unknown') {
1665
+ return { kind: 'roster-rejected', reason: 'unknown' };
1666
+ }
1667
+ throw new Error('Invalid Peer Mesh roster announcement response');
1668
+ }
1388
1669
  function decodeRoutePage(value) {
1389
1670
  if (!Array.isArray(value) || value.length > ROUTE_PAGE_SIZE) {
1390
1671
  throw new Error('Invalid Peer Mesh route page');