@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.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import fs2, { readFileSync } from 'fs';
2
2
  import path2, { dirname, resolve } from 'path';
3
3
  import os2 from 'os';
4
- import { createArbiClient, base64ToBytes, deriveEncryptionKeypairFromSigning, sealedBoxDecrypt, sealKeyForSession, buildWebSocketUrl, createAuthMessage, parseServerMessage, isMessageType, createContentHash, encryptFile, initSodium, bytesToBase64, decryptFile, changePassword } from '@arbidocs/client';
4
+ import { createArbiClient, base64ToBytes, deriveEncryptionKeypairFromSigning, sealedBoxDecrypt, sealKeyForSession, buildWebSocketUrl, createAuthMessage, parseServerMessage, isMessageType, createContentHash, encryptFile, initSodium, bytesToBase64, encryptWithChatKey, decryptWithChatKey, decryptFile, deriveDirectChatKey, openSealedChatKey, generateChatKey, sealChatKey, encryptMessage, changePassword } from '@arbidocs/client';
5
5
  import { execSync, spawn } from 'child_process';
6
6
  import { createHash } from 'crypto';
7
7
  import { fileURLToPath } from 'url';
@@ -4820,6 +4820,9 @@ function formatWsMessage(msg) {
4820
4820
  level: msg.status === "completed" ? "success" : "error"
4821
4821
  };
4822
4822
  }
4823
+ if (msg.type === "chat.message") {
4824
+ return { text: `New message in ${msg.chat_ext_id}`, level: "info" };
4825
+ }
4823
4826
  if (isNotification(msg)) {
4824
4827
  const sender = msg.sender?.email || "someone";
4825
4828
  const content = msg.content ?? msg.type;
@@ -4903,6 +4906,7 @@ __export(documents_exports, {
4903
4906
  listPaginated: () => listPaginated,
4904
4907
  listVersions: () => listVersions,
4905
4908
  mimeFromName: () => mimeFromName,
4909
+ presignedPut: () => presignedPut,
4906
4910
  sanitizeFolderPath: () => sanitizeFolderPath,
4907
4911
  updateDocuments: () => updateDocuments,
4908
4912
  uploadDocumentsDirect: () => uploadDocumentsDirect,
@@ -5175,12 +5179,15 @@ function mimeFromName(name) {
5175
5179
  return void 0;
5176
5180
  }
5177
5181
  }
5178
- async function presignedPut(url, body, onProgress) {
5182
+ async function presignedPut(url, body, onProgress, headers) {
5179
5183
  const XhrGlobal = globalThis.XMLHttpRequest;
5180
5184
  if (XhrGlobal) {
5181
5185
  await new Promise((resolve2, reject) => {
5182
5186
  const xhr = new XhrGlobal();
5183
5187
  xhr.open("PUT", url);
5188
+ for (const [name, value] of Object.entries(headers ?? {})) {
5189
+ xhr.setRequestHeader(name, value);
5190
+ }
5184
5191
  if (onProgress) {
5185
5192
  xhr.upload.addEventListener("progress", (e) => {
5186
5193
  if (e.lengthComputable) onProgress(e.loaded, e.total);
@@ -5200,7 +5207,7 @@ async function presignedPut(url, body, onProgress) {
5200
5207
  });
5201
5208
  return;
5202
5209
  }
5203
- const putRes = await fetch(url, { method: "PUT", body });
5210
+ const putRes = await fetch(url, { method: "PUT", body, ...headers ? { headers } : {} });
5204
5211
  if (!putRes.ok) {
5205
5212
  const snippet = await putRes.text().catch(() => "");
5206
5213
  throw new Error(`Presigned PUT failed: ${putRes.status} ${snippet.slice(0, 200)}`);
@@ -5972,37 +5979,57 @@ function mergeKindFieldDefinitions(current, wanted, { keepOthers = false } = {})
5972
5979
  // src/operations/contacts.ts
5973
5980
  var contacts_exports = {};
5974
5981
  __export(contacts_exports, {
5975
- addContacts: () => addContacts,
5982
+ createContact: () => createContact,
5983
+ deleteContact: () => deleteContact,
5976
5984
  groupContactsByStatus: () => groupContactsByStatus,
5985
+ inviteContacts: () => inviteContacts,
5977
5986
  listContacts: () => listContacts,
5978
- removeContacts: () => removeContacts
5987
+ searchContacts: () => searchContacts,
5988
+ updateContact: () => updateContact
5979
5989
  });
5980
5990
  async function listContacts(arbi) {
5981
- return requireData(await arbi.fetch.GET("/v1/user/contacts"), "Failed to fetch contacts");
5991
+ return requireData(await arbi.fetch.GET("/v1/contacts/"), "Failed to fetch contacts");
5982
5992
  }
5983
- async function addContacts(arbi, emails) {
5993
+ async function inviteContacts(arbi, emails) {
5984
5994
  return requireData(
5985
- await arbi.fetch.POST("/v1/user/contacts", { body: { emails } }),
5986
- "Failed to add contacts"
5995
+ await arbi.fetch.POST("/v1/contacts/invitations", { body: { emails } }),
5996
+ "Failed to invite contacts"
5997
+ );
5998
+ }
5999
+ async function createContact(arbi, body) {
6000
+ return requireData(await arbi.fetch.POST("/v1/contacts/", { body }), "Failed to create contact");
6001
+ }
6002
+ async function updateContact(arbi, contactId, card) {
6003
+ return requireData(
6004
+ await arbi.fetch.PATCH("/v1/contacts/{cnt_id}", {
6005
+ params: { path: { cnt_id: contactId } },
6006
+ body: { card, invite: false }
6007
+ }),
6008
+ "Failed to update contact"
5987
6009
  );
5988
6010
  }
5989
- async function removeContacts(arbi, contactIds) {
6011
+ async function deleteContact(arbi, contactId) {
5990
6012
  requireOk(
5991
- await arbi.fetch.DELETE("/v1/user/contacts", { body: { contact_ids: contactIds } }),
5992
- "Failed to remove contacts"
6013
+ await arbi.fetch.DELETE("/v1/contacts/{cnt_id}", { params: { path: { cnt_id: contactId } } }),
6014
+ "Failed to delete contact"
6015
+ );
6016
+ }
6017
+ async function searchContacts(arbi, q2) {
6018
+ return requireData(
6019
+ await arbi.fetch.GET("/v1/contacts/search", { params: { query: { q: q2 } } }),
6020
+ "Failed to search contacts"
5993
6021
  );
5994
6022
  }
5995
6023
  function groupContactsByStatus(contactList) {
5996
6024
  const registered = [];
5997
6025
  const pending = [];
6026
+ const cards = [];
5998
6027
  for (const c2 of contactList) {
5999
- if (c2.status === "registered") {
6000
- registered.push(c2);
6001
- } else {
6002
- pending.push(c2);
6003
- }
6028
+ if (c2.status === "registered") registered.push(c2);
6029
+ else if (c2.status === "card") cards.push(c2);
6030
+ else pending.push(c2);
6004
6031
  }
6005
- return { registered, pending };
6032
+ return { registered, pending, cards };
6006
6033
  }
6007
6034
 
6008
6035
  // src/operations/doctags.ts
@@ -6048,32 +6075,44 @@ async function generateDocTags(arbi, tagIds, docIds, options) {
6048
6075
  );
6049
6076
  }
6050
6077
 
6051
- // src/operations/dm.ts
6052
- var dm_exports = {};
6053
- __export(dm_exports, {
6054
- DM_ATTACHMENT_MAX_BYTES: () => DM_ATTACHMENT_MAX_BYTES,
6055
- DM_ATTACHMENT_MAX_FILES: () => DM_ATTACHMENT_MAX_FILES,
6056
- checkDmAttachmentLimits: () => checkDmAttachmentLimits,
6057
- createDmCryptoContext: () => createDmCryptoContext,
6058
- decryptDmAttachments: () => decryptDmAttachments,
6059
- decryptDmBatch: () => decryptDmBatch,
6060
- decryptDmContent: () => decryptDmContent,
6061
- deleteDMs: () => deleteDMs,
6062
- downloadDmAttachment: () => downloadDmAttachment,
6063
- encryptDmAttachmentManifest: () => encryptDmAttachmentManifest,
6064
- encryptDmContent: () => encryptDmContent,
6065
- listActivity: () => listActivity,
6066
- listDMs: () => listDMs,
6067
- listDecryptedDMs: () => listDecryptedDMs,
6068
- markRead: () => markRead,
6069
- parseDmAttachmentManifest: () => parseDmAttachmentManifest,
6070
- requestWorkspaceAccess: () => requestWorkspaceAccess,
6078
+ // src/operations/chats.ts
6079
+ var chats_exports = {};
6080
+ __export(chats_exports, {
6081
+ CHAT_ATTACHMENT_MAX_BYTES: () => CHAT_ATTACHMENT_MAX_BYTES,
6082
+ CHAT_ATTACHMENT_MAX_FILES: () => CHAT_ATTACHMENT_MAX_FILES,
6083
+ DECRYPTION_FAILED: () => DECRYPTION_FAILED,
6084
+ addChatMembers: () => addChatMembers,
6085
+ checkChatAttachmentLimits: () => checkChatAttachmentLimits,
6086
+ createChatCryptoContext: () => createChatCryptoContext,
6087
+ createGroupChat: () => createGroupChat,
6088
+ decryptChatAttachmentManifest: () => decryptChatAttachmentManifest,
6089
+ decryptChatMessage: () => decryptChatMessage,
6090
+ decryptChatMessages: () => decryptChatMessages,
6091
+ decryptChatTitle: () => decryptChatTitle,
6092
+ deleteChatMessage: () => deleteChatMessage,
6093
+ directPeer: () => directPeer,
6094
+ downloadChatAttachment: () => downloadChatAttachment,
6095
+ encryptChatAttachmentManifest: () => encryptChatAttachmentManifest,
6096
+ ensureChatKeyCurrent: () => ensureChatKeyCurrent,
6097
+ getChat: () => getChat,
6098
+ hasRead: () => hasRead,
6099
+ isAgentExtId: () => isAgentExtId,
6100
+ listChatMessages: () => listChatMessages,
6101
+ listChats: () => listChats,
6102
+ loadDecryptedChat: () => loadDecryptedChat,
6103
+ markChatRead: () => markChatRead,
6104
+ openChatKeyRing: () => openChatKeyRing,
6105
+ openDirectChat: () => openDirectChat,
6106
+ parseChatAttachmentManifest: () => parseChatAttachmentManifest,
6107
+ removeChatMember: () => removeChatMember,
6108
+ renameChat: () => renameChat,
6071
6109
  resolveRecipient: () => resolveRecipient,
6072
- sendDM: () => sendDM,
6073
- sendEncryptedDM: () => sendEncryptedDM,
6074
- serializeDmAttachmentManifest: () => serializeDmAttachmentManifest,
6075
- uploadDmAttachment: () => uploadDmAttachment,
6076
- uploadDmAttachments: () => uploadDmAttachments
6110
+ rotateChatKey: () => rotateChatKey,
6111
+ sendChatMessage: () => sendChatMessage,
6112
+ sendDirectMessage: () => sendDirectMessage,
6113
+ serializeChatAttachmentManifest: () => serializeChatAttachmentManifest,
6114
+ uploadChatAttachment: () => uploadChatAttachment,
6115
+ uploadChatAttachments: () => uploadChatAttachments
6077
6116
  });
6078
6117
 
6079
6118
  // src/operations/agents.ts
@@ -6180,27 +6219,27 @@ async function stageAgentFile(auth, agentId, file, name) {
6180
6219
  });
6181
6220
  return response.json();
6182
6221
  }
6183
- var DM_ATTACHMENT_MAX_BYTES = 15 * 1024 * 1024;
6184
- var DM_ATTACHMENT_MAX_FILES = 10;
6222
+ var CHAT_ATTACHMENT_MAX_BYTES = 15 * 1024 * 1024;
6223
+ var CHAT_ATTACHMENT_MAX_FILES = 10;
6185
6224
  var ATTACHMENT_ID = /^att-[a-zA-Z0-9]{8}$/;
6186
6225
  var MANIFEST_VERSION = 1;
6187
6226
  var MB = 1024 * 1024;
6188
- function checkDmAttachmentLimits(files) {
6189
- if (files.length > DM_ATTACHMENT_MAX_FILES) {
6227
+ function checkChatAttachmentLimits(files) {
6228
+ if (files.length > CHAT_ATTACHMENT_MAX_FILES) {
6190
6229
  throw new Error(
6191
- `You can attach at most ${DM_ATTACHMENT_MAX_FILES} files to a message (this one has ${files.length}).`
6230
+ `You can attach at most ${CHAT_ATTACHMENT_MAX_FILES} files to a message (this one has ${files.length}).`
6192
6231
  );
6193
6232
  }
6194
6233
  for (const file of files) {
6195
- if (file.size > DM_ATTACHMENT_MAX_BYTES) {
6234
+ if (file.size > CHAT_ATTACHMENT_MAX_BYTES) {
6196
6235
  throw new Error(
6197
- `${file.name} is too large (${(file.size / MB).toFixed(1)} MB). Files can be at most ${DM_ATTACHMENT_MAX_BYTES / MB} MB.`
6236
+ `${file.name} is too large (${(file.size / MB).toFixed(1)} MB). Files can be at most ${CHAT_ATTACHMENT_MAX_BYTES / MB} MB.`
6198
6237
  );
6199
6238
  }
6200
6239
  }
6201
6240
  }
6202
- async function uploadDmAttachment(arbi, input) {
6203
- checkDmAttachmentLimits([{ name: input.name, size: input.bytes.length }]);
6241
+ async function uploadChatAttachment(arbi, input) {
6242
+ checkChatAttachmentLimits([{ name: input.name, size: input.bytes.length }]);
6204
6243
  await initSodium();
6205
6244
  const key = globalThis.crypto.getRandomValues(new Uint8Array(32));
6206
6245
  try {
@@ -6211,13 +6250,13 @@ async function uploadDmAttachment(arbi, input) {
6211
6250
  new Blob([ciphertext], { type: "application/octet-stream" }),
6212
6251
  "attachment.bin"
6213
6252
  );
6214
- const result = await arbi.fetch.POST("/v1/notifications/attachments", {
6253
+ const result = await arbi.fetch.POST("/v1/chats/attachments", {
6215
6254
  body: { file: "" },
6216
6255
  bodySerializer: () => form
6217
6256
  });
6218
6257
  if (result.response?.status === 413) {
6219
6258
  throw new ArbiApiError(
6220
- `${input.name} is too large. Files can be at most ${DM_ATTACHMENT_MAX_BYTES / MB} MB.`,
6259
+ `${input.name} is too large. Files can be at most ${CHAT_ATTACHMENT_MAX_BYTES / MB} MB.`,
6221
6260
  result.error,
6222
6261
  413
6223
6262
  );
@@ -6234,19 +6273,19 @@ async function uploadDmAttachment(arbi, input) {
6234
6273
  key.fill(0);
6235
6274
  }
6236
6275
  }
6237
- async function uploadDmAttachments(arbi, inputs) {
6238
- checkDmAttachmentLimits(inputs.map((i2) => ({ name: i2.name, size: i2.bytes.length })));
6276
+ async function uploadChatAttachments(arbi, inputs) {
6277
+ checkChatAttachmentLimits(inputs.map((i2) => ({ name: i2.name, size: i2.bytes.length })));
6239
6278
  const files = [];
6240
- for (const input of inputs) files.push(await uploadDmAttachment(arbi, input));
6279
+ for (const input of inputs) files.push(await uploadChatAttachment(arbi, input));
6241
6280
  return files;
6242
6281
  }
6243
- function serializeDmAttachmentManifest(files) {
6282
+ function serializeChatAttachmentManifest(files) {
6244
6283
  return JSON.stringify({
6245
6284
  v: MANIFEST_VERSION,
6246
6285
  files: files.map(({ id, name, type, size, key }) => ({ id, name, type, size, key }))
6247
6286
  });
6248
6287
  }
6249
- function parseDmAttachmentManifest(json2) {
6288
+ function parseChatAttachmentManifest(json2) {
6250
6289
  const manifest = JSON.parse(json2);
6251
6290
  if (manifest?.v !== MANIFEST_VERSION || !Array.isArray(manifest.files)) {
6252
6291
  throw new Error("Unsupported attachment manifest");
@@ -6265,27 +6304,15 @@ function parseDmAttachmentManifest(json2) {
6265
6304
  };
6266
6305
  });
6267
6306
  }
6268
- async function encryptDmAttachmentManifest(arbi, files, recipientEncryptionPubKeyBase64, senderEncryptionSecretKey) {
6269
- return arbi.crypto.encryptMessage(
6270
- serializeDmAttachmentManifest(files),
6271
- recipientEncryptionPubKeyBase64,
6272
- senderEncryptionSecretKey
6273
- );
6307
+ async function encryptChatAttachmentManifest(files, chatKey) {
6308
+ return encryptWithChatKey(serializeChatAttachmentManifest(files), chatKey);
6274
6309
  }
6275
- async function decryptDmAttachments(arbi, notification, crypto2) {
6276
- if (!notification.attachments) return [];
6277
- const isSent = notification.sender.external_id === crypto2.userExtId;
6278
- const otherParty = isSent ? notification.recipient : notification.sender;
6279
- const json2 = await arbi.crypto.decryptMessage(
6280
- notification.attachments,
6281
- otherParty.encryption_public_key,
6282
- crypto2.encryptionKeypair.secretKey
6283
- );
6284
- return parseDmAttachmentManifest(json2);
6310
+ async function decryptChatAttachmentManifest(manifest, chatKey) {
6311
+ return parseChatAttachmentManifest(await decryptWithChatKey(manifest, chatKey));
6285
6312
  }
6286
- async function downloadDmAttachment(arbi, file) {
6313
+ async function downloadChatAttachment(arbi, file) {
6287
6314
  if (!ATTACHMENT_ID.test(file.id)) throw new Error(`Invalid attachment id: ${file.id}`);
6288
- const result = await arbi.fetch.GET("/v1/notifications/attachments/{external_id}", {
6315
+ const result = await arbi.fetch.GET("/v1/chats/attachments/{external_id}", {
6289
6316
  params: { path: { external_id: file.id } },
6290
6317
  parseAs: "arrayBuffer"
6291
6318
  });
@@ -6313,78 +6340,275 @@ async function downloadDmAttachment(arbi, file) {
6313
6340
  return plain;
6314
6341
  }
6315
6342
 
6316
- // src/operations/dm.ts
6317
- function createDmCryptoContext(arbi, signingPrivateKeyBytes, userExtId) {
6318
- const ed25519PublicKey = signingPrivateKeyBytes.slice(32, 64);
6319
- const encryptionKeypair = arbi.crypto.deriveEncryptionKeypairFromSigning({
6320
- publicKey: ed25519PublicKey,
6343
+ // src/operations/chats.ts
6344
+ function createChatCryptoContext(signingPrivateKeyBytes, userExtId) {
6345
+ const encryptionKeypair = deriveEncryptionKeypairFromSigning({
6346
+ publicKey: signingPrivateKeyBytes.slice(32, 64),
6321
6347
  secretKey: signingPrivateKeyBytes
6322
6348
  });
6323
6349
  return { encryptionKeypair, userExtId };
6324
6350
  }
6325
- async function encryptDmContent(arbi, plaintext, recipientEncryptionPubKeyBase64, senderEncryptionSecretKey) {
6326
- return arbi.crypto.encryptMessage(
6327
- plaintext,
6328
- recipientEncryptionPubKeyBase64,
6329
- senderEncryptionSecretKey
6330
- );
6351
+ function isAgentExtId(extId) {
6352
+ return !!extId && extId.startsWith("agt-");
6331
6353
  }
6332
- async function decryptDmContent(arbi, notification, crypto2) {
6333
- if (!notification.content) return null;
6334
- const isSent = notification.sender.external_id === crypto2.userExtId;
6335
- const otherParty = isSent ? notification.recipient : notification.sender;
6336
- return arbi.crypto.decryptMessage(
6337
- notification.content,
6338
- otherParty.encryption_public_key,
6339
- crypto2.encryptionKeypair.secretKey
6340
- );
6354
+ function directPeer(chat, myExtId) {
6355
+ if (chat.kind !== "direct") return void 0;
6356
+ return chat.members.find((m2) => m2.user.external_id !== myExtId)?.user;
6341
6357
  }
6342
- async function decryptDmBatch(arbi, notifications, crypto2) {
6343
- const results = [];
6344
- for (const n2 of notifications) {
6345
- if (n2.type !== "user_message" || !n2.content && !n2.attachments) {
6346
- results.push(n2);
6347
- continue;
6358
+ async function openChatKeyRing(chat, crypto2) {
6359
+ const keys = /* @__PURE__ */ new Map();
6360
+ if (chat.kind === "direct") {
6361
+ const peer = directPeer(chat, crypto2.userExtId);
6362
+ const peerPub = peer?.encryption_public_key ?? bytesToBase64(crypto2.encryptionKeypair.publicKey);
6363
+ keys.set(0, await deriveDirectChatKey(peerPub, crypto2.encryptionKeypair.secretKey));
6364
+ } else {
6365
+ for (const k2 of chat.my_keys ?? []) {
6366
+ try {
6367
+ keys.set(
6368
+ k2.version,
6369
+ await openSealedChatKey(k2.sealed_key, crypto2.encryptionKeypair.secretKey)
6370
+ );
6371
+ } catch {
6372
+ }
6348
6373
  }
6349
- let row;
6374
+ }
6375
+ return { chatExtId: chat.external_id, kind: chat.kind, currentVersion: chat.key_version, keys };
6376
+ }
6377
+ function keyFor(ring, version) {
6378
+ const key = ring.keys.get(version);
6379
+ if (!key) throw new Error(`No key for epoch ${version} of ${ring.chatExtId}`);
6380
+ return key;
6381
+ }
6382
+ var DECRYPTION_FAILED = "[Decryption failed]";
6383
+ async function decryptChatMessage(ring, message) {
6384
+ const key = ring.keys.get(message.key_version);
6385
+ const row = { ...message };
6386
+ if (message.content) {
6350
6387
  try {
6351
- row = { ...n2, content: await decryptDmContent(arbi, n2, crypto2) };
6388
+ if (!key) throw new Error("no key");
6389
+ row.content = await decryptWithChatKey(message.content, key);
6352
6390
  } catch {
6353
- row = { ...n2, content: "[Decryption failed]" };
6391
+ row.content = DECRYPTION_FAILED;
6392
+ row.decryptFailed = true;
6354
6393
  }
6355
- if (n2.attachments) {
6356
- try {
6357
- row.attachmentFiles = await decryptDmAttachments(arbi, n2, crypto2);
6358
- } catch {
6359
- row.attachmentFiles = [];
6360
- row.attachmentsError = "The attachments could not be decrypted";
6361
- }
6394
+ }
6395
+ if (message.attachments) {
6396
+ try {
6397
+ if (!key) throw new Error("no key");
6398
+ row.attachmentFiles = await decryptChatAttachmentManifest(message.attachments, key);
6399
+ } catch {
6400
+ row.attachmentFiles = [];
6401
+ row.attachmentsError = "The attachments could not be decrypted";
6362
6402
  }
6363
- results.push(row);
6364
6403
  }
6365
- return results;
6404
+ return row;
6405
+ }
6406
+ async function decryptChatMessages(ring, messages) {
6407
+ return Promise.all(messages.map((m2) => decryptChatMessage(ring, m2)));
6408
+ }
6409
+ async function decryptChatTitle(ring, chat) {
6410
+ if (!chat.title) return null;
6411
+ const key = ring.keys.get(chat.key_version);
6412
+ if (!key) return null;
6413
+ try {
6414
+ return await decryptWithChatKey(chat.title, key);
6415
+ } catch {
6416
+ return null;
6417
+ }
6366
6418
  }
6367
- async function listDMs(arbi) {
6368
- return requireData(await arbi.fetch.GET("/v1/notifications/"), "Failed to fetch messages");
6419
+ async function listChats(arbi, kind) {
6420
+ return requireData(
6421
+ await arbi.fetch.GET("/v1/chats/", { params: { query: kind ? { kind } : {} } }),
6422
+ "Failed to list chats"
6423
+ );
6369
6424
  }
6370
- async function listDecryptedDMs(arbi, crypto2) {
6371
- const raw = await listDMs(arbi);
6372
- return decryptDmBatch(arbi, raw, crypto2);
6425
+ async function getChat(arbi, chatExtId) {
6426
+ return requireData(
6427
+ await arbi.fetch.GET("/v1/chats/{chat_ext_id}", {
6428
+ params: { path: { chat_ext_id: chatExtId } }
6429
+ }),
6430
+ "Failed to load chat"
6431
+ );
6373
6432
  }
6374
- async function listActivity(arbi, options) {
6433
+ async function openDirectChat(arbi, peerExtId) {
6375
6434
  return requireData(
6376
- await arbi.fetch.GET("/v1/notifications/", {
6435
+ await arbi.fetch.POST("/v1/chats/", { body: { kind: "direct", peer_ext_id: peerExtId } }),
6436
+ "Failed to open chat"
6437
+ );
6438
+ }
6439
+ async function createGroupChat(arbi, crypto2, params) {
6440
+ const members = params.members.filter((m2) => m2.external_id !== crypto2.userExtId);
6441
+ if (members.length === 0) throw new Error("A group needs at least one other member");
6442
+ const agent = members.find((m2) => isAgentExtId(m2.external_id));
6443
+ if (agent) throw new Error("Personal agents cannot join a group chat");
6444
+ const key = await generateChatKey();
6445
+ try {
6446
+ const title = params.title?.trim();
6447
+ return requireData(
6448
+ await arbi.fetch.POST("/v1/chats/", {
6449
+ body: {
6450
+ kind: "group",
6451
+ title: title ? await encryptWithChatKey(title, key) : null,
6452
+ members: await Promise.all(
6453
+ members.map(async (m2) => ({
6454
+ user_ext_id: m2.external_id,
6455
+ sealed_key: await sealChatKey(key, m2.encryption_public_key)
6456
+ }))
6457
+ ),
6458
+ creator_sealed_key: await sealChatKey(
6459
+ key,
6460
+ bytesToBase64(crypto2.encryptionKeypair.publicKey)
6461
+ )
6462
+ }
6463
+ }),
6464
+ "Failed to create group"
6465
+ );
6466
+ } finally {
6467
+ key.fill(0);
6468
+ }
6469
+ }
6470
+ async function renameChat(arbi, ring, title) {
6471
+ const trimmed = title?.trim();
6472
+ return requireData(
6473
+ await arbi.fetch.PATCH("/v1/chats/{chat_ext_id}", {
6474
+ params: { path: { chat_ext_id: ring.chatExtId } },
6475
+ body: {
6476
+ title: trimmed ? await encryptWithChatKey(trimmed, keyFor(ring, ring.currentVersion)) : null
6477
+ }
6478
+ }),
6479
+ "Failed to rename chat"
6480
+ );
6481
+ }
6482
+ async function addChatMembers(arbi, ring, members) {
6483
+ if (ring.kind === "direct") {
6484
+ throw new Error("A direct chat cannot gain members: create a group instead");
6485
+ }
6486
+ if (members.some((m2) => isAgentExtId(m2.external_id))) {
6487
+ throw new Error("Personal agents cannot join a group chat");
6488
+ }
6489
+ const key = keyFor(ring, ring.currentVersion);
6490
+ return requireData(
6491
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/members", {
6492
+ params: { path: { chat_ext_id: ring.chatExtId } },
6493
+ body: {
6494
+ members: await Promise.all(
6495
+ members.map(async (m2) => ({
6496
+ user_ext_id: m2.external_id,
6497
+ sealed_key: await sealChatKey(key, m2.encryption_public_key)
6498
+ }))
6499
+ )
6500
+ }
6501
+ }),
6502
+ "Failed to add members"
6503
+ );
6504
+ }
6505
+ async function removeChatMember(arbi, chatExtId, userExtId) {
6506
+ requireOk(
6507
+ await arbi.fetch.DELETE("/v1/chats/{chat_ext_id}/members/{user_ext_id}", {
6508
+ params: { path: { chat_ext_id: chatExtId, user_ext_id: userExtId } }
6509
+ }),
6510
+ "Failed to remove member"
6511
+ );
6512
+ }
6513
+ async function rotateChatKey(arbi, chat, ring) {
6514
+ if (chat.kind === "direct") throw new Error("Direct chats have no epochs");
6515
+ const oldTitle = await decryptChatTitle(ring, chat);
6516
+ if (chat.title && oldTitle === null) {
6517
+ throw new Error("Cannot re-encrypt the chat title: its key is not available");
6518
+ }
6519
+ const key = await generateChatKey();
6520
+ try {
6521
+ const sealed = {};
6522
+ for (const m2 of chat.members) {
6523
+ sealed[m2.user.external_id] = await sealChatKey(key, m2.user.encryption_public_key);
6524
+ }
6525
+ return requireData(
6526
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/keys", {
6527
+ params: { path: { chat_ext_id: chat.external_id } },
6528
+ body: {
6529
+ version: chat.key_version + 1,
6530
+ sealed_keys: sealed,
6531
+ ...oldTitle !== null ? { title: await encryptWithChatKey(oldTitle, key) } : {}
6532
+ }
6533
+ }),
6534
+ "Failed to rotate chat key"
6535
+ );
6536
+ } finally {
6537
+ key.fill(0);
6538
+ }
6539
+ }
6540
+ async function ensureChatKeyCurrent(arbi, chat, crypto2) {
6541
+ if (!chat.rotation_required || chat.kind === "direct") return chat;
6542
+ if (!chat.members.some((m2) => m2.user.external_id === crypto2.userExtId)) return chat;
6543
+ try {
6544
+ return await rotateChatKey(arbi, chat, await openChatKeyRing(chat, crypto2));
6545
+ } catch (err) {
6546
+ if (err instanceof ArbiApiError && err.status === 409) return getChat(arbi, chat.external_id);
6547
+ throw err;
6548
+ }
6549
+ }
6550
+ async function listChatMessages(arbi, chatExtId, options) {
6551
+ return requireData(
6552
+ await arbi.fetch.GET("/v1/chats/{chat_ext_id}/messages", {
6377
6553
  params: {
6554
+ path: { chat_ext_id: chatExtId },
6378
6555
  query: {
6379
- type: "activity",
6380
- ...options?.limit != null ? { limit: options.limit } : {},
6381
- ...options?.offset != null ? { offset: options.offset } : {}
6556
+ ...options?.before ? { before: options.before } : {},
6557
+ ...options?.limit ? { limit: options.limit } : {}
6382
6558
  }
6383
6559
  }
6384
6560
  }),
6385
- "Failed to fetch activity"
6561
+ "Failed to load messages"
6562
+ );
6563
+ }
6564
+ async function sendChatMessage(arbi, ring, text, options = {}) {
6565
+ const attachments = options.attachments ?? [];
6566
+ checkChatAttachmentLimits(attachments);
6567
+ const key = keyFor(ring, ring.currentVersion);
6568
+ const created = requireData(
6569
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/messages", {
6570
+ params: { path: { chat_ext_id: ring.chatExtId } },
6571
+ body: {
6572
+ content: await encryptWithChatKey(text, key),
6573
+ key_version: ring.currentVersion,
6574
+ kind: "text",
6575
+ ...attachments.length ? {
6576
+ attachments: await encryptChatAttachmentManifest(attachments, key),
6577
+ attachment_ext_ids: attachments.map((f2) => f2.id)
6578
+ } : {},
6579
+ ...options.workspaceExtId ? { workspace_ext_id: options.workspaceExtId } : {},
6580
+ context_only: !!options.contextOnly
6581
+ }
6582
+ }),
6583
+ "Failed to send message"
6584
+ );
6585
+ return {
6586
+ ...created,
6587
+ content: text,
6588
+ ...attachments.length ? { attachmentFiles: attachments } : {}
6589
+ };
6590
+ }
6591
+ async function deleteChatMessage(arbi, chatExtId, messageExtId) {
6592
+ requireOk(
6593
+ await arbi.fetch.DELETE("/v1/chats/{chat_ext_id}/messages/{message_ext_id}", {
6594
+ params: { path: { chat_ext_id: chatExtId, message_ext_id: messageExtId } }
6595
+ }),
6596
+ "Failed to delete message"
6386
6597
  );
6387
6598
  }
6599
+ async function markChatRead(arbi, chatExtId, messageExtId) {
6600
+ return requireData(
6601
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/read", {
6602
+ params: { path: { chat_ext_id: chatExtId } },
6603
+ body: messageExtId ? { message_ext_id: messageExtId } : {}
6604
+ }),
6605
+ "Failed to mark chat read"
6606
+ );
6607
+ }
6608
+ function hasRead(member, message) {
6609
+ if (!member?.last_read_at) return false;
6610
+ return Date.parse(member.last_read_at) >= Date.parse(message.created_at);
6611
+ }
6388
6612
  async function resolveRecipient(arbi, ref) {
6389
6613
  const isEmail = ref.includes("@");
6390
6614
  const matchKey = isEmail ? "email" : "external_id";
@@ -6416,52 +6640,63 @@ async function resolveRecipient(arbi, ref) {
6416
6640
  }
6417
6641
  return null;
6418
6642
  }
6419
- async function sendEncryptedDM(arbi, messages, crypto2, options) {
6420
- const attachments = options?.attachments ?? [];
6421
- checkDmAttachmentLimits(attachments);
6422
- const plaintextFor = new Map(messages.map((m2) => [m2.recipient_ext_id, m2.content]));
6423
- const encrypted = await Promise.all(
6424
- messages.map(async (msg) => ({
6425
- recipient_ext_id: msg.recipient_ext_id,
6426
- content: await encryptDmContent(
6427
- arbi,
6428
- msg.content,
6429
- msg.recipient_encryption_public_key,
6430
- crypto2.encryptionKeypair.secretKey
6431
- ),
6432
- ...attachments.length ? {
6433
- attachments: await encryptDmAttachmentManifest(
6434
- arbi,
6435
- attachments,
6436
- msg.recipient_encryption_public_key,
6437
- crypto2.encryptionKeypair.secretKey
6438
- )
6439
- } : {}
6440
- }))
6441
- );
6442
- const created = requireData(
6443
- await arbi.fetch.POST("/v1/notifications/", {
6444
- body: {
6445
- messages: encrypted,
6446
- context_only: false,
6447
- ...attachments.length ? { attachment_ext_ids: attachments.map((f2) => f2.id) } : {}
6643
+ async function sendDirectMessage(arbi, crypto2, peerExtId, text, options) {
6644
+ const chat = await openDirectChat(arbi, peerExtId);
6645
+ return sendChatMessage(arbi, await openChatKeyRing(chat, crypto2), text, options);
6646
+ }
6647
+ async function loadDecryptedChat(arbi, crypto2, chat, options) {
6648
+ const ring = await openChatKeyRing(chat, crypto2);
6649
+ const raw = await listChatMessages(arbi, chat.external_id, { limit: options?.limit });
6650
+ const messages = (await decryptChatMessages(ring, raw)).reverse();
6651
+ return { chat, ring, title: await decryptChatTitle(ring, chat), messages };
6652
+ }
6653
+
6654
+ // src/operations/notifications.ts
6655
+ var notifications_exports = {};
6656
+ __export(notifications_exports, {
6657
+ deleteNotifications: () => deleteNotifications,
6658
+ listActivity: () => listActivity,
6659
+ listNotifications: () => listNotifications,
6660
+ markNotificationsRead: () => markNotificationsRead,
6661
+ requestWorkspaceAccess: () => requestWorkspaceAccess
6662
+ });
6663
+ async function listNotifications(arbi) {
6664
+ return requireData(await arbi.fetch.GET("/v1/notifications/"), "Failed to fetch notifications");
6665
+ }
6666
+ async function listActivity(arbi, options) {
6667
+ return requireData(
6668
+ await arbi.fetch.GET("/v1/notifications/", {
6669
+ params: {
6670
+ query: {
6671
+ type: "activity",
6672
+ ...options?.limit != null ? { limit: options.limit } : {},
6673
+ ...options?.offset != null ? { offset: options.offset } : {}
6674
+ }
6448
6675
  }
6449
6676
  }),
6450
- "Failed to send message"
6677
+ "Failed to fetch activity"
6678
+ );
6679
+ }
6680
+ async function markNotificationsRead(arbi, ids) {
6681
+ return requireData(
6682
+ await arbi.fetch.PATCH("/v1/notifications/", {
6683
+ body: { updates: ids.map((id) => ({ external_id: id, read: true })) }
6684
+ }),
6685
+ "Failed to update notifications"
6686
+ );
6687
+ }
6688
+ async function deleteNotifications(arbi, ids) {
6689
+ requireOk(
6690
+ await arbi.fetch.DELETE("/v1/notifications/", { body: { external_ids: ids } }),
6691
+ "Failed to delete notifications"
6451
6692
  );
6452
- return created.map((n2) => ({
6453
- ...n2,
6454
- content: plaintextFor.get(n2.recipient.external_id) ?? n2.content,
6455
- ...attachments.length ? { attachmentFiles: attachments } : {}
6456
- }));
6457
6693
  }
6458
6694
  async function requestWorkspaceAccess(arbi, params, crypto2) {
6459
6695
  const payload = JSON.stringify({
6460
6696
  session_pubkey_b64: params.sessionPubkeyB64,
6461
6697
  note: params.note?.trim() || void 0
6462
6698
  });
6463
- const content = await encryptDmContent(
6464
- arbi,
6699
+ const content = await encryptMessage(
6465
6700
  payload,
6466
6701
  params.recipientEncryptionPublicKey,
6467
6702
  crypto2.encryptionKeypair.secretKey
@@ -6477,28 +6712,6 @@ async function requestWorkspaceAccess(arbi, params, crypto2) {
6477
6712
  "Failed to request workspace access"
6478
6713
  );
6479
6714
  }
6480
- async function sendDM(arbi, messages) {
6481
- return requireData(
6482
- await arbi.fetch.POST("/v1/notifications/", {
6483
- body: { messages, context_only: false }
6484
- }),
6485
- "Failed to send message"
6486
- );
6487
- }
6488
- async function markRead(arbi, messageIds) {
6489
- return requireData(
6490
- await arbi.fetch.PATCH("/v1/notifications/", {
6491
- body: { updates: messageIds.map((id) => ({ external_id: id, read: true })) }
6492
- }),
6493
- "Failed to update messages"
6494
- );
6495
- }
6496
- async function deleteDMs(arbi, messageIds) {
6497
- requireOk(
6498
- await arbi.fetch.DELETE("/v1/notifications/", { body: { external_ids: messageIds } }),
6499
- "Failed to delete messages"
6500
- );
6501
- }
6502
6715
 
6503
6716
  // src/operations/settings.ts
6504
6717
  var settings_exports = {};
@@ -6722,6 +6935,22 @@ async function updateProfile(arbi, body) {
6722
6935
  );
6723
6936
  }
6724
6937
 
6938
+ // src/operations/firm.ts
6939
+ var firm_exports = {};
6940
+ __export(firm_exports, {
6941
+ getFirmPool: () => getFirmPool,
6942
+ topUpFirmPool: () => topUpFirmPool
6943
+ });
6944
+ async function getFirmPool(arbi) {
6945
+ return requireData(await arbi.fetch.GET("/v1/firm/pool"), "Failed to fetch the firm AI usage");
6946
+ }
6947
+ async function topUpFirmPool(arbi, aiAddons) {
6948
+ return requireData(
6949
+ await arbi.fetch.POST("/v1/firm/pool/topup", { body: { ai_addons: aiAddons } }),
6950
+ "Failed to add firm AI usage"
6951
+ );
6952
+ }
6953
+
6725
6954
  // src/operations/account.ts
6726
6955
  var account_exports = {};
6727
6956
  __export(account_exports, {
@@ -7954,10 +8183,10 @@ function attachmentFromBytes(name, contentType, bytes) {
7954
8183
  name,
7955
8184
  content_type: contentType,
7956
8185
  size: bytes.length,
7957
- content_base64: bytesToBase642(bytes)
8186
+ content_base64: bytesToBase643(bytes)
7958
8187
  };
7959
8188
  }
7960
- function bytesToBase642(bytes) {
8189
+ function bytesToBase643(bytes) {
7961
8190
  let binary = "";
7962
8191
  for (let i2 = 0; i2 < bytes.length; i2 += 32768) {
7963
8192
  binary += String.fromCharCode(...bytes.subarray(i2, i2 + 32768));
@@ -7985,7 +8214,7 @@ var Arbi = class {
7985
8214
  currentWorkspaceId = null;
7986
8215
  /** Wrapped workspace keys seen in the last list/create, so selecting needs no re-fetch. */
7987
8216
  wrappedKeys = /* @__PURE__ */ new Map();
7988
- dmCryptoContext = null;
8217
+ chatCryptoContext = null;
7989
8218
  sessionExpiredListeners = /* @__PURE__ */ new Set();
7990
8219
  options;
7991
8220
  constructor(options) {
@@ -8157,7 +8386,7 @@ var Arbi = class {
8157
8386
  this.userProfile = null;
8158
8387
  this.currentWorkspaceId = null;
8159
8388
  this.wrappedKeys.clear();
8160
- this.dmCryptoContext = null;
8389
+ this.chatCryptoContext = null;
8161
8390
  this.client?.session.clear();
8162
8391
  for (const listener of [...this.sessionExpiredListeners]) listener();
8163
8392
  }
@@ -8203,7 +8432,7 @@ var Arbi = class {
8203
8432
  this.userProfile = null;
8204
8433
  this.currentWorkspaceId = null;
8205
8434
  this.wrappedKeys.clear();
8206
- this.dmCryptoContext = null;
8435
+ this.chatCryptoContext = null;
8207
8436
  }
8208
8437
  // ── Accessors ─────────────────────────────────────────────────────────
8209
8438
  /** Get the underlying ArbiClient (throws if not initialized). */
@@ -8302,6 +8531,13 @@ var Arbi = class {
8302
8531
  */
8303
8532
  me: () => getCurrentUser(this.requireClient())
8304
8533
  };
8534
+ // ── Firm ──────────────────────────────────────────────────────────────
8535
+ firm = {
8536
+ /** The firm's pooled monthly £ of AI usage (`has_pool` false where there is none). */
8537
+ pool: () => getFirmPool(this.requireClient()),
8538
+ /** Buy `aiAddons` renewing add-ons (+£10 of AI usage a month each) for the firm. Box admins only. */
8539
+ topUp: (aiAddons) => topUpFirmPool(this.requireClient(), aiAddons)
8540
+ };
8305
8541
  // ── Profile ───────────────────────────────────────────────────────────
8306
8542
  profile = {
8307
8543
  /** Update the display profile; pass only what changes (`''` clears family name or picture). */
@@ -8467,9 +8703,13 @@ var Arbi = class {
8467
8703
  const lr2 = this.requireLogin();
8468
8704
  const userExtId = lr2.userExtId ?? client.session.getState().userExtId;
8469
8705
  if (!userExtId) throw new ArbiError("No user id in session \u2014 cannot request access");
8470
- const crypto2 = createDmCryptoContext(client, lr2.signingPrivateKey, userExtId);
8706
+ const crypto2 = createChatCryptoContext(lr2.signingPrivateKey, userExtId);
8471
8707
  const sessionPubkeyB64 = client.crypto.bytesToBase64(lr2.serverSessionKey);
8472
- return requestWorkspaceAccess(client, { ...params, sessionPubkeyB64 }, crypto2);
8708
+ return requestWorkspaceAccess(
8709
+ client,
8710
+ { ...params, sessionPubkeyB64 },
8711
+ crypto2
8712
+ );
8473
8713
  },
8474
8714
  copyDocuments: (targetWorkspaceId, docIds, targetWorkspaceKey) => copyDocuments(
8475
8715
  this.requireClient(),
@@ -8759,92 +8999,119 @@ var Arbi = class {
8759
8999
  // ── Contacts ──────────────────────────────────────────────────────────
8760
9000
  contacts = {
8761
9001
  list: () => listContacts(this.requireClient()),
8762
- add: (emails) => addContacts(this.requireClient(), emails),
8763
- remove: (contactIds) => removeContacts(this.requireClient(), contactIds),
9002
+ invite: (emails) => inviteContacts(this.requireClient(), emails),
9003
+ create: (body) => createContact(this.requireClient(), body),
9004
+ update: (contactId, card) => updateContact(this.requireClient(), contactId, card),
9005
+ delete: (contactId) => deleteContact(this.requireClient(), contactId),
9006
+ search: (q2) => searchContacts(this.requireClient(), q2),
8764
9007
  groupByStatus: groupContactsByStatus
8765
9008
  };
8766
- // ── Direct Messages ───────────────────────────────────────────────────
9009
+ // ── Chats (direct + group) ────────────────────────────────────────────
8767
9010
  /**
8768
- * Build (and cache) the DM crypto context for the current session.
8769
- *
8770
- * Derives the user's curve25519 keypair from their signing key and pairs it
8771
- * with their external_id — everything `list()`/`send()` need to encrypt and
8772
- * decrypt. Cached for the session and cleared on logout. Consumers never touch
8773
- * this: it's an internal of the `dm` surface.
9011
+ * Build (and cache) the chat crypto context for the current session: my X25519 keypair
9012
+ * (derived from the signing key) and external id. Cleared on logout.
8774
9013
  *
8775
- * The key comes from the live login result first, exactly as `selectWorkspace`
8776
- * sources it, and only then from persisted storage (which is what restores a
8777
- * session on reload). Reading storage first would make DMs the one feature that
8778
- * breaks whenever persistence is unavailable — `saveSession` deliberately
8779
- * no-ops without Web Crypto (a non-secure origin, tracking prevention, an
8780
- * embedded widget), so a perfectly authenticated user with a working workspace
8781
- * would be told they are "not authenticated" the moment they opened Messages.
9014
+ * The key comes from the live login result first, exactly as `selectWorkspace` sources it, and
9015
+ * only then from persisted storage (which is what restores a session on reload) — persistence
9016
+ * deliberately no-ops without Web Crypto, and chats must not be the one feature that breaks then.
8782
9017
  */
8783
- async requireDmCrypto() {
8784
- if (this.dmCryptoContext) return this.dmCryptoContext;
9018
+ async requireChatCrypto() {
9019
+ if (this.chatCryptoContext) return this.chatCryptoContext;
8785
9020
  const client = this.requireClient();
8786
9021
  const signingPrivateKey = this.loginResult?.signingPrivateKey ?? (await client.storage.getSession())?.signingPrivateKey;
8787
9022
  if (!signingPrivateKey) {
8788
- throw new ArbiError("Not authenticated \u2014 no session available for DM encryption");
9023
+ throw new ArbiError("Not authenticated \u2014 no session available for chat encryption");
8789
9024
  }
8790
9025
  const userExtId = client.session.getState().userExtId;
8791
9026
  if (!userExtId) {
8792
- throw new ArbiError("No user identity in session \u2014 cannot set up DM encryption");
9027
+ throw new ArbiError("No user identity in session \u2014 cannot set up chat encryption");
8793
9028
  }
8794
- this.dmCryptoContext = createDmCryptoContext(client, signingPrivateKey, userExtId);
8795
- return this.dmCryptoContext;
9029
+ this.chatCryptoContext = createChatCryptoContext(signingPrivateKey, userExtId);
9030
+ return this.chatCryptoContext;
8796
9031
  }
9032
+ /** Fetch a chat, sealing a new epoch first when it is `rotation_required`. */
9033
+ async readyChat(chatExtId) {
9034
+ const client = this.requireClient();
9035
+ return ensureChatKeyCurrent(
9036
+ client,
9037
+ await getChat(client, chatExtId),
9038
+ await this.requireChatCrypto()
9039
+ );
9040
+ }
9041
+ chats = {
9042
+ /** My chats, most recently active first (raw: titles/last messages are ciphertext). */
9043
+ list: (kind) => listChats(this.requireClient(), kind),
9044
+ get: (chatExtId) => getChat(this.requireClient(), chatExtId),
9045
+ /** Get-or-create the direct chat with a peer. */
9046
+ openDirect: (peerExtId) => openDirectChat(this.requireClient(), peerExtId),
9047
+ /** Create a group (epoch 1 sealed to every member). Agents are refused. */
9048
+ createGroup: async (params) => createGroupChat(this.requireClient(), await this.requireChatCrypto(), params),
9049
+ /** A chat with its keys opened, title and newest messages decrypted (oldest first). */
9050
+ load: async (chatExtId, options) => {
9051
+ const chat = await this.readyChat(chatExtId);
9052
+ return loadDecryptedChat(
9053
+ this.requireClient(),
9054
+ await this.requireChatCrypto(),
9055
+ chat,
9056
+ options
9057
+ );
9058
+ },
9059
+ /** Post plaintext to a chat (encrypted under its current epoch). */
9060
+ send: async (chatExtId, text, options) => {
9061
+ const chat = await this.readyChat(chatExtId);
9062
+ const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
9063
+ return sendChatMessage(this.requireClient(), ring, text, options);
9064
+ },
9065
+ rename: async (chatExtId, title) => {
9066
+ const chat = await this.readyChat(chatExtId);
9067
+ const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
9068
+ return renameChat(this.requireClient(), ring, title);
9069
+ },
9070
+ addMembers: async (chatExtId, members) => {
9071
+ const chat = await this.readyChat(chatExtId);
9072
+ const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
9073
+ return addChatMembers(this.requireClient(), ring, members);
9074
+ },
9075
+ /** Remove a member (owner) or leave (own id); a remaining member seals the next epoch. */
9076
+ removeMember: async (chatExtId, userExtId) => {
9077
+ await removeChatMember(this.requireClient(), chatExtId, userExtId);
9078
+ const crypto2 = await this.requireChatCrypto();
9079
+ if (userExtId !== crypto2.userExtId) await this.readyChat(chatExtId);
9080
+ },
9081
+ markRead: (chatExtId, messageExtId) => markChatRead(this.requireClient(), chatExtId, messageExtId),
9082
+ deleteMessage: (chatExtId, messageExtId) => deleteChatMessage(this.requireClient(), chatExtId, messageExtId)
9083
+ };
9084
+ /** Direct-chat conveniences addressed by peer (email or `usr-`/`agt-` id). */
8797
9085
  dm = {
8798
9086
  /**
8799
- * List direct messages, newest first, with content already **decrypted**.
8800
- * (A message that can't be decrypted comes back as `[Decryption failed]`.)
8801
- */
8802
- list: async () => listDecryptedDMs(this.requireClient(), await this.requireDmCrypto()),
8803
- /**
8804
- * Send an E2E-encrypted DM to a recipient (email or `usr-`/`agt-` id).
8805
- * Resolves the recipient's public key and encrypts internally — the caller
8806
- * passes plaintext and never handles keys or ciphertext.
9087
+ * Send an E2E-encrypted direct message: resolves the peer, opens (get-or-create) the direct
9088
+ * chat and posts under the pair key. The caller passes plaintext and never handles keys.
8807
9089
  */
8808
9090
  send: async (recipient, text) => {
8809
9091
  const client = this.requireClient();
8810
9092
  const resolved = await resolveRecipient(client, recipient);
8811
9093
  if (!resolved) {
8812
9094
  throw new ArbiError(
8813
- `Could not resolve DM recipient "${recipient}" (not a known contact, agent, or workspace member)`
9095
+ `Could not resolve recipient "${recipient}" (not a known contact, agent, or workspace member)`
8814
9096
  );
8815
9097
  }
8816
- return sendEncryptedDM(
9098
+ return sendDirectMessage(
8817
9099
  client,
8818
- [
8819
- {
8820
- recipient_ext_id: resolved.extId,
8821
- content: text,
8822
- recipient_encryption_public_key: resolved.pubKey
8823
- }
8824
- ],
8825
- await this.requireDmCrypto()
9100
+ await this.requireChatCrypto(),
9101
+ resolved.extId,
9102
+ text
8826
9103
  );
8827
9104
  },
8828
- /**
8829
- * Send to a recipient whose external_id + public key are already known
8830
- * (e.g. from a message's `sender`), skipping directory resolution.
8831
- */
8832
- sendTo: async (recipientExtId, recipientPublicKey, text) => sendEncryptedDM(
9105
+ /** Send to a peer whose external id is already known, skipping directory resolution. */
9106
+ sendTo: async (peerExtId, text) => sendDirectMessage(
8833
9107
  this.requireClient(),
8834
- [
8835
- {
8836
- recipient_ext_id: recipientExtId,
8837
- content: text,
8838
- recipient_encryption_public_key: recipientPublicKey
8839
- }
8840
- ],
8841
- await this.requireDmCrypto()
9108
+ await this.requireChatCrypto(),
9109
+ peerExtId,
9110
+ text
8842
9111
  ),
8843
9112
  /** Resolve a recipient reference to `{ extId, pubKey }` (contacts → agents → workspace). */
8844
9113
  resolveRecipient: (recipient) => resolveRecipient(this.requireClient(), recipient),
8845
- markRead: (messageIds) => markRead(this.requireClient(), messageIds),
8846
- delete: (messageIds) => deleteDMs(this.requireClient(), messageIds),
8847
- /** List the current user's durable activity feed (never unread; excluded from DMs). */
9114
+ /** List the current user's durable activity feed. */
8848
9115
  listActivity: (options) => listActivity(this.requireClient(), options)
8849
9116
  };
8850
9117
  // ── Settings ──────────────────────────────────────────────────────────
@@ -9937,6 +10204,7 @@ var OpenClawOrchestrator = class {
9937
10204
  };
9938
10205
 
9939
10206
  // src/listen/dm-listener.ts
10207
+ var BACKFILL_LIMIT = 50;
9940
10208
  async function startDmListener(options) {
9941
10209
  const { arbi, baseUrl, crypto: crypto2, orchestrator, parentExtId, onLog, onError } = options;
9942
10210
  const log = onLog ?? (() => {
@@ -9946,72 +10214,87 @@ async function startDmListener(options) {
9946
10214
  if (!initialToken) {
9947
10215
  throw new Error("No access token \u2014 run `arbi login` first.");
9948
10216
  }
9949
- const handleNotification = async (msg) => {
9950
- if (msg.type !== "user_message") return;
9951
- const senderExtId = msg.sender?.external_id;
10217
+ const rings = /* @__PURE__ */ new Map();
10218
+ const ringFor = (chatExtId) => {
10219
+ let ring = rings.get(chatExtId);
10220
+ if (!ring) {
10221
+ ring = getChat(arbi, chatExtId).then(
10222
+ (chat) => chat.kind === "direct" && chat.members.some((m2) => m2.user.external_id === parentExtId) ? openChatKeyRing(chat, crypto2) : null
10223
+ );
10224
+ ring.catch(() => rings.delete(chatExtId));
10225
+ rings.set(chatExtId, ring);
10226
+ }
10227
+ return ring;
10228
+ };
10229
+ const handled = /* @__PURE__ */ new Set();
10230
+ const handleMessage = async (chatExtId, msg) => {
10231
+ if (handled.has(msg.external_id)) return;
10232
+ if (msg.kind !== "text" || msg.context_only) return;
10233
+ const senderExtId = msg.sender_ext_id;
9952
10234
  if (!senderExtId || senderExtId !== parentExtId) {
9953
- log(`Ignoring message from ${senderExtId ?? "unknown"} (not parent)`);
10235
+ if (senderExtId !== crypto2.userExtId) {
10236
+ log(`Ignoring message from ${senderExtId ?? "unknown"} (not parent)`);
10237
+ }
9954
10238
  return;
9955
10239
  }
9956
- let plaintext;
9957
- try {
9958
- plaintext = await decryptDmContent(arbi, msg, crypto2);
9959
- } catch (err) {
9960
- logError("Failed to decrypt incoming DM", err);
10240
+ handled.add(msg.external_id);
10241
+ const ring = await ringFor(chatExtId);
10242
+ if (!ring) {
10243
+ log(`Ignoring message in ${chatExtId} (not the direct chat with the parent)`);
9961
10244
  return;
9962
10245
  }
10246
+ const decrypted = await decryptChatMessage(ring, msg);
10247
+ if (decrypted.decryptFailed) {
10248
+ logError("Failed to decrypt incoming message");
10249
+ return;
10250
+ }
10251
+ const plaintext = decrypted.content;
9963
10252
  if (!plaintext) {
9964
10253
  log("Received empty message, skipping");
9965
10254
  return;
9966
10255
  }
9967
- log(`Received prompt from ${msg.sender?.email ?? senderExtId}: ${plaintext.slice(0, 80)}...`);
10256
+ log(`Received prompt from ${senderExtId}: ${plaintext.slice(0, 80)}...`);
9968
10257
  let response;
9969
10258
  try {
9970
10259
  response = await orchestrator.prompt(plaintext, {
9971
10260
  senderExtId,
9972
- senderEmail: msg.sender?.email ?? void 0
10261
+ ...msg.workspace_ext_id ? { workspaceId: msg.workspace_ext_id } : {}
9973
10262
  });
9974
10263
  } catch (err) {
9975
10264
  logError(`Orchestrator "${orchestrator.name}" failed`, err);
9976
10265
  response = `[Error: orchestrator failed \u2014 ${err instanceof Error ? err.message : String(err)}]`;
9977
10266
  }
9978
10267
  log(`Orchestrator response (${response.length} chars): ${response.slice(0, 80)}...`);
9979
- const senderPubKey = msg.sender?.encryption_public_key;
9980
- if (!senderPubKey) {
9981
- logError("Cannot reply \u2014 sender has no encryption public key");
9982
- return;
9983
- }
9984
10268
  try {
9985
- await sendEncryptedDM(
9986
- arbi,
9987
- [
9988
- {
9989
- recipient_ext_id: senderExtId,
9990
- content: response,
9991
- recipient_encryption_public_key: senderPubKey
9992
- }
9993
- ],
9994
- crypto2
9995
- );
9996
- log(`Reply sent to ${msg.sender?.email ?? senderExtId}`);
10269
+ await sendChatMessage(arbi, ring, response);
10270
+ log(`Reply sent to ${senderExtId}`);
9997
10271
  } catch (err) {
9998
10272
  logError("Failed to send encrypted reply", err);
9999
10273
  }
10274
+ try {
10275
+ await markChatRead(arbi, chatExtId, msg.external_id);
10276
+ } catch {
10277
+ }
10000
10278
  };
10001
10279
  try {
10002
- const unreadFromParent = (await listDMs(arbi)).filter(
10003
- (n2) => n2.type === "user_message" && n2.read === false && n2.sender?.external_id === parentExtId
10280
+ const chats = (await listChats(arbi, "direct")).filter(
10281
+ (c2) => c2.unread_count > 0 && c2.members.some((m2) => m2.user.external_id === parentExtId)
10004
10282
  );
10005
- if (unreadFromParent.length > 0) {
10006
- log(`Backfilling ${unreadFromParent.length} unread DM(s) from parent`);
10007
- for (const n2 of unreadFromParent) {
10008
- await handleNotification(n2).catch(
10283
+ for (const chat of chats) {
10284
+ const me2 = chat.members.find((m2) => m2.user.external_id === crypto2.userExtId);
10285
+ const since = me2?.last_read_at ? Date.parse(me2.last_read_at) : 0;
10286
+ const unread = (await listChatMessages(arbi, chat.external_id, {
10287
+ limit: Math.min(chat.unread_count, BACKFILL_LIMIT)
10288
+ })).filter((m2) => m2.sender_ext_id === parentExtId && Date.parse(m2.created_at) > since).reverse();
10289
+ if (unread.length > 0) log(`Backfilling ${unread.length} unread message(s) from parent`);
10290
+ for (const m2 of unread) {
10291
+ await handleMessage(chat.external_id, m2).catch(
10009
10292
  (err) => logError("Backfill handler error", err)
10010
10293
  );
10011
10294
  }
10012
10295
  }
10013
10296
  } catch (err) {
10014
- logError("Failed to backfill unread DMs", err);
10297
+ logError("Failed to backfill unread messages", err);
10015
10298
  }
10016
10299
  const ws = await connectWithReconnect({
10017
10300
  baseUrl,
@@ -10020,14 +10303,9 @@ async function startDmListener(options) {
10020
10303
  refreshAuth: () => arbi.auth.relogin(),
10021
10304
  maxRetries: Infinity,
10022
10305
  onMessage: (msg) => {
10023
- if ("sender" in msg && "recipient" in msg) {
10024
- const notification = msg;
10025
- if (notification.type === "user_message") {
10026
- handleNotification(notification).catch(
10027
- (err) => logError("Notification handler error", err)
10028
- );
10029
- }
10030
- }
10306
+ if (msg.type !== "chat.message") return;
10307
+ const { chat_ext_id, message } = msg;
10308
+ handleMessage(chat_ext_id, message).catch((err) => logError("Message handler error", err));
10031
10309
  },
10032
10310
  onReconnecting: (attempt, max) => {
10033
10311
  const limit = Number.isFinite(max) ? `/${max}` : "";
@@ -10040,7 +10318,7 @@ async function startDmListener(options) {
10040
10318
  log(`WebSocket closed: ${reason || "no reason"}`);
10041
10319
  }
10042
10320
  });
10043
- log(`Listening for DMs (orchestrator: ${orchestrator.name}, parent: ${parentExtId})`);
10321
+ log(`Listening for messages (orchestrator: ${orchestrator.name}, parent: ${parentExtId})`);
10044
10322
  return {
10045
10323
  close() {
10046
10324
  ws.close();
@@ -10049,6 +10327,6 @@ async function startDmListener(options) {
10049
10327
  };
10050
10328
  }
10051
10329
 
10052
- export { Arbi, ArbiApiError, ArbiError, ArbiSessionExpiredError, ClaudeOrchestrator, DEFAULT_AI_USD_PER_GBP, DOC_TERMINAL_STATUSES, FileConfigStore, OpenClawOrchestrator, PlanStepsError, STEP_FIELD_OPTION_TONES, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, agents_exports as agents, assistant_exports as assistant, authenticatedFetch, buildDocNameMap, buildFactsContextTool, buildRetrievalChunkTool, buildRetrievalFullContextTool, buildRetrievalTocTool, connectWebSocket, connectWithReconnect, consumeSSEStream, contacts_exports as contacts, conversations_exports as conversations, countCitations, createAuthenticatedClient, createDocumentWaiter, device_flow_exports as deviceFlow, dm_exports as dm, doctags_exports as doctags, documents_exports as documents, documents_node_exports as documentsNode, facts_exports as facts, files_exports as files, filterSkills, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatStreamSummary, formatUserName, formatWorkspaceChoices, formatWsMessage, generateEncryptedWorkspaceKey, generateNewWorkspaceKey, getErrorCode, getErrorMessage, getRawWorkspaceKey, health_exports as health, identityErrorCode, identity_exports as identityVerification, listen_exports as listen, mail_exports as mail, mail_node_exports as mailNode, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, performPasswordLogin, performSigningKeyLogin, performSsoDeviceFlowLogin, profile_exports as profile, projects_exports as projects, requireData, requireOk, resolveAuth, resolveCitations, resolveWorkspace, responses_exports as responses, selectWorkspace, selectWorkspaceById, sessions_exports as sessions, settings_exports as settings, signature_requests_exports as signatureRequests, startDmListener, streamSSE, stripCitationMarkdown, summarizeCitations, tags_exports as tags, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaces_exports as workspaces };
10330
+ export { Arbi, ArbiApiError, ArbiError, ArbiSessionExpiredError, ClaudeOrchestrator, DEFAULT_AI_USD_PER_GBP, DOC_TERMINAL_STATUSES, FileConfigStore, OpenClawOrchestrator, PlanStepsError, STEP_FIELD_OPTION_TONES, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, agents_exports as agents, assistant_exports as assistant, authenticatedFetch, buildDocNameMap, buildFactsContextTool, buildRetrievalChunkTool, buildRetrievalFullContextTool, buildRetrievalTocTool, chats_exports as chats, connectWebSocket, connectWithReconnect, consumeSSEStream, contacts_exports as contacts, conversations_exports as conversations, countCitations, createAuthenticatedClient, createDocumentWaiter, device_flow_exports as deviceFlow, doctags_exports as doctags, documents_exports as documents, documents_node_exports as documentsNode, facts_exports as facts, files_exports as files, filterSkills, firm_exports as firm, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatStreamSummary, formatUserName, formatWorkspaceChoices, formatWsMessage, generateEncryptedWorkspaceKey, generateNewWorkspaceKey, getErrorCode, getErrorMessage, getRawWorkspaceKey, health_exports as health, identityErrorCode, identity_exports as identityVerification, listen_exports as listen, mail_exports as mail, mail_node_exports as mailNode, notifications_exports as notifications, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, performPasswordLogin, performSigningKeyLogin, performSsoDeviceFlowLogin, profile_exports as profile, projects_exports as projects, requireData, requireOk, resolveAuth, resolveCitations, resolveWorkspace, responses_exports as responses, selectWorkspace, selectWorkspaceById, sessions_exports as sessions, settings_exports as settings, signature_requests_exports as signatureRequests, startDmListener, streamSSE, stripCitationMarkdown, summarizeCitations, tags_exports as tags, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaces_exports as workspaces };
10053
10331
  //# sourceMappingURL=index.js.map
10054
10332
  //# sourceMappingURL=index.js.map