@arbidocs/sdk 0.4.107 → 0.4.110

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