@arbidocs/sdk 0.4.108 → 0.4.111

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -4829,6 +4829,9 @@ function formatWsMessage(msg) {
4829
4829
  level: msg.status === "completed" ? "success" : "error"
4830
4830
  };
4831
4831
  }
4832
+ if (msg.type === "chat.message") {
4833
+ return { text: `New message in ${msg.chat_ext_id}`, level: "info" };
4834
+ }
4832
4835
  if (isNotification(msg)) {
4833
4836
  const sender = msg.sender?.email || "someone";
4834
4837
  const content = msg.content ?? msg.type;
@@ -4912,6 +4915,7 @@ __export(documents_exports, {
4912
4915
  listPaginated: () => listPaginated,
4913
4916
  listVersions: () => listVersions,
4914
4917
  mimeFromName: () => mimeFromName,
4918
+ presignedPut: () => presignedPut,
4915
4919
  sanitizeFolderPath: () => sanitizeFolderPath,
4916
4920
  updateDocuments: () => updateDocuments,
4917
4921
  uploadDocumentsDirect: () => uploadDocumentsDirect,
@@ -5184,12 +5188,15 @@ function mimeFromName(name) {
5184
5188
  return void 0;
5185
5189
  }
5186
5190
  }
5187
- async function presignedPut(url, body, onProgress) {
5191
+ async function presignedPut(url, body, onProgress, headers) {
5188
5192
  const XhrGlobal = globalThis.XMLHttpRequest;
5189
5193
  if (XhrGlobal) {
5190
5194
  await new Promise((resolve2, reject) => {
5191
5195
  const xhr = new XhrGlobal();
5192
5196
  xhr.open("PUT", url);
5197
+ for (const [name, value] of Object.entries(headers ?? {})) {
5198
+ xhr.setRequestHeader(name, value);
5199
+ }
5193
5200
  if (onProgress) {
5194
5201
  xhr.upload.addEventListener("progress", (e) => {
5195
5202
  if (e.lengthComputable) onProgress(e.loaded, e.total);
@@ -5209,7 +5216,7 @@ async function presignedPut(url, body, onProgress) {
5209
5216
  });
5210
5217
  return;
5211
5218
  }
5212
- const putRes = await fetch(url, { method: "PUT", body });
5219
+ const putRes = await fetch(url, { method: "PUT", body, ...headers ? { headers } : {} });
5213
5220
  if (!putRes.ok) {
5214
5221
  const snippet = await putRes.text().catch(() => "");
5215
5222
  throw new Error(`Presigned PUT failed: ${putRes.status} ${snippet.slice(0, 200)}`);
@@ -5981,37 +5988,57 @@ function mergeKindFieldDefinitions(current, wanted, { keepOthers = false } = {})
5981
5988
  // src/operations/contacts.ts
5982
5989
  var contacts_exports = {};
5983
5990
  __export(contacts_exports, {
5984
- addContacts: () => addContacts,
5991
+ createContact: () => createContact,
5992
+ deleteContact: () => deleteContact,
5985
5993
  groupContactsByStatus: () => groupContactsByStatus,
5994
+ inviteContacts: () => inviteContacts,
5986
5995
  listContacts: () => listContacts,
5987
- removeContacts: () => removeContacts
5996
+ searchContacts: () => searchContacts,
5997
+ updateContact: () => updateContact
5988
5998
  });
5989
5999
  async function listContacts(arbi) {
5990
- return requireData(await arbi.fetch.GET("/v1/user/contacts"), "Failed to fetch contacts");
6000
+ return requireData(await arbi.fetch.GET("/v1/contacts/"), "Failed to fetch contacts");
5991
6001
  }
5992
- async function addContacts(arbi, emails) {
6002
+ async function inviteContacts(arbi, emails) {
5993
6003
  return requireData(
5994
- await arbi.fetch.POST("/v1/user/contacts", { body: { emails } }),
5995
- "Failed to add contacts"
6004
+ await arbi.fetch.POST("/v1/contacts/invitations", { body: { emails } }),
6005
+ "Failed to invite contacts"
6006
+ );
6007
+ }
6008
+ async function createContact(arbi, body) {
6009
+ return requireData(await arbi.fetch.POST("/v1/contacts/", { body }), "Failed to create contact");
6010
+ }
6011
+ async function updateContact(arbi, contactId, card) {
6012
+ return requireData(
6013
+ await arbi.fetch.PATCH("/v1/contacts/{cnt_id}", {
6014
+ params: { path: { cnt_id: contactId } },
6015
+ body: { card, invite: false }
6016
+ }),
6017
+ "Failed to update contact"
5996
6018
  );
5997
6019
  }
5998
- async function removeContacts(arbi, contactIds) {
6020
+ async function deleteContact(arbi, contactId) {
5999
6021
  requireOk(
6000
- await arbi.fetch.DELETE("/v1/user/contacts", { body: { contact_ids: contactIds } }),
6001
- "Failed to remove contacts"
6022
+ await arbi.fetch.DELETE("/v1/contacts/{cnt_id}", { params: { path: { cnt_id: contactId } } }),
6023
+ "Failed to delete contact"
6024
+ );
6025
+ }
6026
+ async function searchContacts(arbi, q2) {
6027
+ return requireData(
6028
+ await arbi.fetch.GET("/v1/contacts/search", { params: { query: { q: q2 } } }),
6029
+ "Failed to search contacts"
6002
6030
  );
6003
6031
  }
6004
6032
  function groupContactsByStatus(contactList) {
6005
6033
  const registered = [];
6006
6034
  const pending = [];
6035
+ const cards = [];
6007
6036
  for (const c2 of contactList) {
6008
- if (c2.status === "registered") {
6009
- registered.push(c2);
6010
- } else {
6011
- pending.push(c2);
6012
- }
6037
+ if (c2.status === "registered") registered.push(c2);
6038
+ else if (c2.status === "card") cards.push(c2);
6039
+ else pending.push(c2);
6013
6040
  }
6014
- return { registered, pending };
6041
+ return { registered, pending, cards };
6015
6042
  }
6016
6043
 
6017
6044
  // src/operations/doctags.ts
@@ -6057,32 +6084,45 @@ async function generateDocTags(arbi, tagIds, docIds, options) {
6057
6084
  );
6058
6085
  }
6059
6086
 
6060
- // src/operations/dm.ts
6061
- var dm_exports = {};
6062
- __export(dm_exports, {
6063
- DM_ATTACHMENT_MAX_BYTES: () => DM_ATTACHMENT_MAX_BYTES,
6064
- DM_ATTACHMENT_MAX_FILES: () => DM_ATTACHMENT_MAX_FILES,
6065
- checkDmAttachmentLimits: () => checkDmAttachmentLimits,
6066
- createDmCryptoContext: () => createDmCryptoContext,
6067
- decryptDmAttachments: () => decryptDmAttachments,
6068
- decryptDmBatch: () => decryptDmBatch,
6069
- decryptDmContent: () => decryptDmContent,
6070
- deleteDMs: () => deleteDMs,
6071
- downloadDmAttachment: () => downloadDmAttachment,
6072
- encryptDmAttachmentManifest: () => encryptDmAttachmentManifest,
6073
- encryptDmContent: () => encryptDmContent,
6074
- listActivity: () => listActivity,
6075
- listDMs: () => listDMs,
6076
- listDecryptedDMs: () => listDecryptedDMs,
6077
- markRead: () => markRead,
6078
- parseDmAttachmentManifest: () => parseDmAttachmentManifest,
6079
- requestWorkspaceAccess: () => requestWorkspaceAccess,
6087
+ // src/operations/chats.ts
6088
+ var chats_exports = {};
6089
+ __export(chats_exports, {
6090
+ CHAT_ATTACHMENT_MAX_BYTES: () => CHAT_ATTACHMENT_MAX_BYTES,
6091
+ CHAT_ATTACHMENT_MAX_FILES: () => CHAT_ATTACHMENT_MAX_FILES,
6092
+ DECRYPTION_FAILED: () => DECRYPTION_FAILED,
6093
+ addChatMembers: () => addChatMembers,
6094
+ chatMessageTombstone: () => chatMessageTombstone,
6095
+ checkChatAttachmentLimits: () => checkChatAttachmentLimits,
6096
+ createChatCryptoContext: () => createChatCryptoContext,
6097
+ createGroupChat: () => createGroupChat,
6098
+ decryptChatAttachmentManifest: () => decryptChatAttachmentManifest,
6099
+ decryptChatMessage: () => decryptChatMessage,
6100
+ decryptChatMessages: () => decryptChatMessages,
6101
+ decryptChatTitle: () => decryptChatTitle,
6102
+ deleteChatMessage: () => deleteChatMessage,
6103
+ directPeer: () => directPeer,
6104
+ downloadChatAttachment: () => downloadChatAttachment,
6105
+ encryptChatAttachmentManifest: () => encryptChatAttachmentManifest,
6106
+ ensureChatKeyCurrent: () => ensureChatKeyCurrent,
6107
+ getChat: () => getChat,
6108
+ hasRead: () => hasRead,
6109
+ isAgentExtId: () => isAgentExtId,
6110
+ listChatMessages: () => listChatMessages,
6111
+ listChats: () => listChats,
6112
+ loadDecryptedChat: () => loadDecryptedChat,
6113
+ markChatRead: () => markChatRead,
6114
+ openChatKeyRing: () => openChatKeyRing,
6115
+ openDirectChat: () => openDirectChat,
6116
+ parseChatAttachmentManifest: () => parseChatAttachmentManifest,
6117
+ removeChatMember: () => removeChatMember,
6118
+ renameChat: () => renameChat,
6080
6119
  resolveRecipient: () => resolveRecipient,
6081
- sendDM: () => sendDM,
6082
- sendEncryptedDM: () => sendEncryptedDM,
6083
- serializeDmAttachmentManifest: () => serializeDmAttachmentManifest,
6084
- uploadDmAttachment: () => uploadDmAttachment,
6085
- uploadDmAttachments: () => uploadDmAttachments
6120
+ rotateChatKey: () => rotateChatKey,
6121
+ sendChatMessage: () => sendChatMessage,
6122
+ sendDirectMessage: () => sendDirectMessage,
6123
+ serializeChatAttachmentManifest: () => serializeChatAttachmentManifest,
6124
+ uploadChatAttachment: () => uploadChatAttachment,
6125
+ uploadChatAttachments: () => uploadChatAttachments
6086
6126
  });
6087
6127
 
6088
6128
  // src/operations/agents.ts
@@ -6189,27 +6229,27 @@ async function stageAgentFile(auth, agentId, file, name) {
6189
6229
  });
6190
6230
  return response.json();
6191
6231
  }
6192
- var DM_ATTACHMENT_MAX_BYTES = 15 * 1024 * 1024;
6193
- var DM_ATTACHMENT_MAX_FILES = 10;
6232
+ var CHAT_ATTACHMENT_MAX_BYTES = 15 * 1024 * 1024;
6233
+ var CHAT_ATTACHMENT_MAX_FILES = 10;
6194
6234
  var ATTACHMENT_ID = /^att-[a-zA-Z0-9]{8}$/;
6195
6235
  var MANIFEST_VERSION = 1;
6196
6236
  var MB = 1024 * 1024;
6197
- function checkDmAttachmentLimits(files) {
6198
- if (files.length > DM_ATTACHMENT_MAX_FILES) {
6237
+ function checkChatAttachmentLimits(files) {
6238
+ if (files.length > CHAT_ATTACHMENT_MAX_FILES) {
6199
6239
  throw new Error(
6200
- `You can attach at most ${DM_ATTACHMENT_MAX_FILES} files to a message (this one has ${files.length}).`
6240
+ `You can attach at most ${CHAT_ATTACHMENT_MAX_FILES} files to a message (this one has ${files.length}).`
6201
6241
  );
6202
6242
  }
6203
6243
  for (const file of files) {
6204
- if (file.size > DM_ATTACHMENT_MAX_BYTES) {
6244
+ if (file.size > CHAT_ATTACHMENT_MAX_BYTES) {
6205
6245
  throw new Error(
6206
- `${file.name} is too large (${(file.size / MB).toFixed(1)} MB). Files can be at most ${DM_ATTACHMENT_MAX_BYTES / MB} MB.`
6246
+ `${file.name} is too large (${(file.size / MB).toFixed(1)} MB). Files can be at most ${CHAT_ATTACHMENT_MAX_BYTES / MB} MB.`
6207
6247
  );
6208
6248
  }
6209
6249
  }
6210
6250
  }
6211
- async function uploadDmAttachment(arbi, input) {
6212
- checkDmAttachmentLimits([{ name: input.name, size: input.bytes.length }]);
6251
+ async function uploadChatAttachment(arbi, input) {
6252
+ checkChatAttachmentLimits([{ name: input.name, size: input.bytes.length }]);
6213
6253
  await client.initSodium();
6214
6254
  const key = globalThis.crypto.getRandomValues(new Uint8Array(32));
6215
6255
  try {
@@ -6220,13 +6260,13 @@ async function uploadDmAttachment(arbi, input) {
6220
6260
  new Blob([ciphertext], { type: "application/octet-stream" }),
6221
6261
  "attachment.bin"
6222
6262
  );
6223
- const result = await arbi.fetch.POST("/v1/notifications/attachments", {
6263
+ const result = await arbi.fetch.POST("/v1/chats/attachments", {
6224
6264
  body: { file: "" },
6225
6265
  bodySerializer: () => form
6226
6266
  });
6227
6267
  if (result.response?.status === 413) {
6228
6268
  throw new ArbiApiError(
6229
- `${input.name} is too large. Files can be at most ${DM_ATTACHMENT_MAX_BYTES / MB} MB.`,
6269
+ `${input.name} is too large. Files can be at most ${CHAT_ATTACHMENT_MAX_BYTES / MB} MB.`,
6230
6270
  result.error,
6231
6271
  413
6232
6272
  );
@@ -6243,19 +6283,19 @@ async function uploadDmAttachment(arbi, input) {
6243
6283
  key.fill(0);
6244
6284
  }
6245
6285
  }
6246
- async function uploadDmAttachments(arbi, inputs) {
6247
- checkDmAttachmentLimits(inputs.map((i2) => ({ name: i2.name, size: i2.bytes.length })));
6286
+ async function uploadChatAttachments(arbi, inputs) {
6287
+ checkChatAttachmentLimits(inputs.map((i2) => ({ name: i2.name, size: i2.bytes.length })));
6248
6288
  const files = [];
6249
- for (const input of inputs) files.push(await uploadDmAttachment(arbi, input));
6289
+ for (const input of inputs) files.push(await uploadChatAttachment(arbi, input));
6250
6290
  return files;
6251
6291
  }
6252
- function serializeDmAttachmentManifest(files) {
6292
+ function serializeChatAttachmentManifest(files) {
6253
6293
  return JSON.stringify({
6254
6294
  v: MANIFEST_VERSION,
6255
6295
  files: files.map(({ id, name, type, size, key }) => ({ id, name, type, size, key }))
6256
6296
  });
6257
6297
  }
6258
- function parseDmAttachmentManifest(json2) {
6298
+ function parseChatAttachmentManifest(json2) {
6259
6299
  const manifest = JSON.parse(json2);
6260
6300
  if (manifest?.v !== MANIFEST_VERSION || !Array.isArray(manifest.files)) {
6261
6301
  throw new Error("Unsupported attachment manifest");
@@ -6274,27 +6314,15 @@ function parseDmAttachmentManifest(json2) {
6274
6314
  };
6275
6315
  });
6276
6316
  }
6277
- async function encryptDmAttachmentManifest(arbi, files, recipientEncryptionPubKeyBase64, senderEncryptionSecretKey) {
6278
- return arbi.crypto.encryptMessage(
6279
- serializeDmAttachmentManifest(files),
6280
- recipientEncryptionPubKeyBase64,
6281
- senderEncryptionSecretKey
6282
- );
6317
+ async function encryptChatAttachmentManifest(files, chatKey) {
6318
+ return client.encryptWithChatKey(serializeChatAttachmentManifest(files), chatKey);
6283
6319
  }
6284
- async function decryptDmAttachments(arbi, notification, crypto2) {
6285
- if (!notification.attachments) return [];
6286
- const isSent = notification.sender.external_id === crypto2.userExtId;
6287
- const otherParty = isSent ? notification.recipient : notification.sender;
6288
- const json2 = await arbi.crypto.decryptMessage(
6289
- notification.attachments,
6290
- otherParty.encryption_public_key,
6291
- crypto2.encryptionKeypair.secretKey
6292
- );
6293
- return parseDmAttachmentManifest(json2);
6320
+ async function decryptChatAttachmentManifest(manifest, chatKey) {
6321
+ return parseChatAttachmentManifest(await client.decryptWithChatKey(manifest, chatKey));
6294
6322
  }
6295
- async function downloadDmAttachment(arbi, file) {
6323
+ async function downloadChatAttachment(arbi, file) {
6296
6324
  if (!ATTACHMENT_ID.test(file.id)) throw new Error(`Invalid attachment id: ${file.id}`);
6297
- const result = await arbi.fetch.GET("/v1/notifications/attachments/{external_id}", {
6325
+ const result = await arbi.fetch.GET("/v1/chats/attachments/{external_id}", {
6298
6326
  params: { path: { external_id: file.id } },
6299
6327
  parseAs: "arrayBuffer"
6300
6328
  });
@@ -6322,78 +6350,289 @@ async function downloadDmAttachment(arbi, file) {
6322
6350
  return plain;
6323
6351
  }
6324
6352
 
6325
- // src/operations/dm.ts
6326
- function createDmCryptoContext(arbi, signingPrivateKeyBytes, userExtId) {
6327
- const ed25519PublicKey = signingPrivateKeyBytes.slice(32, 64);
6328
- const encryptionKeypair = arbi.crypto.deriveEncryptionKeypairFromSigning({
6329
- publicKey: ed25519PublicKey,
6353
+ // src/operations/chats.ts
6354
+ function createChatCryptoContext(signingPrivateKeyBytes, userExtId) {
6355
+ const encryptionKeypair = client.deriveEncryptionKeypairFromSigning({
6356
+ publicKey: signingPrivateKeyBytes.slice(32, 64),
6330
6357
  secretKey: signingPrivateKeyBytes
6331
6358
  });
6332
6359
  return { encryptionKeypair, userExtId };
6333
6360
  }
6334
- async function encryptDmContent(arbi, plaintext, recipientEncryptionPubKeyBase64, senderEncryptionSecretKey) {
6335
- return arbi.crypto.encryptMessage(
6336
- plaintext,
6337
- recipientEncryptionPubKeyBase64,
6338
- senderEncryptionSecretKey
6339
- );
6361
+ function isAgentExtId(extId) {
6362
+ return !!extId && extId.startsWith("agt-");
6340
6363
  }
6341
- async function decryptDmContent(arbi, notification, crypto2) {
6342
- if (!notification.content) return null;
6343
- const isSent = notification.sender.external_id === crypto2.userExtId;
6344
- const otherParty = isSent ? notification.recipient : notification.sender;
6345
- return arbi.crypto.decryptMessage(
6346
- notification.content,
6347
- otherParty.encryption_public_key,
6348
- crypto2.encryptionKeypair.secretKey
6349
- );
6364
+ function directPeer(chat, myExtId) {
6365
+ if (chat.kind !== "direct") return void 0;
6366
+ return chat.members.find((m2) => m2.user.external_id !== myExtId)?.user;
6350
6367
  }
6351
- async function decryptDmBatch(arbi, notifications, crypto2) {
6352
- const results = [];
6353
- for (const n2 of notifications) {
6354
- if (n2.type !== "user_message" || !n2.content && !n2.attachments) {
6355
- results.push(n2);
6356
- continue;
6368
+ async function openChatKeyRing(chat, crypto2) {
6369
+ const keys = /* @__PURE__ */ new Map();
6370
+ if (chat.kind === "direct") {
6371
+ const peer = directPeer(chat, crypto2.userExtId);
6372
+ const peerPub = peer?.encryption_public_key ?? client.bytesToBase64(crypto2.encryptionKeypair.publicKey);
6373
+ keys.set(0, await client.deriveDirectChatKey(peerPub, crypto2.encryptionKeypair.secretKey));
6374
+ } else {
6375
+ for (const k2 of chat.my_keys ?? []) {
6376
+ try {
6377
+ keys.set(
6378
+ k2.version,
6379
+ await client.openSealedChatKey(k2.sealed_key, crypto2.encryptionKeypair.secretKey)
6380
+ );
6381
+ } catch {
6382
+ }
6357
6383
  }
6358
- let row;
6384
+ }
6385
+ return { chatExtId: chat.external_id, kind: chat.kind, currentVersion: chat.key_version, keys };
6386
+ }
6387
+ function keyFor(ring, version) {
6388
+ const key = ring.keys.get(version);
6389
+ if (!key) throw new Error(`No key for epoch ${version} of ${ring.chatExtId}`);
6390
+ return key;
6391
+ }
6392
+ var DECRYPTION_FAILED = "[Decryption failed]";
6393
+ function chatMessageTombstone(message) {
6394
+ const row = {
6395
+ ...message,
6396
+ deleted: true,
6397
+ content: null,
6398
+ attachments: null,
6399
+ dedupe_key: null
6400
+ };
6401
+ delete row.decryptFailed;
6402
+ delete row.attachmentFiles;
6403
+ delete row.attachmentsError;
6404
+ return row;
6405
+ }
6406
+ async function decryptChatMessage(ring, message) {
6407
+ if (message.deleted) return chatMessageTombstone(message);
6408
+ const key = ring.keys.get(message.key_version);
6409
+ const row = { ...message };
6410
+ if (message.content) {
6359
6411
  try {
6360
- row = { ...n2, content: await decryptDmContent(arbi, n2, crypto2) };
6412
+ if (!key) throw new Error("no key");
6413
+ row.content = await client.decryptWithChatKey(message.content, key);
6361
6414
  } catch {
6362
- row = { ...n2, content: "[Decryption failed]" };
6415
+ row.content = DECRYPTION_FAILED;
6416
+ row.decryptFailed = true;
6363
6417
  }
6364
- if (n2.attachments) {
6365
- try {
6366
- row.attachmentFiles = await decryptDmAttachments(arbi, n2, crypto2);
6367
- } catch {
6368
- row.attachmentFiles = [];
6369
- row.attachmentsError = "The attachments could not be decrypted";
6370
- }
6418
+ }
6419
+ if (message.attachments) {
6420
+ try {
6421
+ if (!key) throw new Error("no key");
6422
+ row.attachmentFiles = await decryptChatAttachmentManifest(message.attachments, key);
6423
+ } catch {
6424
+ row.attachmentFiles = [];
6425
+ row.attachmentsError = "The attachments could not be decrypted";
6371
6426
  }
6372
- results.push(row);
6373
6427
  }
6374
- return results;
6428
+ return row;
6429
+ }
6430
+ async function decryptChatMessages(ring, messages) {
6431
+ return Promise.all(messages.map((m2) => decryptChatMessage(ring, m2)));
6432
+ }
6433
+ async function decryptChatTitle(ring, chat) {
6434
+ if (!chat.title) return null;
6435
+ const key = ring.keys.get(chat.key_version);
6436
+ if (!key) return null;
6437
+ try {
6438
+ return await client.decryptWithChatKey(chat.title, key);
6439
+ } catch {
6440
+ return null;
6441
+ }
6375
6442
  }
6376
- async function listDMs(arbi) {
6377
- return requireData(await arbi.fetch.GET("/v1/notifications/"), "Failed to fetch messages");
6443
+ async function listChats(arbi, kind) {
6444
+ return requireData(
6445
+ await arbi.fetch.GET("/v1/chats/", { params: { query: kind ? { kind } : {} } }),
6446
+ "Failed to list chats"
6447
+ );
6378
6448
  }
6379
- async function listDecryptedDMs(arbi, crypto2) {
6380
- const raw = await listDMs(arbi);
6381
- return decryptDmBatch(arbi, raw, crypto2);
6449
+ async function getChat(arbi, chatExtId) {
6450
+ return requireData(
6451
+ await arbi.fetch.GET("/v1/chats/{chat_ext_id}", {
6452
+ params: { path: { chat_ext_id: chatExtId } }
6453
+ }),
6454
+ "Failed to load chat"
6455
+ );
6382
6456
  }
6383
- async function listActivity(arbi, options) {
6457
+ async function openDirectChat(arbi, peerExtId) {
6384
6458
  return requireData(
6385
- await arbi.fetch.GET("/v1/notifications/", {
6459
+ await arbi.fetch.POST("/v1/chats/", { body: { kind: "direct", peer_ext_id: peerExtId } }),
6460
+ "Failed to open chat"
6461
+ );
6462
+ }
6463
+ async function createGroupChat(arbi, crypto2, params) {
6464
+ const members = params.members.filter((m2) => m2.external_id !== crypto2.userExtId);
6465
+ if (members.length === 0) throw new Error("A group needs at least one other member");
6466
+ const agent = members.find((m2) => isAgentExtId(m2.external_id));
6467
+ if (agent) throw new Error("Personal agents cannot join a group chat");
6468
+ const key = await client.generateChatKey();
6469
+ try {
6470
+ const title = params.title?.trim();
6471
+ return requireData(
6472
+ await arbi.fetch.POST("/v1/chats/", {
6473
+ body: {
6474
+ kind: "group",
6475
+ title: title ? await client.encryptWithChatKey(title, key) : null,
6476
+ members: await Promise.all(
6477
+ members.map(async (m2) => ({
6478
+ user_ext_id: m2.external_id,
6479
+ sealed_key: await client.sealChatKey(key, m2.encryption_public_key)
6480
+ }))
6481
+ ),
6482
+ creator_sealed_key: await client.sealChatKey(
6483
+ key,
6484
+ client.bytesToBase64(crypto2.encryptionKeypair.publicKey)
6485
+ )
6486
+ }
6487
+ }),
6488
+ "Failed to create group"
6489
+ );
6490
+ } finally {
6491
+ key.fill(0);
6492
+ }
6493
+ }
6494
+ async function renameChat(arbi, ring, title) {
6495
+ const trimmed = title?.trim();
6496
+ return requireData(
6497
+ await arbi.fetch.PATCH("/v1/chats/{chat_ext_id}", {
6498
+ params: { path: { chat_ext_id: ring.chatExtId } },
6499
+ body: {
6500
+ title: trimmed ? await client.encryptWithChatKey(trimmed, keyFor(ring, ring.currentVersion)) : null
6501
+ }
6502
+ }),
6503
+ "Failed to rename chat"
6504
+ );
6505
+ }
6506
+ async function addChatMembers(arbi, ring, members) {
6507
+ if (ring.kind === "direct") {
6508
+ throw new Error("A direct chat cannot gain members: create a group instead");
6509
+ }
6510
+ if (members.some((m2) => isAgentExtId(m2.external_id))) {
6511
+ throw new Error("Personal agents cannot join a group chat");
6512
+ }
6513
+ const key = keyFor(ring, ring.currentVersion);
6514
+ return requireData(
6515
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/members", {
6516
+ params: { path: { chat_ext_id: ring.chatExtId } },
6517
+ body: {
6518
+ members: await Promise.all(
6519
+ members.map(async (m2) => ({
6520
+ user_ext_id: m2.external_id,
6521
+ sealed_key: await client.sealChatKey(key, m2.encryption_public_key)
6522
+ }))
6523
+ )
6524
+ }
6525
+ }),
6526
+ "Failed to add members"
6527
+ );
6528
+ }
6529
+ async function removeChatMember(arbi, chatExtId, userExtId) {
6530
+ requireOk(
6531
+ await arbi.fetch.DELETE("/v1/chats/{chat_ext_id}/members/{user_ext_id}", {
6532
+ params: { path: { chat_ext_id: chatExtId, user_ext_id: userExtId } }
6533
+ }),
6534
+ "Failed to remove member"
6535
+ );
6536
+ }
6537
+ async function rotateChatKey(arbi, chat, ring) {
6538
+ if (chat.kind === "direct") throw new Error("Direct chats have no epochs");
6539
+ const oldTitle = await decryptChatTitle(ring, chat);
6540
+ if (chat.title && oldTitle === null) {
6541
+ throw new Error("Cannot re-encrypt the chat title: its key is not available");
6542
+ }
6543
+ const key = await client.generateChatKey();
6544
+ try {
6545
+ const sealed = {};
6546
+ for (const m2 of chat.members) {
6547
+ sealed[m2.user.external_id] = await client.sealChatKey(key, m2.user.encryption_public_key);
6548
+ }
6549
+ return requireData(
6550
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/keys", {
6551
+ params: { path: { chat_ext_id: chat.external_id } },
6552
+ body: {
6553
+ version: chat.key_version + 1,
6554
+ sealed_keys: sealed,
6555
+ ...oldTitle !== null ? { title: await client.encryptWithChatKey(oldTitle, key) } : {}
6556
+ }
6557
+ }),
6558
+ "Failed to rotate chat key"
6559
+ );
6560
+ } finally {
6561
+ key.fill(0);
6562
+ }
6563
+ }
6564
+ async function ensureChatKeyCurrent(arbi, chat, crypto2) {
6565
+ if (!chat.rotation_required || chat.kind === "direct") return chat;
6566
+ if (!chat.members.some((m2) => m2.user.external_id === crypto2.userExtId)) return chat;
6567
+ try {
6568
+ return await rotateChatKey(arbi, chat, await openChatKeyRing(chat, crypto2));
6569
+ } catch (err) {
6570
+ if (err instanceof ArbiApiError && err.status === 409) return getChat(arbi, chat.external_id);
6571
+ throw err;
6572
+ }
6573
+ }
6574
+ async function listChatMessages(arbi, chatExtId, options) {
6575
+ return requireData(
6576
+ await arbi.fetch.GET("/v1/chats/{chat_ext_id}/messages", {
6386
6577
  params: {
6578
+ path: { chat_ext_id: chatExtId },
6387
6579
  query: {
6388
- type: "activity",
6389
- ...options?.limit != null ? { limit: options.limit } : {},
6390
- ...options?.offset != null ? { offset: options.offset } : {}
6580
+ ...options?.before ? { before: options.before } : {},
6581
+ ...options?.limit ? { limit: options.limit } : {}
6391
6582
  }
6392
6583
  }
6393
6584
  }),
6394
- "Failed to fetch activity"
6585
+ "Failed to load messages"
6395
6586
  );
6396
6587
  }
6588
+ async function sendChatMessage(arbi, ring, text, options = {}) {
6589
+ const attachments = options.attachments ?? [];
6590
+ checkChatAttachmentLimits(attachments);
6591
+ const key = keyFor(ring, ring.currentVersion);
6592
+ const created = requireData(
6593
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/messages", {
6594
+ params: { path: { chat_ext_id: ring.chatExtId } },
6595
+ body: {
6596
+ content: await client.encryptWithChatKey(text, key),
6597
+ key_version: ring.currentVersion,
6598
+ kind: "text",
6599
+ ...attachments.length ? {
6600
+ attachments: await encryptChatAttachmentManifest(attachments, key),
6601
+ attachment_ext_ids: attachments.map((f2) => f2.id)
6602
+ } : {},
6603
+ ...options.workspaceExtId ? { workspace_ext_id: options.workspaceExtId } : {},
6604
+ context_only: !!options.contextOnly
6605
+ }
6606
+ }),
6607
+ "Failed to send message"
6608
+ );
6609
+ return {
6610
+ ...created,
6611
+ content: text,
6612
+ ...attachments.length ? { attachmentFiles: attachments } : {}
6613
+ };
6614
+ }
6615
+ async function deleteChatMessage(arbi, chatExtId, messageExtId) {
6616
+ requireOk(
6617
+ await arbi.fetch.DELETE("/v1/chats/{chat_ext_id}/messages/{message_ext_id}", {
6618
+ params: { path: { chat_ext_id: chatExtId, message_ext_id: messageExtId } }
6619
+ }),
6620
+ "Failed to delete message"
6621
+ );
6622
+ }
6623
+ async function markChatRead(arbi, chatExtId, messageExtId) {
6624
+ return requireData(
6625
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/read", {
6626
+ params: { path: { chat_ext_id: chatExtId } },
6627
+ body: messageExtId ? { message_ext_id: messageExtId } : {}
6628
+ }),
6629
+ "Failed to mark chat read"
6630
+ );
6631
+ }
6632
+ function hasRead(member, message) {
6633
+ if (!member?.last_read_at) return false;
6634
+ return Date.parse(member.last_read_at) >= Date.parse(message.created_at);
6635
+ }
6397
6636
  async function resolveRecipient(arbi, ref) {
6398
6637
  const isEmail = ref.includes("@");
6399
6638
  const matchKey = isEmail ? "email" : "external_id";
@@ -6425,52 +6664,63 @@ async function resolveRecipient(arbi, ref) {
6425
6664
  }
6426
6665
  return null;
6427
6666
  }
6428
- async function sendEncryptedDM(arbi, messages, crypto2, options) {
6429
- const attachments = options?.attachments ?? [];
6430
- checkDmAttachmentLimits(attachments);
6431
- const plaintextFor = new Map(messages.map((m2) => [m2.recipient_ext_id, m2.content]));
6432
- const encrypted = await Promise.all(
6433
- messages.map(async (msg) => ({
6434
- recipient_ext_id: msg.recipient_ext_id,
6435
- content: await encryptDmContent(
6436
- arbi,
6437
- msg.content,
6438
- msg.recipient_encryption_public_key,
6439
- crypto2.encryptionKeypair.secretKey
6440
- ),
6441
- ...attachments.length ? {
6442
- attachments: await encryptDmAttachmentManifest(
6443
- arbi,
6444
- attachments,
6445
- msg.recipient_encryption_public_key,
6446
- crypto2.encryptionKeypair.secretKey
6447
- )
6448
- } : {}
6449
- }))
6450
- );
6451
- const created = requireData(
6452
- await arbi.fetch.POST("/v1/notifications/", {
6453
- body: {
6454
- messages: encrypted,
6455
- context_only: false,
6456
- ...attachments.length ? { attachment_ext_ids: attachments.map((f2) => f2.id) } : {}
6667
+ async function sendDirectMessage(arbi, crypto2, peerExtId, text, options) {
6668
+ const chat = await openDirectChat(arbi, peerExtId);
6669
+ return sendChatMessage(arbi, await openChatKeyRing(chat, crypto2), text, options);
6670
+ }
6671
+ async function loadDecryptedChat(arbi, crypto2, chat, options) {
6672
+ const ring = await openChatKeyRing(chat, crypto2);
6673
+ const raw = await listChatMessages(arbi, chat.external_id, { limit: options?.limit });
6674
+ const messages = (await decryptChatMessages(ring, raw)).reverse();
6675
+ return { chat, ring, title: await decryptChatTitle(ring, chat), messages };
6676
+ }
6677
+
6678
+ // src/operations/notifications.ts
6679
+ var notifications_exports = {};
6680
+ __export(notifications_exports, {
6681
+ deleteNotifications: () => deleteNotifications,
6682
+ listActivity: () => listActivity,
6683
+ listNotifications: () => listNotifications,
6684
+ markNotificationsRead: () => markNotificationsRead,
6685
+ requestWorkspaceAccess: () => requestWorkspaceAccess
6686
+ });
6687
+ async function listNotifications(arbi) {
6688
+ return requireData(await arbi.fetch.GET("/v1/notifications/"), "Failed to fetch notifications");
6689
+ }
6690
+ async function listActivity(arbi, options) {
6691
+ return requireData(
6692
+ await arbi.fetch.GET("/v1/notifications/", {
6693
+ params: {
6694
+ query: {
6695
+ type: "activity",
6696
+ ...options?.limit != null ? { limit: options.limit } : {},
6697
+ ...options?.offset != null ? { offset: options.offset } : {}
6698
+ }
6457
6699
  }
6458
6700
  }),
6459
- "Failed to send message"
6701
+ "Failed to fetch activity"
6702
+ );
6703
+ }
6704
+ async function markNotificationsRead(arbi, ids) {
6705
+ return requireData(
6706
+ await arbi.fetch.PATCH("/v1/notifications/", {
6707
+ body: { updates: ids.map((id) => ({ external_id: id, read: true })) }
6708
+ }),
6709
+ "Failed to update notifications"
6710
+ );
6711
+ }
6712
+ async function deleteNotifications(arbi, ids) {
6713
+ requireOk(
6714
+ await arbi.fetch.DELETE("/v1/notifications/", { body: { external_ids: ids } }),
6715
+ "Failed to delete notifications"
6460
6716
  );
6461
- return created.map((n2) => ({
6462
- ...n2,
6463
- content: plaintextFor.get(n2.recipient.external_id) ?? n2.content,
6464
- ...attachments.length ? { attachmentFiles: attachments } : {}
6465
- }));
6466
6717
  }
6467
6718
  async function requestWorkspaceAccess(arbi, params, crypto2) {
6468
6719
  const payload = JSON.stringify({
6469
6720
  session_pubkey_b64: params.sessionPubkeyB64,
6470
6721
  note: params.note?.trim() || void 0
6471
6722
  });
6472
- const content = await encryptDmContent(
6473
- arbi,
6723
+ const content = await client.encryptMessage(
6474
6724
  payload,
6475
6725
  params.recipientEncryptionPublicKey,
6476
6726
  crypto2.encryptionKeypair.secretKey
@@ -6486,28 +6736,6 @@ async function requestWorkspaceAccess(arbi, params, crypto2) {
6486
6736
  "Failed to request workspace access"
6487
6737
  );
6488
6738
  }
6489
- async function sendDM(arbi, messages) {
6490
- return requireData(
6491
- await arbi.fetch.POST("/v1/notifications/", {
6492
- body: { messages, context_only: false }
6493
- }),
6494
- "Failed to send message"
6495
- );
6496
- }
6497
- async function markRead(arbi, messageIds) {
6498
- return requireData(
6499
- await arbi.fetch.PATCH("/v1/notifications/", {
6500
- body: { updates: messageIds.map((id) => ({ external_id: id, read: true })) }
6501
- }),
6502
- "Failed to update messages"
6503
- );
6504
- }
6505
- async function deleteDMs(arbi, messageIds) {
6506
- requireOk(
6507
- await arbi.fetch.DELETE("/v1/notifications/", { body: { external_ids: messageIds } }),
6508
- "Failed to delete messages"
6509
- );
6510
- }
6511
6739
 
6512
6740
  // src/operations/settings.ts
6513
6741
  var settings_exports = {};
@@ -6731,6 +6959,22 @@ async function updateProfile(arbi, body) {
6731
6959
  );
6732
6960
  }
6733
6961
 
6962
+ // src/operations/firm.ts
6963
+ var firm_exports = {};
6964
+ __export(firm_exports, {
6965
+ getFirmPool: () => getFirmPool,
6966
+ topUpFirmPool: () => topUpFirmPool
6967
+ });
6968
+ async function getFirmPool(arbi) {
6969
+ return requireData(await arbi.fetch.GET("/v1/firm/pool"), "Failed to fetch the firm AI usage");
6970
+ }
6971
+ async function topUpFirmPool(arbi, aiAddons) {
6972
+ return requireData(
6973
+ await arbi.fetch.POST("/v1/firm/pool/topup", { body: { ai_addons: aiAddons } }),
6974
+ "Failed to add firm AI usage"
6975
+ );
6976
+ }
6977
+
6734
6978
  // src/operations/account.ts
6735
6979
  var account_exports = {};
6736
6980
  __export(account_exports, {
@@ -7963,10 +8207,10 @@ function attachmentFromBytes(name, contentType, bytes) {
7963
8207
  name,
7964
8208
  content_type: contentType,
7965
8209
  size: bytes.length,
7966
- content_base64: bytesToBase642(bytes)
8210
+ content_base64: bytesToBase643(bytes)
7967
8211
  };
7968
8212
  }
7969
- function bytesToBase642(bytes) {
8213
+ function bytesToBase643(bytes) {
7970
8214
  let binary = "";
7971
8215
  for (let i2 = 0; i2 < bytes.length; i2 += 32768) {
7972
8216
  binary += String.fromCharCode(...bytes.subarray(i2, i2 + 32768));
@@ -7994,7 +8238,7 @@ var Arbi = class {
7994
8238
  currentWorkspaceId = null;
7995
8239
  /** Wrapped workspace keys seen in the last list/create, so selecting needs no re-fetch. */
7996
8240
  wrappedKeys = /* @__PURE__ */ new Map();
7997
- dmCryptoContext = null;
8241
+ chatCryptoContext = null;
7998
8242
  sessionExpiredListeners = /* @__PURE__ */ new Set();
7999
8243
  options;
8000
8244
  constructor(options) {
@@ -8166,7 +8410,7 @@ var Arbi = class {
8166
8410
  this.userProfile = null;
8167
8411
  this.currentWorkspaceId = null;
8168
8412
  this.wrappedKeys.clear();
8169
- this.dmCryptoContext = null;
8413
+ this.chatCryptoContext = null;
8170
8414
  this.client?.session.clear();
8171
8415
  for (const listener of [...this.sessionExpiredListeners]) listener();
8172
8416
  }
@@ -8212,7 +8456,7 @@ var Arbi = class {
8212
8456
  this.userProfile = null;
8213
8457
  this.currentWorkspaceId = null;
8214
8458
  this.wrappedKeys.clear();
8215
- this.dmCryptoContext = null;
8459
+ this.chatCryptoContext = null;
8216
8460
  }
8217
8461
  // ── Accessors ─────────────────────────────────────────────────────────
8218
8462
  /** Get the underlying ArbiClient (throws if not initialized). */
@@ -8311,6 +8555,13 @@ var Arbi = class {
8311
8555
  */
8312
8556
  me: () => getCurrentUser(this.requireClient())
8313
8557
  };
8558
+ // ── Firm ──────────────────────────────────────────────────────────────
8559
+ firm = {
8560
+ /** The firm's pooled monthly £ of AI usage (`has_pool` false where there is none). */
8561
+ pool: () => getFirmPool(this.requireClient()),
8562
+ /** Buy `aiAddons` renewing add-ons (+£10 of AI usage a month each) for the firm. Box admins only. */
8563
+ topUp: (aiAddons) => topUpFirmPool(this.requireClient(), aiAddons)
8564
+ };
8314
8565
  // ── Profile ───────────────────────────────────────────────────────────
8315
8566
  profile = {
8316
8567
  /** Update the display profile; pass only what changes (`''` clears family name or picture). */
@@ -8476,9 +8727,13 @@ var Arbi = class {
8476
8727
  const lr2 = this.requireLogin();
8477
8728
  const userExtId = lr2.userExtId ?? client.session.getState().userExtId;
8478
8729
  if (!userExtId) throw new ArbiError("No user id in session \u2014 cannot request access");
8479
- const crypto2 = createDmCryptoContext(client, lr2.signingPrivateKey, userExtId);
8730
+ const crypto2 = createChatCryptoContext(lr2.signingPrivateKey, userExtId);
8480
8731
  const sessionPubkeyB64 = client.crypto.bytesToBase64(lr2.serverSessionKey);
8481
- return requestWorkspaceAccess(client, { ...params, sessionPubkeyB64 }, crypto2);
8732
+ return requestWorkspaceAccess(
8733
+ client,
8734
+ { ...params, sessionPubkeyB64 },
8735
+ crypto2
8736
+ );
8482
8737
  },
8483
8738
  copyDocuments: (targetWorkspaceId, docIds, targetWorkspaceKey) => copyDocuments(
8484
8739
  this.requireClient(),
@@ -8768,92 +9023,119 @@ var Arbi = class {
8768
9023
  // ── Contacts ──────────────────────────────────────────────────────────
8769
9024
  contacts = {
8770
9025
  list: () => listContacts(this.requireClient()),
8771
- add: (emails) => addContacts(this.requireClient(), emails),
8772
- remove: (contactIds) => removeContacts(this.requireClient(), contactIds),
9026
+ invite: (emails) => inviteContacts(this.requireClient(), emails),
9027
+ create: (body) => createContact(this.requireClient(), body),
9028
+ update: (contactId, card) => updateContact(this.requireClient(), contactId, card),
9029
+ delete: (contactId) => deleteContact(this.requireClient(), contactId),
9030
+ search: (q2) => searchContacts(this.requireClient(), q2),
8773
9031
  groupByStatus: groupContactsByStatus
8774
9032
  };
8775
- // ── Direct Messages ───────────────────────────────────────────────────
9033
+ // ── Chats (direct + group) ────────────────────────────────────────────
8776
9034
  /**
8777
- * Build (and cache) the DM crypto context for the current session.
8778
- *
8779
- * Derives the user's curve25519 keypair from their signing key and pairs it
8780
- * with their external_id — everything `list()`/`send()` need to encrypt and
8781
- * decrypt. Cached for the session and cleared on logout. Consumers never touch
8782
- * this: it's an internal of the `dm` surface.
9035
+ * Build (and cache) the chat crypto context for the current session: my X25519 keypair
9036
+ * (derived from the signing key) and external id. Cleared on logout.
8783
9037
  *
8784
- * The key comes from the live login result first, exactly as `selectWorkspace`
8785
- * sources it, and only then from persisted storage (which is what restores a
8786
- * session on reload). Reading storage first would make DMs the one feature that
8787
- * breaks whenever persistence is unavailable — `saveSession` deliberately
8788
- * no-ops without Web Crypto (a non-secure origin, tracking prevention, an
8789
- * embedded widget), so a perfectly authenticated user with a working workspace
8790
- * would be told they are "not authenticated" the moment they opened Messages.
9038
+ * The key comes from the live login result first, exactly as `selectWorkspace` sources it, and
9039
+ * only then from persisted storage (which is what restores a session on reload) — persistence
9040
+ * deliberately no-ops without Web Crypto, and chats must not be the one feature that breaks then.
8791
9041
  */
8792
- async requireDmCrypto() {
8793
- if (this.dmCryptoContext) return this.dmCryptoContext;
9042
+ async requireChatCrypto() {
9043
+ if (this.chatCryptoContext) return this.chatCryptoContext;
8794
9044
  const client = this.requireClient();
8795
9045
  const signingPrivateKey = this.loginResult?.signingPrivateKey ?? (await client.storage.getSession())?.signingPrivateKey;
8796
9046
  if (!signingPrivateKey) {
8797
- throw new ArbiError("Not authenticated \u2014 no session available for DM encryption");
9047
+ throw new ArbiError("Not authenticated \u2014 no session available for chat encryption");
8798
9048
  }
8799
9049
  const userExtId = client.session.getState().userExtId;
8800
9050
  if (!userExtId) {
8801
- throw new ArbiError("No user identity in session \u2014 cannot set up DM encryption");
9051
+ throw new ArbiError("No user identity in session \u2014 cannot set up chat encryption");
8802
9052
  }
8803
- this.dmCryptoContext = createDmCryptoContext(client, signingPrivateKey, userExtId);
8804
- return this.dmCryptoContext;
9053
+ this.chatCryptoContext = createChatCryptoContext(signingPrivateKey, userExtId);
9054
+ return this.chatCryptoContext;
8805
9055
  }
9056
+ /** Fetch a chat, sealing a new epoch first when it is `rotation_required`. */
9057
+ async readyChat(chatExtId) {
9058
+ const client = this.requireClient();
9059
+ return ensureChatKeyCurrent(
9060
+ client,
9061
+ await getChat(client, chatExtId),
9062
+ await this.requireChatCrypto()
9063
+ );
9064
+ }
9065
+ chats = {
9066
+ /** My chats, most recently active first (raw: titles/last messages are ciphertext). */
9067
+ list: (kind) => listChats(this.requireClient(), kind),
9068
+ get: (chatExtId) => getChat(this.requireClient(), chatExtId),
9069
+ /** Get-or-create the direct chat with a peer. */
9070
+ openDirect: (peerExtId) => openDirectChat(this.requireClient(), peerExtId),
9071
+ /** Create a group (epoch 1 sealed to every member). Agents are refused. */
9072
+ createGroup: async (params) => createGroupChat(this.requireClient(), await this.requireChatCrypto(), params),
9073
+ /** A chat with its keys opened, title and newest messages decrypted (oldest first). */
9074
+ load: async (chatExtId, options) => {
9075
+ const chat = await this.readyChat(chatExtId);
9076
+ return loadDecryptedChat(
9077
+ this.requireClient(),
9078
+ await this.requireChatCrypto(),
9079
+ chat,
9080
+ options
9081
+ );
9082
+ },
9083
+ /** Post plaintext to a chat (encrypted under its current epoch). */
9084
+ send: async (chatExtId, text, options) => {
9085
+ const chat = await this.readyChat(chatExtId);
9086
+ const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
9087
+ return sendChatMessage(this.requireClient(), ring, text, options);
9088
+ },
9089
+ rename: async (chatExtId, title) => {
9090
+ const chat = await this.readyChat(chatExtId);
9091
+ const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
9092
+ return renameChat(this.requireClient(), ring, title);
9093
+ },
9094
+ addMembers: async (chatExtId, members) => {
9095
+ const chat = await this.readyChat(chatExtId);
9096
+ const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
9097
+ return addChatMembers(this.requireClient(), ring, members);
9098
+ },
9099
+ /** Remove a member (owner) or leave (own id); a remaining member seals the next epoch. */
9100
+ removeMember: async (chatExtId, userExtId) => {
9101
+ await removeChatMember(this.requireClient(), chatExtId, userExtId);
9102
+ const crypto2 = await this.requireChatCrypto();
9103
+ if (userExtId !== crypto2.userExtId) await this.readyChat(chatExtId);
9104
+ },
9105
+ markRead: (chatExtId, messageExtId) => markChatRead(this.requireClient(), chatExtId, messageExtId),
9106
+ deleteMessage: (chatExtId, messageExtId) => deleteChatMessage(this.requireClient(), chatExtId, messageExtId)
9107
+ };
9108
+ /** Direct-chat conveniences addressed by peer (email or `usr-`/`agt-` id). */
8806
9109
  dm = {
8807
9110
  /**
8808
- * List direct messages, newest first, with content already **decrypted**.
8809
- * (A message that can't be decrypted comes back as `[Decryption failed]`.)
8810
- */
8811
- list: async () => listDecryptedDMs(this.requireClient(), await this.requireDmCrypto()),
8812
- /**
8813
- * Send an E2E-encrypted DM to a recipient (email or `usr-`/`agt-` id).
8814
- * Resolves the recipient's public key and encrypts internally — the caller
8815
- * passes plaintext and never handles keys or ciphertext.
9111
+ * Send an E2E-encrypted direct message: resolves the peer, opens (get-or-create) the direct
9112
+ * chat and posts under the pair key. The caller passes plaintext and never handles keys.
8816
9113
  */
8817
9114
  send: async (recipient, text) => {
8818
9115
  const client = this.requireClient();
8819
9116
  const resolved = await resolveRecipient(client, recipient);
8820
9117
  if (!resolved) {
8821
9118
  throw new ArbiError(
8822
- `Could not resolve DM recipient "${recipient}" (not a known contact, agent, or workspace member)`
9119
+ `Could not resolve recipient "${recipient}" (not a known contact, agent, or workspace member)`
8823
9120
  );
8824
9121
  }
8825
- return sendEncryptedDM(
9122
+ return sendDirectMessage(
8826
9123
  client,
8827
- [
8828
- {
8829
- recipient_ext_id: resolved.extId,
8830
- content: text,
8831
- recipient_encryption_public_key: resolved.pubKey
8832
- }
8833
- ],
8834
- await this.requireDmCrypto()
9124
+ await this.requireChatCrypto(),
9125
+ resolved.extId,
9126
+ text
8835
9127
  );
8836
9128
  },
8837
- /**
8838
- * Send to a recipient whose external_id + public key are already known
8839
- * (e.g. from a message's `sender`), skipping directory resolution.
8840
- */
8841
- sendTo: async (recipientExtId, recipientPublicKey, text) => sendEncryptedDM(
9129
+ /** Send to a peer whose external id is already known, skipping directory resolution. */
9130
+ sendTo: async (peerExtId, text) => sendDirectMessage(
8842
9131
  this.requireClient(),
8843
- [
8844
- {
8845
- recipient_ext_id: recipientExtId,
8846
- content: text,
8847
- recipient_encryption_public_key: recipientPublicKey
8848
- }
8849
- ],
8850
- await this.requireDmCrypto()
9132
+ await this.requireChatCrypto(),
9133
+ peerExtId,
9134
+ text
8851
9135
  ),
8852
9136
  /** Resolve a recipient reference to `{ extId, pubKey }` (contacts → agents → workspace). */
8853
9137
  resolveRecipient: (recipient) => resolveRecipient(this.requireClient(), recipient),
8854
- markRead: (messageIds) => markRead(this.requireClient(), messageIds),
8855
- delete: (messageIds) => deleteDMs(this.requireClient(), messageIds),
8856
- /** List the current user's durable activity feed (never unread; excluded from DMs). */
9138
+ /** List the current user's durable activity feed. */
8857
9139
  listActivity: (options) => listActivity(this.requireClient(), options)
8858
9140
  };
8859
9141
  // ── Settings ──────────────────────────────────────────────────────────
@@ -9946,6 +10228,7 @@ var OpenClawOrchestrator = class {
9946
10228
  };
9947
10229
 
9948
10230
  // src/listen/dm-listener.ts
10231
+ var BACKFILL_LIMIT = 50;
9949
10232
  async function startDmListener(options) {
9950
10233
  const { arbi, baseUrl, crypto: crypto2, orchestrator, parentExtId, onLog, onError } = options;
9951
10234
  const log = onLog ?? (() => {
@@ -9955,72 +10238,87 @@ async function startDmListener(options) {
9955
10238
  if (!initialToken) {
9956
10239
  throw new Error("No access token \u2014 run `arbi login` first.");
9957
10240
  }
9958
- const handleNotification = async (msg) => {
9959
- if (msg.type !== "user_message") return;
9960
- const senderExtId = msg.sender?.external_id;
10241
+ const rings = /* @__PURE__ */ new Map();
10242
+ const ringFor = (chatExtId) => {
10243
+ let ring = rings.get(chatExtId);
10244
+ if (!ring) {
10245
+ ring = getChat(arbi, chatExtId).then(
10246
+ (chat) => chat.kind === "direct" && chat.members.some((m2) => m2.user.external_id === parentExtId) ? openChatKeyRing(chat, crypto2) : null
10247
+ );
10248
+ ring.catch(() => rings.delete(chatExtId));
10249
+ rings.set(chatExtId, ring);
10250
+ }
10251
+ return ring;
10252
+ };
10253
+ const handled = /* @__PURE__ */ new Set();
10254
+ const handleMessage = async (chatExtId, msg) => {
10255
+ if (handled.has(msg.external_id)) return;
10256
+ if (msg.kind !== "text" || msg.context_only) return;
10257
+ const senderExtId = msg.sender_ext_id;
9961
10258
  if (!senderExtId || senderExtId !== parentExtId) {
9962
- log(`Ignoring message from ${senderExtId ?? "unknown"} (not parent)`);
10259
+ if (senderExtId !== crypto2.userExtId) {
10260
+ log(`Ignoring message from ${senderExtId ?? "unknown"} (not parent)`);
10261
+ }
9963
10262
  return;
9964
10263
  }
9965
- let plaintext;
9966
- try {
9967
- plaintext = await decryptDmContent(arbi, msg, crypto2);
9968
- } catch (err) {
9969
- logError("Failed to decrypt incoming DM", err);
10264
+ handled.add(msg.external_id);
10265
+ const ring = await ringFor(chatExtId);
10266
+ if (!ring) {
10267
+ log(`Ignoring message in ${chatExtId} (not the direct chat with the parent)`);
9970
10268
  return;
9971
10269
  }
10270
+ const decrypted = await decryptChatMessage(ring, msg);
10271
+ if (decrypted.decryptFailed) {
10272
+ logError("Failed to decrypt incoming message");
10273
+ return;
10274
+ }
10275
+ const plaintext = decrypted.content;
9972
10276
  if (!plaintext) {
9973
10277
  log("Received empty message, skipping");
9974
10278
  return;
9975
10279
  }
9976
- log(`Received prompt from ${msg.sender?.email ?? senderExtId}: ${plaintext.slice(0, 80)}...`);
10280
+ log(`Received prompt from ${senderExtId}: ${plaintext.slice(0, 80)}...`);
9977
10281
  let response;
9978
10282
  try {
9979
10283
  response = await orchestrator.prompt(plaintext, {
9980
10284
  senderExtId,
9981
- senderEmail: msg.sender?.email ?? void 0
10285
+ ...msg.workspace_ext_id ? { workspaceId: msg.workspace_ext_id } : {}
9982
10286
  });
9983
10287
  } catch (err) {
9984
10288
  logError(`Orchestrator "${orchestrator.name}" failed`, err);
9985
10289
  response = `[Error: orchestrator failed \u2014 ${err instanceof Error ? err.message : String(err)}]`;
9986
10290
  }
9987
10291
  log(`Orchestrator response (${response.length} chars): ${response.slice(0, 80)}...`);
9988
- const senderPubKey = msg.sender?.encryption_public_key;
9989
- if (!senderPubKey) {
9990
- logError("Cannot reply \u2014 sender has no encryption public key");
9991
- return;
9992
- }
9993
10292
  try {
9994
- await sendEncryptedDM(
9995
- arbi,
9996
- [
9997
- {
9998
- recipient_ext_id: senderExtId,
9999
- content: response,
10000
- recipient_encryption_public_key: senderPubKey
10001
- }
10002
- ],
10003
- crypto2
10004
- );
10005
- log(`Reply sent to ${msg.sender?.email ?? senderExtId}`);
10293
+ await sendChatMessage(arbi, ring, response);
10294
+ log(`Reply sent to ${senderExtId}`);
10006
10295
  } catch (err) {
10007
10296
  logError("Failed to send encrypted reply", err);
10008
10297
  }
10298
+ try {
10299
+ await markChatRead(arbi, chatExtId, msg.external_id);
10300
+ } catch {
10301
+ }
10009
10302
  };
10010
10303
  try {
10011
- const unreadFromParent = (await listDMs(arbi)).filter(
10012
- (n2) => n2.type === "user_message" && n2.read === false && n2.sender?.external_id === parentExtId
10304
+ const chats = (await listChats(arbi, "direct")).filter(
10305
+ (c2) => c2.unread_count > 0 && c2.members.some((m2) => m2.user.external_id === parentExtId)
10013
10306
  );
10014
- if (unreadFromParent.length > 0) {
10015
- log(`Backfilling ${unreadFromParent.length} unread DM(s) from parent`);
10016
- for (const n2 of unreadFromParent) {
10017
- await handleNotification(n2).catch(
10307
+ for (const chat of chats) {
10308
+ const me2 = chat.members.find((m2) => m2.user.external_id === crypto2.userExtId);
10309
+ const since = me2?.last_read_at ? Date.parse(me2.last_read_at) : 0;
10310
+ const unread = (await listChatMessages(arbi, chat.external_id, {
10311
+ limit: Math.min(chat.unread_count, BACKFILL_LIMIT)
10312
+ })).filter((m2) => m2.sender_ext_id === parentExtId && Date.parse(m2.created_at) > since).reverse();
10313
+ if (unread.length > 0) log(`Backfilling ${unread.length} unread message(s) from parent`);
10314
+ for (const m2 of unread) {
10315
+ await handleMessage(chat.external_id, m2).catch(
10018
10316
  (err) => logError("Backfill handler error", err)
10019
10317
  );
10020
10318
  }
10021
10319
  }
10022
10320
  } catch (err) {
10023
- logError("Failed to backfill unread DMs", err);
10321
+ logError("Failed to backfill unread messages", err);
10024
10322
  }
10025
10323
  const ws = await connectWithReconnect({
10026
10324
  baseUrl,
@@ -10029,14 +10327,9 @@ async function startDmListener(options) {
10029
10327
  refreshAuth: () => arbi.auth.relogin(),
10030
10328
  maxRetries: Infinity,
10031
10329
  onMessage: (msg) => {
10032
- if ("sender" in msg && "recipient" in msg) {
10033
- const notification = msg;
10034
- if (notification.type === "user_message") {
10035
- handleNotification(notification).catch(
10036
- (err) => logError("Notification handler error", err)
10037
- );
10038
- }
10039
- }
10330
+ if (msg.type !== "chat.message") return;
10331
+ const { chat_ext_id, message } = msg;
10332
+ handleMessage(chat_ext_id, message).catch((err) => logError("Message handler error", err));
10040
10333
  },
10041
10334
  onReconnecting: (attempt, max) => {
10042
10335
  const limit = Number.isFinite(max) ? `/${max}` : "";
@@ -10049,7 +10342,7 @@ async function startDmListener(options) {
10049
10342
  log(`WebSocket closed: ${reason || "no reason"}`);
10050
10343
  }
10051
10344
  });
10052
- log(`Listening for DMs (orchestrator: ${orchestrator.name}, parent: ${parentExtId})`);
10345
+ log(`Listening for messages (orchestrator: ${orchestrator.name}, parent: ${parentExtId})`);
10053
10346
  return {
10054
10347
  close() {
10055
10348
  ws.close();
@@ -10080,6 +10373,7 @@ exports.buildFactsContextTool = buildFactsContextTool;
10080
10373
  exports.buildRetrievalChunkTool = buildRetrievalChunkTool;
10081
10374
  exports.buildRetrievalFullContextTool = buildRetrievalFullContextTool;
10082
10375
  exports.buildRetrievalTocTool = buildRetrievalTocTool;
10376
+ exports.chats = chats_exports;
10083
10377
  exports.connectWebSocket = connectWebSocket;
10084
10378
  exports.connectWithReconnect = connectWithReconnect;
10085
10379
  exports.consumeSSEStream = consumeSSEStream;
@@ -10089,13 +10383,13 @@ exports.countCitations = countCitations;
10089
10383
  exports.createAuthenticatedClient = createAuthenticatedClient;
10090
10384
  exports.createDocumentWaiter = createDocumentWaiter;
10091
10385
  exports.deviceFlow = device_flow_exports;
10092
- exports.dm = dm_exports;
10093
10386
  exports.doctags = doctags_exports;
10094
10387
  exports.documents = documents_exports;
10095
10388
  exports.documentsNode = documents_node_exports;
10096
10389
  exports.facts = facts_exports;
10097
10390
  exports.files = files_exports;
10098
10391
  exports.filterSkills = filterSkills;
10392
+ exports.firm = firm_exports;
10099
10393
  exports.formatAgentStepLabel = formatAgentStepLabel;
10100
10394
  exports.formatFileSize = formatFileSize;
10101
10395
  exports.formatGbp = formatGbp;
@@ -10116,6 +10410,7 @@ exports.identityVerification = identity_exports;
10116
10410
  exports.listen = listen_exports;
10117
10411
  exports.mail = mail_exports;
10118
10412
  exports.mailNode = mail_node_exports;
10413
+ exports.notifications = notifications_exports;
10119
10414
  exports.parseSSEEvents = parseSSEEvents;
10120
10415
  exports.parseSlashCommand = parseSlashCommand;
10121
10416
  exports.parseSlashTokenInProgress = parseSlashTokenInProgress;