@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/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,44 @@ 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
+ checkChatAttachmentLimits: () => checkChatAttachmentLimits,
6095
+ createChatCryptoContext: () => createChatCryptoContext,
6096
+ createGroupChat: () => createGroupChat,
6097
+ decryptChatAttachmentManifest: () => decryptChatAttachmentManifest,
6098
+ decryptChatMessage: () => decryptChatMessage,
6099
+ decryptChatMessages: () => decryptChatMessages,
6100
+ decryptChatTitle: () => decryptChatTitle,
6101
+ deleteChatMessage: () => deleteChatMessage,
6102
+ directPeer: () => directPeer,
6103
+ downloadChatAttachment: () => downloadChatAttachment,
6104
+ encryptChatAttachmentManifest: () => encryptChatAttachmentManifest,
6105
+ ensureChatKeyCurrent: () => ensureChatKeyCurrent,
6106
+ getChat: () => getChat,
6107
+ hasRead: () => hasRead,
6108
+ isAgentExtId: () => isAgentExtId,
6109
+ listChatMessages: () => listChatMessages,
6110
+ listChats: () => listChats,
6111
+ loadDecryptedChat: () => loadDecryptedChat,
6112
+ markChatRead: () => markChatRead,
6113
+ openChatKeyRing: () => openChatKeyRing,
6114
+ openDirectChat: () => openDirectChat,
6115
+ parseChatAttachmentManifest: () => parseChatAttachmentManifest,
6116
+ removeChatMember: () => removeChatMember,
6117
+ renameChat: () => renameChat,
6080
6118
  resolveRecipient: () => resolveRecipient,
6081
- sendDM: () => sendDM,
6082
- sendEncryptedDM: () => sendEncryptedDM,
6083
- serializeDmAttachmentManifest: () => serializeDmAttachmentManifest,
6084
- uploadDmAttachment: () => uploadDmAttachment,
6085
- uploadDmAttachments: () => uploadDmAttachments
6119
+ rotateChatKey: () => rotateChatKey,
6120
+ sendChatMessage: () => sendChatMessage,
6121
+ sendDirectMessage: () => sendDirectMessage,
6122
+ serializeChatAttachmentManifest: () => serializeChatAttachmentManifest,
6123
+ uploadChatAttachment: () => uploadChatAttachment,
6124
+ uploadChatAttachments: () => uploadChatAttachments
6086
6125
  });
6087
6126
 
6088
6127
  // src/operations/agents.ts
@@ -6189,27 +6228,27 @@ async function stageAgentFile(auth, agentId, file, name) {
6189
6228
  });
6190
6229
  return response.json();
6191
6230
  }
6192
- var DM_ATTACHMENT_MAX_BYTES = 15 * 1024 * 1024;
6193
- var DM_ATTACHMENT_MAX_FILES = 10;
6231
+ var CHAT_ATTACHMENT_MAX_BYTES = 15 * 1024 * 1024;
6232
+ var CHAT_ATTACHMENT_MAX_FILES = 10;
6194
6233
  var ATTACHMENT_ID = /^att-[a-zA-Z0-9]{8}$/;
6195
6234
  var MANIFEST_VERSION = 1;
6196
6235
  var MB = 1024 * 1024;
6197
- function checkDmAttachmentLimits(files) {
6198
- if (files.length > DM_ATTACHMENT_MAX_FILES) {
6236
+ function checkChatAttachmentLimits(files) {
6237
+ if (files.length > CHAT_ATTACHMENT_MAX_FILES) {
6199
6238
  throw new Error(
6200
- `You can attach at most ${DM_ATTACHMENT_MAX_FILES} files to a message (this one has ${files.length}).`
6239
+ `You can attach at most ${CHAT_ATTACHMENT_MAX_FILES} files to a message (this one has ${files.length}).`
6201
6240
  );
6202
6241
  }
6203
6242
  for (const file of files) {
6204
- if (file.size > DM_ATTACHMENT_MAX_BYTES) {
6243
+ if (file.size > CHAT_ATTACHMENT_MAX_BYTES) {
6205
6244
  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.`
6245
+ `${file.name} is too large (${(file.size / MB).toFixed(1)} MB). Files can be at most ${CHAT_ATTACHMENT_MAX_BYTES / MB} MB.`
6207
6246
  );
6208
6247
  }
6209
6248
  }
6210
6249
  }
6211
- async function uploadDmAttachment(arbi, input) {
6212
- checkDmAttachmentLimits([{ name: input.name, size: input.bytes.length }]);
6250
+ async function uploadChatAttachment(arbi, input) {
6251
+ checkChatAttachmentLimits([{ name: input.name, size: input.bytes.length }]);
6213
6252
  await client.initSodium();
6214
6253
  const key = globalThis.crypto.getRandomValues(new Uint8Array(32));
6215
6254
  try {
@@ -6220,13 +6259,13 @@ async function uploadDmAttachment(arbi, input) {
6220
6259
  new Blob([ciphertext], { type: "application/octet-stream" }),
6221
6260
  "attachment.bin"
6222
6261
  );
6223
- const result = await arbi.fetch.POST("/v1/notifications/attachments", {
6262
+ const result = await arbi.fetch.POST("/v1/chats/attachments", {
6224
6263
  body: { file: "" },
6225
6264
  bodySerializer: () => form
6226
6265
  });
6227
6266
  if (result.response?.status === 413) {
6228
6267
  throw new ArbiApiError(
6229
- `${input.name} is too large. Files can be at most ${DM_ATTACHMENT_MAX_BYTES / MB} MB.`,
6268
+ `${input.name} is too large. Files can be at most ${CHAT_ATTACHMENT_MAX_BYTES / MB} MB.`,
6230
6269
  result.error,
6231
6270
  413
6232
6271
  );
@@ -6243,19 +6282,19 @@ async function uploadDmAttachment(arbi, input) {
6243
6282
  key.fill(0);
6244
6283
  }
6245
6284
  }
6246
- async function uploadDmAttachments(arbi, inputs) {
6247
- checkDmAttachmentLimits(inputs.map((i2) => ({ name: i2.name, size: i2.bytes.length })));
6285
+ async function uploadChatAttachments(arbi, inputs) {
6286
+ checkChatAttachmentLimits(inputs.map((i2) => ({ name: i2.name, size: i2.bytes.length })));
6248
6287
  const files = [];
6249
- for (const input of inputs) files.push(await uploadDmAttachment(arbi, input));
6288
+ for (const input of inputs) files.push(await uploadChatAttachment(arbi, input));
6250
6289
  return files;
6251
6290
  }
6252
- function serializeDmAttachmentManifest(files) {
6291
+ function serializeChatAttachmentManifest(files) {
6253
6292
  return JSON.stringify({
6254
6293
  v: MANIFEST_VERSION,
6255
6294
  files: files.map(({ id, name, type, size, key }) => ({ id, name, type, size, key }))
6256
6295
  });
6257
6296
  }
6258
- function parseDmAttachmentManifest(json2) {
6297
+ function parseChatAttachmentManifest(json2) {
6259
6298
  const manifest = JSON.parse(json2);
6260
6299
  if (manifest?.v !== MANIFEST_VERSION || !Array.isArray(manifest.files)) {
6261
6300
  throw new Error("Unsupported attachment manifest");
@@ -6274,27 +6313,15 @@ function parseDmAttachmentManifest(json2) {
6274
6313
  };
6275
6314
  });
6276
6315
  }
6277
- async function encryptDmAttachmentManifest(arbi, files, recipientEncryptionPubKeyBase64, senderEncryptionSecretKey) {
6278
- return arbi.crypto.encryptMessage(
6279
- serializeDmAttachmentManifest(files),
6280
- recipientEncryptionPubKeyBase64,
6281
- senderEncryptionSecretKey
6282
- );
6316
+ async function encryptChatAttachmentManifest(files, chatKey) {
6317
+ return client.encryptWithChatKey(serializeChatAttachmentManifest(files), chatKey);
6283
6318
  }
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);
6319
+ async function decryptChatAttachmentManifest(manifest, chatKey) {
6320
+ return parseChatAttachmentManifest(await client.decryptWithChatKey(manifest, chatKey));
6294
6321
  }
6295
- async function downloadDmAttachment(arbi, file) {
6322
+ async function downloadChatAttachment(arbi, file) {
6296
6323
  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}", {
6324
+ const result = await arbi.fetch.GET("/v1/chats/attachments/{external_id}", {
6298
6325
  params: { path: { external_id: file.id } },
6299
6326
  parseAs: "arrayBuffer"
6300
6327
  });
@@ -6322,78 +6349,275 @@ async function downloadDmAttachment(arbi, file) {
6322
6349
  return plain;
6323
6350
  }
6324
6351
 
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,
6352
+ // src/operations/chats.ts
6353
+ function createChatCryptoContext(signingPrivateKeyBytes, userExtId) {
6354
+ const encryptionKeypair = client.deriveEncryptionKeypairFromSigning({
6355
+ publicKey: signingPrivateKeyBytes.slice(32, 64),
6330
6356
  secretKey: signingPrivateKeyBytes
6331
6357
  });
6332
6358
  return { encryptionKeypair, userExtId };
6333
6359
  }
6334
- async function encryptDmContent(arbi, plaintext, recipientEncryptionPubKeyBase64, senderEncryptionSecretKey) {
6335
- return arbi.crypto.encryptMessage(
6336
- plaintext,
6337
- recipientEncryptionPubKeyBase64,
6338
- senderEncryptionSecretKey
6339
- );
6360
+ function isAgentExtId(extId) {
6361
+ return !!extId && extId.startsWith("agt-");
6340
6362
  }
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
- );
6363
+ function directPeer(chat, myExtId) {
6364
+ if (chat.kind !== "direct") return void 0;
6365
+ return chat.members.find((m2) => m2.user.external_id !== myExtId)?.user;
6350
6366
  }
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;
6367
+ async function openChatKeyRing(chat, crypto2) {
6368
+ const keys = /* @__PURE__ */ new Map();
6369
+ if (chat.kind === "direct") {
6370
+ const peer = directPeer(chat, crypto2.userExtId);
6371
+ const peerPub = peer?.encryption_public_key ?? client.bytesToBase64(crypto2.encryptionKeypair.publicKey);
6372
+ keys.set(0, await client.deriveDirectChatKey(peerPub, crypto2.encryptionKeypair.secretKey));
6373
+ } else {
6374
+ for (const k2 of chat.my_keys ?? []) {
6375
+ try {
6376
+ keys.set(
6377
+ k2.version,
6378
+ await client.openSealedChatKey(k2.sealed_key, crypto2.encryptionKeypair.secretKey)
6379
+ );
6380
+ } catch {
6381
+ }
6357
6382
  }
6358
- let row;
6383
+ }
6384
+ return { chatExtId: chat.external_id, kind: chat.kind, currentVersion: chat.key_version, keys };
6385
+ }
6386
+ function keyFor(ring, version) {
6387
+ const key = ring.keys.get(version);
6388
+ if (!key) throw new Error(`No key for epoch ${version} of ${ring.chatExtId}`);
6389
+ return key;
6390
+ }
6391
+ var DECRYPTION_FAILED = "[Decryption failed]";
6392
+ async function decryptChatMessage(ring, message) {
6393
+ const key = ring.keys.get(message.key_version);
6394
+ const row = { ...message };
6395
+ if (message.content) {
6359
6396
  try {
6360
- row = { ...n2, content: await decryptDmContent(arbi, n2, crypto2) };
6397
+ if (!key) throw new Error("no key");
6398
+ row.content = await client.decryptWithChatKey(message.content, key);
6361
6399
  } catch {
6362
- row = { ...n2, content: "[Decryption failed]" };
6400
+ row.content = DECRYPTION_FAILED;
6401
+ row.decryptFailed = true;
6363
6402
  }
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
- }
6403
+ }
6404
+ if (message.attachments) {
6405
+ try {
6406
+ if (!key) throw new Error("no key");
6407
+ row.attachmentFiles = await decryptChatAttachmentManifest(message.attachments, key);
6408
+ } catch {
6409
+ row.attachmentFiles = [];
6410
+ row.attachmentsError = "The attachments could not be decrypted";
6371
6411
  }
6372
- results.push(row);
6373
6412
  }
6374
- return results;
6413
+ return row;
6414
+ }
6415
+ async function decryptChatMessages(ring, messages) {
6416
+ return Promise.all(messages.map((m2) => decryptChatMessage(ring, m2)));
6417
+ }
6418
+ async function decryptChatTitle(ring, chat) {
6419
+ if (!chat.title) return null;
6420
+ const key = ring.keys.get(chat.key_version);
6421
+ if (!key) return null;
6422
+ try {
6423
+ return await client.decryptWithChatKey(chat.title, key);
6424
+ } catch {
6425
+ return null;
6426
+ }
6375
6427
  }
6376
- async function listDMs(arbi) {
6377
- return requireData(await arbi.fetch.GET("/v1/notifications/"), "Failed to fetch messages");
6428
+ async function listChats(arbi, kind) {
6429
+ return requireData(
6430
+ await arbi.fetch.GET("/v1/chats/", { params: { query: kind ? { kind } : {} } }),
6431
+ "Failed to list chats"
6432
+ );
6378
6433
  }
6379
- async function listDecryptedDMs(arbi, crypto2) {
6380
- const raw = await listDMs(arbi);
6381
- return decryptDmBatch(arbi, raw, crypto2);
6434
+ async function getChat(arbi, chatExtId) {
6435
+ return requireData(
6436
+ await arbi.fetch.GET("/v1/chats/{chat_ext_id}", {
6437
+ params: { path: { chat_ext_id: chatExtId } }
6438
+ }),
6439
+ "Failed to load chat"
6440
+ );
6382
6441
  }
6383
- async function listActivity(arbi, options) {
6442
+ async function openDirectChat(arbi, peerExtId) {
6384
6443
  return requireData(
6385
- await arbi.fetch.GET("/v1/notifications/", {
6444
+ await arbi.fetch.POST("/v1/chats/", { body: { kind: "direct", peer_ext_id: peerExtId } }),
6445
+ "Failed to open chat"
6446
+ );
6447
+ }
6448
+ async function createGroupChat(arbi, crypto2, params) {
6449
+ const members = params.members.filter((m2) => m2.external_id !== crypto2.userExtId);
6450
+ if (members.length === 0) throw new Error("A group needs at least one other member");
6451
+ const agent = members.find((m2) => isAgentExtId(m2.external_id));
6452
+ if (agent) throw new Error("Personal agents cannot join a group chat");
6453
+ const key = await client.generateChatKey();
6454
+ try {
6455
+ const title = params.title?.trim();
6456
+ return requireData(
6457
+ await arbi.fetch.POST("/v1/chats/", {
6458
+ body: {
6459
+ kind: "group",
6460
+ title: title ? await client.encryptWithChatKey(title, key) : null,
6461
+ members: await Promise.all(
6462
+ members.map(async (m2) => ({
6463
+ user_ext_id: m2.external_id,
6464
+ sealed_key: await client.sealChatKey(key, m2.encryption_public_key)
6465
+ }))
6466
+ ),
6467
+ creator_sealed_key: await client.sealChatKey(
6468
+ key,
6469
+ client.bytesToBase64(crypto2.encryptionKeypair.publicKey)
6470
+ )
6471
+ }
6472
+ }),
6473
+ "Failed to create group"
6474
+ );
6475
+ } finally {
6476
+ key.fill(0);
6477
+ }
6478
+ }
6479
+ async function renameChat(arbi, ring, title) {
6480
+ const trimmed = title?.trim();
6481
+ return requireData(
6482
+ await arbi.fetch.PATCH("/v1/chats/{chat_ext_id}", {
6483
+ params: { path: { chat_ext_id: ring.chatExtId } },
6484
+ body: {
6485
+ title: trimmed ? await client.encryptWithChatKey(trimmed, keyFor(ring, ring.currentVersion)) : null
6486
+ }
6487
+ }),
6488
+ "Failed to rename chat"
6489
+ );
6490
+ }
6491
+ async function addChatMembers(arbi, ring, members) {
6492
+ if (ring.kind === "direct") {
6493
+ throw new Error("A direct chat cannot gain members: create a group instead");
6494
+ }
6495
+ if (members.some((m2) => isAgentExtId(m2.external_id))) {
6496
+ throw new Error("Personal agents cannot join a group chat");
6497
+ }
6498
+ const key = keyFor(ring, ring.currentVersion);
6499
+ return requireData(
6500
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/members", {
6501
+ params: { path: { chat_ext_id: ring.chatExtId } },
6502
+ body: {
6503
+ members: await Promise.all(
6504
+ members.map(async (m2) => ({
6505
+ user_ext_id: m2.external_id,
6506
+ sealed_key: await client.sealChatKey(key, m2.encryption_public_key)
6507
+ }))
6508
+ )
6509
+ }
6510
+ }),
6511
+ "Failed to add members"
6512
+ );
6513
+ }
6514
+ async function removeChatMember(arbi, chatExtId, userExtId) {
6515
+ requireOk(
6516
+ await arbi.fetch.DELETE("/v1/chats/{chat_ext_id}/members/{user_ext_id}", {
6517
+ params: { path: { chat_ext_id: chatExtId, user_ext_id: userExtId } }
6518
+ }),
6519
+ "Failed to remove member"
6520
+ );
6521
+ }
6522
+ async function rotateChatKey(arbi, chat, ring) {
6523
+ if (chat.kind === "direct") throw new Error("Direct chats have no epochs");
6524
+ const oldTitle = await decryptChatTitle(ring, chat);
6525
+ if (chat.title && oldTitle === null) {
6526
+ throw new Error("Cannot re-encrypt the chat title: its key is not available");
6527
+ }
6528
+ const key = await client.generateChatKey();
6529
+ try {
6530
+ const sealed = {};
6531
+ for (const m2 of chat.members) {
6532
+ sealed[m2.user.external_id] = await client.sealChatKey(key, m2.user.encryption_public_key);
6533
+ }
6534
+ return requireData(
6535
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/keys", {
6536
+ params: { path: { chat_ext_id: chat.external_id } },
6537
+ body: {
6538
+ version: chat.key_version + 1,
6539
+ sealed_keys: sealed,
6540
+ ...oldTitle !== null ? { title: await client.encryptWithChatKey(oldTitle, key) } : {}
6541
+ }
6542
+ }),
6543
+ "Failed to rotate chat key"
6544
+ );
6545
+ } finally {
6546
+ key.fill(0);
6547
+ }
6548
+ }
6549
+ async function ensureChatKeyCurrent(arbi, chat, crypto2) {
6550
+ if (!chat.rotation_required || chat.kind === "direct") return chat;
6551
+ if (!chat.members.some((m2) => m2.user.external_id === crypto2.userExtId)) return chat;
6552
+ try {
6553
+ return await rotateChatKey(arbi, chat, await openChatKeyRing(chat, crypto2));
6554
+ } catch (err) {
6555
+ if (err instanceof ArbiApiError && err.status === 409) return getChat(arbi, chat.external_id);
6556
+ throw err;
6557
+ }
6558
+ }
6559
+ async function listChatMessages(arbi, chatExtId, options) {
6560
+ return requireData(
6561
+ await arbi.fetch.GET("/v1/chats/{chat_ext_id}/messages", {
6386
6562
  params: {
6563
+ path: { chat_ext_id: chatExtId },
6387
6564
  query: {
6388
- type: "activity",
6389
- ...options?.limit != null ? { limit: options.limit } : {},
6390
- ...options?.offset != null ? { offset: options.offset } : {}
6565
+ ...options?.before ? { before: options.before } : {},
6566
+ ...options?.limit ? { limit: options.limit } : {}
6391
6567
  }
6392
6568
  }
6393
6569
  }),
6394
- "Failed to fetch activity"
6570
+ "Failed to load messages"
6571
+ );
6572
+ }
6573
+ async function sendChatMessage(arbi, ring, text, options = {}) {
6574
+ const attachments = options.attachments ?? [];
6575
+ checkChatAttachmentLimits(attachments);
6576
+ const key = keyFor(ring, ring.currentVersion);
6577
+ const created = requireData(
6578
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/messages", {
6579
+ params: { path: { chat_ext_id: ring.chatExtId } },
6580
+ body: {
6581
+ content: await client.encryptWithChatKey(text, key),
6582
+ key_version: ring.currentVersion,
6583
+ kind: "text",
6584
+ ...attachments.length ? {
6585
+ attachments: await encryptChatAttachmentManifest(attachments, key),
6586
+ attachment_ext_ids: attachments.map((f2) => f2.id)
6587
+ } : {},
6588
+ ...options.workspaceExtId ? { workspace_ext_id: options.workspaceExtId } : {},
6589
+ context_only: !!options.contextOnly
6590
+ }
6591
+ }),
6592
+ "Failed to send message"
6593
+ );
6594
+ return {
6595
+ ...created,
6596
+ content: text,
6597
+ ...attachments.length ? { attachmentFiles: attachments } : {}
6598
+ };
6599
+ }
6600
+ async function deleteChatMessage(arbi, chatExtId, messageExtId) {
6601
+ requireOk(
6602
+ await arbi.fetch.DELETE("/v1/chats/{chat_ext_id}/messages/{message_ext_id}", {
6603
+ params: { path: { chat_ext_id: chatExtId, message_ext_id: messageExtId } }
6604
+ }),
6605
+ "Failed to delete message"
6395
6606
  );
6396
6607
  }
6608
+ async function markChatRead(arbi, chatExtId, messageExtId) {
6609
+ return requireData(
6610
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/read", {
6611
+ params: { path: { chat_ext_id: chatExtId } },
6612
+ body: messageExtId ? { message_ext_id: messageExtId } : {}
6613
+ }),
6614
+ "Failed to mark chat read"
6615
+ );
6616
+ }
6617
+ function hasRead(member, message) {
6618
+ if (!member?.last_read_at) return false;
6619
+ return Date.parse(member.last_read_at) >= Date.parse(message.created_at);
6620
+ }
6397
6621
  async function resolveRecipient(arbi, ref) {
6398
6622
  const isEmail = ref.includes("@");
6399
6623
  const matchKey = isEmail ? "email" : "external_id";
@@ -6425,52 +6649,63 @@ async function resolveRecipient(arbi, ref) {
6425
6649
  }
6426
6650
  return null;
6427
6651
  }
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) } : {}
6652
+ async function sendDirectMessage(arbi, crypto2, peerExtId, text, options) {
6653
+ const chat = await openDirectChat(arbi, peerExtId);
6654
+ return sendChatMessage(arbi, await openChatKeyRing(chat, crypto2), text, options);
6655
+ }
6656
+ async function loadDecryptedChat(arbi, crypto2, chat, options) {
6657
+ const ring = await openChatKeyRing(chat, crypto2);
6658
+ const raw = await listChatMessages(arbi, chat.external_id, { limit: options?.limit });
6659
+ const messages = (await decryptChatMessages(ring, raw)).reverse();
6660
+ return { chat, ring, title: await decryptChatTitle(ring, chat), messages };
6661
+ }
6662
+
6663
+ // src/operations/notifications.ts
6664
+ var notifications_exports = {};
6665
+ __export(notifications_exports, {
6666
+ deleteNotifications: () => deleteNotifications,
6667
+ listActivity: () => listActivity,
6668
+ listNotifications: () => listNotifications,
6669
+ markNotificationsRead: () => markNotificationsRead,
6670
+ requestWorkspaceAccess: () => requestWorkspaceAccess
6671
+ });
6672
+ async function listNotifications(arbi) {
6673
+ return requireData(await arbi.fetch.GET("/v1/notifications/"), "Failed to fetch notifications");
6674
+ }
6675
+ async function listActivity(arbi, options) {
6676
+ return requireData(
6677
+ await arbi.fetch.GET("/v1/notifications/", {
6678
+ params: {
6679
+ query: {
6680
+ type: "activity",
6681
+ ...options?.limit != null ? { limit: options.limit } : {},
6682
+ ...options?.offset != null ? { offset: options.offset } : {}
6683
+ }
6457
6684
  }
6458
6685
  }),
6459
- "Failed to send message"
6686
+ "Failed to fetch activity"
6687
+ );
6688
+ }
6689
+ async function markNotificationsRead(arbi, ids) {
6690
+ return requireData(
6691
+ await arbi.fetch.PATCH("/v1/notifications/", {
6692
+ body: { updates: ids.map((id) => ({ external_id: id, read: true })) }
6693
+ }),
6694
+ "Failed to update notifications"
6695
+ );
6696
+ }
6697
+ async function deleteNotifications(arbi, ids) {
6698
+ requireOk(
6699
+ await arbi.fetch.DELETE("/v1/notifications/", { body: { external_ids: ids } }),
6700
+ "Failed to delete notifications"
6460
6701
  );
6461
- return created.map((n2) => ({
6462
- ...n2,
6463
- content: plaintextFor.get(n2.recipient.external_id) ?? n2.content,
6464
- ...attachments.length ? { attachmentFiles: attachments } : {}
6465
- }));
6466
6702
  }
6467
6703
  async function requestWorkspaceAccess(arbi, params, crypto2) {
6468
6704
  const payload = JSON.stringify({
6469
6705
  session_pubkey_b64: params.sessionPubkeyB64,
6470
6706
  note: params.note?.trim() || void 0
6471
6707
  });
6472
- const content = await encryptDmContent(
6473
- arbi,
6708
+ const content = await client.encryptMessage(
6474
6709
  payload,
6475
6710
  params.recipientEncryptionPublicKey,
6476
6711
  crypto2.encryptionKeypair.secretKey
@@ -6486,28 +6721,6 @@ async function requestWorkspaceAccess(arbi, params, crypto2) {
6486
6721
  "Failed to request workspace access"
6487
6722
  );
6488
6723
  }
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
6724
 
6512
6725
  // src/operations/settings.ts
6513
6726
  var settings_exports = {};
@@ -6731,6 +6944,22 @@ async function updateProfile(arbi, body) {
6731
6944
  );
6732
6945
  }
6733
6946
 
6947
+ // src/operations/firm.ts
6948
+ var firm_exports = {};
6949
+ __export(firm_exports, {
6950
+ getFirmPool: () => getFirmPool,
6951
+ topUpFirmPool: () => topUpFirmPool
6952
+ });
6953
+ async function getFirmPool(arbi) {
6954
+ return requireData(await arbi.fetch.GET("/v1/firm/pool"), "Failed to fetch the firm AI usage");
6955
+ }
6956
+ async function topUpFirmPool(arbi, aiAddons) {
6957
+ return requireData(
6958
+ await arbi.fetch.POST("/v1/firm/pool/topup", { body: { ai_addons: aiAddons } }),
6959
+ "Failed to add firm AI usage"
6960
+ );
6961
+ }
6962
+
6734
6963
  // src/operations/account.ts
6735
6964
  var account_exports = {};
6736
6965
  __export(account_exports, {
@@ -7963,10 +8192,10 @@ function attachmentFromBytes(name, contentType, bytes) {
7963
8192
  name,
7964
8193
  content_type: contentType,
7965
8194
  size: bytes.length,
7966
- content_base64: bytesToBase642(bytes)
8195
+ content_base64: bytesToBase643(bytes)
7967
8196
  };
7968
8197
  }
7969
- function bytesToBase642(bytes) {
8198
+ function bytesToBase643(bytes) {
7970
8199
  let binary = "";
7971
8200
  for (let i2 = 0; i2 < bytes.length; i2 += 32768) {
7972
8201
  binary += String.fromCharCode(...bytes.subarray(i2, i2 + 32768));
@@ -7994,7 +8223,7 @@ var Arbi = class {
7994
8223
  currentWorkspaceId = null;
7995
8224
  /** Wrapped workspace keys seen in the last list/create, so selecting needs no re-fetch. */
7996
8225
  wrappedKeys = /* @__PURE__ */ new Map();
7997
- dmCryptoContext = null;
8226
+ chatCryptoContext = null;
7998
8227
  sessionExpiredListeners = /* @__PURE__ */ new Set();
7999
8228
  options;
8000
8229
  constructor(options) {
@@ -8166,7 +8395,7 @@ var Arbi = class {
8166
8395
  this.userProfile = null;
8167
8396
  this.currentWorkspaceId = null;
8168
8397
  this.wrappedKeys.clear();
8169
- this.dmCryptoContext = null;
8398
+ this.chatCryptoContext = null;
8170
8399
  this.client?.session.clear();
8171
8400
  for (const listener of [...this.sessionExpiredListeners]) listener();
8172
8401
  }
@@ -8212,7 +8441,7 @@ var Arbi = class {
8212
8441
  this.userProfile = null;
8213
8442
  this.currentWorkspaceId = null;
8214
8443
  this.wrappedKeys.clear();
8215
- this.dmCryptoContext = null;
8444
+ this.chatCryptoContext = null;
8216
8445
  }
8217
8446
  // ── Accessors ─────────────────────────────────────────────────────────
8218
8447
  /** Get the underlying ArbiClient (throws if not initialized). */
@@ -8311,6 +8540,13 @@ var Arbi = class {
8311
8540
  */
8312
8541
  me: () => getCurrentUser(this.requireClient())
8313
8542
  };
8543
+ // ── Firm ──────────────────────────────────────────────────────────────
8544
+ firm = {
8545
+ /** The firm's pooled monthly £ of AI usage (`has_pool` false where there is none). */
8546
+ pool: () => getFirmPool(this.requireClient()),
8547
+ /** Buy `aiAddons` renewing add-ons (+£10 of AI usage a month each) for the firm. Box admins only. */
8548
+ topUp: (aiAddons) => topUpFirmPool(this.requireClient(), aiAddons)
8549
+ };
8314
8550
  // ── Profile ───────────────────────────────────────────────────────────
8315
8551
  profile = {
8316
8552
  /** Update the display profile; pass only what changes (`''` clears family name or picture). */
@@ -8476,9 +8712,13 @@ var Arbi = class {
8476
8712
  const lr2 = this.requireLogin();
8477
8713
  const userExtId = lr2.userExtId ?? client.session.getState().userExtId;
8478
8714
  if (!userExtId) throw new ArbiError("No user id in session \u2014 cannot request access");
8479
- const crypto2 = createDmCryptoContext(client, lr2.signingPrivateKey, userExtId);
8715
+ const crypto2 = createChatCryptoContext(lr2.signingPrivateKey, userExtId);
8480
8716
  const sessionPubkeyB64 = client.crypto.bytesToBase64(lr2.serverSessionKey);
8481
- return requestWorkspaceAccess(client, { ...params, sessionPubkeyB64 }, crypto2);
8717
+ return requestWorkspaceAccess(
8718
+ client,
8719
+ { ...params, sessionPubkeyB64 },
8720
+ crypto2
8721
+ );
8482
8722
  },
8483
8723
  copyDocuments: (targetWorkspaceId, docIds, targetWorkspaceKey) => copyDocuments(
8484
8724
  this.requireClient(),
@@ -8768,92 +9008,119 @@ var Arbi = class {
8768
9008
  // ── Contacts ──────────────────────────────────────────────────────────
8769
9009
  contacts = {
8770
9010
  list: () => listContacts(this.requireClient()),
8771
- add: (emails) => addContacts(this.requireClient(), emails),
8772
- remove: (contactIds) => removeContacts(this.requireClient(), contactIds),
9011
+ invite: (emails) => inviteContacts(this.requireClient(), emails),
9012
+ create: (body) => createContact(this.requireClient(), body),
9013
+ update: (contactId, card) => updateContact(this.requireClient(), contactId, card),
9014
+ delete: (contactId) => deleteContact(this.requireClient(), contactId),
9015
+ search: (q2) => searchContacts(this.requireClient(), q2),
8773
9016
  groupByStatus: groupContactsByStatus
8774
9017
  };
8775
- // ── Direct Messages ───────────────────────────────────────────────────
9018
+ // ── Chats (direct + group) ────────────────────────────────────────────
8776
9019
  /**
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.
9020
+ * Build (and cache) the chat crypto context for the current session: my X25519 keypair
9021
+ * (derived from the signing key) and external id. Cleared on logout.
8783
9022
  *
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.
9023
+ * The key comes from the live login result first, exactly as `selectWorkspace` sources it, and
9024
+ * only then from persisted storage (which is what restores a session on reload) — persistence
9025
+ * deliberately no-ops without Web Crypto, and chats must not be the one feature that breaks then.
8791
9026
  */
8792
- async requireDmCrypto() {
8793
- if (this.dmCryptoContext) return this.dmCryptoContext;
9027
+ async requireChatCrypto() {
9028
+ if (this.chatCryptoContext) return this.chatCryptoContext;
8794
9029
  const client = this.requireClient();
8795
9030
  const signingPrivateKey = this.loginResult?.signingPrivateKey ?? (await client.storage.getSession())?.signingPrivateKey;
8796
9031
  if (!signingPrivateKey) {
8797
- throw new ArbiError("Not authenticated \u2014 no session available for DM encryption");
9032
+ throw new ArbiError("Not authenticated \u2014 no session available for chat encryption");
8798
9033
  }
8799
9034
  const userExtId = client.session.getState().userExtId;
8800
9035
  if (!userExtId) {
8801
- throw new ArbiError("No user identity in session \u2014 cannot set up DM encryption");
9036
+ throw new ArbiError("No user identity in session \u2014 cannot set up chat encryption");
8802
9037
  }
8803
- this.dmCryptoContext = createDmCryptoContext(client, signingPrivateKey, userExtId);
8804
- return this.dmCryptoContext;
9038
+ this.chatCryptoContext = createChatCryptoContext(signingPrivateKey, userExtId);
9039
+ return this.chatCryptoContext;
8805
9040
  }
9041
+ /** Fetch a chat, sealing a new epoch first when it is `rotation_required`. */
9042
+ async readyChat(chatExtId) {
9043
+ const client = this.requireClient();
9044
+ return ensureChatKeyCurrent(
9045
+ client,
9046
+ await getChat(client, chatExtId),
9047
+ await this.requireChatCrypto()
9048
+ );
9049
+ }
9050
+ chats = {
9051
+ /** My chats, most recently active first (raw: titles/last messages are ciphertext). */
9052
+ list: (kind) => listChats(this.requireClient(), kind),
9053
+ get: (chatExtId) => getChat(this.requireClient(), chatExtId),
9054
+ /** Get-or-create the direct chat with a peer. */
9055
+ openDirect: (peerExtId) => openDirectChat(this.requireClient(), peerExtId),
9056
+ /** Create a group (epoch 1 sealed to every member). Agents are refused. */
9057
+ createGroup: async (params) => createGroupChat(this.requireClient(), await this.requireChatCrypto(), params),
9058
+ /** A chat with its keys opened, title and newest messages decrypted (oldest first). */
9059
+ load: async (chatExtId, options) => {
9060
+ const chat = await this.readyChat(chatExtId);
9061
+ return loadDecryptedChat(
9062
+ this.requireClient(),
9063
+ await this.requireChatCrypto(),
9064
+ chat,
9065
+ options
9066
+ );
9067
+ },
9068
+ /** Post plaintext to a chat (encrypted under its current epoch). */
9069
+ send: async (chatExtId, text, options) => {
9070
+ const chat = await this.readyChat(chatExtId);
9071
+ const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
9072
+ return sendChatMessage(this.requireClient(), ring, text, options);
9073
+ },
9074
+ rename: async (chatExtId, title) => {
9075
+ const chat = await this.readyChat(chatExtId);
9076
+ const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
9077
+ return renameChat(this.requireClient(), ring, title);
9078
+ },
9079
+ addMembers: async (chatExtId, members) => {
9080
+ const chat = await this.readyChat(chatExtId);
9081
+ const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
9082
+ return addChatMembers(this.requireClient(), ring, members);
9083
+ },
9084
+ /** Remove a member (owner) or leave (own id); a remaining member seals the next epoch. */
9085
+ removeMember: async (chatExtId, userExtId) => {
9086
+ await removeChatMember(this.requireClient(), chatExtId, userExtId);
9087
+ const crypto2 = await this.requireChatCrypto();
9088
+ if (userExtId !== crypto2.userExtId) await this.readyChat(chatExtId);
9089
+ },
9090
+ markRead: (chatExtId, messageExtId) => markChatRead(this.requireClient(), chatExtId, messageExtId),
9091
+ deleteMessage: (chatExtId, messageExtId) => deleteChatMessage(this.requireClient(), chatExtId, messageExtId)
9092
+ };
9093
+ /** Direct-chat conveniences addressed by peer (email or `usr-`/`agt-` id). */
8806
9094
  dm = {
8807
9095
  /**
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.
9096
+ * Send an E2E-encrypted direct message: resolves the peer, opens (get-or-create) the direct
9097
+ * chat and posts under the pair key. The caller passes plaintext and never handles keys.
8816
9098
  */
8817
9099
  send: async (recipient, text) => {
8818
9100
  const client = this.requireClient();
8819
9101
  const resolved = await resolveRecipient(client, recipient);
8820
9102
  if (!resolved) {
8821
9103
  throw new ArbiError(
8822
- `Could not resolve DM recipient "${recipient}" (not a known contact, agent, or workspace member)`
9104
+ `Could not resolve recipient "${recipient}" (not a known contact, agent, or workspace member)`
8823
9105
  );
8824
9106
  }
8825
- return sendEncryptedDM(
9107
+ return sendDirectMessage(
8826
9108
  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()
9109
+ await this.requireChatCrypto(),
9110
+ resolved.extId,
9111
+ text
8835
9112
  );
8836
9113
  },
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(
9114
+ /** Send to a peer whose external id is already known, skipping directory resolution. */
9115
+ sendTo: async (peerExtId, text) => sendDirectMessage(
8842
9116
  this.requireClient(),
8843
- [
8844
- {
8845
- recipient_ext_id: recipientExtId,
8846
- content: text,
8847
- recipient_encryption_public_key: recipientPublicKey
8848
- }
8849
- ],
8850
- await this.requireDmCrypto()
9117
+ await this.requireChatCrypto(),
9118
+ peerExtId,
9119
+ text
8851
9120
  ),
8852
9121
  /** Resolve a recipient reference to `{ extId, pubKey }` (contacts → agents → workspace). */
8853
9122
  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). */
9123
+ /** List the current user's durable activity feed. */
8857
9124
  listActivity: (options) => listActivity(this.requireClient(), options)
8858
9125
  };
8859
9126
  // ── Settings ──────────────────────────────────────────────────────────
@@ -9946,6 +10213,7 @@ var OpenClawOrchestrator = class {
9946
10213
  };
9947
10214
 
9948
10215
  // src/listen/dm-listener.ts
10216
+ var BACKFILL_LIMIT = 50;
9949
10217
  async function startDmListener(options) {
9950
10218
  const { arbi, baseUrl, crypto: crypto2, orchestrator, parentExtId, onLog, onError } = options;
9951
10219
  const log = onLog ?? (() => {
@@ -9955,72 +10223,87 @@ async function startDmListener(options) {
9955
10223
  if (!initialToken) {
9956
10224
  throw new Error("No access token \u2014 run `arbi login` first.");
9957
10225
  }
9958
- const handleNotification = async (msg) => {
9959
- if (msg.type !== "user_message") return;
9960
- const senderExtId = msg.sender?.external_id;
10226
+ const rings = /* @__PURE__ */ new Map();
10227
+ const ringFor = (chatExtId) => {
10228
+ let ring = rings.get(chatExtId);
10229
+ if (!ring) {
10230
+ ring = getChat(arbi, chatExtId).then(
10231
+ (chat) => chat.kind === "direct" && chat.members.some((m2) => m2.user.external_id === parentExtId) ? openChatKeyRing(chat, crypto2) : null
10232
+ );
10233
+ ring.catch(() => rings.delete(chatExtId));
10234
+ rings.set(chatExtId, ring);
10235
+ }
10236
+ return ring;
10237
+ };
10238
+ const handled = /* @__PURE__ */ new Set();
10239
+ const handleMessage = async (chatExtId, msg) => {
10240
+ if (handled.has(msg.external_id)) return;
10241
+ if (msg.kind !== "text" || msg.context_only) return;
10242
+ const senderExtId = msg.sender_ext_id;
9961
10243
  if (!senderExtId || senderExtId !== parentExtId) {
9962
- log(`Ignoring message from ${senderExtId ?? "unknown"} (not parent)`);
10244
+ if (senderExtId !== crypto2.userExtId) {
10245
+ log(`Ignoring message from ${senderExtId ?? "unknown"} (not parent)`);
10246
+ }
9963
10247
  return;
9964
10248
  }
9965
- let plaintext;
9966
- try {
9967
- plaintext = await decryptDmContent(arbi, msg, crypto2);
9968
- } catch (err) {
9969
- logError("Failed to decrypt incoming DM", err);
10249
+ handled.add(msg.external_id);
10250
+ const ring = await ringFor(chatExtId);
10251
+ if (!ring) {
10252
+ log(`Ignoring message in ${chatExtId} (not the direct chat with the parent)`);
9970
10253
  return;
9971
10254
  }
10255
+ const decrypted = await decryptChatMessage(ring, msg);
10256
+ if (decrypted.decryptFailed) {
10257
+ logError("Failed to decrypt incoming message");
10258
+ return;
10259
+ }
10260
+ const plaintext = decrypted.content;
9972
10261
  if (!plaintext) {
9973
10262
  log("Received empty message, skipping");
9974
10263
  return;
9975
10264
  }
9976
- log(`Received prompt from ${msg.sender?.email ?? senderExtId}: ${plaintext.slice(0, 80)}...`);
10265
+ log(`Received prompt from ${senderExtId}: ${plaintext.slice(0, 80)}...`);
9977
10266
  let response;
9978
10267
  try {
9979
10268
  response = await orchestrator.prompt(plaintext, {
9980
10269
  senderExtId,
9981
- senderEmail: msg.sender?.email ?? void 0
10270
+ ...msg.workspace_ext_id ? { workspaceId: msg.workspace_ext_id } : {}
9982
10271
  });
9983
10272
  } catch (err) {
9984
10273
  logError(`Orchestrator "${orchestrator.name}" failed`, err);
9985
10274
  response = `[Error: orchestrator failed \u2014 ${err instanceof Error ? err.message : String(err)}]`;
9986
10275
  }
9987
10276
  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
10277
  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}`);
10278
+ await sendChatMessage(arbi, ring, response);
10279
+ log(`Reply sent to ${senderExtId}`);
10006
10280
  } catch (err) {
10007
10281
  logError("Failed to send encrypted reply", err);
10008
10282
  }
10283
+ try {
10284
+ await markChatRead(arbi, chatExtId, msg.external_id);
10285
+ } catch {
10286
+ }
10009
10287
  };
10010
10288
  try {
10011
- const unreadFromParent = (await listDMs(arbi)).filter(
10012
- (n2) => n2.type === "user_message" && n2.read === false && n2.sender?.external_id === parentExtId
10289
+ const chats = (await listChats(arbi, "direct")).filter(
10290
+ (c2) => c2.unread_count > 0 && c2.members.some((m2) => m2.user.external_id === parentExtId)
10013
10291
  );
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(
10292
+ for (const chat of chats) {
10293
+ const me2 = chat.members.find((m2) => m2.user.external_id === crypto2.userExtId);
10294
+ const since = me2?.last_read_at ? Date.parse(me2.last_read_at) : 0;
10295
+ const unread = (await listChatMessages(arbi, chat.external_id, {
10296
+ limit: Math.min(chat.unread_count, BACKFILL_LIMIT)
10297
+ })).filter((m2) => m2.sender_ext_id === parentExtId && Date.parse(m2.created_at) > since).reverse();
10298
+ if (unread.length > 0) log(`Backfilling ${unread.length} unread message(s) from parent`);
10299
+ for (const m2 of unread) {
10300
+ await handleMessage(chat.external_id, m2).catch(
10018
10301
  (err) => logError("Backfill handler error", err)
10019
10302
  );
10020
10303
  }
10021
10304
  }
10022
10305
  } catch (err) {
10023
- logError("Failed to backfill unread DMs", err);
10306
+ logError("Failed to backfill unread messages", err);
10024
10307
  }
10025
10308
  const ws = await connectWithReconnect({
10026
10309
  baseUrl,
@@ -10029,14 +10312,9 @@ async function startDmListener(options) {
10029
10312
  refreshAuth: () => arbi.auth.relogin(),
10030
10313
  maxRetries: Infinity,
10031
10314
  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
- }
10315
+ if (msg.type !== "chat.message") return;
10316
+ const { chat_ext_id, message } = msg;
10317
+ handleMessage(chat_ext_id, message).catch((err) => logError("Message handler error", err));
10040
10318
  },
10041
10319
  onReconnecting: (attempt, max) => {
10042
10320
  const limit = Number.isFinite(max) ? `/${max}` : "";
@@ -10049,7 +10327,7 @@ async function startDmListener(options) {
10049
10327
  log(`WebSocket closed: ${reason || "no reason"}`);
10050
10328
  }
10051
10329
  });
10052
- log(`Listening for DMs (orchestrator: ${orchestrator.name}, parent: ${parentExtId})`);
10330
+ log(`Listening for messages (orchestrator: ${orchestrator.name}, parent: ${parentExtId})`);
10053
10331
  return {
10054
10332
  close() {
10055
10333
  ws.close();
@@ -10080,6 +10358,7 @@ exports.buildFactsContextTool = buildFactsContextTool;
10080
10358
  exports.buildRetrievalChunkTool = buildRetrievalChunkTool;
10081
10359
  exports.buildRetrievalFullContextTool = buildRetrievalFullContextTool;
10082
10360
  exports.buildRetrievalTocTool = buildRetrievalTocTool;
10361
+ exports.chats = chats_exports;
10083
10362
  exports.connectWebSocket = connectWebSocket;
10084
10363
  exports.connectWithReconnect = connectWithReconnect;
10085
10364
  exports.consumeSSEStream = consumeSSEStream;
@@ -10089,13 +10368,13 @@ exports.countCitations = countCitations;
10089
10368
  exports.createAuthenticatedClient = createAuthenticatedClient;
10090
10369
  exports.createDocumentWaiter = createDocumentWaiter;
10091
10370
  exports.deviceFlow = device_flow_exports;
10092
- exports.dm = dm_exports;
10093
10371
  exports.doctags = doctags_exports;
10094
10372
  exports.documents = documents_exports;
10095
10373
  exports.documentsNode = documents_node_exports;
10096
10374
  exports.facts = facts_exports;
10097
10375
  exports.files = files_exports;
10098
10376
  exports.filterSkills = filterSkills;
10377
+ exports.firm = firm_exports;
10099
10378
  exports.formatAgentStepLabel = formatAgentStepLabel;
10100
10379
  exports.formatFileSize = formatFileSize;
10101
10380
  exports.formatGbp = formatGbp;
@@ -10116,6 +10395,7 @@ exports.identityVerification = identity_exports;
10116
10395
  exports.listen = listen_exports;
10117
10396
  exports.mail = mail_exports;
10118
10397
  exports.mailNode = mail_node_exports;
10398
+ exports.notifications = notifications_exports;
10119
10399
  exports.parseSSEEvents = parseSSEEvents;
10120
10400
  exports.parseSlashCommand = parseSlashCommand;
10121
10401
  exports.parseSlashTokenInProgress = parseSlashTokenInProgress;