@qvac/core 1.0.0-rc.5 → 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 (131) hide show
  1. package/CHANGELOG.md +43 -2
  2. package/README.md +55 -4
  3. package/dist-lib/lib/api/agents.d.ts +2 -1
  4. package/dist-lib/lib/api/agents.js +10 -3
  5. package/dist-lib/lib/api/app-config.d.ts +3 -0
  6. package/dist-lib/lib/api/app-config.js +20 -0
  7. package/dist-lib/lib/api/approval-rules.js +8 -5
  8. package/dist-lib/lib/api/chat.d.ts +1 -2
  9. package/dist-lib/lib/api/chat.js +4 -18
  10. package/dist-lib/lib/api/device-routes.d.ts +1 -1
  11. package/dist-lib/lib/api/device-routes.js +3 -1
  12. package/dist-lib/lib/api/index.d.ts +0 -1
  13. package/dist-lib/lib/api/index.js +3 -3
  14. package/dist-lib/lib/api/mesh.d.ts +1 -1
  15. package/dist-lib/lib/api/mesh.js +1 -1
  16. package/dist-lib/lib/api/projects.js +3 -4
  17. package/dist-lib/lib/api/served.d.ts +2 -2
  18. package/dist-lib/lib/api/served.js +24 -1
  19. package/dist-lib/lib/api/sync.js +12 -2
  20. package/dist-lib/lib/assistant/harness.d.ts +3 -0
  21. package/dist-lib/lib/assistant/history.js +14 -2
  22. package/dist-lib/lib/assistant/message.d.ts +1 -0
  23. package/dist-lib/lib/assistant/model-round.d.ts +3 -0
  24. package/dist-lib/lib/assistant/model-round.js +16 -2
  25. package/dist-lib/lib/assistant/round-host.d.ts +2 -0
  26. package/dist-lib/lib/assistant/round-host.js +8 -0
  27. package/dist-lib/lib/assistant-tree.d.ts +2 -0
  28. package/dist-lib/lib/assistant-tree.js +4 -2
  29. package/dist-lib/lib/assistant.d.ts +11 -2
  30. package/dist-lib/lib/assistant.js +124 -20
  31. package/dist-lib/lib/client.js +4 -1
  32. package/dist-lib/lib/core/agent-copies.js +2 -1
  33. package/dist-lib/lib/core/agent-hosting.js +9 -4
  34. package/dist-lib/lib/core/agent.js +2 -1
  35. package/dist-lib/lib/core/archived-mesh.d.ts +1 -0
  36. package/dist-lib/lib/core/archived-mesh.js +11 -14
  37. package/dist-lib/lib/core/chat-copy.d.ts +1 -1
  38. package/dist-lib/lib/core/chat-copy.js +14 -4
  39. package/dist-lib/lib/core/chat-move.d.ts +3 -1
  40. package/dist-lib/lib/core/chat-move.js +5 -2
  41. package/dist-lib/lib/core/chat.d.ts +0 -1
  42. package/dist-lib/lib/core/chat.js +0 -3
  43. package/dist-lib/lib/core/collections.d.ts +7 -7
  44. package/dist-lib/lib/core/collections.js +7 -7
  45. package/dist-lib/lib/core/contract/joined-meshes.js +2 -1
  46. package/dist-lib/lib/core/contract/project-device-keys.d.ts +4 -2
  47. package/dist-lib/lib/core/contract/project-device-keys.js +12 -12
  48. package/dist-lib/lib/core/contract/project-host-keys.d.ts +5 -3
  49. package/dist-lib/lib/core/contract/project-host-keys.js +22 -11
  50. package/dist-lib/lib/core/contract/projects.d.ts +4 -2
  51. package/dist-lib/lib/core/contract/projects.js +29 -17
  52. package/dist-lib/lib/core/deleted-agent-runs.d.ts +1 -0
  53. package/dist-lib/lib/core/deleted-agent-runs.js +22 -11
  54. package/dist-lib/lib/core/helpers/index.d.ts +1 -1
  55. package/dist-lib/lib/core/helpers/index.js +2 -2
  56. package/dist-lib/lib/core/local/index.d.ts +2 -1
  57. package/dist-lib/lib/core/local/index.js +3 -2
  58. package/dist-lib/lib/core/mesh.d.ts +1 -0
  59. package/dist-lib/lib/core/mesh.js +4 -4
  60. package/dist-lib/lib/core/project-keys.d.ts +5 -2
  61. package/dist-lib/lib/core/project-keys.js +15 -6
  62. package/dist-lib/lib/core/public-mesh.d.ts +6 -8
  63. package/dist-lib/lib/core/public-mesh.js +19 -29
  64. package/dist-lib/lib/core/sync/index.js +6 -6
  65. package/dist-lib/lib/core.d.ts +17 -8
  66. package/dist-lib/lib/core.js +317 -224
  67. package/dist-lib/lib/errors.d.ts +4 -12
  68. package/dist-lib/lib/errors.js +4 -12
  69. package/dist-lib/lib/kv-cache-ledger.d.ts +22 -0
  70. package/dist-lib/lib/kv-cache-ledger.js +72 -0
  71. package/dist-lib/lib/kv-cache-retention.d.ts +1 -0
  72. package/dist-lib/lib/kv-cache-retention.js +5 -2
  73. package/dist-lib/lib/model-memory-cap.d.ts +3 -0
  74. package/dist-lib/lib/model-memory-cap.js +15 -6
  75. package/dist-lib/lib/run-replay.d.ts +3 -2
  76. package/dist-lib/lib/run-replay.js +16 -5
  77. package/dist-lib/lib/run-transcript.js +1 -1
  78. package/dist-lib/schema/engine.js +64 -4
  79. package/dist-lib/schema/local.js +4 -2
  80. package/dist-lib/schema/qvac.js +64 -2
  81. package/dist-lib/spec/bind.js +3 -0
  82. package/dist-lib/spec/calls.js +1 -0
  83. package/dist-lib/spec/capabilities.d.ts +4 -2
  84. package/dist-lib/spec/hrpc/hrpc.json +14 -1
  85. package/dist-lib/spec/hrpc/index.js +16 -4
  86. package/dist-lib/spec/hrpc/messages.js +508 -235
  87. package/dist-lib/spec/hyperschema/index.js +508 -235
  88. package/dist-lib/spec/hyperschema/schema.json +214 -6
  89. package/dist-lib/spec/hyperschema/types.d.ts +40 -1
  90. package/dist-lib/spec/local/hyperdb/messages.js +26 -12
  91. package/dist-lib/spec/local/hyperschema/index.js +13 -6
  92. package/dist-lib/spec/local/hyperschema/schema.json +10 -0
  93. package/dist-lib/spec/local/hyperschema/types.d.ts +2 -0
  94. package/dist-lib/spec/mesh/hyperdb/db.json +110 -0
  95. package/dist-lib/spec/mesh/hyperdb/index.js +498 -2
  96. package/dist-lib/spec/mesh/hyperdb/messages.js +895 -416
  97. package/dist-lib/spec/mesh/hyperdispatch/messages.js +259 -6
  98. package/dist-lib/spec/mesh/hyperschema/index.js +259 -6
  99. package/dist-lib/spec/mesh/hyperschema/schema.json +160 -0
  100. package/dist-lib/spec/mesh/hyperschema/types.d.ts +38 -0
  101. package/package.json +27 -11
  102. package/tui/README.md +190 -0
  103. package/tui/app.mjs +8282 -0
  104. package/tui/boot.mjs +159 -0
  105. package/tui/index.mjs +89 -0
  106. package/tui/lib/boot-timing.mjs +41 -0
  107. package/tui/lib/busy-words.mjs +116 -0
  108. package/tui/lib/connect-sheet.mjs +350 -0
  109. package/tui/lib/device-target.mjs +64 -0
  110. package/tui/lib/export.mjs +194 -0
  111. package/tui/lib/folders-command.mjs +84 -0
  112. package/tui/lib/fork-command.mjs +43 -0
  113. package/tui/lib/knowledge-command.mjs +190 -0
  114. package/tui/lib/knowledge-import.mjs +153 -0
  115. package/tui/lib/local-path.mjs +21 -0
  116. package/tui/lib/move-command.mjs +17 -0
  117. package/tui/lib/render.mjs +225 -0
  118. package/tui/lib/save-file.mjs +88 -0
  119. package/tui/lib/select.mjs +81 -0
  120. package/tui/lib/selection.mjs +18 -0
  121. package/tui/lib/setup.mjs +135 -0
  122. package/tui/lib/sidebar.mjs +63 -0
  123. package/tui/lib/skill-connect.mjs +145 -0
  124. package/tui/lib/splash-art.mjs +107 -0
  125. package/tui/lib/splash.mjs +18 -0
  126. package/tui/lib/upload-frames.mjs +9 -0
  127. package/tui/lib/usage.mjs +59 -0
  128. package/tui/lib/wrap.mjs +143 -0
  129. package/tui/main.mjs +279 -0
  130. package/tui/plugins.mjs +158 -0
  131. package/worker/assistant-sidecar.mjs +1 -0
@@ -14,7 +14,7 @@ import ReadyResource from 'ready-resource';
14
14
  import ScopeLock from 'scope-lock';
15
15
  import { isAndroid } from 'which-runtime';
16
16
  import { createApi } from './api/index.js';
17
- import { writeAutoDownloadModels } from './api/app-config.js';
17
+ import { backfillLastModelName, readLastModelName, writeAutoDownloadModels } from './api/app-config.js';
18
18
  import { requireOurAdmin, requireWorkspace } from './api/members.js';
19
19
  import { projectName } from './api/projects.js';
20
20
  import { createServedApi } from './api/served.js';
@@ -25,7 +25,7 @@ import { openSealedToDevice, sealToDevice } from './core/device-seal.js';
25
25
  import { removedBy } from './core/contract/invites.js';
26
26
  import { meshKind } from './core/contract/mesh-kind.js';
27
27
  import { WORKSPACES_RULES, bornUnderRules, rulesVersion } from './core/contract/mesh-rules.js';
28
- import { inProject, listedProject, listsMember, liveMember, projectMember, projectOfGroup, readProjectKey, UNGROUPED } from './core/contract/projects.js';
28
+ import { inProject, listedProject, listsMember, liveMember, projectMember, projectOfGroup, projectKeys, readProject, UNGROUPED } from './core/contract/projects.js';
29
29
  import { requireMesh } from './api/current-mesh.js';
30
30
  import { CoreError } from './errors.js';
31
31
  import { ChatMoves } from './core/chat-move.js';
@@ -34,12 +34,12 @@ import { copyContent } from './core/chat-copy.js';
34
34
  import { followAgentCopies, keepCopyChats } from './core/agent-copies.js';
35
35
  import { cancelDeletedAgentRuns } from './core/deleted-agent-runs.js';
36
36
  import { devicesOfMember } from './core/contract/activity.js';
37
- import { followPickedAgents, followSharedAgents, liveSharedAgent, pickAgent, shareAgent, unpickAgent } from './core/shared-agents.js';
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
- import { dueProjectDeviceKeys, dueProjectHostKey, dueProjectKey } from './core/project-keys.js';
42
- import { readProjectDeviceKey } from './core/contract/project-device-keys.js';
41
+ import { dueProjectDeviceKeys, dueProjectHostKey, dueProjectKey, seedFingerprint, seedOpens } from './core/project-keys.js';
42
+ import { projectDeviceKeys } from './core/contract/project-device-keys.js';
43
43
  import { agentJoin, freshHostRecord, hostRecordKey, hostState, hostTargets, isHostRecord } from './core/agent-hosting.js';
44
44
  import { hostForWriter } from './core/contract/model-requests.js';
45
45
  import { asEncoded, watchModels } from './models-watch.js';
@@ -56,7 +56,8 @@ import { backgroundSyncKey } from './core/local/files.js';
56
56
  import { FOLD_PENDING, GROUPS_PENDING, agentsFoldKey, groupBuckets, groupRecordKey, isGroupRecord, liveGroups, projectsByGroup, upgradeCheckedKey } from './core/workspace-upgrade.js';
57
57
  import { foldAgents, ownCopies } from './core/upgrade-agents.js';
58
58
  import { MAX_MESH_NAME_CHARS, meshNameWithinBounds } from '../schema/qvac.js';
59
- import { rehomeAgents } from './core/agent.js';
59
+ import { getDefaultAgent, mustGetActiveAgent, rehomeAgents } from './core/agent.js';
60
+ import { pickRunner } from './core/run-requests.js';
60
61
  import { countContents, migrateContents, withArchivedMesh } from './core/archived-mesh.js';
61
62
  import { isMobilePlatform } from '@qvac/harness/lib/models/model-catalog.ts';
62
63
  import { storeSkillSecret, syncSkillSecrets } from './core/skill-secrets.js';
@@ -212,14 +213,16 @@ export class Core extends ReadyResource {
212
213
  _publicBoots = new Map();
213
214
  _meshNames = new Map();
214
215
  _ownWorkspaceId = null;
216
+ _ownDecided = null;
215
217
  _publicWriters = new WeakMap();
216
218
  _leftPublic = new WeakSet();
217
219
  _publicWaiters = new Set();
218
220
  _publicFollow = new ScopeLock({ debounce: true });
219
221
  _publicMerges = new Map();
220
- _publicCarries = new Map();
221
- _ownCarries = new Map();
222
+ _publicDrops = new Map();
222
223
  _publicMigration = null;
224
+ _copyAgain = false;
225
+ _accountCopied = null;
223
226
  _agentCopies = new ScopeLock({ debounce: true });
224
227
  _sharedAgents = new ScopeLock({ debounce: true });
225
228
  _memberKeyWrites = new WeakMap();
@@ -239,6 +242,7 @@ export class Core extends ReadyResource {
239
242
  _backfill = Promise.resolve();
240
243
  _leaving;
241
244
  _kickedMeshes = new Set();
245
+ _haltedMeshes = new Set();
242
246
  _kickCloses = new Map();
243
247
  _retiredMeshes = new Set();
244
248
  _retiredAccount = null;
@@ -471,7 +475,8 @@ export class Core extends ReadyResource {
471
475
  deviceId,
472
476
  log: this._log,
473
477
  account: () => this._accountMesh(),
474
- agents: this._agentPicks()
478
+ agents: this._agentPicks(),
479
+ meshIdOf: (key) => this._workspaceOfPublic(b4a.toHex(key))
475
480
  })
476
481
  : null;
477
482
  const api = createApi({
@@ -521,11 +526,6 @@ export class Core extends ReadyResource {
521
526
  const id = b4a.toHex(projectKey);
522
527
  return this._pooled(id)?.name ?? this._meshNames.get(id) ?? null;
523
528
  },
524
- workspaceOf: async (projectId) => {
525
- const key = (await this.local.readMeshSession(this._meshKeyOf(projectId)))?.workspaceKey;
526
- const workspaceId = key ? b4a.toHex(key) : null;
527
- return workspaceId === this._ownWorkspaceId ? null : workspaceId;
528
- },
529
529
  pushSkillSecret: (request) => this.pushSkillSecret(request),
530
530
  beforeConfigSet: (entry) => validateVaultManagedSkill(this._vaultManagedSkills, entry),
531
531
  onConfigSet: async (entry) => {
@@ -658,6 +658,7 @@ export class Core extends ReadyResource {
658
658
  })
659
659
  : null
660
660
  });
661
+ api.skillOauth = (request) => this._skillOauth(request);
661
662
  this._servedToSiblings = servedToSiblings(api);
662
663
  this._api = {
663
664
  ...api,
@@ -686,6 +687,7 @@ export class Core extends ReadyResource {
686
687
  const rpc = settleOnClose(new HRPC(this._stream));
687
688
  bindApi(rpc, this._api);
688
689
  this._rpcs.add(rpc);
690
+ this._stream.on('close', () => this._rpcs.delete(rpc));
689
691
  this._offlineBoot.exit();
690
692
  void this._pushIdentityPhrase();
691
693
  this._chatMoves
@@ -1236,7 +1238,7 @@ export class Core extends ReadyResource {
1236
1238
  const session = await this.local.resolveSession(this._requireDeviceKeyPair().publicKey, opts);
1237
1239
  return this._openMeshSession(session, opts);
1238
1240
  }
1239
- async _openMeshSession(session, { blindPeerKeys, account, sharing, workspace, project } = {}) {
1241
+ async _openMeshSession(session, { blindPeerKeys, account, initial, sharing, workspace, project } = {}) {
1240
1242
  const deviceId = this._requireDeviceKeyPair().publicKey;
1241
1243
  const mesh = this._newMesh(session, session.role ?? (account ? 'account' : 'project'), blindPeerKeys);
1242
1244
  try {
@@ -1255,6 +1257,7 @@ export class Core extends ReadyResource {
1255
1257
  await this._appendOwnBirth(mesh, session, {
1256
1258
  deviceId,
1257
1259
  account,
1260
+ initial,
1258
1261
  sharing,
1259
1262
  workspace,
1260
1263
  project
@@ -1262,8 +1265,8 @@ export class Core extends ReadyResource {
1262
1265
  }
1263
1266
  }
1264
1267
  catch (err) {
1265
- if (mesh.opened && mesh.interrupted && !this._upgradeRequired) {
1266
- this._setUpgradeRequired('halt');
1268
+ if (mesh.opened && mesh.interrupted) {
1269
+ this._markHalted(mesh);
1267
1270
  }
1268
1271
  await mesh.close().catch(noop);
1269
1272
  throw err;
@@ -1289,7 +1292,7 @@ export class Core extends ReadyResource {
1289
1292
  });
1290
1293
  return mesh;
1291
1294
  }
1292
- async _appendOwnBirth(mesh, session, { deviceId, account, sharing, workspace, project }) {
1295
+ async _appendOwnBirth(mesh, session, { deviceId, account, initial, sharing, workspace, project }) {
1293
1296
  await raceResource(mesh.autobee, (async () => {
1294
1297
  const birth = sharing
1295
1298
  ? await this._accountBirthMember(mesh, session)
@@ -1297,10 +1300,11 @@ export class Core extends ReadyResource {
1297
1300
  await mesh.appendBirthOp(this._requireDeviceKeyPair(), this._localDevice ?? undefined, {
1298
1301
  member: birth?.member,
1299
1302
  sharing,
1303
+ modelName: (await readLastModelName(this.local)) ?? undefined,
1300
1304
  workspace,
1301
1305
  project
1302
1306
  });
1303
- await this.local.recordMesh(mesh.key, session, { deviceId, account });
1307
+ await this.local.recordMesh(mesh.key, session, { deviceId, account, initial });
1304
1308
  if (account && birth?.mnemonic) {
1305
1309
  await this._publishRecovery(birth.mnemonic, {
1306
1310
  meshKey: mesh.key,
@@ -1321,8 +1325,8 @@ export class Core extends ReadyResource {
1321
1325
  return appended.catch((err) => {
1322
1326
  if (this.closing || mesh.closing)
1323
1327
  return;
1324
- if (mesh.interrupted && !this._upgradeRequired) {
1325
- this._setUpgradeRequired('halt');
1328
+ if (mesh.interrupted) {
1329
+ this._markHalted(mesh);
1326
1330
  }
1327
1331
  this._log?.warn(['p2p', 'mesh'], 'appending the join failed', err);
1328
1332
  });
@@ -1696,6 +1700,44 @@ export class Core extends ReadyResource {
1696
1700
  return false;
1697
1701
  }
1698
1702
  }
1703
+ async _skillOauth(request) {
1704
+ const account = this._accountMesh();
1705
+ if (!account) {
1706
+ throw new CoreError('MESH_NOT_FOUND', ['account']);
1707
+ }
1708
+ const deviceId = this._requireDeviceKeyPair().publicKey;
1709
+ if (request.operation === 'target' && !isMobilePlatform(this._localDevice?.platform ?? '')) {
1710
+ return { phase: 'local', deviceId };
1711
+ }
1712
+ const agent = await mustGetActiveAgent(account, request.agentId);
1713
+ const owner = await ownerOf(account, agent);
1714
+ if (!owner || !account.ourMemberId || !b4a.equals(owner, account.ourMemberId)) {
1715
+ throw new CoreError('AGENT_NOT_OURS');
1716
+ }
1717
+ if (request.operation === 'target') {
1718
+ const mesh = request.meshId
1719
+ ? await requireMesh(this._meshPool(), request.meshId, { route: 'put-chat' })
1720
+ : account;
1721
+ const runner = await pickRunner(mesh, {
1722
+ deviceId,
1723
+ peers: this.peerDeviceIds,
1724
+ agent
1725
+ });
1726
+ return { phase: runner ? 'ready' : 'local', deviceId: runner ?? deviceId };
1727
+ }
1728
+ for (const rpc of this._rpcs) {
1729
+ const response = await rpc.skillOauth(request);
1730
+ if (response.phase === 'unavailable') {
1731
+ continue;
1732
+ }
1733
+ if ((request.operation !== 'config' && response.phase === 'connected') ||
1734
+ (request.operation === 'disconnect' && response.phase === 'ready')) {
1735
+ await this._skillCatalog?.(request.agentId, null, { refresh: true });
1736
+ }
1737
+ return response;
1738
+ }
1739
+ throw new CoreError('DEVICE_ROUTE_NOT_SERVED', ['skillOauth']);
1740
+ }
1699
1741
  _startBlindPeering(mesh) {
1700
1742
  const peering = this._blindPeeringClient();
1701
1743
  if (peering) {
@@ -2089,6 +2131,7 @@ export class Core extends ReadyResource {
2089
2131
  await this.local.dropMesh(key, { keepDeparture: true, cores });
2090
2132
  this._meshNames.delete(b4a.toHex(key));
2091
2133
  this._kickedMeshes.delete(b4a.toHex(key));
2134
+ this._haltedMeshes.delete(b4a.toHex(key));
2092
2135
  this._notifyStatus();
2093
2136
  }
2094
2137
  if (cores) {
@@ -2118,14 +2161,22 @@ export class Core extends ReadyResource {
2118
2161
  _withdrawFromMesh(mesh, err) {
2119
2162
  if (this.closing)
2120
2163
  return;
2121
- if (!this._upgradeRequired) {
2122
- this._log?.error(['p2p', 'mesh'], 'mesh needs a newer build - withdrawing from it', err);
2123
- this._setUpgradeRequired('halt');
2124
- }
2164
+ this._log?.error(['p2p', 'mesh'], 'mesh needs a newer build - withdrawing from it', err);
2165
+ this._markHalted(mesh);
2125
2166
  this._retirePooledMesh(mesh).catch((retireErr) => {
2126
2167
  this._log?.warn(['p2p', 'mesh'], 'retiring the stalled mesh failed', retireErr);
2127
2168
  });
2128
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
+ }
2129
2180
  async _reviewKick(mesh) {
2130
2181
  const entry = this._meshes.get(this._meshIdOf(mesh));
2131
2182
  if (entry?.mesh !== mesh || !(await entry.kickLock.lock())) {
@@ -2312,12 +2363,12 @@ export class Core extends ReadyResource {
2312
2363
  }
2313
2364
  }
2314
2365
  async _dropOwnMint(fresh) {
2315
- const seed = ownWorkspaceSeed(fresh.seed);
2316
- for (const row of await this.local.listMeshes()) {
2317
- 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)) {
2318
2370
  continue;
2319
2371
  }
2320
- const id = b4a.toHex(row.key);
2321
2372
  const own = this._publicMesh(id);
2322
2373
  if (own) {
2323
2374
  await this._teardownMesh(own, { purge: true });
@@ -2465,7 +2516,9 @@ export class Core extends ReadyResource {
2465
2516
  if (!invite) {
2466
2517
  throw new CoreError('INVITE_INVALID');
2467
2518
  }
2468
- await this._awaitMesh();
2519
+ if (!this.opened) {
2520
+ await this.ready();
2521
+ }
2469
2522
  this._requireLocalDevice();
2470
2523
  await this._meshTransitionLock.lock();
2471
2524
  let ownsTransition = false;
@@ -2998,7 +3051,7 @@ export class Core extends ReadyResource {
2998
3051
  }
2999
3052
  async _copyGroup(workspace, project, { chats }) {
3000
3053
  const deviceId = this._requireDeviceKeyPair().publicKey;
3001
- await copyContent({ from: workspace, into: project, deviceId, chats });
3054
+ await copyContent({ from: workspace, into: project, deviceId, chats, endsOpenRuns: true });
3002
3055
  }
3003
3056
  async _addWorkspaceMembers(workspace, project) {
3004
3057
  for (const memberId of await this._workspaceMembers(workspace)) {
@@ -3353,10 +3406,6 @@ export class Core extends ReadyResource {
3353
3406
  void this._followPublicMesh(mesh);
3354
3407
  void this._followSkillSecrets();
3355
3408
  }
3356
- const account = this._accountMesh();
3357
- if (account && this._meshIdOf(mesh) === this._ownWorkspaceId) {
3358
- void this._followPublicMesh(account);
3359
- }
3360
3409
  if (this._isOwnPublic(mesh)) {
3361
3410
  void this._followAgentCopies();
3362
3411
  }
@@ -3440,7 +3489,7 @@ export class Core extends ReadyResource {
3440
3489
  return;
3441
3490
  void this._followAccountName(mesh);
3442
3491
  });
3443
- 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 }));
3444
3493
  mesh.on('joined', () => {
3445
3494
  if (entry.meshesPending) {
3446
3495
  void this._followJoinedMeshes(mesh);
@@ -3469,10 +3518,10 @@ export class Core extends ReadyResource {
3469
3518
  this._listenMesh(mesh, handlers);
3470
3519
  this._startMeshServices(entry);
3471
3520
  this._startEntryIndexing(entry);
3472
- this._onMeshesDirty(entry, { changed: true, groupsChanged: true });
3521
+ this._onMeshesDirty(entry, { changed: true, groupsChanged: true, chatsChanged: true });
3473
3522
  this._reviewKick(mesh).catch((err) => this._log?.warn(['p2p', 'mesh'], 'reviewing a kick failed', err));
3474
3523
  }
3475
- _onMeshesDirty(entry, { changed, groupsChanged }) {
3524
+ _onMeshesDirty(entry, { changed, groupsChanged, chatsChanged }) {
3476
3525
  const { mesh } = entry;
3477
3526
  if (this._isHidden(this._meshIdOf(mesh), mesh.workspaceKey)) {
3478
3527
  return;
@@ -3490,9 +3539,14 @@ export class Core extends ReadyResource {
3490
3539
  if ((changed || groupsChanged) && mesh.role === 'workspace') {
3491
3540
  this._followGroups(mesh);
3492
3541
  }
3493
- 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)) {
3494
3544
  void this._followPublicMesh(mesh);
3495
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
+ }
3496
3550
  }
3497
3551
  _listenMesh(mesh, handlers) {
3498
3552
  mesh.autobee.on('writable', handlers.writable);
@@ -3537,19 +3591,27 @@ export class Core extends ReadyResource {
3537
3591
  this._notifyStatus();
3538
3592
  void this._followPublicMesh(mesh);
3539
3593
  void this._followSkillSecrets();
3594
+ void this._backfillModelPick(mesh);
3595
+ }
3596
+ async _backfillModelPick(mesh) {
3597
+ const deviceId = this._requireDeviceKeyPair().publicKey;
3598
+ try {
3599
+ await backfillLastModelName(this.local, async () => (await getDefaultAgent(mesh, deviceId))?.modelName ?? null);
3600
+ }
3601
+ catch (err) {
3602
+ this._log?.warn(['mesh'], 'backfilling the model pick failed', err);
3603
+ }
3540
3604
  }
3541
- _publicMesh(workspaceId = this._accountId) {
3605
+ _publicMesh(workspaceId = this._ownWorkspaceId) {
3542
3606
  return this._pooled(this._publicIdOf(workspaceId));
3543
3607
  }
3544
- _publicIdOf(meshId) {
3545
- const workspaceId = meshId !== null && meshId === this._accountId ? this._ownWorkspaceId : meshId;
3608
+ _publicIdOf(workspaceId) {
3546
3609
  return workspaceId === null ? null : (this._publicIds.get(workspaceId) ?? null);
3547
3610
  }
3548
3611
  _workspaceOfPublic(meshId) {
3549
3612
  for (const [workspaceId, publicId] of this._publicIds) {
3550
- if (publicId !== meshId)
3551
- continue;
3552
- return workspaceId === this._ownWorkspaceId ? (this._accountId ?? workspaceId) : workspaceId;
3613
+ if (publicId === meshId)
3614
+ return workspaceId;
3553
3615
  }
3554
3616
  return meshId;
3555
3617
  }
@@ -3583,8 +3645,9 @@ export class Core extends ReadyResource {
3583
3645
  }
3584
3646
  async _shareProjectSeed(batch, { workspace, project, agent, picking }) {
3585
3647
  const projectId = project.key;
3586
- const seed = await this._heldProjectSeed(workspace, projectId);
3587
- const sealing = seed && { projectId, seed, project: project.view, picking };
3648
+ const sealedBy = workspace.ourMemberId;
3649
+ const seed = sealedBy && (await this._heldProjectSeed(workspace, projectId));
3650
+ const sealing = seed && { projectId, seed, project: project.view, sealedBy, picking };
3588
3651
  const due = sealing && (await dueProjectHostKey(workspace.view, agent, sealing));
3589
3652
  if (due) {
3590
3653
  batch.dispatch('put-project-host-key', due);
@@ -3616,14 +3679,11 @@ export class Core extends ReadyResource {
3616
3679
  }
3617
3680
  await workspace.dispatch('put-member-key', { memberId, boxKey });
3618
3681
  }
3619
- _contentMesh() {
3620
- return this._publicMesh() ?? this._accountMesh();
3621
- }
3622
3682
  _devicesOf(mesh) {
3623
3683
  return this._isOwnPublic(mesh) ? (this._accountMesh() ?? mesh) : mesh;
3624
3684
  }
3625
3685
  _hasPublic(mesh) {
3626
- return this._isAccount(mesh) || (mesh.role === 'workspace' && this._isPooled(mesh));
3686
+ return mesh.role === 'workspace' && this._isPooled(mesh);
3627
3687
  }
3628
3688
  async _publicOf(scope, { follow = false } = {}) {
3629
3689
  const workspaceId = this._meshIdOf(scope);
@@ -3729,34 +3789,72 @@ export class Core extends ReadyResource {
3729
3789
  return settled;
3730
3790
  }
3731
3791
  async _settleOwnWorkspace(account) {
3732
- const { own, lost } = await ownWorkspaces(account);
3733
- if (own && account.writable) {
3734
- for (const joined of lost) {
3735
- this._carryLostMint(account, { own, joined });
3736
- }
3792
+ if (this._localDevice && !account.ourMemberId) {
3793
+ return;
3737
3794
  }
3738
- const mints = account.minted || !(await bornUnderRules(account.view));
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 }));
3739
3806
  if (!this._isAccount(account)) {
3740
3807
  return;
3741
3808
  }
3742
- if (own || !mints) {
3743
- this._setOwnWorkspace(own ? b4a.toHex(own) : null);
3744
- 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();
3745
3816
  }
3746
- await this._mintOwnWorkspace(account);
3747
3817
  }
3748
- async _mintOwnWorkspace(account) {
3749
- const seed = ownWorkspaceSeed(account.seed);
3750
- const recorded = (await this.local.listMeshes()).find((row) => b4a.equals(row.seed, seed));
3751
- if (recorded) {
3752
- await this._openPooledMesh(b4a.toHex(recorded.key), 'follow');
3753
- return;
3818
+ async _mintsOwnWorkspace(account, { rows, local }) {
3819
+ if (!rows.length && !local.length) {
3820
+ return account.minted || !(await bornUnderRules(account.view));
3754
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
+ }
3839
+ }
3840
+ return false;
3841
+ }
3842
+ async _mintOwnWorkspace(account) {
3755
3843
  if (!account.writable || !account.ourMemberId) {
3756
3844
  return;
3757
3845
  }
3758
3846
  const workspace = { name: await this._defaultWorkspaceName(account) };
3759
- 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);
3760
3858
  }
3761
3859
  _setOwnWorkspace(workspaceId) {
3762
3860
  if (this._ownWorkspaceId !== workspaceId) {
@@ -3775,13 +3873,13 @@ export class Core extends ReadyResource {
3775
3873
  }
3776
3874
  const held = this._pooled(publicId);
3777
3875
  this._publicIds.delete(workspaceId);
3778
- const carried = held?.workspaceKey && (await this._publicRecord(account, held.workspaceKey))?.key;
3779
- if (held && !carried) {
3876
+ const recorded = held?.workspaceKey && (await this._publicRecord(account, held.workspaceKey))?.key;
3877
+ if (held && !recorded) {
3780
3878
  await this._teardownMesh(held);
3781
3879
  }
3782
3880
  }
3783
3881
  for (const workspaceKey of await this._leftWorkspaces(account)) {
3784
- this._carryLeftPublic(account, workspaceKey);
3882
+ this._dropLeftPublic(account, workspaceKey);
3785
3883
  }
3786
3884
  }
3787
3885
  async _leftWorkspaces(account) {
@@ -3795,120 +3893,31 @@ export class Core extends ReadyResource {
3795
3893
  }
3796
3894
  return keys;
3797
3895
  }
3798
- _carryLostMint(account, { own: ownKey, joined }) {
3799
- const lostId = b4a.toHex(joined.meshKey);
3800
- if (this._ownCarries.has(lostId)) {
3801
- return;
3802
- }
3803
- const carry = (async () => {
3804
- const lost = await this._heldMesh(joined.meshKey);
3805
- const own = lost && (await this._heldMesh(ownKey));
3806
- if (!lost || !own) {
3807
- return;
3808
- }
3809
- await own.waitForWritable();
3810
- if (!this._isAccount(account) || !this._isPooled(own) || !this._isPooled(lost)) {
3811
- return;
3812
- }
3813
- await lost.autobee.update();
3814
- await this._carryProjects(account, { lost, own }, joined.memberId);
3815
- if (!joined.leftAt) {
3816
- await this._releaseJoinedMesh(joined.meshKey, account);
3817
- }
3818
- this._log?.info(['p2p', 'mesh'], 'carried a lost mint of your own workspace into the winner', {
3819
- lost: lostId.slice(0, 8),
3820
- winner: this._meshIdOf(own).slice(0, 8)
3821
- });
3822
- await this._teardownMesh(lost);
3823
- })()
3824
- .catch((err) => {
3825
- if (!this.closing) {
3826
- this._log?.warn(['p2p', 'mesh'], 'carrying a lost mint of your own workspace failed', err);
3827
- }
3828
- })
3829
- .finally(() => {
3830
- this._ownCarries.delete(lostId);
3831
- });
3832
- this._ownCarries.set(lostId, carry);
3833
- }
3834
- async _carryProjects(account, mints, ours) {
3835
- const { lost, own } = mints;
3836
- const deviceId = this._requireDeviceKeyPair().publicKey;
3837
- const rows = await lost.view.find(PROJECTS).toArray();
3838
- for (const row of rows.filter((listed) => listedProject(listed, ours))) {
3839
- const session = await this.local.readMeshSession(row.id);
3840
- const seed = session?.seed ?? (await this._ownProjectSeed(lost, row.id));
3841
- if (!seed) {
3842
- continue;
3843
- }
3844
- const { createdAt, updatedAt } = row;
3845
- await this._listProject(own, { key: row.id, seed }, { createdAt, updatedAt });
3846
- if (session && (await this._isProjectOf(lost.key, row.id))) {
3847
- await this.local.recordMesh(row.id, { ...session, workspaceKey: own.key }, { deviceId });
3848
- }
3849
- await this._carryAgentUsers(account, mints, row.id);
3850
- }
3851
- }
3852
- async _carryAgentUsers(account, { lost, own }, projectId) {
3853
- const batch = own.batch();
3854
- for (const { agentId, userId } of await lost.view.find(AGENT_USERS).toArray()) {
3855
- if (!b4a.equals(userId, projectId) || !(await liveSharedAgent(lost, agentId))) {
3856
- continue;
3857
- }
3858
- try {
3859
- await shareAgent(account, own, agentId);
3860
- }
3861
- catch (err) {
3862
- if (!(err instanceof CoreError)) {
3863
- throw err;
3864
- }
3865
- this._log?.warn(['p2p', 'mesh'], 'a lost mint kept a shared agent the winner refuses', {
3866
- agentId,
3867
- code: err.code
3868
- });
3869
- continue;
3870
- }
3871
- if (!(await own.view.get(AGENT_USERS, { agentId, userId }))) {
3872
- batch.dispatch('put-agent-user', { agentId, projectId });
3873
- }
3874
- }
3875
- await batch.flush();
3876
- }
3877
- _carryLeftPublic(account, workspaceKey) {
3896
+ _dropLeftPublic(account, workspaceKey) {
3878
3897
  const workspaceId = b4a.toHex(workspaceKey);
3879
- if (this._publicCarries.has(workspaceId)) {
3898
+ if (this._publicDrops.has(workspaceId)) {
3880
3899
  return;
3881
3900
  }
3882
- const carry = (async () => {
3901
+ const drop = (async () => {
3883
3902
  const record = await this._publicRecord(account, workspaceKey);
3884
- const into = record?.key ? await this._publicOf(account, { follow: true }) : null;
3885
- if (!record?.key || !into || into === account) {
3903
+ if (!record?.key || !this._isAccount(account)) {
3886
3904
  return;
3887
3905
  }
3888
- const from = this._pooled(record.key) ?? (await this._openPublicMesh(account, { workspaceKey, record }));
3889
- await into.waitForWritable();
3890
- if (!this._isAccount(account) || !this._isPooled(into) || !this._isPooled(from)) {
3891
- return;
3892
- }
3893
- const deviceId = this._requireDeviceKeyPair().publicKey;
3894
- const unlinkProjects = !(await onOwnSeed(account, workspaceKey));
3895
- await copyContent({ from, into, deviceId, unlinkProjects });
3896
3906
  await this.local.deleteAll([publicRecordKey(account.key, workspaceKey)]);
3897
- this._log?.info(['p2p', 'mesh'], "copied a left workspace's private chats into your own", {
3898
- workspace: workspaceId.slice(0, 8),
3899
- 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)
3900
3909
  });
3901
- await this._teardownMesh(from);
3910
+ await this._teardownMesh(this._pooled(record.key) ?? b4a.from(record.key, 'hex'));
3902
3911
  })()
3903
3912
  .catch((err) => {
3904
3913
  if (!this.closing) {
3905
- 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);
3906
3915
  }
3907
3916
  })
3908
3917
  .finally(() => {
3909
- this._publicCarries.delete(workspaceId);
3918
+ this._publicDrops.delete(workspaceId);
3910
3919
  });
3911
- this._publicCarries.set(workspaceId, carry);
3920
+ this._publicDrops.set(workspaceId, drop);
3912
3921
  }
3913
3922
  async _settlePublicMesh(account, workspaceKey) {
3914
3923
  const workspaceId = b4a.toHex(workspaceKey);
@@ -4057,21 +4066,40 @@ export class Core extends ReadyResource {
4057
4066
  this._publicMerges.set(workspaceId, merge);
4058
4067
  }
4059
4068
  _migrateIntoPublic(account, workspaceKey) {
4060
- if (this._publicMigration)
4069
+ if (this._publicMigration) {
4070
+ this._copyAgain = true;
4061
4071
  return;
4072
+ }
4062
4073
  this._publicMigration = (async () => {
4063
- const record = await this._publicRecord(account, workspaceKey);
4064
4074
  const into = this._publicMesh(b4a.toHex(workspaceKey));
4065
- 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;
4066
4087
  return;
4067
4088
  }
4068
4089
  await into.waitForWritable();
4069
4090
  if (!this._isAccount(account) || !this._isPooled(into)) {
4070
4091
  return;
4071
4092
  }
4072
- await copyContent({ from: account, into, deviceId: this._requireDeviceKeyPair().publicKey });
4073
- const latest = (await this._publicRecord(account, workspaceKey)) ?? record;
4074
- await this._savePublicRecord(account, workspaceKey, { ...latest, migrated: true });
4093
+ await copyContent({
4094
+ from: account,
4095
+ into,
4096
+ deviceId: this._requireDeviceKeyPair().publicKey,
4097
+ endsOpenRuns: true
4098
+ });
4099
+ await this._recordCopied(account, workspaceKey);
4100
+ if (await this._markCopied(account, workspaceKey)) {
4101
+ this._accountCopied = copied;
4102
+ }
4075
4103
  this._log?.info(['p2p', 'mesh'], 'copied the account into its public mesh', {
4076
4104
  mesh: this._meshIdOf(into).slice(0, 8)
4077
4105
  });
@@ -4083,8 +4111,31 @@ export class Core extends ReadyResource {
4083
4111
  })
4084
4112
  .finally(() => {
4085
4113
  this._publicMigration = null;
4114
+ if (this._copyAgain && !this.closing) {
4115
+ this._copyAgain = false;
4116
+ this._migrateIntoPublic(account, workspaceKey);
4117
+ }
4086
4118
  });
4087
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
+ }
4088
4139
  async _followAgentCopies(agentId) {
4089
4140
  if (!agentId && !(await this._agentCopies.lock()))
4090
4141
  return;
@@ -4837,9 +4888,6 @@ export class Core extends ReadyResource {
4837
4888
  requireWorkspace(departing, meshId);
4838
4889
  }
4839
4890
  const account = this._accountMesh();
4840
- if (account && isOwnWorkspace(account, departing)) {
4841
- throw new CoreError('OWN_WORKSPACE_LEAVE_REFUSED');
4842
- }
4843
4891
  const kicked = this._kickedMeshes.has(meshId) && departing !== account;
4844
4892
  const member = departing.role === 'workspace' && !kicked ? await this._leavingMember(departing) : null;
4845
4893
  const leavingAccount = await this._isStoredAccount(departing);
@@ -5057,7 +5105,7 @@ export class Core extends ReadyResource {
5057
5105
  const counts = await this._withArchivedMesh(row, (mesh, archived) => countContents(mesh, account, archived));
5058
5106
  return { meshId, ...counts };
5059
5107
  }
5060
- async migrateArchivedMesh(meshId) {
5108
+ async migrateArchivedMesh(meshId, workspaceId) {
5061
5109
  if (!this.opened)
5062
5110
  await this.ready();
5063
5111
  await this._meshTransitionLock.lock();
@@ -5068,22 +5116,33 @@ export class Core extends ReadyResource {
5068
5116
  const row = await this._archivedRow(meshId);
5069
5117
  if (row.migratedAt) {
5070
5118
  const none = { chats: 0, agents: 0, knowledge: 0 };
5071
- return { meshId, migrated: false, migratedAt: row.migratedAt, ...none };
5119
+ return { meshId, workspaceId, migrated: false, migratedAt: row.migratedAt, ...none };
5072
5120
  }
5073
5121
  const account = await this._writableAccount();
5074
5122
  if (!account) {
5075
5123
  throw new CoreError('ACCOUNT_NOT_WRITABLE');
5076
5124
  }
5077
- const into = await this._publicOf(account);
5125
+ const into = await this._archiveDestination(workspaceId);
5078
5126
  const counts = await this._withArchivedMesh(row, (mesh, archived) => migrateContents(mesh, into, { from: archived, into: account }));
5079
5127
  const migratedAt = Date.now();
5080
5128
  await this.local.markMeshMigrated(row.key, migratedAt);
5081
- return { meshId, migrated: true, migratedAt, ...counts };
5129
+ return { meshId, workspaceId, migrated: true, migratedAt, ...counts };
5082
5130
  }
5083
5131
  finally {
5084
5132
  this._meshTransitionLock.unlock();
5085
5133
  }
5086
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
+ }
5087
5146
  async _archivedRow(meshId) {
5088
5147
  const key = this._meshKeyOf(meshId);
5089
5148
  const row = (await this.local.listArchivedMeshes()).find((row) => b4a.equals(row.key, key));
@@ -5255,11 +5314,11 @@ export class Core extends ReadyResource {
5255
5314
  }
5256
5315
  async _listProject(workspace, project, listing) {
5257
5316
  const batch = workspace.batch();
5258
- batch.dispatch('put-project', { project: { id: project.key, ...listing } });
5317
+ const listed = { id: project.key, ...listing, seedFingerprint: seedFingerprint(project.seed) };
5318
+ batch.dispatch('put-project', { project: listed });
5259
5319
  const ours = workspace.ourMemberId;
5260
- const own = ours
5261
- ? await dueProjectKey(workspace.view, ours, { projectId: project.key, seed: project.seed })
5262
- : null;
5320
+ const sealing = ours && { projectId: project.key, seed: project.seed, sealedBy: ours };
5321
+ const own = sealing ? await dueProjectKey(workspace.view, ours, sealing) : null;
5263
5322
  if (own) {
5264
5323
  batch.dispatch('put-project-key', own);
5265
5324
  }
@@ -5375,7 +5434,7 @@ export class Core extends ReadyResource {
5375
5434
  });
5376
5435
  }
5377
5436
  async _mintMesh(opts) {
5378
- const { shared, workspace, seed } = opts;
5437
+ const { shared, workspace, initial } = opts;
5379
5438
  if (this.closing) {
5380
5439
  throw new CoreError('CORE_CLOSING', ['Core']);
5381
5440
  }
@@ -5393,7 +5452,7 @@ export class Core extends ReadyResource {
5393
5452
  throw new CoreError('ACCOUNT_MEMBER_UNKNOWN');
5394
5453
  }
5395
5454
  const role = workspace ? 'workspace' : undefined;
5396
- 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 });
5397
5456
  this._wireMesh(this._poolEntry(mesh));
5398
5457
  this._bringMeshOnline(mesh, { new: true });
5399
5458
  try {
@@ -5541,11 +5600,12 @@ export class Core extends ReadyResource {
5541
5600
  const mesh = this._pooled(meshId);
5542
5601
  const account = !!accountKey && b4a.equals(accountKey, row.key);
5543
5602
  const joined = meshes.get(meshId);
5544
- const state = this._meshEntryState(mesh, account);
5603
+ const state = this._meshEntryState(meshId, mesh, account);
5604
+ const content = row.role !== 'workspace' || !this._accountMesh()?.ourMemberId;
5545
5605
  return {
5546
5606
  meshId,
5547
5607
  state,
5548
- writable: mesh?.writable ?? false,
5608
+ writable: !!mesh?.writable && (content || !!this._publicMesh(meshId)?.writable),
5549
5609
  open: mesh !== null,
5550
5610
  account,
5551
5611
  label: joined?.label || undefined,
@@ -5556,10 +5616,12 @@ export class Core extends ReadyResource {
5556
5616
  workspace: row.role === 'workspace'
5557
5617
  };
5558
5618
  }
5559
- _meshEntryState(mesh, account) {
5619
+ _meshEntryState(meshId, mesh, account) {
5560
5620
  if (account) {
5561
5621
  return this._statusState();
5562
5622
  }
5623
+ if (this._haltedMeshes.has(meshId))
5624
+ return 'needs-upgrade';
5563
5625
  if (!mesh)
5564
5626
  return 'idle';
5565
5627
  return mesh.writable ? 'joined' : 'joining';
@@ -5726,8 +5788,7 @@ export class Core extends ReadyResource {
5726
5788
  return {
5727
5789
  meshId: key ? b4a.toHex(key) : undefined,
5728
5790
  writable: this._accountWritable(),
5729
- displayName: (await this.displayName()) ?? undefined,
5730
- ownWorkspace: this._ownWorkspaceId ?? undefined
5791
+ displayName: (await this.displayName()) ?? undefined
5731
5792
  };
5732
5793
  }
5733
5794
  async displayName() {
@@ -5818,9 +5879,6 @@ export class Core extends ReadyResource {
5818
5879
  if (!isOwnMesh) {
5819
5880
  throw new CoreError(mesh.writable ? 'MEMBER_INVITE_ACCOUNT_REFUSED' : 'MESH_STILL_JOINING');
5820
5881
  }
5821
- if (isOwnWorkspace(registry, mesh)) {
5822
- throw new CoreError('OWN_WORKSPACE_INVITE_REFUSED');
5823
- }
5824
5882
  if (workspace) {
5825
5883
  await requireOurAdmin(mesh, 'invite a member');
5826
5884
  }
@@ -5876,8 +5934,7 @@ export class Core extends ReadyResource {
5876
5934
  }
5877
5935
  async _publicHeads() {
5878
5936
  const heads = [];
5879
- const ids = new Set([this._publicIdOf(this._accountId), ...this._publicIds.values()]);
5880
- for (const meshId of ids) {
5937
+ for (const meshId of new Set(this._publicIds.values())) {
5881
5938
  const mesh = this._pooled(meshId);
5882
5939
  const head = mesh && (await inviteHead(mesh));
5883
5940
  if (head) {
@@ -6080,9 +6137,6 @@ export class Core extends ReadyResource {
6080
6137
  }
6081
6138
  const held = this._pooled(meshId);
6082
6139
  const failed = await this._trackFollow(meshId, async () => {
6083
- if (await lostMint(memberMesh, joined.meshKey)) {
6084
- return;
6085
- }
6086
6140
  if (joined.kicked && !joined.leftAt) {
6087
6141
  await this._followKick(meshId, held);
6088
6142
  return;
@@ -6110,6 +6164,7 @@ export class Core extends ReadyResource {
6110
6164
  }
6111
6165
  if (await this.local.readMeshSession(joined.meshKey)) {
6112
6166
  if (this._upgradeRequired !== 'halt' &&
6167
+ !this._haltedMeshes.has(meshId) &&
6113
6168
  (await this.local.awaitsAdmission(joined.meshKey))) {
6114
6169
  tally.readmitted++;
6115
6170
  await this._openPooledMesh(meshId, 'readmit');
@@ -6177,10 +6232,13 @@ export class Core extends ReadyResource {
6177
6232
  }
6178
6233
  }
6179
6234
  async _openFollowedMesh(memberMesh, joined) {
6180
- 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)) {
6181
6240
  return 'skipped';
6182
6241
  }
6183
- const { meshKey } = joined;
6184
6242
  const held = await memberMesh.view.get(MESH_SEEDS, { meshKey });
6185
6243
  if (!held) {
6186
6244
  return 'no-seed';
@@ -6310,27 +6368,36 @@ export class Core extends ReadyResource {
6310
6368
  }
6311
6369
  }
6312
6370
  async _sealListedMembers(workspace, row, seed) {
6371
+ const sealedBy = workspace.ourMemberId;
6372
+ if (!sealedBy) {
6373
+ return;
6374
+ }
6313
6375
  const batch = workspace.batch();
6314
6376
  for (const memberId of row.memberIds ?? []) {
6315
- const due = await dueProjectKey(workspace.view, memberId, { projectId: row.id, seed });
6377
+ const due = await dueProjectKey(workspace.view, memberId, {
6378
+ projectId: row.id,
6379
+ seed,
6380
+ sealedBy
6381
+ });
6316
6382
  if (due) {
6317
6383
  batch.dispatch('put-project-key', due);
6318
6384
  }
6319
6385
  }
6320
- for (const due of await dueProjectDeviceKeys(workspace.view, row, seed)) {
6386
+ for (const due of await dueProjectDeviceKeys(workspace.view, row, { seed, sealedBy })) {
6321
6387
  batch.dispatch('put-project-device-key', due);
6322
6388
  }
6323
6389
  await batch.flush();
6324
6390
  }
6325
6391
  async _sealProjectHosts(workspace, projectId, seed) {
6326
6392
  const project = this._pooled(b4a.toHex(projectId));
6327
- if (!project || this._isForeign(project)) {
6393
+ const sealedBy = workspace.ourMemberId;
6394
+ if (!project || this._isForeign(project) || !sealedBy) {
6328
6395
  return;
6329
6396
  }
6330
6397
  const batch = workspace.batch();
6331
6398
  for (const user of await workspace.view.find(AGENT_USERS).toArray()) {
6332
6399
  const agent = b4a.equals(user.userId, projectId) && (await liveSharedAgent(workspace, user.agentId));
6333
- const sealing = { projectId, seed, project: project.view };
6400
+ const sealing = { projectId, seed, project: project.view, sealedBy };
6334
6401
  const due = agent && (await dueProjectHostKey(workspace.view, agent, sealing));
6335
6402
  if (due) {
6336
6403
  batch.dispatch('put-project-host-key', due);
@@ -6351,19 +6418,29 @@ export class Core extends ReadyResource {
6351
6418
  async _memberProjectSeed(workspace, projectId) {
6352
6419
  const ours = workspace.ourMemberId;
6353
6420
  const account = this._accountMesh();
6354
- if (!ours || !account) {
6421
+ const project = await readProject(workspace.view, projectId);
6422
+ if (!ours || !account || !project) {
6355
6423
  return null;
6356
6424
  }
6357
- const row = await readProjectKey(workspace.view, projectId, ours);
6358
6425
  const pair = memberBoxKeyPair(account.seed);
6359
- return row && b4a.equals(row.boxKey, pair.publicKey)
6360
- ? openSealedToMember(row.sealedSeed, pair)
6361
- : null;
6426
+ for (const row of await projectKeys(workspace.view, projectId, ours)) {
6427
+ const seed = b4a.equals(row.boxKey, pair.publicKey) && openSealedToMember(row.sealedSeed, pair);
6428
+ if (seed && seedOpens(project, seed)) {
6429
+ return seed;
6430
+ }
6431
+ }
6432
+ return null;
6362
6433
  }
6363
6434
  async _deviceProjectSeed(workspace, projectId) {
6364
6435
  const device = this._requireDeviceKeyPair();
6365
- const row = await readProjectDeviceKey(workspace.view, projectId, device.publicKey);
6366
- return row && openSealedToDevice(row.sealedSeed, device);
6436
+ const project = await readProject(workspace.view, projectId);
6437
+ for (const row of await projectDeviceKeys(workspace.view, projectId, device.publicKey)) {
6438
+ const seed = openSealedToDevice(row.sealedSeed, device);
6439
+ if (project && seed && seedOpens(project, seed)) {
6440
+ return seed;
6441
+ }
6442
+ }
6443
+ return null;
6367
6444
  }
6368
6445
  async _projectGone(projectId) {
6369
6446
  if (this._isHidden(projectId, this._pooled(projectId)?.workspaceKey)) {
@@ -6655,6 +6732,9 @@ export class Core extends ReadyResource {
6655
6732
  if (pooled && this._definesAgents(pooled, request)) {
6656
6733
  return this._accountMesh() ?? pooled;
6657
6734
  }
6735
+ if (pooled) {
6736
+ this._refuseAccountContent(pooled, request);
6737
+ }
6658
6738
  if (pooled && !this._routesToPublic(pooled, request)) {
6659
6739
  return pooled;
6660
6740
  }
@@ -6708,18 +6788,29 @@ export class Core extends ReadyResource {
6708
6788
  };
6709
6789
  }
6710
6790
  _definesAgents(mesh, { route }) {
6711
- return ((route === 'put-agent' || route === 'put-tool-configs') &&
6791
+ return ((route === 'put-agent' || route === 'put-tool-configs' || route === 'put-approval-rule') &&
6712
6792
  mesh.role === 'workspace' &&
6713
6793
  this._hasPublic(mesh));
6714
6794
  }
6795
+ _refuseAccountContent(mesh, { route }) {
6796
+ if (route && publicRoute(route) && this._isAccount(mesh)) {
6797
+ throw new CoreError('ROUTE_NEEDS_WORKSPACE', [route]);
6798
+ }
6799
+ }
6715
6800
  _routesToPublic(mesh, { route }) {
6716
6801
  return !!route && publicRoute(route) && this._hasPublic(mesh);
6717
6802
  }
6718
6803
  async _routedMesh(pooled, meshId, request) {
6719
6804
  const mesh = pooled ?? (await this._publicById(meshId)) ?? (await this._openPooledMesh(meshId));
6720
- 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));
6721
6808
  return this._routesToPublic(mesh, request) ? this._publicOf(mesh, { ...request, follow }) : mesh;
6722
6809
  }
6810
+ async _holdsPublic(workspace) {
6811
+ const account = this._accountMesh();
6812
+ return !!account && !!(await this._publicRecord(account, workspace.key))?.key;
6813
+ }
6723
6814
  async _publicById(meshId) {
6724
6815
  const account = this._accountMesh();
6725
6816
  if (!account) {
@@ -6729,9 +6820,9 @@ export class Core extends ReadyResource {
6729
6820
  if ((await this._publicRecord(account, workspaceKey))?.key !== meshId) {
6730
6821
  continue;
6731
6822
  }
6732
- const workspaceId = b4a.toHex(workspaceKey);
6733
- const scope = workspaceId === this._ownWorkspaceId ? account : this._pooled(workspaceId);
6734
- 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 }));
6735
6826
  return mesh && this._meshIdOf(mesh) === meshId ? mesh : null;
6736
6827
  }
6737
6828
  return null;
@@ -6772,7 +6863,7 @@ export class Core extends ReadyResource {
6772
6863
  createProject: (workspaceId, opts) => this.createProject(workspaceId, opts),
6773
6864
  listArchived: () => this.listArchivedMeshes(),
6774
6865
  archivedContents: (meshId) => this.archivedMeshContents(meshId),
6775
- migrateArchived: (meshId) => this.migrateArchivedMesh(meshId),
6866
+ migrateArchived: (meshId, workspaceId) => this.migrateArchivedMesh(meshId, workspaceId),
6776
6867
  recoverable: () => this.accountRecoverable(),
6777
6868
  publishRecovery: async (phrase) => void (await this.publishAccountRecovery(phrase)),
6778
6869
  recover: (phrase, timeout) => this.recoverAccount(phrase, { timeout }),
@@ -7298,12 +7389,14 @@ export class Core extends ReadyResource {
7298
7389
  return 'joining';
7299
7390
  }
7300
7391
  if (this._accountMesh()) {
7301
- return this._accountWritable() ? 'joined' : 'joining';
7392
+ return this._accountWritable() && this._ownDecided === this._accountMesh()
7393
+ ? 'joined'
7394
+ : 'joining';
7302
7395
  }
7303
7396
  return 'idle';
7304
7397
  }
7305
7398
  _accountWritable() {
7306
- return !!this._accountMesh()?.writable && !!this._publicMesh()?.writable;
7399
+ return !!this._accountMesh()?.writable;
7307
7400
  }
7308
7401
  async _chatSenders(meshId) {
7309
7402
  const project = this._pooled(meshId);