@arbidocs/sdk 0.4.108 → 0.4.111

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.
package/dist/browser.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createArbiClient, base64ToBytes, deriveEncryptionKeypairFromSigning, sealedBoxDecrypt, sealKeyForSession, buildWebSocketUrl, createAuthMessage, parseServerMessage, isMessageType, createContentHash, encryptFile, initSodium, bytesToBase64, decryptFile, changePassword } from '@arbidocs/client';
1
+ import { createArbiClient, base64ToBytes, deriveEncryptionKeypairFromSigning, sealedBoxDecrypt, sealKeyForSession, buildWebSocketUrl, createAuthMessage, parseServerMessage, isMessageType, createContentHash, encryptFile, initSodium, bytesToBase64, encryptWithChatKey, decryptWithChatKey, decryptFile, deriveDirectChatKey, openSealedChatKey, generateChatKey, sealChatKey, encryptMessage, changePassword } from '@arbidocs/client';
2
2
 
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -4358,6 +4358,7 @@ __export(documents_exports, {
4358
4358
  listPaginated: () => listPaginated,
4359
4359
  listVersions: () => listVersions,
4360
4360
  mimeFromName: () => mimeFromName,
4361
+ presignedPut: () => presignedPut,
4361
4362
  sanitizeFolderPath: () => sanitizeFolderPath,
4362
4363
  updateDocuments: () => updateDocuments,
4363
4364
  uploadDocumentsDirect: () => uploadDocumentsDirect,
@@ -4630,12 +4631,15 @@ function mimeFromName(name) {
4630
4631
  return void 0;
4631
4632
  }
4632
4633
  }
4633
- async function presignedPut(url, body, onProgress) {
4634
+ async function presignedPut(url, body, onProgress, headers) {
4634
4635
  const XhrGlobal = globalThis.XMLHttpRequest;
4635
4636
  if (XhrGlobal) {
4636
4637
  await new Promise((resolve, reject) => {
4637
4638
  const xhr = new XhrGlobal();
4638
4639
  xhr.open("PUT", url);
4640
+ for (const [name, value] of Object.entries(headers ?? {})) {
4641
+ xhr.setRequestHeader(name, value);
4642
+ }
4639
4643
  if (onProgress) {
4640
4644
  xhr.upload.addEventListener("progress", (e) => {
4641
4645
  if (e.lengthComputable) onProgress(e.loaded, e.total);
@@ -4655,7 +4659,7 @@ async function presignedPut(url, body, onProgress) {
4655
4659
  });
4656
4660
  return;
4657
4661
  }
4658
- const putRes = await fetch(url, { method: "PUT", body });
4662
+ const putRes = await fetch(url, { method: "PUT", body, ...headers ? { headers } : {} });
4659
4663
  if (!putRes.ok) {
4660
4664
  const snippet = await putRes.text().catch(() => "");
4661
4665
  throw new Error(`Presigned PUT failed: ${putRes.status} ${snippet.slice(0, 200)}`);
@@ -5406,37 +5410,57 @@ function mergeKindFieldDefinitions(current, wanted, { keepOthers = false } = {})
5406
5410
  // src/operations/contacts.ts
5407
5411
  var contacts_exports = {};
5408
5412
  __export(contacts_exports, {
5409
- addContacts: () => addContacts,
5413
+ createContact: () => createContact,
5414
+ deleteContact: () => deleteContact,
5410
5415
  groupContactsByStatus: () => groupContactsByStatus,
5416
+ inviteContacts: () => inviteContacts,
5411
5417
  listContacts: () => listContacts,
5412
- removeContacts: () => removeContacts
5418
+ searchContacts: () => searchContacts,
5419
+ updateContact: () => updateContact
5413
5420
  });
5414
5421
  async function listContacts(arbi) {
5415
- return requireData(await arbi.fetch.GET("/v1/user/contacts"), "Failed to fetch contacts");
5422
+ return requireData(await arbi.fetch.GET("/v1/contacts/"), "Failed to fetch contacts");
5423
+ }
5424
+ async function inviteContacts(arbi, emails) {
5425
+ return requireData(
5426
+ await arbi.fetch.POST("/v1/contacts/invitations", { body: { emails } }),
5427
+ "Failed to invite contacts"
5428
+ );
5429
+ }
5430
+ async function createContact(arbi, body) {
5431
+ return requireData(await arbi.fetch.POST("/v1/contacts/", { body }), "Failed to create contact");
5416
5432
  }
5417
- async function addContacts(arbi, emails) {
5433
+ async function updateContact(arbi, contactId, card) {
5418
5434
  return requireData(
5419
- await arbi.fetch.POST("/v1/user/contacts", { body: { emails } }),
5420
- "Failed to add contacts"
5435
+ await arbi.fetch.PATCH("/v1/contacts/{cnt_id}", {
5436
+ params: { path: { cnt_id: contactId } },
5437
+ body: { card, invite: false }
5438
+ }),
5439
+ "Failed to update contact"
5421
5440
  );
5422
5441
  }
5423
- async function removeContacts(arbi, contactIds) {
5442
+ async function deleteContact(arbi, contactId) {
5424
5443
  requireOk(
5425
- await arbi.fetch.DELETE("/v1/user/contacts", { body: { contact_ids: contactIds } }),
5426
- "Failed to remove contacts"
5444
+ await arbi.fetch.DELETE("/v1/contacts/{cnt_id}", { params: { path: { cnt_id: contactId } } }),
5445
+ "Failed to delete contact"
5446
+ );
5447
+ }
5448
+ async function searchContacts(arbi, q2) {
5449
+ return requireData(
5450
+ await arbi.fetch.GET("/v1/contacts/search", { params: { query: { q: q2 } } }),
5451
+ "Failed to search contacts"
5427
5452
  );
5428
5453
  }
5429
5454
  function groupContactsByStatus(contactList) {
5430
5455
  const registered = [];
5431
5456
  const pending = [];
5457
+ const cards = [];
5432
5458
  for (const c2 of contactList) {
5433
- if (c2.status === "registered") {
5434
- registered.push(c2);
5435
- } else {
5436
- pending.push(c2);
5437
- }
5459
+ if (c2.status === "registered") registered.push(c2);
5460
+ else if (c2.status === "card") cards.push(c2);
5461
+ else pending.push(c2);
5438
5462
  }
5439
- return { registered, pending };
5463
+ return { registered, pending, cards };
5440
5464
  }
5441
5465
 
5442
5466
  // src/operations/doctags.ts
@@ -5482,32 +5506,45 @@ async function generateDocTags(arbi, tagIds, docIds, options) {
5482
5506
  );
5483
5507
  }
5484
5508
 
5485
- // src/operations/dm.ts
5486
- var dm_exports = {};
5487
- __export(dm_exports, {
5488
- DM_ATTACHMENT_MAX_BYTES: () => DM_ATTACHMENT_MAX_BYTES,
5489
- DM_ATTACHMENT_MAX_FILES: () => DM_ATTACHMENT_MAX_FILES,
5490
- checkDmAttachmentLimits: () => checkDmAttachmentLimits,
5491
- createDmCryptoContext: () => createDmCryptoContext,
5492
- decryptDmAttachments: () => decryptDmAttachments,
5493
- decryptDmBatch: () => decryptDmBatch,
5494
- decryptDmContent: () => decryptDmContent,
5495
- deleteDMs: () => deleteDMs,
5496
- downloadDmAttachment: () => downloadDmAttachment,
5497
- encryptDmAttachmentManifest: () => encryptDmAttachmentManifest,
5498
- encryptDmContent: () => encryptDmContent,
5499
- listActivity: () => listActivity,
5500
- listDMs: () => listDMs,
5501
- listDecryptedDMs: () => listDecryptedDMs,
5502
- markRead: () => markRead,
5503
- parseDmAttachmentManifest: () => parseDmAttachmentManifest,
5504
- requestWorkspaceAccess: () => requestWorkspaceAccess,
5509
+ // src/operations/chats.ts
5510
+ var chats_exports = {};
5511
+ __export(chats_exports, {
5512
+ CHAT_ATTACHMENT_MAX_BYTES: () => CHAT_ATTACHMENT_MAX_BYTES,
5513
+ CHAT_ATTACHMENT_MAX_FILES: () => CHAT_ATTACHMENT_MAX_FILES,
5514
+ DECRYPTION_FAILED: () => DECRYPTION_FAILED,
5515
+ addChatMembers: () => addChatMembers,
5516
+ chatMessageTombstone: () => chatMessageTombstone,
5517
+ checkChatAttachmentLimits: () => checkChatAttachmentLimits,
5518
+ createChatCryptoContext: () => createChatCryptoContext,
5519
+ createGroupChat: () => createGroupChat,
5520
+ decryptChatAttachmentManifest: () => decryptChatAttachmentManifest,
5521
+ decryptChatMessage: () => decryptChatMessage,
5522
+ decryptChatMessages: () => decryptChatMessages,
5523
+ decryptChatTitle: () => decryptChatTitle,
5524
+ deleteChatMessage: () => deleteChatMessage,
5525
+ directPeer: () => directPeer,
5526
+ downloadChatAttachment: () => downloadChatAttachment,
5527
+ encryptChatAttachmentManifest: () => encryptChatAttachmentManifest,
5528
+ ensureChatKeyCurrent: () => ensureChatKeyCurrent,
5529
+ getChat: () => getChat,
5530
+ hasRead: () => hasRead,
5531
+ isAgentExtId: () => isAgentExtId,
5532
+ listChatMessages: () => listChatMessages,
5533
+ listChats: () => listChats,
5534
+ loadDecryptedChat: () => loadDecryptedChat,
5535
+ markChatRead: () => markChatRead,
5536
+ openChatKeyRing: () => openChatKeyRing,
5537
+ openDirectChat: () => openDirectChat,
5538
+ parseChatAttachmentManifest: () => parseChatAttachmentManifest,
5539
+ removeChatMember: () => removeChatMember,
5540
+ renameChat: () => renameChat,
5505
5541
  resolveRecipient: () => resolveRecipient,
5506
- sendDM: () => sendDM,
5507
- sendEncryptedDM: () => sendEncryptedDM,
5508
- serializeDmAttachmentManifest: () => serializeDmAttachmentManifest,
5509
- uploadDmAttachment: () => uploadDmAttachment,
5510
- uploadDmAttachments: () => uploadDmAttachments
5542
+ rotateChatKey: () => rotateChatKey,
5543
+ sendChatMessage: () => sendChatMessage,
5544
+ sendDirectMessage: () => sendDirectMessage,
5545
+ serializeChatAttachmentManifest: () => serializeChatAttachmentManifest,
5546
+ uploadChatAttachment: () => uploadChatAttachment,
5547
+ uploadChatAttachments: () => uploadChatAttachments
5511
5548
  });
5512
5549
 
5513
5550
  // src/operations/agents.ts
@@ -5599,27 +5636,27 @@ async function stageAgentFile(auth, agentId, file, name) {
5599
5636
  });
5600
5637
  return response.json();
5601
5638
  }
5602
- var DM_ATTACHMENT_MAX_BYTES = 15 * 1024 * 1024;
5603
- var DM_ATTACHMENT_MAX_FILES = 10;
5639
+ var CHAT_ATTACHMENT_MAX_BYTES = 15 * 1024 * 1024;
5640
+ var CHAT_ATTACHMENT_MAX_FILES = 10;
5604
5641
  var ATTACHMENT_ID = /^att-[a-zA-Z0-9]{8}$/;
5605
5642
  var MANIFEST_VERSION = 1;
5606
5643
  var MB = 1024 * 1024;
5607
- function checkDmAttachmentLimits(files) {
5608
- if (files.length > DM_ATTACHMENT_MAX_FILES) {
5644
+ function checkChatAttachmentLimits(files) {
5645
+ if (files.length > CHAT_ATTACHMENT_MAX_FILES) {
5609
5646
  throw new Error(
5610
- `You can attach at most ${DM_ATTACHMENT_MAX_FILES} files to a message (this one has ${files.length}).`
5647
+ `You can attach at most ${CHAT_ATTACHMENT_MAX_FILES} files to a message (this one has ${files.length}).`
5611
5648
  );
5612
5649
  }
5613
5650
  for (const file of files) {
5614
- if (file.size > DM_ATTACHMENT_MAX_BYTES) {
5651
+ if (file.size > CHAT_ATTACHMENT_MAX_BYTES) {
5615
5652
  throw new Error(
5616
- `${file.name} is too large (${(file.size / MB).toFixed(1)} MB). Files can be at most ${DM_ATTACHMENT_MAX_BYTES / MB} MB.`
5653
+ `${file.name} is too large (${(file.size / MB).toFixed(1)} MB). Files can be at most ${CHAT_ATTACHMENT_MAX_BYTES / MB} MB.`
5617
5654
  );
5618
5655
  }
5619
5656
  }
5620
5657
  }
5621
- async function uploadDmAttachment(arbi, input) {
5622
- checkDmAttachmentLimits([{ name: input.name, size: input.bytes.length }]);
5658
+ async function uploadChatAttachment(arbi, input) {
5659
+ checkChatAttachmentLimits([{ name: input.name, size: input.bytes.length }]);
5623
5660
  await initSodium();
5624
5661
  const key = globalThis.crypto.getRandomValues(new Uint8Array(32));
5625
5662
  try {
@@ -5630,13 +5667,13 @@ async function uploadDmAttachment(arbi, input) {
5630
5667
  new Blob([ciphertext], { type: "application/octet-stream" }),
5631
5668
  "attachment.bin"
5632
5669
  );
5633
- const result = await arbi.fetch.POST("/v1/notifications/attachments", {
5670
+ const result = await arbi.fetch.POST("/v1/chats/attachments", {
5634
5671
  body: { file: "" },
5635
5672
  bodySerializer: () => form
5636
5673
  });
5637
5674
  if (result.response?.status === 413) {
5638
5675
  throw new ArbiApiError(
5639
- `${input.name} is too large. Files can be at most ${DM_ATTACHMENT_MAX_BYTES / MB} MB.`,
5676
+ `${input.name} is too large. Files can be at most ${CHAT_ATTACHMENT_MAX_BYTES / MB} MB.`,
5640
5677
  result.error,
5641
5678
  413
5642
5679
  );
@@ -5653,19 +5690,19 @@ async function uploadDmAttachment(arbi, input) {
5653
5690
  key.fill(0);
5654
5691
  }
5655
5692
  }
5656
- async function uploadDmAttachments(arbi, inputs) {
5657
- checkDmAttachmentLimits(inputs.map((i2) => ({ name: i2.name, size: i2.bytes.length })));
5693
+ async function uploadChatAttachments(arbi, inputs) {
5694
+ checkChatAttachmentLimits(inputs.map((i2) => ({ name: i2.name, size: i2.bytes.length })));
5658
5695
  const files = [];
5659
- for (const input of inputs) files.push(await uploadDmAttachment(arbi, input));
5696
+ for (const input of inputs) files.push(await uploadChatAttachment(arbi, input));
5660
5697
  return files;
5661
5698
  }
5662
- function serializeDmAttachmentManifest(files) {
5699
+ function serializeChatAttachmentManifest(files) {
5663
5700
  return JSON.stringify({
5664
5701
  v: MANIFEST_VERSION,
5665
5702
  files: files.map(({ id, name, type, size, key }) => ({ id, name, type, size, key }))
5666
5703
  });
5667
5704
  }
5668
- function parseDmAttachmentManifest(json2) {
5705
+ function parseChatAttachmentManifest(json2) {
5669
5706
  const manifest = JSON.parse(json2);
5670
5707
  if (manifest?.v !== MANIFEST_VERSION || !Array.isArray(manifest.files)) {
5671
5708
  throw new Error("Unsupported attachment manifest");
@@ -5684,27 +5721,15 @@ function parseDmAttachmentManifest(json2) {
5684
5721
  };
5685
5722
  });
5686
5723
  }
5687
- async function encryptDmAttachmentManifest(arbi, files, recipientEncryptionPubKeyBase64, senderEncryptionSecretKey) {
5688
- return arbi.crypto.encryptMessage(
5689
- serializeDmAttachmentManifest(files),
5690
- recipientEncryptionPubKeyBase64,
5691
- senderEncryptionSecretKey
5692
- );
5724
+ async function encryptChatAttachmentManifest(files, chatKey) {
5725
+ return encryptWithChatKey(serializeChatAttachmentManifest(files), chatKey);
5693
5726
  }
5694
- async function decryptDmAttachments(arbi, notification, crypto2) {
5695
- if (!notification.attachments) return [];
5696
- const isSent = notification.sender.external_id === crypto2.userExtId;
5697
- const otherParty = isSent ? notification.recipient : notification.sender;
5698
- const json2 = await arbi.crypto.decryptMessage(
5699
- notification.attachments,
5700
- otherParty.encryption_public_key,
5701
- crypto2.encryptionKeypair.secretKey
5702
- );
5703
- return parseDmAttachmentManifest(json2);
5727
+ async function decryptChatAttachmentManifest(manifest, chatKey) {
5728
+ return parseChatAttachmentManifest(await decryptWithChatKey(manifest, chatKey));
5704
5729
  }
5705
- async function downloadDmAttachment(arbi, file) {
5730
+ async function downloadChatAttachment(arbi, file) {
5706
5731
  if (!ATTACHMENT_ID.test(file.id)) throw new Error(`Invalid attachment id: ${file.id}`);
5707
- const result = await arbi.fetch.GET("/v1/notifications/attachments/{external_id}", {
5732
+ const result = await arbi.fetch.GET("/v1/chats/attachments/{external_id}", {
5708
5733
  params: { path: { external_id: file.id } },
5709
5734
  parseAs: "arrayBuffer"
5710
5735
  });
@@ -5732,78 +5757,289 @@ async function downloadDmAttachment(arbi, file) {
5732
5757
  return plain;
5733
5758
  }
5734
5759
 
5735
- // src/operations/dm.ts
5736
- function createDmCryptoContext(arbi, signingPrivateKeyBytes, userExtId) {
5737
- const ed25519PublicKey = signingPrivateKeyBytes.slice(32, 64);
5738
- const encryptionKeypair = arbi.crypto.deriveEncryptionKeypairFromSigning({
5739
- publicKey: ed25519PublicKey,
5760
+ // src/operations/chats.ts
5761
+ function createChatCryptoContext(signingPrivateKeyBytes, userExtId) {
5762
+ const encryptionKeypair = deriveEncryptionKeypairFromSigning({
5763
+ publicKey: signingPrivateKeyBytes.slice(32, 64),
5740
5764
  secretKey: signingPrivateKeyBytes
5741
5765
  });
5742
5766
  return { encryptionKeypair, userExtId };
5743
5767
  }
5744
- async function encryptDmContent(arbi, plaintext, recipientEncryptionPubKeyBase64, senderEncryptionSecretKey) {
5745
- return arbi.crypto.encryptMessage(
5746
- plaintext,
5747
- recipientEncryptionPubKeyBase64,
5748
- senderEncryptionSecretKey
5749
- );
5750
- }
5751
- async function decryptDmContent(arbi, notification, crypto2) {
5752
- if (!notification.content) return null;
5753
- const isSent = notification.sender.external_id === crypto2.userExtId;
5754
- const otherParty = isSent ? notification.recipient : notification.sender;
5755
- return arbi.crypto.decryptMessage(
5756
- notification.content,
5757
- otherParty.encryption_public_key,
5758
- crypto2.encryptionKeypair.secretKey
5759
- );
5760
- }
5761
- async function decryptDmBatch(arbi, notifications, crypto2) {
5762
- const results = [];
5763
- for (const n2 of notifications) {
5764
- if (n2.type !== "user_message" || !n2.content && !n2.attachments) {
5765
- results.push(n2);
5766
- continue;
5768
+ function isAgentExtId(extId) {
5769
+ return !!extId && extId.startsWith("agt-");
5770
+ }
5771
+ function directPeer(chat, myExtId) {
5772
+ if (chat.kind !== "direct") return void 0;
5773
+ return chat.members.find((m2) => m2.user.external_id !== myExtId)?.user;
5774
+ }
5775
+ async function openChatKeyRing(chat, crypto2) {
5776
+ const keys = /* @__PURE__ */ new Map();
5777
+ if (chat.kind === "direct") {
5778
+ const peer = directPeer(chat, crypto2.userExtId);
5779
+ const peerPub = peer?.encryption_public_key ?? bytesToBase64(crypto2.encryptionKeypair.publicKey);
5780
+ keys.set(0, await deriveDirectChatKey(peerPub, crypto2.encryptionKeypair.secretKey));
5781
+ } else {
5782
+ for (const k2 of chat.my_keys ?? []) {
5783
+ try {
5784
+ keys.set(
5785
+ k2.version,
5786
+ await openSealedChatKey(k2.sealed_key, crypto2.encryptionKeypair.secretKey)
5787
+ );
5788
+ } catch {
5789
+ }
5767
5790
  }
5768
- let row;
5791
+ }
5792
+ return { chatExtId: chat.external_id, kind: chat.kind, currentVersion: chat.key_version, keys };
5793
+ }
5794
+ function keyFor(ring, version) {
5795
+ const key = ring.keys.get(version);
5796
+ if (!key) throw new Error(`No key for epoch ${version} of ${ring.chatExtId}`);
5797
+ return key;
5798
+ }
5799
+ var DECRYPTION_FAILED = "[Decryption failed]";
5800
+ function chatMessageTombstone(message) {
5801
+ const row = {
5802
+ ...message,
5803
+ deleted: true,
5804
+ content: null,
5805
+ attachments: null,
5806
+ dedupe_key: null
5807
+ };
5808
+ delete row.decryptFailed;
5809
+ delete row.attachmentFiles;
5810
+ delete row.attachmentsError;
5811
+ return row;
5812
+ }
5813
+ async function decryptChatMessage(ring, message) {
5814
+ if (message.deleted) return chatMessageTombstone(message);
5815
+ const key = ring.keys.get(message.key_version);
5816
+ const row = { ...message };
5817
+ if (message.content) {
5769
5818
  try {
5770
- row = { ...n2, content: await decryptDmContent(arbi, n2, crypto2) };
5819
+ if (!key) throw new Error("no key");
5820
+ row.content = await decryptWithChatKey(message.content, key);
5771
5821
  } catch {
5772
- row = { ...n2, content: "[Decryption failed]" };
5822
+ row.content = DECRYPTION_FAILED;
5823
+ row.decryptFailed = true;
5773
5824
  }
5774
- if (n2.attachments) {
5775
- try {
5776
- row.attachmentFiles = await decryptDmAttachments(arbi, n2, crypto2);
5777
- } catch {
5778
- row.attachmentFiles = [];
5779
- row.attachmentsError = "The attachments could not be decrypted";
5780
- }
5825
+ }
5826
+ if (message.attachments) {
5827
+ try {
5828
+ if (!key) throw new Error("no key");
5829
+ row.attachmentFiles = await decryptChatAttachmentManifest(message.attachments, key);
5830
+ } catch {
5831
+ row.attachmentFiles = [];
5832
+ row.attachmentsError = "The attachments could not be decrypted";
5781
5833
  }
5782
- results.push(row);
5783
5834
  }
5784
- return results;
5835
+ return row;
5785
5836
  }
5786
- async function listDMs(arbi) {
5787
- return requireData(await arbi.fetch.GET("/v1/notifications/"), "Failed to fetch messages");
5837
+ async function decryptChatMessages(ring, messages) {
5838
+ return Promise.all(messages.map((m2) => decryptChatMessage(ring, m2)));
5788
5839
  }
5789
- async function listDecryptedDMs(arbi, crypto2) {
5790
- const raw = await listDMs(arbi);
5791
- return decryptDmBatch(arbi, raw, crypto2);
5840
+ async function decryptChatTitle(ring, chat) {
5841
+ if (!chat.title) return null;
5842
+ const key = ring.keys.get(chat.key_version);
5843
+ if (!key) return null;
5844
+ try {
5845
+ return await decryptWithChatKey(chat.title, key);
5846
+ } catch {
5847
+ return null;
5848
+ }
5792
5849
  }
5793
- async function listActivity(arbi, options) {
5850
+ async function listChats(arbi, kind) {
5794
5851
  return requireData(
5795
- await arbi.fetch.GET("/v1/notifications/", {
5852
+ await arbi.fetch.GET("/v1/chats/", { params: { query: kind ? { kind } : {} } }),
5853
+ "Failed to list chats"
5854
+ );
5855
+ }
5856
+ async function getChat(arbi, chatExtId) {
5857
+ return requireData(
5858
+ await arbi.fetch.GET("/v1/chats/{chat_ext_id}", {
5859
+ params: { path: { chat_ext_id: chatExtId } }
5860
+ }),
5861
+ "Failed to load chat"
5862
+ );
5863
+ }
5864
+ async function openDirectChat(arbi, peerExtId) {
5865
+ return requireData(
5866
+ await arbi.fetch.POST("/v1/chats/", { body: { kind: "direct", peer_ext_id: peerExtId } }),
5867
+ "Failed to open chat"
5868
+ );
5869
+ }
5870
+ async function createGroupChat(arbi, crypto2, params) {
5871
+ const members = params.members.filter((m2) => m2.external_id !== crypto2.userExtId);
5872
+ if (members.length === 0) throw new Error("A group needs at least one other member");
5873
+ const agent = members.find((m2) => isAgentExtId(m2.external_id));
5874
+ if (agent) throw new Error("Personal agents cannot join a group chat");
5875
+ const key = await generateChatKey();
5876
+ try {
5877
+ const title = params.title?.trim();
5878
+ return requireData(
5879
+ await arbi.fetch.POST("/v1/chats/", {
5880
+ body: {
5881
+ kind: "group",
5882
+ title: title ? await encryptWithChatKey(title, key) : null,
5883
+ members: await Promise.all(
5884
+ members.map(async (m2) => ({
5885
+ user_ext_id: m2.external_id,
5886
+ sealed_key: await sealChatKey(key, m2.encryption_public_key)
5887
+ }))
5888
+ ),
5889
+ creator_sealed_key: await sealChatKey(
5890
+ key,
5891
+ bytesToBase64(crypto2.encryptionKeypair.publicKey)
5892
+ )
5893
+ }
5894
+ }),
5895
+ "Failed to create group"
5896
+ );
5897
+ } finally {
5898
+ key.fill(0);
5899
+ }
5900
+ }
5901
+ async function renameChat(arbi, ring, title) {
5902
+ const trimmed = title?.trim();
5903
+ return requireData(
5904
+ await arbi.fetch.PATCH("/v1/chats/{chat_ext_id}", {
5905
+ params: { path: { chat_ext_id: ring.chatExtId } },
5906
+ body: {
5907
+ title: trimmed ? await encryptWithChatKey(trimmed, keyFor(ring, ring.currentVersion)) : null
5908
+ }
5909
+ }),
5910
+ "Failed to rename chat"
5911
+ );
5912
+ }
5913
+ async function addChatMembers(arbi, ring, members) {
5914
+ if (ring.kind === "direct") {
5915
+ throw new Error("A direct chat cannot gain members: create a group instead");
5916
+ }
5917
+ if (members.some((m2) => isAgentExtId(m2.external_id))) {
5918
+ throw new Error("Personal agents cannot join a group chat");
5919
+ }
5920
+ const key = keyFor(ring, ring.currentVersion);
5921
+ return requireData(
5922
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/members", {
5923
+ params: { path: { chat_ext_id: ring.chatExtId } },
5924
+ body: {
5925
+ members: await Promise.all(
5926
+ members.map(async (m2) => ({
5927
+ user_ext_id: m2.external_id,
5928
+ sealed_key: await sealChatKey(key, m2.encryption_public_key)
5929
+ }))
5930
+ )
5931
+ }
5932
+ }),
5933
+ "Failed to add members"
5934
+ );
5935
+ }
5936
+ async function removeChatMember(arbi, chatExtId, userExtId) {
5937
+ requireOk(
5938
+ await arbi.fetch.DELETE("/v1/chats/{chat_ext_id}/members/{user_ext_id}", {
5939
+ params: { path: { chat_ext_id: chatExtId, user_ext_id: userExtId } }
5940
+ }),
5941
+ "Failed to remove member"
5942
+ );
5943
+ }
5944
+ async function rotateChatKey(arbi, chat, ring) {
5945
+ if (chat.kind === "direct") throw new Error("Direct chats have no epochs");
5946
+ const oldTitle = await decryptChatTitle(ring, chat);
5947
+ if (chat.title && oldTitle === null) {
5948
+ throw new Error("Cannot re-encrypt the chat title: its key is not available");
5949
+ }
5950
+ const key = await generateChatKey();
5951
+ try {
5952
+ const sealed = {};
5953
+ for (const m2 of chat.members) {
5954
+ sealed[m2.user.external_id] = await sealChatKey(key, m2.user.encryption_public_key);
5955
+ }
5956
+ return requireData(
5957
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/keys", {
5958
+ params: { path: { chat_ext_id: chat.external_id } },
5959
+ body: {
5960
+ version: chat.key_version + 1,
5961
+ sealed_keys: sealed,
5962
+ ...oldTitle !== null ? { title: await encryptWithChatKey(oldTitle, key) } : {}
5963
+ }
5964
+ }),
5965
+ "Failed to rotate chat key"
5966
+ );
5967
+ } finally {
5968
+ key.fill(0);
5969
+ }
5970
+ }
5971
+ async function ensureChatKeyCurrent(arbi, chat, crypto2) {
5972
+ if (!chat.rotation_required || chat.kind === "direct") return chat;
5973
+ if (!chat.members.some((m2) => m2.user.external_id === crypto2.userExtId)) return chat;
5974
+ try {
5975
+ return await rotateChatKey(arbi, chat, await openChatKeyRing(chat, crypto2));
5976
+ } catch (err) {
5977
+ if (err instanceof ArbiApiError && err.status === 409) return getChat(arbi, chat.external_id);
5978
+ throw err;
5979
+ }
5980
+ }
5981
+ async function listChatMessages(arbi, chatExtId, options) {
5982
+ return requireData(
5983
+ await arbi.fetch.GET("/v1/chats/{chat_ext_id}/messages", {
5796
5984
  params: {
5985
+ path: { chat_ext_id: chatExtId },
5797
5986
  query: {
5798
- type: "activity",
5799
- ...options?.limit != null ? { limit: options.limit } : {},
5800
- ...options?.offset != null ? { offset: options.offset } : {}
5987
+ ...options?.before ? { before: options.before } : {},
5988
+ ...options?.limit ? { limit: options.limit } : {}
5801
5989
  }
5802
5990
  }
5803
5991
  }),
5804
- "Failed to fetch activity"
5992
+ "Failed to load messages"
5993
+ );
5994
+ }
5995
+ async function sendChatMessage(arbi, ring, text, options = {}) {
5996
+ const attachments = options.attachments ?? [];
5997
+ checkChatAttachmentLimits(attachments);
5998
+ const key = keyFor(ring, ring.currentVersion);
5999
+ const created = requireData(
6000
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/messages", {
6001
+ params: { path: { chat_ext_id: ring.chatExtId } },
6002
+ body: {
6003
+ content: await encryptWithChatKey(text, key),
6004
+ key_version: ring.currentVersion,
6005
+ kind: "text",
6006
+ ...attachments.length ? {
6007
+ attachments: await encryptChatAttachmentManifest(attachments, key),
6008
+ attachment_ext_ids: attachments.map((f2) => f2.id)
6009
+ } : {},
6010
+ ...options.workspaceExtId ? { workspace_ext_id: options.workspaceExtId } : {},
6011
+ context_only: !!options.contextOnly
6012
+ }
6013
+ }),
6014
+ "Failed to send message"
6015
+ );
6016
+ return {
6017
+ ...created,
6018
+ content: text,
6019
+ ...attachments.length ? { attachmentFiles: attachments } : {}
6020
+ };
6021
+ }
6022
+ async function deleteChatMessage(arbi, chatExtId, messageExtId) {
6023
+ requireOk(
6024
+ await arbi.fetch.DELETE("/v1/chats/{chat_ext_id}/messages/{message_ext_id}", {
6025
+ params: { path: { chat_ext_id: chatExtId, message_ext_id: messageExtId } }
6026
+ }),
6027
+ "Failed to delete message"
6028
+ );
6029
+ }
6030
+ async function markChatRead(arbi, chatExtId, messageExtId) {
6031
+ return requireData(
6032
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/read", {
6033
+ params: { path: { chat_ext_id: chatExtId } },
6034
+ body: messageExtId ? { message_ext_id: messageExtId } : {}
6035
+ }),
6036
+ "Failed to mark chat read"
5805
6037
  );
5806
6038
  }
6039
+ function hasRead(member, message) {
6040
+ if (!member?.last_read_at) return false;
6041
+ return Date.parse(member.last_read_at) >= Date.parse(message.created_at);
6042
+ }
5807
6043
  async function resolveRecipient(arbi, ref) {
5808
6044
  const isEmail = ref.includes("@");
5809
6045
  const matchKey = isEmail ? "email" : "external_id";
@@ -5835,52 +6071,63 @@ async function resolveRecipient(arbi, ref) {
5835
6071
  }
5836
6072
  return null;
5837
6073
  }
5838
- async function sendEncryptedDM(arbi, messages, crypto2, options) {
5839
- const attachments = options?.attachments ?? [];
5840
- checkDmAttachmentLimits(attachments);
5841
- const plaintextFor = new Map(messages.map((m2) => [m2.recipient_ext_id, m2.content]));
5842
- const encrypted = await Promise.all(
5843
- messages.map(async (msg) => ({
5844
- recipient_ext_id: msg.recipient_ext_id,
5845
- content: await encryptDmContent(
5846
- arbi,
5847
- msg.content,
5848
- msg.recipient_encryption_public_key,
5849
- crypto2.encryptionKeypair.secretKey
5850
- ),
5851
- ...attachments.length ? {
5852
- attachments: await encryptDmAttachmentManifest(
5853
- arbi,
5854
- attachments,
5855
- msg.recipient_encryption_public_key,
5856
- crypto2.encryptionKeypair.secretKey
5857
- )
5858
- } : {}
5859
- }))
5860
- );
5861
- const created = requireData(
5862
- await arbi.fetch.POST("/v1/notifications/", {
5863
- body: {
5864
- messages: encrypted,
5865
- context_only: false,
5866
- ...attachments.length ? { attachment_ext_ids: attachments.map((f2) => f2.id) } : {}
6074
+ async function sendDirectMessage(arbi, crypto2, peerExtId, text, options) {
6075
+ const chat = await openDirectChat(arbi, peerExtId);
6076
+ return sendChatMessage(arbi, await openChatKeyRing(chat, crypto2), text, options);
6077
+ }
6078
+ async function loadDecryptedChat(arbi, crypto2, chat, options) {
6079
+ const ring = await openChatKeyRing(chat, crypto2);
6080
+ const raw = await listChatMessages(arbi, chat.external_id, { limit: options?.limit });
6081
+ const messages = (await decryptChatMessages(ring, raw)).reverse();
6082
+ return { chat, ring, title: await decryptChatTitle(ring, chat), messages };
6083
+ }
6084
+
6085
+ // src/operations/notifications.ts
6086
+ var notifications_exports = {};
6087
+ __export(notifications_exports, {
6088
+ deleteNotifications: () => deleteNotifications,
6089
+ listActivity: () => listActivity,
6090
+ listNotifications: () => listNotifications,
6091
+ markNotificationsRead: () => markNotificationsRead,
6092
+ requestWorkspaceAccess: () => requestWorkspaceAccess
6093
+ });
6094
+ async function listNotifications(arbi) {
6095
+ return requireData(await arbi.fetch.GET("/v1/notifications/"), "Failed to fetch notifications");
6096
+ }
6097
+ async function listActivity(arbi, options) {
6098
+ return requireData(
6099
+ await arbi.fetch.GET("/v1/notifications/", {
6100
+ params: {
6101
+ query: {
6102
+ type: "activity",
6103
+ ...options?.limit != null ? { limit: options.limit } : {},
6104
+ ...options?.offset != null ? { offset: options.offset } : {}
6105
+ }
5867
6106
  }
5868
6107
  }),
5869
- "Failed to send message"
6108
+ "Failed to fetch activity"
6109
+ );
6110
+ }
6111
+ async function markNotificationsRead(arbi, ids) {
6112
+ return requireData(
6113
+ await arbi.fetch.PATCH("/v1/notifications/", {
6114
+ body: { updates: ids.map((id) => ({ external_id: id, read: true })) }
6115
+ }),
6116
+ "Failed to update notifications"
6117
+ );
6118
+ }
6119
+ async function deleteNotifications(arbi, ids) {
6120
+ requireOk(
6121
+ await arbi.fetch.DELETE("/v1/notifications/", { body: { external_ids: ids } }),
6122
+ "Failed to delete notifications"
5870
6123
  );
5871
- return created.map((n2) => ({
5872
- ...n2,
5873
- content: plaintextFor.get(n2.recipient.external_id) ?? n2.content,
5874
- ...attachments.length ? { attachmentFiles: attachments } : {}
5875
- }));
5876
6124
  }
5877
6125
  async function requestWorkspaceAccess(arbi, params, crypto2) {
5878
6126
  const payload = JSON.stringify({
5879
6127
  session_pubkey_b64: params.sessionPubkeyB64,
5880
6128
  note: params.note?.trim() || void 0
5881
6129
  });
5882
- const content = await encryptDmContent(
5883
- arbi,
6130
+ const content = await encryptMessage(
5884
6131
  payload,
5885
6132
  params.recipientEncryptionPublicKey,
5886
6133
  crypto2.encryptionKeypair.secretKey
@@ -5896,28 +6143,6 @@ async function requestWorkspaceAccess(arbi, params, crypto2) {
5896
6143
  "Failed to request workspace access"
5897
6144
  );
5898
6145
  }
5899
- async function sendDM(arbi, messages) {
5900
- return requireData(
5901
- await arbi.fetch.POST("/v1/notifications/", {
5902
- body: { messages, context_only: false }
5903
- }),
5904
- "Failed to send message"
5905
- );
5906
- }
5907
- async function markRead(arbi, messageIds) {
5908
- return requireData(
5909
- await arbi.fetch.PATCH("/v1/notifications/", {
5910
- body: { updates: messageIds.map((id) => ({ external_id: id, read: true })) }
5911
- }),
5912
- "Failed to update messages"
5913
- );
5914
- }
5915
- async function deleteDMs(arbi, messageIds) {
5916
- requireOk(
5917
- await arbi.fetch.DELETE("/v1/notifications/", { body: { external_ids: messageIds } }),
5918
- "Failed to delete messages"
5919
- );
5920
- }
5921
6146
 
5922
6147
  // src/operations/settings.ts
5923
6148
  var settings_exports = {};
@@ -6141,6 +6366,17 @@ async function updateProfile(arbi, body) {
6141
6366
  );
6142
6367
  }
6143
6368
 
6369
+ // src/operations/firm.ts
6370
+ async function getFirmPool(arbi) {
6371
+ return requireData(await arbi.fetch.GET("/v1/firm/pool"), "Failed to fetch the firm AI usage");
6372
+ }
6373
+ async function topUpFirmPool(arbi, aiAddons) {
6374
+ return requireData(
6375
+ await arbi.fetch.POST("/v1/firm/pool/topup", { body: { ai_addons: aiAddons } }),
6376
+ "Failed to add firm AI usage"
6377
+ );
6378
+ }
6379
+
6144
6380
  // src/operations/account.ts
6145
6381
  var account_exports = {};
6146
6382
  __export(account_exports, {
@@ -7373,10 +7609,10 @@ function attachmentFromBytes(name, contentType, bytes) {
7373
7609
  name,
7374
7610
  content_type: contentType,
7375
7611
  size: bytes.length,
7376
- content_base64: bytesToBase642(bytes)
7612
+ content_base64: bytesToBase643(bytes)
7377
7613
  };
7378
7614
  }
7379
- function bytesToBase642(bytes) {
7615
+ function bytesToBase643(bytes) {
7380
7616
  let binary = "";
7381
7617
  for (let i2 = 0; i2 < bytes.length; i2 += 32768) {
7382
7618
  binary += String.fromCharCode(...bytes.subarray(i2, i2 + 32768));
@@ -7404,7 +7640,7 @@ var Arbi = class {
7404
7640
  currentWorkspaceId = null;
7405
7641
  /** Wrapped workspace keys seen in the last list/create, so selecting needs no re-fetch. */
7406
7642
  wrappedKeys = /* @__PURE__ */ new Map();
7407
- dmCryptoContext = null;
7643
+ chatCryptoContext = null;
7408
7644
  sessionExpiredListeners = /* @__PURE__ */ new Set();
7409
7645
  options;
7410
7646
  constructor(options) {
@@ -7576,7 +7812,7 @@ var Arbi = class {
7576
7812
  this.userProfile = null;
7577
7813
  this.currentWorkspaceId = null;
7578
7814
  this.wrappedKeys.clear();
7579
- this.dmCryptoContext = null;
7815
+ this.chatCryptoContext = null;
7580
7816
  this.client?.session.clear();
7581
7817
  for (const listener of [...this.sessionExpiredListeners]) listener();
7582
7818
  }
@@ -7622,7 +7858,7 @@ var Arbi = class {
7622
7858
  this.userProfile = null;
7623
7859
  this.currentWorkspaceId = null;
7624
7860
  this.wrappedKeys.clear();
7625
- this.dmCryptoContext = null;
7861
+ this.chatCryptoContext = null;
7626
7862
  }
7627
7863
  // ── Accessors ─────────────────────────────────────────────────────────
7628
7864
  /** Get the underlying ArbiClient (throws if not initialized). */
@@ -7721,6 +7957,13 @@ var Arbi = class {
7721
7957
  */
7722
7958
  me: () => getCurrentUser(this.requireClient())
7723
7959
  };
7960
+ // ── Firm ──────────────────────────────────────────────────────────────
7961
+ firm = {
7962
+ /** The firm's pooled monthly £ of AI usage (`has_pool` false where there is none). */
7963
+ pool: () => getFirmPool(this.requireClient()),
7964
+ /** Buy `aiAddons` renewing add-ons (+£10 of AI usage a month each) for the firm. Box admins only. */
7965
+ topUp: (aiAddons) => topUpFirmPool(this.requireClient(), aiAddons)
7966
+ };
7724
7967
  // ── Profile ───────────────────────────────────────────────────────────
7725
7968
  profile = {
7726
7969
  /** Update the display profile; pass only what changes (`''` clears family name or picture). */
@@ -7886,9 +8129,13 @@ var Arbi = class {
7886
8129
  const lr2 = this.requireLogin();
7887
8130
  const userExtId = lr2.userExtId ?? client.session.getState().userExtId;
7888
8131
  if (!userExtId) throw new ArbiError("No user id in session \u2014 cannot request access");
7889
- const crypto2 = createDmCryptoContext(client, lr2.signingPrivateKey, userExtId);
8132
+ const crypto2 = createChatCryptoContext(lr2.signingPrivateKey, userExtId);
7890
8133
  const sessionPubkeyB64 = client.crypto.bytesToBase64(lr2.serverSessionKey);
7891
- return requestWorkspaceAccess(client, { ...params, sessionPubkeyB64 }, crypto2);
8134
+ return requestWorkspaceAccess(
8135
+ client,
8136
+ { ...params, sessionPubkeyB64 },
8137
+ crypto2
8138
+ );
7892
8139
  },
7893
8140
  copyDocuments: (targetWorkspaceId, docIds, targetWorkspaceKey) => copyDocuments(
7894
8141
  this.requireClient(),
@@ -8178,92 +8425,119 @@ var Arbi = class {
8178
8425
  // ── Contacts ──────────────────────────────────────────────────────────
8179
8426
  contacts = {
8180
8427
  list: () => listContacts(this.requireClient()),
8181
- add: (emails) => addContacts(this.requireClient(), emails),
8182
- remove: (contactIds) => removeContacts(this.requireClient(), contactIds),
8428
+ invite: (emails) => inviteContacts(this.requireClient(), emails),
8429
+ create: (body) => createContact(this.requireClient(), body),
8430
+ update: (contactId, card) => updateContact(this.requireClient(), contactId, card),
8431
+ delete: (contactId) => deleteContact(this.requireClient(), contactId),
8432
+ search: (q2) => searchContacts(this.requireClient(), q2),
8183
8433
  groupByStatus: groupContactsByStatus
8184
8434
  };
8185
- // ── Direct Messages ───────────────────────────────────────────────────
8435
+ // ── Chats (direct + group) ────────────────────────────────────────────
8186
8436
  /**
8187
- * Build (and cache) the DM crypto context for the current session.
8188
- *
8189
- * Derives the user's curve25519 keypair from their signing key and pairs it
8190
- * with their external_id — everything `list()`/`send()` need to encrypt and
8191
- * decrypt. Cached for the session and cleared on logout. Consumers never touch
8192
- * this: it's an internal of the `dm` surface.
8437
+ * Build (and cache) the chat crypto context for the current session: my X25519 keypair
8438
+ * (derived from the signing key) and external id. Cleared on logout.
8193
8439
  *
8194
- * The key comes from the live login result first, exactly as `selectWorkspace`
8195
- * sources it, and only then from persisted storage (which is what restores a
8196
- * session on reload). Reading storage first would make DMs the one feature that
8197
- * breaks whenever persistence is unavailable — `saveSession` deliberately
8198
- * no-ops without Web Crypto (a non-secure origin, tracking prevention, an
8199
- * embedded widget), so a perfectly authenticated user with a working workspace
8200
- * would be told they are "not authenticated" the moment they opened Messages.
8440
+ * The key comes from the live login result first, exactly as `selectWorkspace` sources it, and
8441
+ * only then from persisted storage (which is what restores a session on reload) — persistence
8442
+ * deliberately no-ops without Web Crypto, and chats must not be the one feature that breaks then.
8201
8443
  */
8202
- async requireDmCrypto() {
8203
- if (this.dmCryptoContext) return this.dmCryptoContext;
8444
+ async requireChatCrypto() {
8445
+ if (this.chatCryptoContext) return this.chatCryptoContext;
8204
8446
  const client = this.requireClient();
8205
8447
  const signingPrivateKey = this.loginResult?.signingPrivateKey ?? (await client.storage.getSession())?.signingPrivateKey;
8206
8448
  if (!signingPrivateKey) {
8207
- throw new ArbiError("Not authenticated \u2014 no session available for DM encryption");
8449
+ throw new ArbiError("Not authenticated \u2014 no session available for chat encryption");
8208
8450
  }
8209
8451
  const userExtId = client.session.getState().userExtId;
8210
8452
  if (!userExtId) {
8211
- throw new ArbiError("No user identity in session \u2014 cannot set up DM encryption");
8453
+ throw new ArbiError("No user identity in session \u2014 cannot set up chat encryption");
8212
8454
  }
8213
- this.dmCryptoContext = createDmCryptoContext(client, signingPrivateKey, userExtId);
8214
- return this.dmCryptoContext;
8455
+ this.chatCryptoContext = createChatCryptoContext(signingPrivateKey, userExtId);
8456
+ return this.chatCryptoContext;
8457
+ }
8458
+ /** Fetch a chat, sealing a new epoch first when it is `rotation_required`. */
8459
+ async readyChat(chatExtId) {
8460
+ const client = this.requireClient();
8461
+ return ensureChatKeyCurrent(
8462
+ client,
8463
+ await getChat(client, chatExtId),
8464
+ await this.requireChatCrypto()
8465
+ );
8215
8466
  }
8467
+ chats = {
8468
+ /** My chats, most recently active first (raw: titles/last messages are ciphertext). */
8469
+ list: (kind) => listChats(this.requireClient(), kind),
8470
+ get: (chatExtId) => getChat(this.requireClient(), chatExtId),
8471
+ /** Get-or-create the direct chat with a peer. */
8472
+ openDirect: (peerExtId) => openDirectChat(this.requireClient(), peerExtId),
8473
+ /** Create a group (epoch 1 sealed to every member). Agents are refused. */
8474
+ createGroup: async (params) => createGroupChat(this.requireClient(), await this.requireChatCrypto(), params),
8475
+ /** A chat with its keys opened, title and newest messages decrypted (oldest first). */
8476
+ load: async (chatExtId, options) => {
8477
+ const chat = await this.readyChat(chatExtId);
8478
+ return loadDecryptedChat(
8479
+ this.requireClient(),
8480
+ await this.requireChatCrypto(),
8481
+ chat,
8482
+ options
8483
+ );
8484
+ },
8485
+ /** Post plaintext to a chat (encrypted under its current epoch). */
8486
+ send: async (chatExtId, text, options) => {
8487
+ const chat = await this.readyChat(chatExtId);
8488
+ const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
8489
+ return sendChatMessage(this.requireClient(), ring, text, options);
8490
+ },
8491
+ rename: async (chatExtId, title) => {
8492
+ const chat = await this.readyChat(chatExtId);
8493
+ const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
8494
+ return renameChat(this.requireClient(), ring, title);
8495
+ },
8496
+ addMembers: async (chatExtId, members) => {
8497
+ const chat = await this.readyChat(chatExtId);
8498
+ const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
8499
+ return addChatMembers(this.requireClient(), ring, members);
8500
+ },
8501
+ /** Remove a member (owner) or leave (own id); a remaining member seals the next epoch. */
8502
+ removeMember: async (chatExtId, userExtId) => {
8503
+ await removeChatMember(this.requireClient(), chatExtId, userExtId);
8504
+ const crypto2 = await this.requireChatCrypto();
8505
+ if (userExtId !== crypto2.userExtId) await this.readyChat(chatExtId);
8506
+ },
8507
+ markRead: (chatExtId, messageExtId) => markChatRead(this.requireClient(), chatExtId, messageExtId),
8508
+ deleteMessage: (chatExtId, messageExtId) => deleteChatMessage(this.requireClient(), chatExtId, messageExtId)
8509
+ };
8510
+ /** Direct-chat conveniences addressed by peer (email or `usr-`/`agt-` id). */
8216
8511
  dm = {
8217
8512
  /**
8218
- * List direct messages, newest first, with content already **decrypted**.
8219
- * (A message that can't be decrypted comes back as `[Decryption failed]`.)
8220
- */
8221
- list: async () => listDecryptedDMs(this.requireClient(), await this.requireDmCrypto()),
8222
- /**
8223
- * Send an E2E-encrypted DM to a recipient (email or `usr-`/`agt-` id).
8224
- * Resolves the recipient's public key and encrypts internally — the caller
8225
- * passes plaintext and never handles keys or ciphertext.
8513
+ * Send an E2E-encrypted direct message: resolves the peer, opens (get-or-create) the direct
8514
+ * chat and posts under the pair key. The caller passes plaintext and never handles keys.
8226
8515
  */
8227
8516
  send: async (recipient, text) => {
8228
8517
  const client = this.requireClient();
8229
8518
  const resolved = await resolveRecipient(client, recipient);
8230
8519
  if (!resolved) {
8231
8520
  throw new ArbiError(
8232
- `Could not resolve DM recipient "${recipient}" (not a known contact, agent, or workspace member)`
8521
+ `Could not resolve recipient "${recipient}" (not a known contact, agent, or workspace member)`
8233
8522
  );
8234
8523
  }
8235
- return sendEncryptedDM(
8524
+ return sendDirectMessage(
8236
8525
  client,
8237
- [
8238
- {
8239
- recipient_ext_id: resolved.extId,
8240
- content: text,
8241
- recipient_encryption_public_key: resolved.pubKey
8242
- }
8243
- ],
8244
- await this.requireDmCrypto()
8526
+ await this.requireChatCrypto(),
8527
+ resolved.extId,
8528
+ text
8245
8529
  );
8246
8530
  },
8247
- /**
8248
- * Send to a recipient whose external_id + public key are already known
8249
- * (e.g. from a message's `sender`), skipping directory resolution.
8250
- */
8251
- sendTo: async (recipientExtId, recipientPublicKey, text) => sendEncryptedDM(
8531
+ /** Send to a peer whose external id is already known, skipping directory resolution. */
8532
+ sendTo: async (peerExtId, text) => sendDirectMessage(
8252
8533
  this.requireClient(),
8253
- [
8254
- {
8255
- recipient_ext_id: recipientExtId,
8256
- content: text,
8257
- recipient_encryption_public_key: recipientPublicKey
8258
- }
8259
- ],
8260
- await this.requireDmCrypto()
8534
+ await this.requireChatCrypto(),
8535
+ peerExtId,
8536
+ text
8261
8537
  ),
8262
8538
  /** Resolve a recipient reference to `{ extId, pubKey }` (contacts → agents → workspace). */
8263
8539
  resolveRecipient: (recipient) => resolveRecipient(this.requireClient(), recipient),
8264
- markRead: (messageIds) => markRead(this.requireClient(), messageIds),
8265
- delete: (messageIds) => deleteDMs(this.requireClient(), messageIds),
8266
- /** List the current user's durable activity feed (never unread; excluded from DMs). */
8540
+ /** List the current user's durable activity feed. */
8267
8541
  listActivity: (options) => listActivity(this.requireClient(), options)
8268
8542
  };
8269
8543
  // ── Settings ──────────────────────────────────────────────────────────
@@ -8406,6 +8680,6 @@ var Arbi = class {
8406
8680
  }
8407
8681
  };
8408
8682
 
8409
- export { Arbi, ArbiApiError, ArbiError, DEFAULT_AI_USD_PER_GBP, PlanStepsError, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, assistant_exports as assistant, authenticatedFetch, buildFactsContextTool, buildRetrievalChunkTool, buildRetrievalFullContextTool, buildRetrievalTocTool, connectWebSocket, connectWithReconnect, consumeSSEStream, contacts_exports as contacts, conversations_exports as conversations, countCitations, createAuthenticatedClient, dm_exports as dm, doctags_exports as doctags, documents_exports as documents, facts_exports as facts, files_exports as files, filterSkills, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatUserName, formatWorkspaceChoices, getErrorMessage, getRawWorkspaceKey, health_exports as health, identityErrorCode, identity_exports as identityVerification, mail_exports as mail, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, performPasswordLogin, profile_exports as profile, projects_exports as projects, requireData, requireOk, resolveAuth, resolveCitations, resolveWorkspace, responses_exports as responses, selectWorkspace, selectWorkspaceById, sessions_exports as sessions, settings_exports as settings, streamSSE, stripCitationMarkdown, summarizeCitations, tags_exports as tags, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaces_exports as workspaces };
8683
+ export { Arbi, ArbiApiError, ArbiError, DEFAULT_AI_USD_PER_GBP, PlanStepsError, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, assistant_exports as assistant, authenticatedFetch, buildFactsContextTool, buildRetrievalChunkTool, buildRetrievalFullContextTool, buildRetrievalTocTool, chats_exports as chats, connectWebSocket, connectWithReconnect, consumeSSEStream, contacts_exports as contacts, conversations_exports as conversations, countCitations, createAuthenticatedClient, doctags_exports as doctags, documents_exports as documents, facts_exports as facts, files_exports as files, filterSkills, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatUserName, formatWorkspaceChoices, getErrorMessage, getRawWorkspaceKey, health_exports as health, identityErrorCode, identity_exports as identityVerification, mail_exports as mail, notifications_exports as notifications, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, performPasswordLogin, profile_exports as profile, projects_exports as projects, requireData, requireOk, resolveAuth, resolveCitations, resolveWorkspace, responses_exports as responses, selectWorkspace, selectWorkspaceById, sessions_exports as sessions, settings_exports as settings, streamSSE, stripCitationMarkdown, summarizeCitations, tags_exports as tags, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaces_exports as workspaces };
8410
8684
  //# sourceMappingURL=browser.js.map
8411
8685
  //# sourceMappingURL=browser.js.map