@qvac/core 1.0.0-rc.6 → 1.0.0-rc.7

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 (48) hide show
  1. package/dist-lib/lib/api/agents.js +5 -2
  2. package/dist-lib/lib/api/approval-rules.js +8 -5
  3. package/dist-lib/lib/api/chat.d.ts +1 -2
  4. package/dist-lib/lib/api/chat.js +4 -18
  5. package/dist-lib/lib/api/index.d.ts +0 -1
  6. package/dist-lib/lib/api/index.js +1 -2
  7. package/dist-lib/lib/api/mesh.d.ts +1 -1
  8. package/dist-lib/lib/api/mesh.js +1 -1
  9. package/dist-lib/lib/api/sync.js +12 -2
  10. package/dist-lib/lib/assistant.d.ts +0 -1
  11. package/dist-lib/lib/assistant.js +10 -13
  12. package/dist-lib/lib/core/archived-mesh.d.ts +1 -0
  13. package/dist-lib/lib/core/archived-mesh.js +11 -14
  14. package/dist-lib/lib/core/chat-copy.d.ts +0 -1
  15. package/dist-lib/lib/core/chat-copy.js +1 -2
  16. package/dist-lib/lib/core/chat-move.d.ts +3 -1
  17. package/dist-lib/lib/core/chat-move.js +5 -2
  18. package/dist-lib/lib/core/contract/joined-meshes.js +2 -1
  19. package/dist-lib/lib/core/local/index.d.ts +2 -1
  20. package/dist-lib/lib/core/local/index.js +3 -2
  21. package/dist-lib/lib/core/public-mesh.d.ts +6 -8
  22. package/dist-lib/lib/core/public-mesh.js +19 -29
  23. package/dist-lib/lib/core/sync/index.js +1 -1
  24. package/dist-lib/lib/core.d.ts +15 -8
  25. package/dist-lib/lib/core.js +219 -203
  26. package/dist-lib/lib/errors.d.ts +4 -12
  27. package/dist-lib/lib/errors.js +4 -12
  28. package/dist-lib/schema/engine.js +10 -3
  29. package/dist-lib/schema/local.js +4 -2
  30. package/dist-lib/schema/qvac.js +2 -1
  31. package/dist-lib/spec/capabilities.d.ts +2 -2
  32. package/dist-lib/spec/hrpc/hrpc.json +1 -1
  33. package/dist-lib/spec/hrpc/index.js +1 -1
  34. package/dist-lib/spec/hrpc/messages.js +273 -250
  35. package/dist-lib/spec/hyperschema/index.js +273 -250
  36. package/dist-lib/spec/hyperschema/schema.json +27 -6
  37. package/dist-lib/spec/hyperschema/types.d.ts +7 -1
  38. package/dist-lib/spec/local/hyperdb/messages.js +26 -12
  39. package/dist-lib/spec/local/hyperschema/index.js +13 -6
  40. package/dist-lib/spec/local/hyperschema/schema.json +10 -0
  41. package/dist-lib/spec/local/hyperschema/types.d.ts +2 -0
  42. package/dist-lib/spec/mesh/hyperdb/messages.js +30 -6
  43. package/dist-lib/spec/mesh/hyperdispatch/messages.js +15 -3
  44. package/dist-lib/spec/mesh/hyperschema/index.js +15 -3
  45. package/dist-lib/spec/mesh/hyperschema/schema.json +5 -0
  46. package/dist-lib/spec/mesh/hyperschema/types.d.ts +1 -0
  47. package/package.json +1 -1
  48. package/tui/app.mjs +47 -12
@@ -36,7 +36,7 @@ import { cancelDeletedAgentRuns } from './core/deleted-agent-runs.js';
36
36
  import { devicesOfMember } from './core/contract/activity.js';
37
37
  import { followPickedAgents, followSharedAgents, ownerOf, liveSharedAgent, pickAgent, shareAgent, unpickAgent } from './core/shared-agents.js';
38
38
  import { inRole, publicRoute } from './core/contract/roles.js';
39
- import { freshPublicRecord, isOwnWorkspace, isPublicRecord, lostMint, onOwnSeed, leftPublicRecordKey, ownWorkspaceSeed, ownWorkspaces, publicMeshKey, publicRecordKey, publicSeed, servesAgents, servesChat, servesChunk } from './core/public-mesh.js';
39
+ import { freshPublicRecord, isPublicRecord, leftPublicRecordKey, derivedSeed, oldChats, ourRows, publicMeshKey, publicRecordKey, publicSeed, servesAgents, servesChat, servesChunk } from './core/public-mesh.js';
40
40
  import { memberBoxKeyPair, openSealedToMember } from './core/member-key.js';
41
41
  import { dueProjectDeviceKeys, dueProjectHostKey, dueProjectKey, seedFingerprint, seedOpens } from './core/project-keys.js';
42
42
  import { projectDeviceKeys } from './core/contract/project-device-keys.js';
@@ -213,14 +213,16 @@ export class Core extends ReadyResource {
213
213
  _publicBoots = new Map();
214
214
  _meshNames = new Map();
215
215
  _ownWorkspaceId = null;
216
+ _ownDecided = null;
216
217
  _publicWriters = new WeakMap();
217
218
  _leftPublic = new WeakSet();
218
219
  _publicWaiters = new Set();
219
220
  _publicFollow = new ScopeLock({ debounce: true });
220
221
  _publicMerges = new Map();
221
- _publicCarries = new Map();
222
- _ownCarries = new Map();
222
+ _publicDrops = new Map();
223
223
  _publicMigration = null;
224
+ _copyAgain = false;
225
+ _accountCopied = null;
224
226
  _agentCopies = new ScopeLock({ debounce: true });
225
227
  _sharedAgents = new ScopeLock({ debounce: true });
226
228
  _memberKeyWrites = new WeakMap();
@@ -240,6 +242,7 @@ export class Core extends ReadyResource {
240
242
  _backfill = Promise.resolve();
241
243
  _leaving;
242
244
  _kickedMeshes = new Set();
245
+ _haltedMeshes = new Set();
243
246
  _kickCloses = new Map();
244
247
  _retiredMeshes = new Set();
245
248
  _retiredAccount = null;
@@ -472,7 +475,8 @@ export class Core extends ReadyResource {
472
475
  deviceId,
473
476
  log: this._log,
474
477
  account: () => this._accountMesh(),
475
- agents: this._agentPicks()
478
+ agents: this._agentPicks(),
479
+ meshIdOf: (key) => this._workspaceOfPublic(b4a.toHex(key))
476
480
  })
477
481
  : null;
478
482
  const api = createApi({
@@ -522,11 +526,6 @@ export class Core extends ReadyResource {
522
526
  const id = b4a.toHex(projectKey);
523
527
  return this._pooled(id)?.name ?? this._meshNames.get(id) ?? null;
524
528
  },
525
- workspaceOf: async (projectId) => {
526
- const key = (await this.local.readMeshSession(this._meshKeyOf(projectId)))?.workspaceKey;
527
- const workspaceId = key ? b4a.toHex(key) : null;
528
- return workspaceId === this._ownWorkspaceId ? null : workspaceId;
529
- },
530
529
  pushSkillSecret: (request) => this.pushSkillSecret(request),
531
530
  beforeConfigSet: (entry) => validateVaultManagedSkill(this._vaultManagedSkills, entry),
532
531
  onConfigSet: async (entry) => {
@@ -1239,7 +1238,7 @@ export class Core extends ReadyResource {
1239
1238
  const session = await this.local.resolveSession(this._requireDeviceKeyPair().publicKey, opts);
1240
1239
  return this._openMeshSession(session, opts);
1241
1240
  }
1242
- async _openMeshSession(session, { blindPeerKeys, account, sharing, workspace, project } = {}) {
1241
+ async _openMeshSession(session, { blindPeerKeys, account, initial, sharing, workspace, project } = {}) {
1243
1242
  const deviceId = this._requireDeviceKeyPair().publicKey;
1244
1243
  const mesh = this._newMesh(session, session.role ?? (account ? 'account' : 'project'), blindPeerKeys);
1245
1244
  try {
@@ -1258,6 +1257,7 @@ export class Core extends ReadyResource {
1258
1257
  await this._appendOwnBirth(mesh, session, {
1259
1258
  deviceId,
1260
1259
  account,
1260
+ initial,
1261
1261
  sharing,
1262
1262
  workspace,
1263
1263
  project
@@ -1265,8 +1265,8 @@ export class Core extends ReadyResource {
1265
1265
  }
1266
1266
  }
1267
1267
  catch (err) {
1268
- if (mesh.opened && mesh.interrupted && !this._upgradeRequired) {
1269
- this._setUpgradeRequired('halt');
1268
+ if (mesh.opened && mesh.interrupted) {
1269
+ this._markHalted(mesh);
1270
1270
  }
1271
1271
  await mesh.close().catch(noop);
1272
1272
  throw err;
@@ -1292,7 +1292,7 @@ export class Core extends ReadyResource {
1292
1292
  });
1293
1293
  return mesh;
1294
1294
  }
1295
- async _appendOwnBirth(mesh, session, { deviceId, account, sharing, workspace, project }) {
1295
+ async _appendOwnBirth(mesh, session, { deviceId, account, initial, sharing, workspace, project }) {
1296
1296
  await raceResource(mesh.autobee, (async () => {
1297
1297
  const birth = sharing
1298
1298
  ? await this._accountBirthMember(mesh, session)
@@ -1304,7 +1304,7 @@ export class Core extends ReadyResource {
1304
1304
  workspace,
1305
1305
  project
1306
1306
  });
1307
- await this.local.recordMesh(mesh.key, session, { deviceId, account });
1307
+ await this.local.recordMesh(mesh.key, session, { deviceId, account, initial });
1308
1308
  if (account && birth?.mnemonic) {
1309
1309
  await this._publishRecovery(birth.mnemonic, {
1310
1310
  meshKey: mesh.key,
@@ -1325,8 +1325,8 @@ export class Core extends ReadyResource {
1325
1325
  return appended.catch((err) => {
1326
1326
  if (this.closing || mesh.closing)
1327
1327
  return;
1328
- if (mesh.interrupted && !this._upgradeRequired) {
1329
- this._setUpgradeRequired('halt');
1328
+ if (mesh.interrupted) {
1329
+ this._markHalted(mesh);
1330
1330
  }
1331
1331
  this._log?.warn(['p2p', 'mesh'], 'appending the join failed', err);
1332
1332
  });
@@ -1715,9 +1715,9 @@ export class Core extends ReadyResource {
1715
1715
  throw new CoreError('AGENT_NOT_OURS');
1716
1716
  }
1717
1717
  if (request.operation === 'target') {
1718
- const mesh = await requireMesh(this._meshPool(), request.meshId ?? this._meshIdOf(account), {
1719
- route: 'put-chat'
1720
- });
1718
+ const mesh = request.meshId
1719
+ ? await requireMesh(this._meshPool(), request.meshId, { route: 'put-chat' })
1720
+ : account;
1721
1721
  const runner = await pickRunner(mesh, {
1722
1722
  deviceId,
1723
1723
  peers: this.peerDeviceIds,
@@ -2131,6 +2131,7 @@ export class Core extends ReadyResource {
2131
2131
  await this.local.dropMesh(key, { keepDeparture: true, cores });
2132
2132
  this._meshNames.delete(b4a.toHex(key));
2133
2133
  this._kickedMeshes.delete(b4a.toHex(key));
2134
+ this._haltedMeshes.delete(b4a.toHex(key));
2134
2135
  this._notifyStatus();
2135
2136
  }
2136
2137
  if (cores) {
@@ -2160,14 +2161,22 @@ export class Core extends ReadyResource {
2160
2161
  _withdrawFromMesh(mesh, err) {
2161
2162
  if (this.closing)
2162
2163
  return;
2163
- if (!this._upgradeRequired) {
2164
- this._log?.error(['p2p', 'mesh'], 'mesh needs a newer build - withdrawing from it', err);
2165
- this._setUpgradeRequired('halt');
2166
- }
2164
+ this._log?.error(['p2p', 'mesh'], 'mesh needs a newer build - withdrawing from it', err);
2165
+ this._markHalted(mesh);
2167
2166
  this._retirePooledMesh(mesh).catch((retireErr) => {
2168
2167
  this._log?.warn(['p2p', 'mesh'], 'retiring the stalled mesh failed', retireErr);
2169
2168
  });
2170
2169
  }
2170
+ _markHalted(mesh) {
2171
+ if (mesh.role === 'account' || this._isOwnPublic(mesh)) {
2172
+ if (!this._upgradeRequired) {
2173
+ this._setUpgradeRequired('halt');
2174
+ }
2175
+ return;
2176
+ }
2177
+ this._haltedMeshes.add(this._meshIdOf(mesh));
2178
+ this._notifyStatus();
2179
+ }
2171
2180
  async _reviewKick(mesh) {
2172
2181
  const entry = this._meshes.get(this._meshIdOf(mesh));
2173
2182
  if (entry?.mesh !== mesh || !(await entry.kickLock.lock())) {
@@ -2354,12 +2363,12 @@ export class Core extends ReadyResource {
2354
2363
  }
2355
2364
  }
2356
2365
  async _dropOwnMint(fresh) {
2357
- const seed = ownWorkspaceSeed(fresh.seed);
2358
- for (const row of await this.local.listMeshes()) {
2359
- if (!b4a.equals(row.seed, seed)) {
2366
+ const minted = new Set((await this.local.listMeshes()).filter((row) => row.initial).map((row) => b4a.toHex(row.key)));
2367
+ for (const joined of await fresh.view.find(JOINED_MESHES).toArray()) {
2368
+ const id = b4a.toHex(joined.meshKey);
2369
+ if (!minted.has(id)) {
2360
2370
  continue;
2361
2371
  }
2362
- const id = b4a.toHex(row.key);
2363
2372
  const own = this._publicMesh(id);
2364
2373
  if (own) {
2365
2374
  await this._teardownMesh(own, { purge: true });
@@ -2507,7 +2516,9 @@ export class Core extends ReadyResource {
2507
2516
  if (!invite) {
2508
2517
  throw new CoreError('INVITE_INVALID');
2509
2518
  }
2510
- await this._awaitMesh();
2519
+ if (!this.opened) {
2520
+ await this.ready();
2521
+ }
2511
2522
  this._requireLocalDevice();
2512
2523
  await this._meshTransitionLock.lock();
2513
2524
  let ownsTransition = false;
@@ -3395,10 +3406,6 @@ export class Core extends ReadyResource {
3395
3406
  void this._followPublicMesh(mesh);
3396
3407
  void this._followSkillSecrets();
3397
3408
  }
3398
- const account = this._accountMesh();
3399
- if (account && this._meshIdOf(mesh) === this._ownWorkspaceId) {
3400
- void this._followPublicMesh(account);
3401
- }
3402
3409
  if (this._isOwnPublic(mesh)) {
3403
3410
  void this._followAgentCopies();
3404
3411
  }
@@ -3482,7 +3489,7 @@ export class Core extends ReadyResource {
3482
3489
  return;
3483
3490
  void this._followAccountName(mesh);
3484
3491
  });
3485
- mesh.on('meshes-dirty', (changed, groupsChanged = false) => this._onMeshesDirty(entry, { changed, groupsChanged }));
3492
+ mesh.on('meshes-dirty', (changed, groupsChanged = false, chatsChanged = true) => this._onMeshesDirty(entry, { changed, groupsChanged, chatsChanged }));
3486
3493
  mesh.on('joined', () => {
3487
3494
  if (entry.meshesPending) {
3488
3495
  void this._followJoinedMeshes(mesh);
@@ -3511,10 +3518,10 @@ export class Core extends ReadyResource {
3511
3518
  this._listenMesh(mesh, handlers);
3512
3519
  this._startMeshServices(entry);
3513
3520
  this._startEntryIndexing(entry);
3514
- this._onMeshesDirty(entry, { changed: true, groupsChanged: true });
3521
+ this._onMeshesDirty(entry, { changed: true, groupsChanged: true, chatsChanged: true });
3515
3522
  this._reviewKick(mesh).catch((err) => this._log?.warn(['p2p', 'mesh'], 'reviewing a kick failed', err));
3516
3523
  }
3517
- _onMeshesDirty(entry, { changed, groupsChanged }) {
3524
+ _onMeshesDirty(entry, { changed, groupsChanged, chatsChanged }) {
3518
3525
  const { mesh } = entry;
3519
3526
  if (this._isHidden(this._meshIdOf(mesh), mesh.workspaceKey)) {
3520
3527
  return;
@@ -3532,9 +3539,14 @@ export class Core extends ReadyResource {
3532
3539
  if ((changed || groupsChanged) && mesh.role === 'workspace') {
3533
3540
  this._followGroups(mesh);
3534
3541
  }
3535
- if (this._isAccount(mesh) && (changed || entry.publicPending || !this._publicMesh())) {
3542
+ const opening = this._ownWorkspaceId !== null && !this._publicMesh();
3543
+ if (this._isAccount(mesh) && (changed || entry.publicPending || opening)) {
3536
3544
  void this._followPublicMesh(mesh);
3537
3545
  }
3546
+ const copying = chatsChanged || this._accountCopied === null;
3547
+ if (copying && this._isAccount(mesh) && this._ownWorkspaceId && this._publicMesh()) {
3548
+ this._migrateIntoPublic(mesh, b4a.from(this._ownWorkspaceId, 'hex'));
3549
+ }
3538
3550
  }
3539
3551
  _listenMesh(mesh, handlers) {
3540
3552
  mesh.autobee.on('writable', handlers.writable);
@@ -3590,18 +3602,16 @@ export class Core extends ReadyResource {
3590
3602
  this._log?.warn(['mesh'], 'backfilling the model pick failed', err);
3591
3603
  }
3592
3604
  }
3593
- _publicMesh(workspaceId = this._accountId) {
3605
+ _publicMesh(workspaceId = this._ownWorkspaceId) {
3594
3606
  return this._pooled(this._publicIdOf(workspaceId));
3595
3607
  }
3596
- _publicIdOf(meshId) {
3597
- const workspaceId = meshId !== null && meshId === this._accountId ? this._ownWorkspaceId : meshId;
3608
+ _publicIdOf(workspaceId) {
3598
3609
  return workspaceId === null ? null : (this._publicIds.get(workspaceId) ?? null);
3599
3610
  }
3600
3611
  _workspaceOfPublic(meshId) {
3601
3612
  for (const [workspaceId, publicId] of this._publicIds) {
3602
- if (publicId !== meshId)
3603
- continue;
3604
- return workspaceId === this._ownWorkspaceId ? (this._accountId ?? workspaceId) : workspaceId;
3613
+ if (publicId === meshId)
3614
+ return workspaceId;
3605
3615
  }
3606
3616
  return meshId;
3607
3617
  }
@@ -3669,14 +3679,11 @@ export class Core extends ReadyResource {
3669
3679
  }
3670
3680
  await workspace.dispatch('put-member-key', { memberId, boxKey });
3671
3681
  }
3672
- _contentMesh() {
3673
- return this._publicMesh() ?? this._accountMesh();
3674
- }
3675
3682
  _devicesOf(mesh) {
3676
3683
  return this._isOwnPublic(mesh) ? (this._accountMesh() ?? mesh) : mesh;
3677
3684
  }
3678
3685
  _hasPublic(mesh) {
3679
- return this._isAccount(mesh) || (mesh.role === 'workspace' && this._isPooled(mesh));
3686
+ return mesh.role === 'workspace' && this._isPooled(mesh);
3680
3687
  }
3681
3688
  async _publicOf(scope, { follow = false } = {}) {
3682
3689
  const workspaceId = this._meshIdOf(scope);
@@ -3782,34 +3789,72 @@ export class Core extends ReadyResource {
3782
3789
  return settled;
3783
3790
  }
3784
3791
  async _settleOwnWorkspace(account) {
3785
- const { own, lost } = await ownWorkspaces(account);
3786
- if (own && account.writable) {
3787
- for (const joined of lost) {
3788
- this._carryLostMint(account, { own, joined });
3789
- }
3790
- }
3791
- const mints = account.minted || !(await bornUnderRules(account.view));
3792
+ if (this._localDevice && !account.ourMemberId) {
3793
+ return;
3794
+ }
3795
+ const local = (await this.local.listMeshes()).filter((row) => !b4a.equals(row.key, account.key) &&
3796
+ !row.workspaceKey &&
3797
+ !this._isHidden(b4a.toHex(row.key)));
3798
+ const rows = await ourRows(account);
3799
+ const ours = local.filter((row) => !row.joinedAt || rows.some((joined) => b4a.equals(joined.meshKey, row.key)));
3800
+ const own = ours
3801
+ .filter((row) => row.initial && !row.kicked)
3802
+ .sort((a, b) => (b.joinedAt || Infinity) - (a.joinedAt || Infinity))[0];
3803
+ const mints = !own &&
3804
+ !(await this._markDerivedInitial(account, rows)) &&
3805
+ (await this._mintsOwnWorkspace(account, { rows, local: ours }));
3792
3806
  if (!this._isAccount(account)) {
3793
3807
  return;
3794
3808
  }
3795
- if (own || !mints) {
3796
- this._setOwnWorkspace(own ? b4a.toHex(own) : null);
3797
- return;
3809
+ this._setOwnWorkspace(own ? b4a.toHex(own.key) : null);
3810
+ if (mints) {
3811
+ await this._mintOwnWorkspace(account);
3812
+ }
3813
+ if (account.writable && this._ownDecided !== account) {
3814
+ this._ownDecided = account;
3815
+ this._notifyStatus();
3798
3816
  }
3799
- await this._mintOwnWorkspace(account);
3800
3817
  }
3801
- async _mintOwnWorkspace(account) {
3802
- const seed = ownWorkspaceSeed(account.seed);
3803
- const recorded = (await this.local.listMeshes()).find((row) => b4a.equals(row.seed, seed));
3804
- if (recorded) {
3805
- await this._openPooledMesh(b4a.toHex(recorded.key), 'follow');
3806
- return;
3818
+ async _mintsOwnWorkspace(account, { rows, local }) {
3819
+ if (!rows.length && !local.length) {
3820
+ return account.minted || !(await bornUnderRules(account.view));
3821
+ }
3822
+ return !rows.some((row) => row.initial) && !!(await oldChats(account))?.messages;
3823
+ }
3824
+ async _markDerivedInitial(account, rows) {
3825
+ if (rows.some((row) => row.initial)) {
3826
+ return false;
3827
+ }
3828
+ const derived = derivedSeed(account);
3829
+ for (const { meshKey, memberId, joinedAt } of rows) {
3830
+ const held = await account.view.get(MESH_SEEDS, { meshKey });
3831
+ if (held && b4a.equals(held.seed, derived)) {
3832
+ if (account.writable) {
3833
+ await account.dispatch('put-joined-mesh', {
3834
+ room: { meshKey, memberId, joinedAt, initial: true }
3835
+ });
3836
+ }
3837
+ return true;
3838
+ }
3807
3839
  }
3840
+ return false;
3841
+ }
3842
+ async _mintOwnWorkspace(account) {
3808
3843
  if (!account.writable || !account.ourMemberId) {
3809
3844
  return;
3810
3845
  }
3811
3846
  const workspace = { name: await this._defaultWorkspaceName(account) };
3812
- this._setOwnWorkspace(await this._mintMesh({ shared: false, workspace, registry: account, seed }));
3847
+ const minted = await this._mintMesh({
3848
+ shared: false,
3849
+ workspace,
3850
+ registry: account,
3851
+ initial: true
3852
+ });
3853
+ if (!this._isAccount(account)) {
3854
+ await this._teardownMesh(this._pooled(minted) ?? b4a.from(minted, 'hex'));
3855
+ return;
3856
+ }
3857
+ this._setOwnWorkspace(minted);
3813
3858
  }
3814
3859
  _setOwnWorkspace(workspaceId) {
3815
3860
  if (this._ownWorkspaceId !== workspaceId) {
@@ -3828,13 +3873,13 @@ export class Core extends ReadyResource {
3828
3873
  }
3829
3874
  const held = this._pooled(publicId);
3830
3875
  this._publicIds.delete(workspaceId);
3831
- const carried = held?.workspaceKey && (await this._publicRecord(account, held.workspaceKey))?.key;
3832
- if (held && !carried) {
3876
+ const recorded = held?.workspaceKey && (await this._publicRecord(account, held.workspaceKey))?.key;
3877
+ if (held && !recorded) {
3833
3878
  await this._teardownMesh(held);
3834
3879
  }
3835
3880
  }
3836
3881
  for (const workspaceKey of await this._leftWorkspaces(account)) {
3837
- this._carryLeftPublic(account, workspaceKey);
3882
+ this._dropLeftPublic(account, workspaceKey);
3838
3883
  }
3839
3884
  }
3840
3885
  async _leftWorkspaces(account) {
@@ -3848,120 +3893,31 @@ export class Core extends ReadyResource {
3848
3893
  }
3849
3894
  return keys;
3850
3895
  }
3851
- _carryLostMint(account, { own: ownKey, joined }) {
3852
- const lostId = b4a.toHex(joined.meshKey);
3853
- if (this._ownCarries.has(lostId)) {
3854
- return;
3855
- }
3856
- const carry = (async () => {
3857
- const lost = await this._heldMesh(joined.meshKey);
3858
- const own = lost && (await this._heldMesh(ownKey));
3859
- if (!lost || !own) {
3860
- return;
3861
- }
3862
- await own.waitForWritable();
3863
- if (!this._isAccount(account) || !this._isPooled(own) || !this._isPooled(lost)) {
3864
- return;
3865
- }
3866
- await lost.autobee.update();
3867
- await this._carryProjects(account, { lost, own }, joined.memberId);
3868
- if (!joined.leftAt) {
3869
- await this._releaseJoinedMesh(joined.meshKey, account);
3870
- }
3871
- this._log?.info(['p2p', 'mesh'], 'carried a lost mint of your own workspace into the winner', {
3872
- lost: lostId.slice(0, 8),
3873
- winner: this._meshIdOf(own).slice(0, 8)
3874
- });
3875
- await this._teardownMesh(lost);
3876
- })()
3877
- .catch((err) => {
3878
- if (!this.closing) {
3879
- this._log?.warn(['p2p', 'mesh'], 'carrying a lost mint of your own workspace failed', err);
3880
- }
3881
- })
3882
- .finally(() => {
3883
- this._ownCarries.delete(lostId);
3884
- });
3885
- this._ownCarries.set(lostId, carry);
3886
- }
3887
- async _carryProjects(account, mints, ours) {
3888
- const { lost, own } = mints;
3889
- const deviceId = this._requireDeviceKeyPair().publicKey;
3890
- const rows = await lost.view.find(PROJECTS).toArray();
3891
- for (const row of rows.filter((listed) => listedProject(listed, ours))) {
3892
- const session = await this.local.readMeshSession(row.id);
3893
- const seed = session?.seed ?? (await this._ownProjectSeed(lost, row.id));
3894
- if (!seed) {
3895
- continue;
3896
- }
3897
- const { createdAt, updatedAt } = row;
3898
- await this._listProject(own, { key: row.id, seed }, { createdAt, updatedAt });
3899
- if (session && (await this._isProjectOf(lost.key, row.id))) {
3900
- await this.local.recordMesh(row.id, { ...session, workspaceKey: own.key }, { deviceId });
3901
- }
3902
- await this._carryAgentUsers(account, mints, row.id);
3903
- }
3904
- }
3905
- async _carryAgentUsers(account, { lost, own }, projectId) {
3906
- const batch = own.batch();
3907
- for (const { agentId, userId } of await lost.view.find(AGENT_USERS).toArray()) {
3908
- if (!b4a.equals(userId, projectId) || !(await liveSharedAgent(lost, agentId))) {
3909
- continue;
3910
- }
3911
- try {
3912
- await shareAgent(account, own, agentId);
3913
- }
3914
- catch (err) {
3915
- if (!(err instanceof CoreError)) {
3916
- throw err;
3917
- }
3918
- this._log?.warn(['p2p', 'mesh'], 'a lost mint kept a shared agent the winner refuses', {
3919
- agentId,
3920
- code: err.code
3921
- });
3922
- continue;
3923
- }
3924
- if (!(await own.view.get(AGENT_USERS, { agentId, userId }))) {
3925
- batch.dispatch('put-agent-user', { agentId, projectId });
3926
- }
3927
- }
3928
- await batch.flush();
3929
- }
3930
- _carryLeftPublic(account, workspaceKey) {
3896
+ _dropLeftPublic(account, workspaceKey) {
3931
3897
  const workspaceId = b4a.toHex(workspaceKey);
3932
- if (this._publicCarries.has(workspaceId)) {
3898
+ if (this._publicDrops.has(workspaceId)) {
3933
3899
  return;
3934
3900
  }
3935
- const carry = (async () => {
3901
+ const drop = (async () => {
3936
3902
  const record = await this._publicRecord(account, workspaceKey);
3937
- const into = record?.key ? await this._publicOf(account, { follow: true }) : null;
3938
- if (!record?.key || !into || into === account) {
3903
+ if (!record?.key || !this._isAccount(account)) {
3939
3904
  return;
3940
3905
  }
3941
- const from = this._pooled(record.key) ?? (await this._openPublicMesh(account, { workspaceKey, record }));
3942
- await into.waitForWritable();
3943
- if (!this._isAccount(account) || !this._isPooled(into) || !this._isPooled(from)) {
3944
- return;
3945
- }
3946
- const deviceId = this._requireDeviceKeyPair().publicKey;
3947
- const unlinkProjects = !(await onOwnSeed(account, workspaceKey));
3948
- await copyContent({ from, into, deviceId, unlinkProjects });
3949
3906
  await this.local.deleteAll([publicRecordKey(account.key, workspaceKey)]);
3950
- this._log?.info(['p2p', 'mesh'], "copied a left workspace's private chats into your own", {
3951
- workspace: workspaceId.slice(0, 8),
3952
- into: this._meshIdOf(into).slice(0, 8)
3907
+ this._log?.info(['p2p', 'mesh'], "dropped a left workspace's private chats", {
3908
+ workspace: workspaceId.slice(0, 8)
3953
3909
  });
3954
- await this._teardownMesh(from);
3910
+ await this._teardownMesh(this._pooled(record.key) ?? b4a.from(record.key, 'hex'));
3955
3911
  })()
3956
3912
  .catch((err) => {
3957
3913
  if (!this.closing) {
3958
- this._log?.warn(['p2p', 'mesh'], "copying a left workspace's chats failed", err);
3914
+ this._log?.warn(['p2p', 'mesh'], "dropping a left workspace's chats failed", err);
3959
3915
  }
3960
3916
  })
3961
3917
  .finally(() => {
3962
- this._publicCarries.delete(workspaceId);
3918
+ this._publicDrops.delete(workspaceId);
3963
3919
  });
3964
- this._publicCarries.set(workspaceId, carry);
3920
+ this._publicDrops.set(workspaceId, drop);
3965
3921
  }
3966
3922
  async _settlePublicMesh(account, workspaceKey) {
3967
3923
  const workspaceId = b4a.toHex(workspaceKey);
@@ -4110,12 +4066,24 @@ export class Core extends ReadyResource {
4110
4066
  this._publicMerges.set(workspaceId, merge);
4111
4067
  }
4112
4068
  _migrateIntoPublic(account, workspaceKey) {
4113
- if (this._publicMigration)
4069
+ if (this._publicMigration) {
4070
+ this._copyAgain = true;
4114
4071
  return;
4072
+ }
4115
4073
  this._publicMigration = (async () => {
4116
- const record = await this._publicRecord(account, workspaceKey);
4117
4074
  const into = this._publicMesh(b4a.toHex(workspaceKey));
4118
- if (!record || record.migrated || !into) {
4075
+ const workspace = into && (await this._heldMesh(workspaceKey));
4076
+ if (!into || !workspace?.minted) {
4077
+ return;
4078
+ }
4079
+ const chats = await oldChats(account);
4080
+ const copied = `${this._meshIdOf(account)}:${chats?.mark}`;
4081
+ if (this._accountCopied === copied) {
4082
+ return;
4083
+ }
4084
+ if (!chats) {
4085
+ await this._recordCopied(account, workspaceKey);
4086
+ this._accountCopied = copied;
4119
4087
  return;
4120
4088
  }
4121
4089
  await into.waitForWritable();
@@ -4128,8 +4096,10 @@ export class Core extends ReadyResource {
4128
4096
  deviceId: this._requireDeviceKeyPair().publicKey,
4129
4097
  endsOpenRuns: true
4130
4098
  });
4131
- const latest = (await this._publicRecord(account, workspaceKey)) ?? record;
4132
- await this._savePublicRecord(account, workspaceKey, { ...latest, migrated: true });
4099
+ await this._recordCopied(account, workspaceKey);
4100
+ if (await this._markCopied(account, workspaceKey)) {
4101
+ this._accountCopied = copied;
4102
+ }
4133
4103
  this._log?.info(['p2p', 'mesh'], 'copied the account into its public mesh', {
4134
4104
  mesh: this._meshIdOf(into).slice(0, 8)
4135
4105
  });
@@ -4141,8 +4111,31 @@ export class Core extends ReadyResource {
4141
4111
  })
4142
4112
  .finally(() => {
4143
4113
  this._publicMigration = null;
4114
+ if (this._copyAgain && !this.closing) {
4115
+ this._copyAgain = false;
4116
+ this._migrateIntoPublic(account, workspaceKey);
4117
+ }
4144
4118
  });
4145
4119
  }
4120
+ async _recordCopied(account, workspaceKey) {
4121
+ const record = await this._publicRecord(account, workspaceKey);
4122
+ if (record && !record.migrated) {
4123
+ await this._savePublicRecord(account, workspaceKey, { ...record, migrated: true });
4124
+ }
4125
+ }
4126
+ async _markCopied(account, workspaceKey) {
4127
+ const row = await account.view.get(JOINED_MESHES, { meshKey: workspaceKey });
4128
+ if (!row || !account.writable) {
4129
+ return false;
4130
+ }
4131
+ if (!row.initial) {
4132
+ const { meshKey, memberId, joinedAt } = row;
4133
+ await account.dispatch('put-joined-mesh', {
4134
+ room: { meshKey, memberId, joinedAt, initial: true }
4135
+ });
4136
+ }
4137
+ return true;
4138
+ }
4146
4139
  async _followAgentCopies(agentId) {
4147
4140
  if (!agentId && !(await this._agentCopies.lock()))
4148
4141
  return;
@@ -4895,9 +4888,6 @@ export class Core extends ReadyResource {
4895
4888
  requireWorkspace(departing, meshId);
4896
4889
  }
4897
4890
  const account = this._accountMesh();
4898
- if (account && isOwnWorkspace(account, departing)) {
4899
- throw new CoreError('OWN_WORKSPACE_LEAVE_REFUSED');
4900
- }
4901
4891
  const kicked = this._kickedMeshes.has(meshId) && departing !== account;
4902
4892
  const member = departing.role === 'workspace' && !kicked ? await this._leavingMember(departing) : null;
4903
4893
  const leavingAccount = await this._isStoredAccount(departing);
@@ -5115,7 +5105,7 @@ export class Core extends ReadyResource {
5115
5105
  const counts = await this._withArchivedMesh(row, (mesh, archived) => countContents(mesh, account, archived));
5116
5106
  return { meshId, ...counts };
5117
5107
  }
5118
- async migrateArchivedMesh(meshId) {
5108
+ async migrateArchivedMesh(meshId, workspaceId) {
5119
5109
  if (!this.opened)
5120
5110
  await this.ready();
5121
5111
  await this._meshTransitionLock.lock();
@@ -5126,22 +5116,33 @@ export class Core extends ReadyResource {
5126
5116
  const row = await this._archivedRow(meshId);
5127
5117
  if (row.migratedAt) {
5128
5118
  const none = { chats: 0, agents: 0, knowledge: 0 };
5129
- return { meshId, migrated: false, migratedAt: row.migratedAt, ...none };
5119
+ return { meshId, workspaceId, migrated: false, migratedAt: row.migratedAt, ...none };
5130
5120
  }
5131
5121
  const account = await this._writableAccount();
5132
5122
  if (!account) {
5133
5123
  throw new CoreError('ACCOUNT_NOT_WRITABLE');
5134
5124
  }
5135
- const into = await this._publicOf(account);
5125
+ const into = await this._archiveDestination(workspaceId);
5136
5126
  const counts = await this._withArchivedMesh(row, (mesh, archived) => migrateContents(mesh, into, { from: archived, into: account }));
5137
5127
  const migratedAt = Date.now();
5138
5128
  await this.local.markMeshMigrated(row.key, migratedAt);
5139
- return { meshId, migrated: true, migratedAt, ...counts };
5129
+ return { meshId, workspaceId, migrated: true, migratedAt, ...counts };
5140
5130
  }
5141
5131
  finally {
5142
5132
  this._meshTransitionLock.unlock();
5143
5133
  }
5144
5134
  }
5135
+ async _archiveDestination(workspaceId) {
5136
+ const workspace = await this._heldMesh(this._meshKeyOf(workspaceId));
5137
+ if (workspace?.role !== 'workspace' || this._isHidden(workspaceId)) {
5138
+ throw new CoreError('MESH_NOT_FOUND', [workspaceId]);
5139
+ }
5140
+ const into = await this._publicOf(workspace);
5141
+ if (into.role !== 'public' || !into.writable) {
5142
+ throw new CoreError('MESH_STILL_JOINING');
5143
+ }
5144
+ return into;
5145
+ }
5145
5146
  async _archivedRow(meshId) {
5146
5147
  const key = this._meshKeyOf(meshId);
5147
5148
  const row = (await this.local.listArchivedMeshes()).find((row) => b4a.equals(row.key, key));
@@ -5433,7 +5434,7 @@ export class Core extends ReadyResource {
5433
5434
  });
5434
5435
  }
5435
5436
  async _mintMesh(opts) {
5436
- const { shared, workspace, seed } = opts;
5437
+ const { shared, workspace, initial } = opts;
5437
5438
  if (this.closing) {
5438
5439
  throw new CoreError('CORE_CLOSING', ['Core']);
5439
5440
  }
@@ -5451,7 +5452,7 @@ export class Core extends ReadyResource {
5451
5452
  throw new CoreError('ACCOUNT_MEMBER_UNKNOWN');
5452
5453
  }
5453
5454
  const role = workspace ? 'workspace' : undefined;
5454
- const mesh = await this._openMesh({ new: true, sharing: true, role, workspace, seed });
5455
+ const mesh = await this._openMesh({ new: true, sharing: true, role, workspace, initial });
5455
5456
  this._wireMesh(this._poolEntry(mesh));
5456
5457
  this._bringMeshOnline(mesh, { new: true });
5457
5458
  try {
@@ -5599,11 +5600,12 @@ export class Core extends ReadyResource {
5599
5600
  const mesh = this._pooled(meshId);
5600
5601
  const account = !!accountKey && b4a.equals(accountKey, row.key);
5601
5602
  const joined = meshes.get(meshId);
5602
- const state = this._meshEntryState(mesh, account);
5603
+ const state = this._meshEntryState(meshId, mesh, account);
5604
+ const content = row.role !== 'workspace' || !this._accountMesh()?.ourMemberId;
5603
5605
  return {
5604
5606
  meshId,
5605
5607
  state,
5606
- writable: mesh?.writable ?? false,
5608
+ writable: !!mesh?.writable && (content || !!this._publicMesh(meshId)?.writable),
5607
5609
  open: mesh !== null,
5608
5610
  account,
5609
5611
  label: joined?.label || undefined,
@@ -5614,10 +5616,12 @@ export class Core extends ReadyResource {
5614
5616
  workspace: row.role === 'workspace'
5615
5617
  };
5616
5618
  }
5617
- _meshEntryState(mesh, account) {
5619
+ _meshEntryState(meshId, mesh, account) {
5618
5620
  if (account) {
5619
5621
  return this._statusState();
5620
5622
  }
5623
+ if (this._haltedMeshes.has(meshId))
5624
+ return 'needs-upgrade';
5621
5625
  if (!mesh)
5622
5626
  return 'idle';
5623
5627
  return mesh.writable ? 'joined' : 'joining';
@@ -5784,8 +5788,7 @@ export class Core extends ReadyResource {
5784
5788
  return {
5785
5789
  meshId: key ? b4a.toHex(key) : undefined,
5786
5790
  writable: this._accountWritable(),
5787
- displayName: (await this.displayName()) ?? undefined,
5788
- ownWorkspace: this._ownWorkspaceId ?? undefined
5791
+ displayName: (await this.displayName()) ?? undefined
5789
5792
  };
5790
5793
  }
5791
5794
  async displayName() {
@@ -5876,9 +5879,6 @@ export class Core extends ReadyResource {
5876
5879
  if (!isOwnMesh) {
5877
5880
  throw new CoreError(mesh.writable ? 'MEMBER_INVITE_ACCOUNT_REFUSED' : 'MESH_STILL_JOINING');
5878
5881
  }
5879
- if (isOwnWorkspace(registry, mesh)) {
5880
- throw new CoreError('OWN_WORKSPACE_INVITE_REFUSED');
5881
- }
5882
5882
  if (workspace) {
5883
5883
  await requireOurAdmin(mesh, 'invite a member');
5884
5884
  }
@@ -5934,8 +5934,7 @@ export class Core extends ReadyResource {
5934
5934
  }
5935
5935
  async _publicHeads() {
5936
5936
  const heads = [];
5937
- const ids = new Set([this._publicIdOf(this._accountId), ...this._publicIds.values()]);
5938
- for (const meshId of ids) {
5937
+ for (const meshId of new Set(this._publicIds.values())) {
5939
5938
  const mesh = this._pooled(meshId);
5940
5939
  const head = mesh && (await inviteHead(mesh));
5941
5940
  if (head) {
@@ -6138,9 +6137,6 @@ export class Core extends ReadyResource {
6138
6137
  }
6139
6138
  const held = this._pooled(meshId);
6140
6139
  const failed = await this._trackFollow(meshId, async () => {
6141
- if (await lostMint(memberMesh, joined.meshKey)) {
6142
- return;
6143
- }
6144
6140
  if (joined.kicked && !joined.leftAt) {
6145
6141
  await this._followKick(meshId, held);
6146
6142
  return;
@@ -6168,6 +6164,7 @@ export class Core extends ReadyResource {
6168
6164
  }
6169
6165
  if (await this.local.readMeshSession(joined.meshKey)) {
6170
6166
  if (this._upgradeRequired !== 'halt' &&
6167
+ !this._haltedMeshes.has(meshId) &&
6171
6168
  (await this.local.awaitsAdmission(joined.meshKey))) {
6172
6169
  tally.readmitted++;
6173
6170
  await this._openPooledMesh(meshId, 'readmit');
@@ -6235,10 +6232,13 @@ export class Core extends ReadyResource {
6235
6232
  }
6236
6233
  }
6237
6234
  async _openFollowedMesh(memberMesh, joined) {
6238
- if (this._blockedByMinVersion() || this._upgradeRequired || !this._mayFollow(memberMesh)) {
6235
+ const { meshKey } = joined;
6236
+ if (this._blockedByMinVersion() ||
6237
+ this._upgradeRequired ||
6238
+ this._haltedMeshes.has(b4a.toHex(meshKey)) ||
6239
+ !this._mayFollow(memberMesh)) {
6239
6240
  return 'skipped';
6240
6241
  }
6241
- const { meshKey } = joined;
6242
6242
  const held = await memberMesh.view.get(MESH_SEEDS, { meshKey });
6243
6243
  if (!held) {
6244
6244
  return 'no-seed';
@@ -6732,6 +6732,9 @@ export class Core extends ReadyResource {
6732
6732
  if (pooled && this._definesAgents(pooled, request)) {
6733
6733
  return this._accountMesh() ?? pooled;
6734
6734
  }
6735
+ if (pooled) {
6736
+ this._refuseAccountContent(pooled, request);
6737
+ }
6735
6738
  if (pooled && !this._routesToPublic(pooled, request)) {
6736
6739
  return pooled;
6737
6740
  }
@@ -6785,18 +6788,29 @@ export class Core extends ReadyResource {
6785
6788
  };
6786
6789
  }
6787
6790
  _definesAgents(mesh, { route }) {
6788
- return ((route === 'put-agent' || route === 'put-tool-configs') &&
6791
+ return ((route === 'put-agent' || route === 'put-tool-configs' || route === 'put-approval-rule') &&
6789
6792
  mesh.role === 'workspace' &&
6790
6793
  this._hasPublic(mesh));
6791
6794
  }
6795
+ _refuseAccountContent(mesh, { route }) {
6796
+ if (route && publicRoute(route) && this._isAccount(mesh)) {
6797
+ throw new CoreError('ROUTE_NEEDS_WORKSPACE', [route]);
6798
+ }
6799
+ }
6792
6800
  _routesToPublic(mesh, { route }) {
6793
6801
  return !!route && publicRoute(route) && this._hasPublic(mesh);
6794
6802
  }
6795
6803
  async _routedMesh(pooled, meshId, request) {
6796
6804
  const mesh = pooled ?? (await this._publicById(meshId)) ?? (await this._openPooledMesh(meshId));
6797
- const follow = request.follow || (this._isAccount(mesh) && !!mesh.ourMemberId);
6805
+ this._refuseAccountContent(mesh, request);
6806
+ const admitted = mesh.writable && !!this._accountMesh()?.writable;
6807
+ const follow = request.follow || admitted || (await this._holdsPublic(mesh));
6798
6808
  return this._routesToPublic(mesh, request) ? this._publicOf(mesh, { ...request, follow }) : mesh;
6799
6809
  }
6810
+ async _holdsPublic(workspace) {
6811
+ const account = this._accountMesh();
6812
+ return !!account && !!(await this._publicRecord(account, workspace.key))?.key;
6813
+ }
6800
6814
  async _publicById(meshId) {
6801
6815
  const account = this._accountMesh();
6802
6816
  if (!account) {
@@ -6806,9 +6820,9 @@ export class Core extends ReadyResource {
6806
6820
  if ((await this._publicRecord(account, workspaceKey))?.key !== meshId) {
6807
6821
  continue;
6808
6822
  }
6809
- const workspaceId = b4a.toHex(workspaceKey);
6810
- const scope = workspaceId === this._ownWorkspaceId ? account : this._pooled(workspaceId);
6811
- const mesh = scope && (await this._publicOf(scope));
6823
+ const hidden = this._isHidden(b4a.toHex(workspaceKey));
6824
+ const scope = hidden ? null : await this._heldMesh(workspaceKey);
6825
+ const mesh = scope && (await this._publicOf(scope, { follow: true }));
6812
6826
  return mesh && this._meshIdOf(mesh) === meshId ? mesh : null;
6813
6827
  }
6814
6828
  return null;
@@ -6849,7 +6863,7 @@ export class Core extends ReadyResource {
6849
6863
  createProject: (workspaceId, opts) => this.createProject(workspaceId, opts),
6850
6864
  listArchived: () => this.listArchivedMeshes(),
6851
6865
  archivedContents: (meshId) => this.archivedMeshContents(meshId),
6852
- migrateArchived: (meshId) => this.migrateArchivedMesh(meshId),
6866
+ migrateArchived: (meshId, workspaceId) => this.migrateArchivedMesh(meshId, workspaceId),
6853
6867
  recoverable: () => this.accountRecoverable(),
6854
6868
  publishRecovery: async (phrase) => void (await this.publishAccountRecovery(phrase)),
6855
6869
  recover: (phrase, timeout) => this.recoverAccount(phrase, { timeout }),
@@ -7375,12 +7389,14 @@ export class Core extends ReadyResource {
7375
7389
  return 'joining';
7376
7390
  }
7377
7391
  if (this._accountMesh()) {
7378
- return this._accountWritable() ? 'joined' : 'joining';
7392
+ return this._accountWritable() && this._ownDecided === this._accountMesh()
7393
+ ? 'joined'
7394
+ : 'joining';
7379
7395
  }
7380
7396
  return 'idle';
7381
7397
  }
7382
7398
  _accountWritable() {
7383
- return !!this._accountMesh()?.writable && !!this._publicMesh()?.writable;
7399
+ return !!this._accountMesh()?.writable;
7384
7400
  }
7385
7401
  async _chatSenders(meshId) {
7386
7402
  const project = this._pooled(meshId);