@arbidocs/sdk 0.4.108 → 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.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,44 @@ 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
+ checkChatAttachmentLimits: () => checkChatAttachmentLimits,
5517
+ createChatCryptoContext: () => createChatCryptoContext,
5518
+ createGroupChat: () => createGroupChat,
5519
+ decryptChatAttachmentManifest: () => decryptChatAttachmentManifest,
5520
+ decryptChatMessage: () => decryptChatMessage,
5521
+ decryptChatMessages: () => decryptChatMessages,
5522
+ decryptChatTitle: () => decryptChatTitle,
5523
+ deleteChatMessage: () => deleteChatMessage,
5524
+ directPeer: () => directPeer,
5525
+ downloadChatAttachment: () => downloadChatAttachment,
5526
+ encryptChatAttachmentManifest: () => encryptChatAttachmentManifest,
5527
+ ensureChatKeyCurrent: () => ensureChatKeyCurrent,
5528
+ getChat: () => getChat,
5529
+ hasRead: () => hasRead,
5530
+ isAgentExtId: () => isAgentExtId,
5531
+ listChatMessages: () => listChatMessages,
5532
+ listChats: () => listChats,
5533
+ loadDecryptedChat: () => loadDecryptedChat,
5534
+ markChatRead: () => markChatRead,
5535
+ openChatKeyRing: () => openChatKeyRing,
5536
+ openDirectChat: () => openDirectChat,
5537
+ parseChatAttachmentManifest: () => parseChatAttachmentManifest,
5538
+ removeChatMember: () => removeChatMember,
5539
+ renameChat: () => renameChat,
5505
5540
  resolveRecipient: () => resolveRecipient,
5506
- sendDM: () => sendDM,
5507
- sendEncryptedDM: () => sendEncryptedDM,
5508
- serializeDmAttachmentManifest: () => serializeDmAttachmentManifest,
5509
- uploadDmAttachment: () => uploadDmAttachment,
5510
- uploadDmAttachments: () => uploadDmAttachments
5541
+ rotateChatKey: () => rotateChatKey,
5542
+ sendChatMessage: () => sendChatMessage,
5543
+ sendDirectMessage: () => sendDirectMessage,
5544
+ serializeChatAttachmentManifest: () => serializeChatAttachmentManifest,
5545
+ uploadChatAttachment: () => uploadChatAttachment,
5546
+ uploadChatAttachments: () => uploadChatAttachments
5511
5547
  });
5512
5548
 
5513
5549
  // src/operations/agents.ts
@@ -5599,27 +5635,27 @@ async function stageAgentFile(auth, agentId, file, name) {
5599
5635
  });
5600
5636
  return response.json();
5601
5637
  }
5602
- var DM_ATTACHMENT_MAX_BYTES = 15 * 1024 * 1024;
5603
- var DM_ATTACHMENT_MAX_FILES = 10;
5638
+ var CHAT_ATTACHMENT_MAX_BYTES = 15 * 1024 * 1024;
5639
+ var CHAT_ATTACHMENT_MAX_FILES = 10;
5604
5640
  var ATTACHMENT_ID = /^att-[a-zA-Z0-9]{8}$/;
5605
5641
  var MANIFEST_VERSION = 1;
5606
5642
  var MB = 1024 * 1024;
5607
- function checkDmAttachmentLimits(files) {
5608
- if (files.length > DM_ATTACHMENT_MAX_FILES) {
5643
+ function checkChatAttachmentLimits(files) {
5644
+ if (files.length > CHAT_ATTACHMENT_MAX_FILES) {
5609
5645
  throw new Error(
5610
- `You can attach at most ${DM_ATTACHMENT_MAX_FILES} files to a message (this one has ${files.length}).`
5646
+ `You can attach at most ${CHAT_ATTACHMENT_MAX_FILES} files to a message (this one has ${files.length}).`
5611
5647
  );
5612
5648
  }
5613
5649
  for (const file of files) {
5614
- if (file.size > DM_ATTACHMENT_MAX_BYTES) {
5650
+ if (file.size > CHAT_ATTACHMENT_MAX_BYTES) {
5615
5651
  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.`
5652
+ `${file.name} is too large (${(file.size / MB).toFixed(1)} MB). Files can be at most ${CHAT_ATTACHMENT_MAX_BYTES / MB} MB.`
5617
5653
  );
5618
5654
  }
5619
5655
  }
5620
5656
  }
5621
- async function uploadDmAttachment(arbi, input) {
5622
- checkDmAttachmentLimits([{ name: input.name, size: input.bytes.length }]);
5657
+ async function uploadChatAttachment(arbi, input) {
5658
+ checkChatAttachmentLimits([{ name: input.name, size: input.bytes.length }]);
5623
5659
  await initSodium();
5624
5660
  const key = globalThis.crypto.getRandomValues(new Uint8Array(32));
5625
5661
  try {
@@ -5630,13 +5666,13 @@ async function uploadDmAttachment(arbi, input) {
5630
5666
  new Blob([ciphertext], { type: "application/octet-stream" }),
5631
5667
  "attachment.bin"
5632
5668
  );
5633
- const result = await arbi.fetch.POST("/v1/notifications/attachments", {
5669
+ const result = await arbi.fetch.POST("/v1/chats/attachments", {
5634
5670
  body: { file: "" },
5635
5671
  bodySerializer: () => form
5636
5672
  });
5637
5673
  if (result.response?.status === 413) {
5638
5674
  throw new ArbiApiError(
5639
- `${input.name} is too large. Files can be at most ${DM_ATTACHMENT_MAX_BYTES / MB} MB.`,
5675
+ `${input.name} is too large. Files can be at most ${CHAT_ATTACHMENT_MAX_BYTES / MB} MB.`,
5640
5676
  result.error,
5641
5677
  413
5642
5678
  );
@@ -5653,19 +5689,19 @@ async function uploadDmAttachment(arbi, input) {
5653
5689
  key.fill(0);
5654
5690
  }
5655
5691
  }
5656
- async function uploadDmAttachments(arbi, inputs) {
5657
- checkDmAttachmentLimits(inputs.map((i2) => ({ name: i2.name, size: i2.bytes.length })));
5692
+ async function uploadChatAttachments(arbi, inputs) {
5693
+ checkChatAttachmentLimits(inputs.map((i2) => ({ name: i2.name, size: i2.bytes.length })));
5658
5694
  const files = [];
5659
- for (const input of inputs) files.push(await uploadDmAttachment(arbi, input));
5695
+ for (const input of inputs) files.push(await uploadChatAttachment(arbi, input));
5660
5696
  return files;
5661
5697
  }
5662
- function serializeDmAttachmentManifest(files) {
5698
+ function serializeChatAttachmentManifest(files) {
5663
5699
  return JSON.stringify({
5664
5700
  v: MANIFEST_VERSION,
5665
5701
  files: files.map(({ id, name, type, size, key }) => ({ id, name, type, size, key }))
5666
5702
  });
5667
5703
  }
5668
- function parseDmAttachmentManifest(json2) {
5704
+ function parseChatAttachmentManifest(json2) {
5669
5705
  const manifest = JSON.parse(json2);
5670
5706
  if (manifest?.v !== MANIFEST_VERSION || !Array.isArray(manifest.files)) {
5671
5707
  throw new Error("Unsupported attachment manifest");
@@ -5684,27 +5720,15 @@ function parseDmAttachmentManifest(json2) {
5684
5720
  };
5685
5721
  });
5686
5722
  }
5687
- async function encryptDmAttachmentManifest(arbi, files, recipientEncryptionPubKeyBase64, senderEncryptionSecretKey) {
5688
- return arbi.crypto.encryptMessage(
5689
- serializeDmAttachmentManifest(files),
5690
- recipientEncryptionPubKeyBase64,
5691
- senderEncryptionSecretKey
5692
- );
5723
+ async function encryptChatAttachmentManifest(files, chatKey) {
5724
+ return encryptWithChatKey(serializeChatAttachmentManifest(files), chatKey);
5693
5725
  }
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);
5726
+ async function decryptChatAttachmentManifest(manifest, chatKey) {
5727
+ return parseChatAttachmentManifest(await decryptWithChatKey(manifest, chatKey));
5704
5728
  }
5705
- async function downloadDmAttachment(arbi, file) {
5729
+ async function downloadChatAttachment(arbi, file) {
5706
5730
  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}", {
5731
+ const result = await arbi.fetch.GET("/v1/chats/attachments/{external_id}", {
5708
5732
  params: { path: { external_id: file.id } },
5709
5733
  parseAs: "arrayBuffer"
5710
5734
  });
@@ -5732,78 +5756,275 @@ async function downloadDmAttachment(arbi, file) {
5732
5756
  return plain;
5733
5757
  }
5734
5758
 
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,
5759
+ // src/operations/chats.ts
5760
+ function createChatCryptoContext(signingPrivateKeyBytes, userExtId) {
5761
+ const encryptionKeypair = deriveEncryptionKeypairFromSigning({
5762
+ publicKey: signingPrivateKeyBytes.slice(32, 64),
5740
5763
  secretKey: signingPrivateKeyBytes
5741
5764
  });
5742
5765
  return { encryptionKeypair, userExtId };
5743
5766
  }
5744
- async function encryptDmContent(arbi, plaintext, recipientEncryptionPubKeyBase64, senderEncryptionSecretKey) {
5745
- return arbi.crypto.encryptMessage(
5746
- plaintext,
5747
- recipientEncryptionPubKeyBase64,
5748
- senderEncryptionSecretKey
5749
- );
5767
+ function isAgentExtId(extId) {
5768
+ return !!extId && extId.startsWith("agt-");
5769
+ }
5770
+ function directPeer(chat, myExtId) {
5771
+ if (chat.kind !== "direct") return void 0;
5772
+ return chat.members.find((m2) => m2.user.external_id !== myExtId)?.user;
5773
+ }
5774
+ async function openChatKeyRing(chat, crypto2) {
5775
+ const keys = /* @__PURE__ */ new Map();
5776
+ if (chat.kind === "direct") {
5777
+ const peer = directPeer(chat, crypto2.userExtId);
5778
+ const peerPub = peer?.encryption_public_key ?? bytesToBase64(crypto2.encryptionKeypair.publicKey);
5779
+ keys.set(0, await deriveDirectChatKey(peerPub, crypto2.encryptionKeypair.secretKey));
5780
+ } else {
5781
+ for (const k2 of chat.my_keys ?? []) {
5782
+ try {
5783
+ keys.set(
5784
+ k2.version,
5785
+ await openSealedChatKey(k2.sealed_key, crypto2.encryptionKeypair.secretKey)
5786
+ );
5787
+ } catch {
5788
+ }
5789
+ }
5790
+ }
5791
+ return { chatExtId: chat.external_id, kind: chat.kind, currentVersion: chat.key_version, keys };
5750
5792
  }
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
- );
5793
+ function keyFor(ring, version) {
5794
+ const key = ring.keys.get(version);
5795
+ if (!key) throw new Error(`No key for epoch ${version} of ${ring.chatExtId}`);
5796
+ return key;
5760
5797
  }
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;
5798
+ var DECRYPTION_FAILED = "[Decryption failed]";
5799
+ async function decryptChatMessage(ring, message) {
5800
+ const key = ring.keys.get(message.key_version);
5801
+ const row = { ...message };
5802
+ if (message.content) {
5803
+ try {
5804
+ if (!key) throw new Error("no key");
5805
+ row.content = await decryptWithChatKey(message.content, key);
5806
+ } catch {
5807
+ row.content = DECRYPTION_FAILED;
5808
+ row.decryptFailed = true;
5767
5809
  }
5768
- let row;
5810
+ }
5811
+ if (message.attachments) {
5769
5812
  try {
5770
- row = { ...n2, content: await decryptDmContent(arbi, n2, crypto2) };
5813
+ if (!key) throw new Error("no key");
5814
+ row.attachmentFiles = await decryptChatAttachmentManifest(message.attachments, key);
5771
5815
  } catch {
5772
- row = { ...n2, content: "[Decryption failed]" };
5816
+ row.attachmentFiles = [];
5817
+ row.attachmentsError = "The attachments could not be decrypted";
5773
5818
  }
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";
5819
+ }
5820
+ return row;
5821
+ }
5822
+ async function decryptChatMessages(ring, messages) {
5823
+ return Promise.all(messages.map((m2) => decryptChatMessage(ring, m2)));
5824
+ }
5825
+ async function decryptChatTitle(ring, chat) {
5826
+ if (!chat.title) return null;
5827
+ const key = ring.keys.get(chat.key_version);
5828
+ if (!key) return null;
5829
+ try {
5830
+ return await decryptWithChatKey(chat.title, key);
5831
+ } catch {
5832
+ return null;
5833
+ }
5834
+ }
5835
+ async function listChats(arbi, kind) {
5836
+ return requireData(
5837
+ await arbi.fetch.GET("/v1/chats/", { params: { query: kind ? { kind } : {} } }),
5838
+ "Failed to list chats"
5839
+ );
5840
+ }
5841
+ async function getChat(arbi, chatExtId) {
5842
+ return requireData(
5843
+ await arbi.fetch.GET("/v1/chats/{chat_ext_id}", {
5844
+ params: { path: { chat_ext_id: chatExtId } }
5845
+ }),
5846
+ "Failed to load chat"
5847
+ );
5848
+ }
5849
+ async function openDirectChat(arbi, peerExtId) {
5850
+ return requireData(
5851
+ await arbi.fetch.POST("/v1/chats/", { body: { kind: "direct", peer_ext_id: peerExtId } }),
5852
+ "Failed to open chat"
5853
+ );
5854
+ }
5855
+ async function createGroupChat(arbi, crypto2, params) {
5856
+ const members = params.members.filter((m2) => m2.external_id !== crypto2.userExtId);
5857
+ if (members.length === 0) throw new Error("A group needs at least one other member");
5858
+ const agent = members.find((m2) => isAgentExtId(m2.external_id));
5859
+ if (agent) throw new Error("Personal agents cannot join a group chat");
5860
+ const key = await generateChatKey();
5861
+ try {
5862
+ const title = params.title?.trim();
5863
+ return requireData(
5864
+ await arbi.fetch.POST("/v1/chats/", {
5865
+ body: {
5866
+ kind: "group",
5867
+ title: title ? await encryptWithChatKey(title, key) : null,
5868
+ members: await Promise.all(
5869
+ members.map(async (m2) => ({
5870
+ user_ext_id: m2.external_id,
5871
+ sealed_key: await sealChatKey(key, m2.encryption_public_key)
5872
+ }))
5873
+ ),
5874
+ creator_sealed_key: await sealChatKey(
5875
+ key,
5876
+ bytesToBase64(crypto2.encryptionKeypair.publicKey)
5877
+ )
5878
+ }
5879
+ }),
5880
+ "Failed to create group"
5881
+ );
5882
+ } finally {
5883
+ key.fill(0);
5884
+ }
5885
+ }
5886
+ async function renameChat(arbi, ring, title) {
5887
+ const trimmed = title?.trim();
5888
+ return requireData(
5889
+ await arbi.fetch.PATCH("/v1/chats/{chat_ext_id}", {
5890
+ params: { path: { chat_ext_id: ring.chatExtId } },
5891
+ body: {
5892
+ title: trimmed ? await encryptWithChatKey(trimmed, keyFor(ring, ring.currentVersion)) : null
5780
5893
  }
5781
- }
5782
- results.push(row);
5894
+ }),
5895
+ "Failed to rename chat"
5896
+ );
5897
+ }
5898
+ async function addChatMembers(arbi, ring, members) {
5899
+ if (ring.kind === "direct") {
5900
+ throw new Error("A direct chat cannot gain members: create a group instead");
5901
+ }
5902
+ if (members.some((m2) => isAgentExtId(m2.external_id))) {
5903
+ throw new Error("Personal agents cannot join a group chat");
5783
5904
  }
5784
- return results;
5905
+ const key = keyFor(ring, ring.currentVersion);
5906
+ return requireData(
5907
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/members", {
5908
+ params: { path: { chat_ext_id: ring.chatExtId } },
5909
+ body: {
5910
+ members: await Promise.all(
5911
+ members.map(async (m2) => ({
5912
+ user_ext_id: m2.external_id,
5913
+ sealed_key: await sealChatKey(key, m2.encryption_public_key)
5914
+ }))
5915
+ )
5916
+ }
5917
+ }),
5918
+ "Failed to add members"
5919
+ );
5785
5920
  }
5786
- async function listDMs(arbi) {
5787
- return requireData(await arbi.fetch.GET("/v1/notifications/"), "Failed to fetch messages");
5921
+ async function removeChatMember(arbi, chatExtId, userExtId) {
5922
+ requireOk(
5923
+ await arbi.fetch.DELETE("/v1/chats/{chat_ext_id}/members/{user_ext_id}", {
5924
+ params: { path: { chat_ext_id: chatExtId, user_ext_id: userExtId } }
5925
+ }),
5926
+ "Failed to remove member"
5927
+ );
5788
5928
  }
5789
- async function listDecryptedDMs(arbi, crypto2) {
5790
- const raw = await listDMs(arbi);
5791
- return decryptDmBatch(arbi, raw, crypto2);
5929
+ async function rotateChatKey(arbi, chat, ring) {
5930
+ if (chat.kind === "direct") throw new Error("Direct chats have no epochs");
5931
+ const oldTitle = await decryptChatTitle(ring, chat);
5932
+ if (chat.title && oldTitle === null) {
5933
+ throw new Error("Cannot re-encrypt the chat title: its key is not available");
5934
+ }
5935
+ const key = await generateChatKey();
5936
+ try {
5937
+ const sealed = {};
5938
+ for (const m2 of chat.members) {
5939
+ sealed[m2.user.external_id] = await sealChatKey(key, m2.user.encryption_public_key);
5940
+ }
5941
+ return requireData(
5942
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/keys", {
5943
+ params: { path: { chat_ext_id: chat.external_id } },
5944
+ body: {
5945
+ version: chat.key_version + 1,
5946
+ sealed_keys: sealed,
5947
+ ...oldTitle !== null ? { title: await encryptWithChatKey(oldTitle, key) } : {}
5948
+ }
5949
+ }),
5950
+ "Failed to rotate chat key"
5951
+ );
5952
+ } finally {
5953
+ key.fill(0);
5954
+ }
5792
5955
  }
5793
- async function listActivity(arbi, options) {
5956
+ async function ensureChatKeyCurrent(arbi, chat, crypto2) {
5957
+ if (!chat.rotation_required || chat.kind === "direct") return chat;
5958
+ if (!chat.members.some((m2) => m2.user.external_id === crypto2.userExtId)) return chat;
5959
+ try {
5960
+ return await rotateChatKey(arbi, chat, await openChatKeyRing(chat, crypto2));
5961
+ } catch (err) {
5962
+ if (err instanceof ArbiApiError && err.status === 409) return getChat(arbi, chat.external_id);
5963
+ throw err;
5964
+ }
5965
+ }
5966
+ async function listChatMessages(arbi, chatExtId, options) {
5794
5967
  return requireData(
5795
- await arbi.fetch.GET("/v1/notifications/", {
5968
+ await arbi.fetch.GET("/v1/chats/{chat_ext_id}/messages", {
5796
5969
  params: {
5970
+ path: { chat_ext_id: chatExtId },
5797
5971
  query: {
5798
- type: "activity",
5799
- ...options?.limit != null ? { limit: options.limit } : {},
5800
- ...options?.offset != null ? { offset: options.offset } : {}
5972
+ ...options?.before ? { before: options.before } : {},
5973
+ ...options?.limit ? { limit: options.limit } : {}
5801
5974
  }
5802
5975
  }
5803
5976
  }),
5804
- "Failed to fetch activity"
5977
+ "Failed to load messages"
5805
5978
  );
5806
5979
  }
5980
+ async function sendChatMessage(arbi, ring, text, options = {}) {
5981
+ const attachments = options.attachments ?? [];
5982
+ checkChatAttachmentLimits(attachments);
5983
+ const key = keyFor(ring, ring.currentVersion);
5984
+ const created = requireData(
5985
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/messages", {
5986
+ params: { path: { chat_ext_id: ring.chatExtId } },
5987
+ body: {
5988
+ content: await encryptWithChatKey(text, key),
5989
+ key_version: ring.currentVersion,
5990
+ kind: "text",
5991
+ ...attachments.length ? {
5992
+ attachments: await encryptChatAttachmentManifest(attachments, key),
5993
+ attachment_ext_ids: attachments.map((f2) => f2.id)
5994
+ } : {},
5995
+ ...options.workspaceExtId ? { workspace_ext_id: options.workspaceExtId } : {},
5996
+ context_only: !!options.contextOnly
5997
+ }
5998
+ }),
5999
+ "Failed to send message"
6000
+ );
6001
+ return {
6002
+ ...created,
6003
+ content: text,
6004
+ ...attachments.length ? { attachmentFiles: attachments } : {}
6005
+ };
6006
+ }
6007
+ async function deleteChatMessage(arbi, chatExtId, messageExtId) {
6008
+ requireOk(
6009
+ await arbi.fetch.DELETE("/v1/chats/{chat_ext_id}/messages/{message_ext_id}", {
6010
+ params: { path: { chat_ext_id: chatExtId, message_ext_id: messageExtId } }
6011
+ }),
6012
+ "Failed to delete message"
6013
+ );
6014
+ }
6015
+ async function markChatRead(arbi, chatExtId, messageExtId) {
6016
+ return requireData(
6017
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/read", {
6018
+ params: { path: { chat_ext_id: chatExtId } },
6019
+ body: messageExtId ? { message_ext_id: messageExtId } : {}
6020
+ }),
6021
+ "Failed to mark chat read"
6022
+ );
6023
+ }
6024
+ function hasRead(member, message) {
6025
+ if (!member?.last_read_at) return false;
6026
+ return Date.parse(member.last_read_at) >= Date.parse(message.created_at);
6027
+ }
5807
6028
  async function resolveRecipient(arbi, ref) {
5808
6029
  const isEmail = ref.includes("@");
5809
6030
  const matchKey = isEmail ? "email" : "external_id";
@@ -5835,52 +6056,63 @@ async function resolveRecipient(arbi, ref) {
5835
6056
  }
5836
6057
  return null;
5837
6058
  }
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) } : {}
6059
+ async function sendDirectMessage(arbi, crypto2, peerExtId, text, options) {
6060
+ const chat = await openDirectChat(arbi, peerExtId);
6061
+ return sendChatMessage(arbi, await openChatKeyRing(chat, crypto2), text, options);
6062
+ }
6063
+ async function loadDecryptedChat(arbi, crypto2, chat, options) {
6064
+ const ring = await openChatKeyRing(chat, crypto2);
6065
+ const raw = await listChatMessages(arbi, chat.external_id, { limit: options?.limit });
6066
+ const messages = (await decryptChatMessages(ring, raw)).reverse();
6067
+ return { chat, ring, title: await decryptChatTitle(ring, chat), messages };
6068
+ }
6069
+
6070
+ // src/operations/notifications.ts
6071
+ var notifications_exports = {};
6072
+ __export(notifications_exports, {
6073
+ deleteNotifications: () => deleteNotifications,
6074
+ listActivity: () => listActivity,
6075
+ listNotifications: () => listNotifications,
6076
+ markNotificationsRead: () => markNotificationsRead,
6077
+ requestWorkspaceAccess: () => requestWorkspaceAccess
6078
+ });
6079
+ async function listNotifications(arbi) {
6080
+ return requireData(await arbi.fetch.GET("/v1/notifications/"), "Failed to fetch notifications");
6081
+ }
6082
+ async function listActivity(arbi, options) {
6083
+ return requireData(
6084
+ await arbi.fetch.GET("/v1/notifications/", {
6085
+ params: {
6086
+ query: {
6087
+ type: "activity",
6088
+ ...options?.limit != null ? { limit: options.limit } : {},
6089
+ ...options?.offset != null ? { offset: options.offset } : {}
6090
+ }
5867
6091
  }
5868
6092
  }),
5869
- "Failed to send message"
6093
+ "Failed to fetch activity"
6094
+ );
6095
+ }
6096
+ async function markNotificationsRead(arbi, ids) {
6097
+ return requireData(
6098
+ await arbi.fetch.PATCH("/v1/notifications/", {
6099
+ body: { updates: ids.map((id) => ({ external_id: id, read: true })) }
6100
+ }),
6101
+ "Failed to update notifications"
6102
+ );
6103
+ }
6104
+ async function deleteNotifications(arbi, ids) {
6105
+ requireOk(
6106
+ await arbi.fetch.DELETE("/v1/notifications/", { body: { external_ids: ids } }),
6107
+ "Failed to delete notifications"
5870
6108
  );
5871
- return created.map((n2) => ({
5872
- ...n2,
5873
- content: plaintextFor.get(n2.recipient.external_id) ?? n2.content,
5874
- ...attachments.length ? { attachmentFiles: attachments } : {}
5875
- }));
5876
6109
  }
5877
6110
  async function requestWorkspaceAccess(arbi, params, crypto2) {
5878
6111
  const payload = JSON.stringify({
5879
6112
  session_pubkey_b64: params.sessionPubkeyB64,
5880
6113
  note: params.note?.trim() || void 0
5881
6114
  });
5882
- const content = await encryptDmContent(
5883
- arbi,
6115
+ const content = await encryptMessage(
5884
6116
  payload,
5885
6117
  params.recipientEncryptionPublicKey,
5886
6118
  crypto2.encryptionKeypair.secretKey
@@ -5896,28 +6128,6 @@ async function requestWorkspaceAccess(arbi, params, crypto2) {
5896
6128
  "Failed to request workspace access"
5897
6129
  );
5898
6130
  }
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
6131
 
5922
6132
  // src/operations/settings.ts
5923
6133
  var settings_exports = {};
@@ -6141,6 +6351,17 @@ async function updateProfile(arbi, body) {
6141
6351
  );
6142
6352
  }
6143
6353
 
6354
+ // src/operations/firm.ts
6355
+ async function getFirmPool(arbi) {
6356
+ return requireData(await arbi.fetch.GET("/v1/firm/pool"), "Failed to fetch the firm AI usage");
6357
+ }
6358
+ async function topUpFirmPool(arbi, aiAddons) {
6359
+ return requireData(
6360
+ await arbi.fetch.POST("/v1/firm/pool/topup", { body: { ai_addons: aiAddons } }),
6361
+ "Failed to add firm AI usage"
6362
+ );
6363
+ }
6364
+
6144
6365
  // src/operations/account.ts
6145
6366
  var account_exports = {};
6146
6367
  __export(account_exports, {
@@ -7373,10 +7594,10 @@ function attachmentFromBytes(name, contentType, bytes) {
7373
7594
  name,
7374
7595
  content_type: contentType,
7375
7596
  size: bytes.length,
7376
- content_base64: bytesToBase642(bytes)
7597
+ content_base64: bytesToBase643(bytes)
7377
7598
  };
7378
7599
  }
7379
- function bytesToBase642(bytes) {
7600
+ function bytesToBase643(bytes) {
7380
7601
  let binary = "";
7381
7602
  for (let i2 = 0; i2 < bytes.length; i2 += 32768) {
7382
7603
  binary += String.fromCharCode(...bytes.subarray(i2, i2 + 32768));
@@ -7404,7 +7625,7 @@ var Arbi = class {
7404
7625
  currentWorkspaceId = null;
7405
7626
  /** Wrapped workspace keys seen in the last list/create, so selecting needs no re-fetch. */
7406
7627
  wrappedKeys = /* @__PURE__ */ new Map();
7407
- dmCryptoContext = null;
7628
+ chatCryptoContext = null;
7408
7629
  sessionExpiredListeners = /* @__PURE__ */ new Set();
7409
7630
  options;
7410
7631
  constructor(options) {
@@ -7576,7 +7797,7 @@ var Arbi = class {
7576
7797
  this.userProfile = null;
7577
7798
  this.currentWorkspaceId = null;
7578
7799
  this.wrappedKeys.clear();
7579
- this.dmCryptoContext = null;
7800
+ this.chatCryptoContext = null;
7580
7801
  this.client?.session.clear();
7581
7802
  for (const listener of [...this.sessionExpiredListeners]) listener();
7582
7803
  }
@@ -7622,7 +7843,7 @@ var Arbi = class {
7622
7843
  this.userProfile = null;
7623
7844
  this.currentWorkspaceId = null;
7624
7845
  this.wrappedKeys.clear();
7625
- this.dmCryptoContext = null;
7846
+ this.chatCryptoContext = null;
7626
7847
  }
7627
7848
  // ── Accessors ─────────────────────────────────────────────────────────
7628
7849
  /** Get the underlying ArbiClient (throws if not initialized). */
@@ -7721,6 +7942,13 @@ var Arbi = class {
7721
7942
  */
7722
7943
  me: () => getCurrentUser(this.requireClient())
7723
7944
  };
7945
+ // ── Firm ──────────────────────────────────────────────────────────────
7946
+ firm = {
7947
+ /** The firm's pooled monthly £ of AI usage (`has_pool` false where there is none). */
7948
+ pool: () => getFirmPool(this.requireClient()),
7949
+ /** Buy `aiAddons` renewing add-ons (+£10 of AI usage a month each) for the firm. Box admins only. */
7950
+ topUp: (aiAddons) => topUpFirmPool(this.requireClient(), aiAddons)
7951
+ };
7724
7952
  // ── Profile ───────────────────────────────────────────────────────────
7725
7953
  profile = {
7726
7954
  /** Update the display profile; pass only what changes (`''` clears family name or picture). */
@@ -7886,9 +8114,13 @@ var Arbi = class {
7886
8114
  const lr2 = this.requireLogin();
7887
8115
  const userExtId = lr2.userExtId ?? client.session.getState().userExtId;
7888
8116
  if (!userExtId) throw new ArbiError("No user id in session \u2014 cannot request access");
7889
- const crypto2 = createDmCryptoContext(client, lr2.signingPrivateKey, userExtId);
8117
+ const crypto2 = createChatCryptoContext(lr2.signingPrivateKey, userExtId);
7890
8118
  const sessionPubkeyB64 = client.crypto.bytesToBase64(lr2.serverSessionKey);
7891
- return requestWorkspaceAccess(client, { ...params, sessionPubkeyB64 }, crypto2);
8119
+ return requestWorkspaceAccess(
8120
+ client,
8121
+ { ...params, sessionPubkeyB64 },
8122
+ crypto2
8123
+ );
7892
8124
  },
7893
8125
  copyDocuments: (targetWorkspaceId, docIds, targetWorkspaceKey) => copyDocuments(
7894
8126
  this.requireClient(),
@@ -8178,92 +8410,119 @@ var Arbi = class {
8178
8410
  // ── Contacts ──────────────────────────────────────────────────────────
8179
8411
  contacts = {
8180
8412
  list: () => listContacts(this.requireClient()),
8181
- add: (emails) => addContacts(this.requireClient(), emails),
8182
- remove: (contactIds) => removeContacts(this.requireClient(), contactIds),
8413
+ invite: (emails) => inviteContacts(this.requireClient(), emails),
8414
+ create: (body) => createContact(this.requireClient(), body),
8415
+ update: (contactId, card) => updateContact(this.requireClient(), contactId, card),
8416
+ delete: (contactId) => deleteContact(this.requireClient(), contactId),
8417
+ search: (q2) => searchContacts(this.requireClient(), q2),
8183
8418
  groupByStatus: groupContactsByStatus
8184
8419
  };
8185
- // ── Direct Messages ───────────────────────────────────────────────────
8420
+ // ── Chats (direct + group) ────────────────────────────────────────────
8186
8421
  /**
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.
8422
+ * Build (and cache) the chat crypto context for the current session: my X25519 keypair
8423
+ * (derived from the signing key) and external id. Cleared on logout.
8193
8424
  *
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.
8425
+ * The key comes from the live login result first, exactly as `selectWorkspace` sources it, and
8426
+ * only then from persisted storage (which is what restores a session on reload) — persistence
8427
+ * deliberately no-ops without Web Crypto, and chats must not be the one feature that breaks then.
8201
8428
  */
8202
- async requireDmCrypto() {
8203
- if (this.dmCryptoContext) return this.dmCryptoContext;
8429
+ async requireChatCrypto() {
8430
+ if (this.chatCryptoContext) return this.chatCryptoContext;
8204
8431
  const client = this.requireClient();
8205
8432
  const signingPrivateKey = this.loginResult?.signingPrivateKey ?? (await client.storage.getSession())?.signingPrivateKey;
8206
8433
  if (!signingPrivateKey) {
8207
- throw new ArbiError("Not authenticated \u2014 no session available for DM encryption");
8434
+ throw new ArbiError("Not authenticated \u2014 no session available for chat encryption");
8208
8435
  }
8209
8436
  const userExtId = client.session.getState().userExtId;
8210
8437
  if (!userExtId) {
8211
- throw new ArbiError("No user identity in session \u2014 cannot set up DM encryption");
8438
+ throw new ArbiError("No user identity in session \u2014 cannot set up chat encryption");
8212
8439
  }
8213
- this.dmCryptoContext = createDmCryptoContext(client, signingPrivateKey, userExtId);
8214
- return this.dmCryptoContext;
8440
+ this.chatCryptoContext = createChatCryptoContext(signingPrivateKey, userExtId);
8441
+ return this.chatCryptoContext;
8442
+ }
8443
+ /** Fetch a chat, sealing a new epoch first when it is `rotation_required`. */
8444
+ async readyChat(chatExtId) {
8445
+ const client = this.requireClient();
8446
+ return ensureChatKeyCurrent(
8447
+ client,
8448
+ await getChat(client, chatExtId),
8449
+ await this.requireChatCrypto()
8450
+ );
8215
8451
  }
8452
+ chats = {
8453
+ /** My chats, most recently active first (raw: titles/last messages are ciphertext). */
8454
+ list: (kind) => listChats(this.requireClient(), kind),
8455
+ get: (chatExtId) => getChat(this.requireClient(), chatExtId),
8456
+ /** Get-or-create the direct chat with a peer. */
8457
+ openDirect: (peerExtId) => openDirectChat(this.requireClient(), peerExtId),
8458
+ /** Create a group (epoch 1 sealed to every member). Agents are refused. */
8459
+ createGroup: async (params) => createGroupChat(this.requireClient(), await this.requireChatCrypto(), params),
8460
+ /** A chat with its keys opened, title and newest messages decrypted (oldest first). */
8461
+ load: async (chatExtId, options) => {
8462
+ const chat = await this.readyChat(chatExtId);
8463
+ return loadDecryptedChat(
8464
+ this.requireClient(),
8465
+ await this.requireChatCrypto(),
8466
+ chat,
8467
+ options
8468
+ );
8469
+ },
8470
+ /** Post plaintext to a chat (encrypted under its current epoch). */
8471
+ send: async (chatExtId, text, options) => {
8472
+ const chat = await this.readyChat(chatExtId);
8473
+ const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
8474
+ return sendChatMessage(this.requireClient(), ring, text, options);
8475
+ },
8476
+ rename: async (chatExtId, title) => {
8477
+ const chat = await this.readyChat(chatExtId);
8478
+ const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
8479
+ return renameChat(this.requireClient(), ring, title);
8480
+ },
8481
+ addMembers: async (chatExtId, members) => {
8482
+ const chat = await this.readyChat(chatExtId);
8483
+ const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
8484
+ return addChatMembers(this.requireClient(), ring, members);
8485
+ },
8486
+ /** Remove a member (owner) or leave (own id); a remaining member seals the next epoch. */
8487
+ removeMember: async (chatExtId, userExtId) => {
8488
+ await removeChatMember(this.requireClient(), chatExtId, userExtId);
8489
+ const crypto2 = await this.requireChatCrypto();
8490
+ if (userExtId !== crypto2.userExtId) await this.readyChat(chatExtId);
8491
+ },
8492
+ markRead: (chatExtId, messageExtId) => markChatRead(this.requireClient(), chatExtId, messageExtId),
8493
+ deleteMessage: (chatExtId, messageExtId) => deleteChatMessage(this.requireClient(), chatExtId, messageExtId)
8494
+ };
8495
+ /** Direct-chat conveniences addressed by peer (email or `usr-`/`agt-` id). */
8216
8496
  dm = {
8217
8497
  /**
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.
8498
+ * Send an E2E-encrypted direct message: resolves the peer, opens (get-or-create) the direct
8499
+ * chat and posts under the pair key. The caller passes plaintext and never handles keys.
8226
8500
  */
8227
8501
  send: async (recipient, text) => {
8228
8502
  const client = this.requireClient();
8229
8503
  const resolved = await resolveRecipient(client, recipient);
8230
8504
  if (!resolved) {
8231
8505
  throw new ArbiError(
8232
- `Could not resolve DM recipient "${recipient}" (not a known contact, agent, or workspace member)`
8506
+ `Could not resolve recipient "${recipient}" (not a known contact, agent, or workspace member)`
8233
8507
  );
8234
8508
  }
8235
- return sendEncryptedDM(
8509
+ return sendDirectMessage(
8236
8510
  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()
8511
+ await this.requireChatCrypto(),
8512
+ resolved.extId,
8513
+ text
8245
8514
  );
8246
8515
  },
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(
8516
+ /** Send to a peer whose external id is already known, skipping directory resolution. */
8517
+ sendTo: async (peerExtId, text) => sendDirectMessage(
8252
8518
  this.requireClient(),
8253
- [
8254
- {
8255
- recipient_ext_id: recipientExtId,
8256
- content: text,
8257
- recipient_encryption_public_key: recipientPublicKey
8258
- }
8259
- ],
8260
- await this.requireDmCrypto()
8519
+ await this.requireChatCrypto(),
8520
+ peerExtId,
8521
+ text
8261
8522
  ),
8262
8523
  /** Resolve a recipient reference to `{ extId, pubKey }` (contacts → agents → workspace). */
8263
8524
  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). */
8525
+ /** List the current user's durable activity feed. */
8267
8526
  listActivity: (options) => listActivity(this.requireClient(), options)
8268
8527
  };
8269
8528
  // ── Settings ──────────────────────────────────────────────────────────
@@ -8406,6 +8665,6 @@ var Arbi = class {
8406
8665
  }
8407
8666
  };
8408
8667
 
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 };
8668
+ 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
8669
  //# sourceMappingURL=browser.js.map
8411
8670
  //# sourceMappingURL=browser.js.map