@arbidocs/sdk 0.4.108 → 0.4.111

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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,45 @@ 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
+ chatMessageTombstone: () => chatMessageTombstone,
6086
+ checkChatAttachmentLimits: () => checkChatAttachmentLimits,
6087
+ createChatCryptoContext: () => createChatCryptoContext,
6088
+ createGroupChat: () => createGroupChat,
6089
+ decryptChatAttachmentManifest: () => decryptChatAttachmentManifest,
6090
+ decryptChatMessage: () => decryptChatMessage,
6091
+ decryptChatMessages: () => decryptChatMessages,
6092
+ decryptChatTitle: () => decryptChatTitle,
6093
+ deleteChatMessage: () => deleteChatMessage,
6094
+ directPeer: () => directPeer,
6095
+ downloadChatAttachment: () => downloadChatAttachment,
6096
+ encryptChatAttachmentManifest: () => encryptChatAttachmentManifest,
6097
+ ensureChatKeyCurrent: () => ensureChatKeyCurrent,
6098
+ getChat: () => getChat,
6099
+ hasRead: () => hasRead,
6100
+ isAgentExtId: () => isAgentExtId,
6101
+ listChatMessages: () => listChatMessages,
6102
+ listChats: () => listChats,
6103
+ loadDecryptedChat: () => loadDecryptedChat,
6104
+ markChatRead: () => markChatRead,
6105
+ openChatKeyRing: () => openChatKeyRing,
6106
+ openDirectChat: () => openDirectChat,
6107
+ parseChatAttachmentManifest: () => parseChatAttachmentManifest,
6108
+ removeChatMember: () => removeChatMember,
6109
+ renameChat: () => renameChat,
6071
6110
  resolveRecipient: () => resolveRecipient,
6072
- sendDM: () => sendDM,
6073
- sendEncryptedDM: () => sendEncryptedDM,
6074
- serializeDmAttachmentManifest: () => serializeDmAttachmentManifest,
6075
- uploadDmAttachment: () => uploadDmAttachment,
6076
- uploadDmAttachments: () => uploadDmAttachments
6111
+ rotateChatKey: () => rotateChatKey,
6112
+ sendChatMessage: () => sendChatMessage,
6113
+ sendDirectMessage: () => sendDirectMessage,
6114
+ serializeChatAttachmentManifest: () => serializeChatAttachmentManifest,
6115
+ uploadChatAttachment: () => uploadChatAttachment,
6116
+ uploadChatAttachments: () => uploadChatAttachments
6077
6117
  });
6078
6118
 
6079
6119
  // src/operations/agents.ts
@@ -6180,27 +6220,27 @@ async function stageAgentFile(auth, agentId, file, name) {
6180
6220
  });
6181
6221
  return response.json();
6182
6222
  }
6183
- var DM_ATTACHMENT_MAX_BYTES = 15 * 1024 * 1024;
6184
- var DM_ATTACHMENT_MAX_FILES = 10;
6223
+ var CHAT_ATTACHMENT_MAX_BYTES = 15 * 1024 * 1024;
6224
+ var CHAT_ATTACHMENT_MAX_FILES = 10;
6185
6225
  var ATTACHMENT_ID = /^att-[a-zA-Z0-9]{8}$/;
6186
6226
  var MANIFEST_VERSION = 1;
6187
6227
  var MB = 1024 * 1024;
6188
- function checkDmAttachmentLimits(files) {
6189
- if (files.length > DM_ATTACHMENT_MAX_FILES) {
6228
+ function checkChatAttachmentLimits(files) {
6229
+ if (files.length > CHAT_ATTACHMENT_MAX_FILES) {
6190
6230
  throw new Error(
6191
- `You can attach at most ${DM_ATTACHMENT_MAX_FILES} files to a message (this one has ${files.length}).`
6231
+ `You can attach at most ${CHAT_ATTACHMENT_MAX_FILES} files to a message (this one has ${files.length}).`
6192
6232
  );
6193
6233
  }
6194
6234
  for (const file of files) {
6195
- if (file.size > DM_ATTACHMENT_MAX_BYTES) {
6235
+ if (file.size > CHAT_ATTACHMENT_MAX_BYTES) {
6196
6236
  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.`
6237
+ `${file.name} is too large (${(file.size / MB).toFixed(1)} MB). Files can be at most ${CHAT_ATTACHMENT_MAX_BYTES / MB} MB.`
6198
6238
  );
6199
6239
  }
6200
6240
  }
6201
6241
  }
6202
- async function uploadDmAttachment(arbi, input) {
6203
- checkDmAttachmentLimits([{ name: input.name, size: input.bytes.length }]);
6242
+ async function uploadChatAttachment(arbi, input) {
6243
+ checkChatAttachmentLimits([{ name: input.name, size: input.bytes.length }]);
6204
6244
  await initSodium();
6205
6245
  const key = globalThis.crypto.getRandomValues(new Uint8Array(32));
6206
6246
  try {
@@ -6211,13 +6251,13 @@ async function uploadDmAttachment(arbi, input) {
6211
6251
  new Blob([ciphertext], { type: "application/octet-stream" }),
6212
6252
  "attachment.bin"
6213
6253
  );
6214
- const result = await arbi.fetch.POST("/v1/notifications/attachments", {
6254
+ const result = await arbi.fetch.POST("/v1/chats/attachments", {
6215
6255
  body: { file: "" },
6216
6256
  bodySerializer: () => form
6217
6257
  });
6218
6258
  if (result.response?.status === 413) {
6219
6259
  throw new ArbiApiError(
6220
- `${input.name} is too large. Files can be at most ${DM_ATTACHMENT_MAX_BYTES / MB} MB.`,
6260
+ `${input.name} is too large. Files can be at most ${CHAT_ATTACHMENT_MAX_BYTES / MB} MB.`,
6221
6261
  result.error,
6222
6262
  413
6223
6263
  );
@@ -6234,19 +6274,19 @@ async function uploadDmAttachment(arbi, input) {
6234
6274
  key.fill(0);
6235
6275
  }
6236
6276
  }
6237
- async function uploadDmAttachments(arbi, inputs) {
6238
- checkDmAttachmentLimits(inputs.map((i2) => ({ name: i2.name, size: i2.bytes.length })));
6277
+ async function uploadChatAttachments(arbi, inputs) {
6278
+ checkChatAttachmentLimits(inputs.map((i2) => ({ name: i2.name, size: i2.bytes.length })));
6239
6279
  const files = [];
6240
- for (const input of inputs) files.push(await uploadDmAttachment(arbi, input));
6280
+ for (const input of inputs) files.push(await uploadChatAttachment(arbi, input));
6241
6281
  return files;
6242
6282
  }
6243
- function serializeDmAttachmentManifest(files) {
6283
+ function serializeChatAttachmentManifest(files) {
6244
6284
  return JSON.stringify({
6245
6285
  v: MANIFEST_VERSION,
6246
6286
  files: files.map(({ id, name, type, size, key }) => ({ id, name, type, size, key }))
6247
6287
  });
6248
6288
  }
6249
- function parseDmAttachmentManifest(json2) {
6289
+ function parseChatAttachmentManifest(json2) {
6250
6290
  const manifest = JSON.parse(json2);
6251
6291
  if (manifest?.v !== MANIFEST_VERSION || !Array.isArray(manifest.files)) {
6252
6292
  throw new Error("Unsupported attachment manifest");
@@ -6265,27 +6305,15 @@ function parseDmAttachmentManifest(json2) {
6265
6305
  };
6266
6306
  });
6267
6307
  }
6268
- async function encryptDmAttachmentManifest(arbi, files, recipientEncryptionPubKeyBase64, senderEncryptionSecretKey) {
6269
- return arbi.crypto.encryptMessage(
6270
- serializeDmAttachmentManifest(files),
6271
- recipientEncryptionPubKeyBase64,
6272
- senderEncryptionSecretKey
6273
- );
6308
+ async function encryptChatAttachmentManifest(files, chatKey) {
6309
+ return encryptWithChatKey(serializeChatAttachmentManifest(files), chatKey);
6274
6310
  }
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);
6311
+ async function decryptChatAttachmentManifest(manifest, chatKey) {
6312
+ return parseChatAttachmentManifest(await decryptWithChatKey(manifest, chatKey));
6285
6313
  }
6286
- async function downloadDmAttachment(arbi, file) {
6314
+ async function downloadChatAttachment(arbi, file) {
6287
6315
  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}", {
6316
+ const result = await arbi.fetch.GET("/v1/chats/attachments/{external_id}", {
6289
6317
  params: { path: { external_id: file.id } },
6290
6318
  parseAs: "arrayBuffer"
6291
6319
  });
@@ -6313,78 +6341,289 @@ async function downloadDmAttachment(arbi, file) {
6313
6341
  return plain;
6314
6342
  }
6315
6343
 
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,
6344
+ // src/operations/chats.ts
6345
+ function createChatCryptoContext(signingPrivateKeyBytes, userExtId) {
6346
+ const encryptionKeypair = deriveEncryptionKeypairFromSigning({
6347
+ publicKey: signingPrivateKeyBytes.slice(32, 64),
6321
6348
  secretKey: signingPrivateKeyBytes
6322
6349
  });
6323
6350
  return { encryptionKeypair, userExtId };
6324
6351
  }
6325
- async function encryptDmContent(arbi, plaintext, recipientEncryptionPubKeyBase64, senderEncryptionSecretKey) {
6326
- return arbi.crypto.encryptMessage(
6327
- plaintext,
6328
- recipientEncryptionPubKeyBase64,
6329
- senderEncryptionSecretKey
6330
- );
6352
+ function isAgentExtId(extId) {
6353
+ return !!extId && extId.startsWith("agt-");
6331
6354
  }
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
- );
6355
+ function directPeer(chat, myExtId) {
6356
+ if (chat.kind !== "direct") return void 0;
6357
+ return chat.members.find((m2) => m2.user.external_id !== myExtId)?.user;
6341
6358
  }
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;
6359
+ async function openChatKeyRing(chat, crypto2) {
6360
+ const keys = /* @__PURE__ */ new Map();
6361
+ if (chat.kind === "direct") {
6362
+ const peer = directPeer(chat, crypto2.userExtId);
6363
+ const peerPub = peer?.encryption_public_key ?? bytesToBase64(crypto2.encryptionKeypair.publicKey);
6364
+ keys.set(0, await deriveDirectChatKey(peerPub, crypto2.encryptionKeypair.secretKey));
6365
+ } else {
6366
+ for (const k2 of chat.my_keys ?? []) {
6367
+ try {
6368
+ keys.set(
6369
+ k2.version,
6370
+ await openSealedChatKey(k2.sealed_key, crypto2.encryptionKeypair.secretKey)
6371
+ );
6372
+ } catch {
6373
+ }
6348
6374
  }
6349
- let row;
6375
+ }
6376
+ return { chatExtId: chat.external_id, kind: chat.kind, currentVersion: chat.key_version, keys };
6377
+ }
6378
+ function keyFor(ring, version) {
6379
+ const key = ring.keys.get(version);
6380
+ if (!key) throw new Error(`No key for epoch ${version} of ${ring.chatExtId}`);
6381
+ return key;
6382
+ }
6383
+ var DECRYPTION_FAILED = "[Decryption failed]";
6384
+ function chatMessageTombstone(message) {
6385
+ const row = {
6386
+ ...message,
6387
+ deleted: true,
6388
+ content: null,
6389
+ attachments: null,
6390
+ dedupe_key: null
6391
+ };
6392
+ delete row.decryptFailed;
6393
+ delete row.attachmentFiles;
6394
+ delete row.attachmentsError;
6395
+ return row;
6396
+ }
6397
+ async function decryptChatMessage(ring, message) {
6398
+ if (message.deleted) return chatMessageTombstone(message);
6399
+ const key = ring.keys.get(message.key_version);
6400
+ const row = { ...message };
6401
+ if (message.content) {
6350
6402
  try {
6351
- row = { ...n2, content: await decryptDmContent(arbi, n2, crypto2) };
6403
+ if (!key) throw new Error("no key");
6404
+ row.content = await decryptWithChatKey(message.content, key);
6352
6405
  } catch {
6353
- row = { ...n2, content: "[Decryption failed]" };
6406
+ row.content = DECRYPTION_FAILED;
6407
+ row.decryptFailed = true;
6354
6408
  }
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
- }
6409
+ }
6410
+ if (message.attachments) {
6411
+ try {
6412
+ if (!key) throw new Error("no key");
6413
+ row.attachmentFiles = await decryptChatAttachmentManifest(message.attachments, key);
6414
+ } catch {
6415
+ row.attachmentFiles = [];
6416
+ row.attachmentsError = "The attachments could not be decrypted";
6362
6417
  }
6363
- results.push(row);
6364
6418
  }
6365
- return results;
6419
+ return row;
6420
+ }
6421
+ async function decryptChatMessages(ring, messages) {
6422
+ return Promise.all(messages.map((m2) => decryptChatMessage(ring, m2)));
6423
+ }
6424
+ async function decryptChatTitle(ring, chat) {
6425
+ if (!chat.title) return null;
6426
+ const key = ring.keys.get(chat.key_version);
6427
+ if (!key) return null;
6428
+ try {
6429
+ return await decryptWithChatKey(chat.title, key);
6430
+ } catch {
6431
+ return null;
6432
+ }
6366
6433
  }
6367
- async function listDMs(arbi) {
6368
- return requireData(await arbi.fetch.GET("/v1/notifications/"), "Failed to fetch messages");
6434
+ async function listChats(arbi, kind) {
6435
+ return requireData(
6436
+ await arbi.fetch.GET("/v1/chats/", { params: { query: kind ? { kind } : {} } }),
6437
+ "Failed to list chats"
6438
+ );
6369
6439
  }
6370
- async function listDecryptedDMs(arbi, crypto2) {
6371
- const raw = await listDMs(arbi);
6372
- return decryptDmBatch(arbi, raw, crypto2);
6440
+ async function getChat(arbi, chatExtId) {
6441
+ return requireData(
6442
+ await arbi.fetch.GET("/v1/chats/{chat_ext_id}", {
6443
+ params: { path: { chat_ext_id: chatExtId } }
6444
+ }),
6445
+ "Failed to load chat"
6446
+ );
6373
6447
  }
6374
- async function listActivity(arbi, options) {
6448
+ async function openDirectChat(arbi, peerExtId) {
6375
6449
  return requireData(
6376
- await arbi.fetch.GET("/v1/notifications/", {
6450
+ await arbi.fetch.POST("/v1/chats/", { body: { kind: "direct", peer_ext_id: peerExtId } }),
6451
+ "Failed to open chat"
6452
+ );
6453
+ }
6454
+ async function createGroupChat(arbi, crypto2, params) {
6455
+ const members = params.members.filter((m2) => m2.external_id !== crypto2.userExtId);
6456
+ if (members.length === 0) throw new Error("A group needs at least one other member");
6457
+ const agent = members.find((m2) => isAgentExtId(m2.external_id));
6458
+ if (agent) throw new Error("Personal agents cannot join a group chat");
6459
+ const key = await generateChatKey();
6460
+ try {
6461
+ const title = params.title?.trim();
6462
+ return requireData(
6463
+ await arbi.fetch.POST("/v1/chats/", {
6464
+ body: {
6465
+ kind: "group",
6466
+ title: title ? await encryptWithChatKey(title, key) : null,
6467
+ members: await Promise.all(
6468
+ members.map(async (m2) => ({
6469
+ user_ext_id: m2.external_id,
6470
+ sealed_key: await sealChatKey(key, m2.encryption_public_key)
6471
+ }))
6472
+ ),
6473
+ creator_sealed_key: await sealChatKey(
6474
+ key,
6475
+ bytesToBase64(crypto2.encryptionKeypair.publicKey)
6476
+ )
6477
+ }
6478
+ }),
6479
+ "Failed to create group"
6480
+ );
6481
+ } finally {
6482
+ key.fill(0);
6483
+ }
6484
+ }
6485
+ async function renameChat(arbi, ring, title) {
6486
+ const trimmed = title?.trim();
6487
+ return requireData(
6488
+ await arbi.fetch.PATCH("/v1/chats/{chat_ext_id}", {
6489
+ params: { path: { chat_ext_id: ring.chatExtId } },
6490
+ body: {
6491
+ title: trimmed ? await encryptWithChatKey(trimmed, keyFor(ring, ring.currentVersion)) : null
6492
+ }
6493
+ }),
6494
+ "Failed to rename chat"
6495
+ );
6496
+ }
6497
+ async function addChatMembers(arbi, ring, members) {
6498
+ if (ring.kind === "direct") {
6499
+ throw new Error("A direct chat cannot gain members: create a group instead");
6500
+ }
6501
+ if (members.some((m2) => isAgentExtId(m2.external_id))) {
6502
+ throw new Error("Personal agents cannot join a group chat");
6503
+ }
6504
+ const key = keyFor(ring, ring.currentVersion);
6505
+ return requireData(
6506
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/members", {
6507
+ params: { path: { chat_ext_id: ring.chatExtId } },
6508
+ body: {
6509
+ members: await Promise.all(
6510
+ members.map(async (m2) => ({
6511
+ user_ext_id: m2.external_id,
6512
+ sealed_key: await sealChatKey(key, m2.encryption_public_key)
6513
+ }))
6514
+ )
6515
+ }
6516
+ }),
6517
+ "Failed to add members"
6518
+ );
6519
+ }
6520
+ async function removeChatMember(arbi, chatExtId, userExtId) {
6521
+ requireOk(
6522
+ await arbi.fetch.DELETE("/v1/chats/{chat_ext_id}/members/{user_ext_id}", {
6523
+ params: { path: { chat_ext_id: chatExtId, user_ext_id: userExtId } }
6524
+ }),
6525
+ "Failed to remove member"
6526
+ );
6527
+ }
6528
+ async function rotateChatKey(arbi, chat, ring) {
6529
+ if (chat.kind === "direct") throw new Error("Direct chats have no epochs");
6530
+ const oldTitle = await decryptChatTitle(ring, chat);
6531
+ if (chat.title && oldTitle === null) {
6532
+ throw new Error("Cannot re-encrypt the chat title: its key is not available");
6533
+ }
6534
+ const key = await generateChatKey();
6535
+ try {
6536
+ const sealed = {};
6537
+ for (const m2 of chat.members) {
6538
+ sealed[m2.user.external_id] = await sealChatKey(key, m2.user.encryption_public_key);
6539
+ }
6540
+ return requireData(
6541
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/keys", {
6542
+ params: { path: { chat_ext_id: chat.external_id } },
6543
+ body: {
6544
+ version: chat.key_version + 1,
6545
+ sealed_keys: sealed,
6546
+ ...oldTitle !== null ? { title: await encryptWithChatKey(oldTitle, key) } : {}
6547
+ }
6548
+ }),
6549
+ "Failed to rotate chat key"
6550
+ );
6551
+ } finally {
6552
+ key.fill(0);
6553
+ }
6554
+ }
6555
+ async function ensureChatKeyCurrent(arbi, chat, crypto2) {
6556
+ if (!chat.rotation_required || chat.kind === "direct") return chat;
6557
+ if (!chat.members.some((m2) => m2.user.external_id === crypto2.userExtId)) return chat;
6558
+ try {
6559
+ return await rotateChatKey(arbi, chat, await openChatKeyRing(chat, crypto2));
6560
+ } catch (err) {
6561
+ if (err instanceof ArbiApiError && err.status === 409) return getChat(arbi, chat.external_id);
6562
+ throw err;
6563
+ }
6564
+ }
6565
+ async function listChatMessages(arbi, chatExtId, options) {
6566
+ return requireData(
6567
+ await arbi.fetch.GET("/v1/chats/{chat_ext_id}/messages", {
6377
6568
  params: {
6569
+ path: { chat_ext_id: chatExtId },
6378
6570
  query: {
6379
- type: "activity",
6380
- ...options?.limit != null ? { limit: options.limit } : {},
6381
- ...options?.offset != null ? { offset: options.offset } : {}
6571
+ ...options?.before ? { before: options.before } : {},
6572
+ ...options?.limit ? { limit: options.limit } : {}
6382
6573
  }
6383
6574
  }
6384
6575
  }),
6385
- "Failed to fetch activity"
6576
+ "Failed to load messages"
6386
6577
  );
6387
6578
  }
6579
+ async function sendChatMessage(arbi, ring, text, options = {}) {
6580
+ const attachments = options.attachments ?? [];
6581
+ checkChatAttachmentLimits(attachments);
6582
+ const key = keyFor(ring, ring.currentVersion);
6583
+ const created = requireData(
6584
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/messages", {
6585
+ params: { path: { chat_ext_id: ring.chatExtId } },
6586
+ body: {
6587
+ content: await encryptWithChatKey(text, key),
6588
+ key_version: ring.currentVersion,
6589
+ kind: "text",
6590
+ ...attachments.length ? {
6591
+ attachments: await encryptChatAttachmentManifest(attachments, key),
6592
+ attachment_ext_ids: attachments.map((f2) => f2.id)
6593
+ } : {},
6594
+ ...options.workspaceExtId ? { workspace_ext_id: options.workspaceExtId } : {},
6595
+ context_only: !!options.contextOnly
6596
+ }
6597
+ }),
6598
+ "Failed to send message"
6599
+ );
6600
+ return {
6601
+ ...created,
6602
+ content: text,
6603
+ ...attachments.length ? { attachmentFiles: attachments } : {}
6604
+ };
6605
+ }
6606
+ async function deleteChatMessage(arbi, chatExtId, messageExtId) {
6607
+ requireOk(
6608
+ await arbi.fetch.DELETE("/v1/chats/{chat_ext_id}/messages/{message_ext_id}", {
6609
+ params: { path: { chat_ext_id: chatExtId, message_ext_id: messageExtId } }
6610
+ }),
6611
+ "Failed to delete message"
6612
+ );
6613
+ }
6614
+ async function markChatRead(arbi, chatExtId, messageExtId) {
6615
+ return requireData(
6616
+ await arbi.fetch.POST("/v1/chats/{chat_ext_id}/read", {
6617
+ params: { path: { chat_ext_id: chatExtId } },
6618
+ body: messageExtId ? { message_ext_id: messageExtId } : {}
6619
+ }),
6620
+ "Failed to mark chat read"
6621
+ );
6622
+ }
6623
+ function hasRead(member, message) {
6624
+ if (!member?.last_read_at) return false;
6625
+ return Date.parse(member.last_read_at) >= Date.parse(message.created_at);
6626
+ }
6388
6627
  async function resolveRecipient(arbi, ref) {
6389
6628
  const isEmail = ref.includes("@");
6390
6629
  const matchKey = isEmail ? "email" : "external_id";
@@ -6416,52 +6655,63 @@ async function resolveRecipient(arbi, ref) {
6416
6655
  }
6417
6656
  return null;
6418
6657
  }
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) } : {}
6658
+ async function sendDirectMessage(arbi, crypto2, peerExtId, text, options) {
6659
+ const chat = await openDirectChat(arbi, peerExtId);
6660
+ return sendChatMessage(arbi, await openChatKeyRing(chat, crypto2), text, options);
6661
+ }
6662
+ async function loadDecryptedChat(arbi, crypto2, chat, options) {
6663
+ const ring = await openChatKeyRing(chat, crypto2);
6664
+ const raw = await listChatMessages(arbi, chat.external_id, { limit: options?.limit });
6665
+ const messages = (await decryptChatMessages(ring, raw)).reverse();
6666
+ return { chat, ring, title: await decryptChatTitle(ring, chat), messages };
6667
+ }
6668
+
6669
+ // src/operations/notifications.ts
6670
+ var notifications_exports = {};
6671
+ __export(notifications_exports, {
6672
+ deleteNotifications: () => deleteNotifications,
6673
+ listActivity: () => listActivity,
6674
+ listNotifications: () => listNotifications,
6675
+ markNotificationsRead: () => markNotificationsRead,
6676
+ requestWorkspaceAccess: () => requestWorkspaceAccess
6677
+ });
6678
+ async function listNotifications(arbi) {
6679
+ return requireData(await arbi.fetch.GET("/v1/notifications/"), "Failed to fetch notifications");
6680
+ }
6681
+ async function listActivity(arbi, options) {
6682
+ return requireData(
6683
+ await arbi.fetch.GET("/v1/notifications/", {
6684
+ params: {
6685
+ query: {
6686
+ type: "activity",
6687
+ ...options?.limit != null ? { limit: options.limit } : {},
6688
+ ...options?.offset != null ? { offset: options.offset } : {}
6689
+ }
6448
6690
  }
6449
6691
  }),
6450
- "Failed to send message"
6692
+ "Failed to fetch activity"
6693
+ );
6694
+ }
6695
+ async function markNotificationsRead(arbi, ids) {
6696
+ return requireData(
6697
+ await arbi.fetch.PATCH("/v1/notifications/", {
6698
+ body: { updates: ids.map((id) => ({ external_id: id, read: true })) }
6699
+ }),
6700
+ "Failed to update notifications"
6701
+ );
6702
+ }
6703
+ async function deleteNotifications(arbi, ids) {
6704
+ requireOk(
6705
+ await arbi.fetch.DELETE("/v1/notifications/", { body: { external_ids: ids } }),
6706
+ "Failed to delete notifications"
6451
6707
  );
6452
- return created.map((n2) => ({
6453
- ...n2,
6454
- content: plaintextFor.get(n2.recipient.external_id) ?? n2.content,
6455
- ...attachments.length ? { attachmentFiles: attachments } : {}
6456
- }));
6457
6708
  }
6458
6709
  async function requestWorkspaceAccess(arbi, params, crypto2) {
6459
6710
  const payload = JSON.stringify({
6460
6711
  session_pubkey_b64: params.sessionPubkeyB64,
6461
6712
  note: params.note?.trim() || void 0
6462
6713
  });
6463
- const content = await encryptDmContent(
6464
- arbi,
6714
+ const content = await encryptMessage(
6465
6715
  payload,
6466
6716
  params.recipientEncryptionPublicKey,
6467
6717
  crypto2.encryptionKeypair.secretKey
@@ -6477,28 +6727,6 @@ async function requestWorkspaceAccess(arbi, params, crypto2) {
6477
6727
  "Failed to request workspace access"
6478
6728
  );
6479
6729
  }
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
6730
 
6503
6731
  // src/operations/settings.ts
6504
6732
  var settings_exports = {};
@@ -6722,6 +6950,22 @@ async function updateProfile(arbi, body) {
6722
6950
  );
6723
6951
  }
6724
6952
 
6953
+ // src/operations/firm.ts
6954
+ var firm_exports = {};
6955
+ __export(firm_exports, {
6956
+ getFirmPool: () => getFirmPool,
6957
+ topUpFirmPool: () => topUpFirmPool
6958
+ });
6959
+ async function getFirmPool(arbi) {
6960
+ return requireData(await arbi.fetch.GET("/v1/firm/pool"), "Failed to fetch the firm AI usage");
6961
+ }
6962
+ async function topUpFirmPool(arbi, aiAddons) {
6963
+ return requireData(
6964
+ await arbi.fetch.POST("/v1/firm/pool/topup", { body: { ai_addons: aiAddons } }),
6965
+ "Failed to add firm AI usage"
6966
+ );
6967
+ }
6968
+
6725
6969
  // src/operations/account.ts
6726
6970
  var account_exports = {};
6727
6971
  __export(account_exports, {
@@ -7954,10 +8198,10 @@ function attachmentFromBytes(name, contentType, bytes) {
7954
8198
  name,
7955
8199
  content_type: contentType,
7956
8200
  size: bytes.length,
7957
- content_base64: bytesToBase642(bytes)
8201
+ content_base64: bytesToBase643(bytes)
7958
8202
  };
7959
8203
  }
7960
- function bytesToBase642(bytes) {
8204
+ function bytesToBase643(bytes) {
7961
8205
  let binary = "";
7962
8206
  for (let i2 = 0; i2 < bytes.length; i2 += 32768) {
7963
8207
  binary += String.fromCharCode(...bytes.subarray(i2, i2 + 32768));
@@ -7985,7 +8229,7 @@ var Arbi = class {
7985
8229
  currentWorkspaceId = null;
7986
8230
  /** Wrapped workspace keys seen in the last list/create, so selecting needs no re-fetch. */
7987
8231
  wrappedKeys = /* @__PURE__ */ new Map();
7988
- dmCryptoContext = null;
8232
+ chatCryptoContext = null;
7989
8233
  sessionExpiredListeners = /* @__PURE__ */ new Set();
7990
8234
  options;
7991
8235
  constructor(options) {
@@ -8157,7 +8401,7 @@ var Arbi = class {
8157
8401
  this.userProfile = null;
8158
8402
  this.currentWorkspaceId = null;
8159
8403
  this.wrappedKeys.clear();
8160
- this.dmCryptoContext = null;
8404
+ this.chatCryptoContext = null;
8161
8405
  this.client?.session.clear();
8162
8406
  for (const listener of [...this.sessionExpiredListeners]) listener();
8163
8407
  }
@@ -8203,7 +8447,7 @@ var Arbi = class {
8203
8447
  this.userProfile = null;
8204
8448
  this.currentWorkspaceId = null;
8205
8449
  this.wrappedKeys.clear();
8206
- this.dmCryptoContext = null;
8450
+ this.chatCryptoContext = null;
8207
8451
  }
8208
8452
  // ── Accessors ─────────────────────────────────────────────────────────
8209
8453
  /** Get the underlying ArbiClient (throws if not initialized). */
@@ -8302,6 +8546,13 @@ var Arbi = class {
8302
8546
  */
8303
8547
  me: () => getCurrentUser(this.requireClient())
8304
8548
  };
8549
+ // ── Firm ──────────────────────────────────────────────────────────────
8550
+ firm = {
8551
+ /** The firm's pooled monthly £ of AI usage (`has_pool` false where there is none). */
8552
+ pool: () => getFirmPool(this.requireClient()),
8553
+ /** Buy `aiAddons` renewing add-ons (+£10 of AI usage a month each) for the firm. Box admins only. */
8554
+ topUp: (aiAddons) => topUpFirmPool(this.requireClient(), aiAddons)
8555
+ };
8305
8556
  // ── Profile ───────────────────────────────────────────────────────────
8306
8557
  profile = {
8307
8558
  /** Update the display profile; pass only what changes (`''` clears family name or picture). */
@@ -8467,9 +8718,13 @@ var Arbi = class {
8467
8718
  const lr2 = this.requireLogin();
8468
8719
  const userExtId = lr2.userExtId ?? client.session.getState().userExtId;
8469
8720
  if (!userExtId) throw new ArbiError("No user id in session \u2014 cannot request access");
8470
- const crypto2 = createDmCryptoContext(client, lr2.signingPrivateKey, userExtId);
8721
+ const crypto2 = createChatCryptoContext(lr2.signingPrivateKey, userExtId);
8471
8722
  const sessionPubkeyB64 = client.crypto.bytesToBase64(lr2.serverSessionKey);
8472
- return requestWorkspaceAccess(client, { ...params, sessionPubkeyB64 }, crypto2);
8723
+ return requestWorkspaceAccess(
8724
+ client,
8725
+ { ...params, sessionPubkeyB64 },
8726
+ crypto2
8727
+ );
8473
8728
  },
8474
8729
  copyDocuments: (targetWorkspaceId, docIds, targetWorkspaceKey) => copyDocuments(
8475
8730
  this.requireClient(),
@@ -8759,92 +9014,119 @@ var Arbi = class {
8759
9014
  // ── Contacts ──────────────────────────────────────────────────────────
8760
9015
  contacts = {
8761
9016
  list: () => listContacts(this.requireClient()),
8762
- add: (emails) => addContacts(this.requireClient(), emails),
8763
- remove: (contactIds) => removeContacts(this.requireClient(), contactIds),
9017
+ invite: (emails) => inviteContacts(this.requireClient(), emails),
9018
+ create: (body) => createContact(this.requireClient(), body),
9019
+ update: (contactId, card) => updateContact(this.requireClient(), contactId, card),
9020
+ delete: (contactId) => deleteContact(this.requireClient(), contactId),
9021
+ search: (q2) => searchContacts(this.requireClient(), q2),
8764
9022
  groupByStatus: groupContactsByStatus
8765
9023
  };
8766
- // ── Direct Messages ───────────────────────────────────────────────────
9024
+ // ── Chats (direct + group) ────────────────────────────────────────────
8767
9025
  /**
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.
9026
+ * Build (and cache) the chat crypto context for the current session: my X25519 keypair
9027
+ * (derived from the signing key) and external id. Cleared on logout.
8774
9028
  *
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.
9029
+ * The key comes from the live login result first, exactly as `selectWorkspace` sources it, and
9030
+ * only then from persisted storage (which is what restores a session on reload) — persistence
9031
+ * deliberately no-ops without Web Crypto, and chats must not be the one feature that breaks then.
8782
9032
  */
8783
- async requireDmCrypto() {
8784
- if (this.dmCryptoContext) return this.dmCryptoContext;
9033
+ async requireChatCrypto() {
9034
+ if (this.chatCryptoContext) return this.chatCryptoContext;
8785
9035
  const client = this.requireClient();
8786
9036
  const signingPrivateKey = this.loginResult?.signingPrivateKey ?? (await client.storage.getSession())?.signingPrivateKey;
8787
9037
  if (!signingPrivateKey) {
8788
- throw new ArbiError("Not authenticated \u2014 no session available for DM encryption");
9038
+ throw new ArbiError("Not authenticated \u2014 no session available for chat encryption");
8789
9039
  }
8790
9040
  const userExtId = client.session.getState().userExtId;
8791
9041
  if (!userExtId) {
8792
- throw new ArbiError("No user identity in session \u2014 cannot set up DM encryption");
9042
+ throw new ArbiError("No user identity in session \u2014 cannot set up chat encryption");
8793
9043
  }
8794
- this.dmCryptoContext = createDmCryptoContext(client, signingPrivateKey, userExtId);
8795
- return this.dmCryptoContext;
9044
+ this.chatCryptoContext = createChatCryptoContext(signingPrivateKey, userExtId);
9045
+ return this.chatCryptoContext;
8796
9046
  }
9047
+ /** Fetch a chat, sealing a new epoch first when it is `rotation_required`. */
9048
+ async readyChat(chatExtId) {
9049
+ const client = this.requireClient();
9050
+ return ensureChatKeyCurrent(
9051
+ client,
9052
+ await getChat(client, chatExtId),
9053
+ await this.requireChatCrypto()
9054
+ );
9055
+ }
9056
+ chats = {
9057
+ /** My chats, most recently active first (raw: titles/last messages are ciphertext). */
9058
+ list: (kind) => listChats(this.requireClient(), kind),
9059
+ get: (chatExtId) => getChat(this.requireClient(), chatExtId),
9060
+ /** Get-or-create the direct chat with a peer. */
9061
+ openDirect: (peerExtId) => openDirectChat(this.requireClient(), peerExtId),
9062
+ /** Create a group (epoch 1 sealed to every member). Agents are refused. */
9063
+ createGroup: async (params) => createGroupChat(this.requireClient(), await this.requireChatCrypto(), params),
9064
+ /** A chat with its keys opened, title and newest messages decrypted (oldest first). */
9065
+ load: async (chatExtId, options) => {
9066
+ const chat = await this.readyChat(chatExtId);
9067
+ return loadDecryptedChat(
9068
+ this.requireClient(),
9069
+ await this.requireChatCrypto(),
9070
+ chat,
9071
+ options
9072
+ );
9073
+ },
9074
+ /** Post plaintext to a chat (encrypted under its current epoch). */
9075
+ send: async (chatExtId, text, options) => {
9076
+ const chat = await this.readyChat(chatExtId);
9077
+ const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
9078
+ return sendChatMessage(this.requireClient(), ring, text, options);
9079
+ },
9080
+ rename: async (chatExtId, title) => {
9081
+ const chat = await this.readyChat(chatExtId);
9082
+ const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
9083
+ return renameChat(this.requireClient(), ring, title);
9084
+ },
9085
+ addMembers: async (chatExtId, members) => {
9086
+ const chat = await this.readyChat(chatExtId);
9087
+ const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
9088
+ return addChatMembers(this.requireClient(), ring, members);
9089
+ },
9090
+ /** Remove a member (owner) or leave (own id); a remaining member seals the next epoch. */
9091
+ removeMember: async (chatExtId, userExtId) => {
9092
+ await removeChatMember(this.requireClient(), chatExtId, userExtId);
9093
+ const crypto2 = await this.requireChatCrypto();
9094
+ if (userExtId !== crypto2.userExtId) await this.readyChat(chatExtId);
9095
+ },
9096
+ markRead: (chatExtId, messageExtId) => markChatRead(this.requireClient(), chatExtId, messageExtId),
9097
+ deleteMessage: (chatExtId, messageExtId) => deleteChatMessage(this.requireClient(), chatExtId, messageExtId)
9098
+ };
9099
+ /** Direct-chat conveniences addressed by peer (email or `usr-`/`agt-` id). */
8797
9100
  dm = {
8798
9101
  /**
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.
9102
+ * Send an E2E-encrypted direct message: resolves the peer, opens (get-or-create) the direct
9103
+ * chat and posts under the pair key. The caller passes plaintext and never handles keys.
8807
9104
  */
8808
9105
  send: async (recipient, text) => {
8809
9106
  const client = this.requireClient();
8810
9107
  const resolved = await resolveRecipient(client, recipient);
8811
9108
  if (!resolved) {
8812
9109
  throw new ArbiError(
8813
- `Could not resolve DM recipient "${recipient}" (not a known contact, agent, or workspace member)`
9110
+ `Could not resolve recipient "${recipient}" (not a known contact, agent, or workspace member)`
8814
9111
  );
8815
9112
  }
8816
- return sendEncryptedDM(
9113
+ return sendDirectMessage(
8817
9114
  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()
9115
+ await this.requireChatCrypto(),
9116
+ resolved.extId,
9117
+ text
8826
9118
  );
8827
9119
  },
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(
9120
+ /** Send to a peer whose external id is already known, skipping directory resolution. */
9121
+ sendTo: async (peerExtId, text) => sendDirectMessage(
8833
9122
  this.requireClient(),
8834
- [
8835
- {
8836
- recipient_ext_id: recipientExtId,
8837
- content: text,
8838
- recipient_encryption_public_key: recipientPublicKey
8839
- }
8840
- ],
8841
- await this.requireDmCrypto()
9123
+ await this.requireChatCrypto(),
9124
+ peerExtId,
9125
+ text
8842
9126
  ),
8843
9127
  /** Resolve a recipient reference to `{ extId, pubKey }` (contacts → agents → workspace). */
8844
9128
  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). */
9129
+ /** List the current user's durable activity feed. */
8848
9130
  listActivity: (options) => listActivity(this.requireClient(), options)
8849
9131
  };
8850
9132
  // ── Settings ──────────────────────────────────────────────────────────
@@ -9937,6 +10219,7 @@ var OpenClawOrchestrator = class {
9937
10219
  };
9938
10220
 
9939
10221
  // src/listen/dm-listener.ts
10222
+ var BACKFILL_LIMIT = 50;
9940
10223
  async function startDmListener(options) {
9941
10224
  const { arbi, baseUrl, crypto: crypto2, orchestrator, parentExtId, onLog, onError } = options;
9942
10225
  const log = onLog ?? (() => {
@@ -9946,72 +10229,87 @@ async function startDmListener(options) {
9946
10229
  if (!initialToken) {
9947
10230
  throw new Error("No access token \u2014 run `arbi login` first.");
9948
10231
  }
9949
- const handleNotification = async (msg) => {
9950
- if (msg.type !== "user_message") return;
9951
- const senderExtId = msg.sender?.external_id;
10232
+ const rings = /* @__PURE__ */ new Map();
10233
+ const ringFor = (chatExtId) => {
10234
+ let ring = rings.get(chatExtId);
10235
+ if (!ring) {
10236
+ ring = getChat(arbi, chatExtId).then(
10237
+ (chat) => chat.kind === "direct" && chat.members.some((m2) => m2.user.external_id === parentExtId) ? openChatKeyRing(chat, crypto2) : null
10238
+ );
10239
+ ring.catch(() => rings.delete(chatExtId));
10240
+ rings.set(chatExtId, ring);
10241
+ }
10242
+ return ring;
10243
+ };
10244
+ const handled = /* @__PURE__ */ new Set();
10245
+ const handleMessage = async (chatExtId, msg) => {
10246
+ if (handled.has(msg.external_id)) return;
10247
+ if (msg.kind !== "text" || msg.context_only) return;
10248
+ const senderExtId = msg.sender_ext_id;
9952
10249
  if (!senderExtId || senderExtId !== parentExtId) {
9953
- log(`Ignoring message from ${senderExtId ?? "unknown"} (not parent)`);
10250
+ if (senderExtId !== crypto2.userExtId) {
10251
+ log(`Ignoring message from ${senderExtId ?? "unknown"} (not parent)`);
10252
+ }
9954
10253
  return;
9955
10254
  }
9956
- let plaintext;
9957
- try {
9958
- plaintext = await decryptDmContent(arbi, msg, crypto2);
9959
- } catch (err) {
9960
- logError("Failed to decrypt incoming DM", err);
10255
+ handled.add(msg.external_id);
10256
+ const ring = await ringFor(chatExtId);
10257
+ if (!ring) {
10258
+ log(`Ignoring message in ${chatExtId} (not the direct chat with the parent)`);
9961
10259
  return;
9962
10260
  }
10261
+ const decrypted = await decryptChatMessage(ring, msg);
10262
+ if (decrypted.decryptFailed) {
10263
+ logError("Failed to decrypt incoming message");
10264
+ return;
10265
+ }
10266
+ const plaintext = decrypted.content;
9963
10267
  if (!plaintext) {
9964
10268
  log("Received empty message, skipping");
9965
10269
  return;
9966
10270
  }
9967
- log(`Received prompt from ${msg.sender?.email ?? senderExtId}: ${plaintext.slice(0, 80)}...`);
10271
+ log(`Received prompt from ${senderExtId}: ${plaintext.slice(0, 80)}...`);
9968
10272
  let response;
9969
10273
  try {
9970
10274
  response = await orchestrator.prompt(plaintext, {
9971
10275
  senderExtId,
9972
- senderEmail: msg.sender?.email ?? void 0
10276
+ ...msg.workspace_ext_id ? { workspaceId: msg.workspace_ext_id } : {}
9973
10277
  });
9974
10278
  } catch (err) {
9975
10279
  logError(`Orchestrator "${orchestrator.name}" failed`, err);
9976
10280
  response = `[Error: orchestrator failed \u2014 ${err instanceof Error ? err.message : String(err)}]`;
9977
10281
  }
9978
10282
  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
10283
  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}`);
10284
+ await sendChatMessage(arbi, ring, response);
10285
+ log(`Reply sent to ${senderExtId}`);
9997
10286
  } catch (err) {
9998
10287
  logError("Failed to send encrypted reply", err);
9999
10288
  }
10289
+ try {
10290
+ await markChatRead(arbi, chatExtId, msg.external_id);
10291
+ } catch {
10292
+ }
10000
10293
  };
10001
10294
  try {
10002
- const unreadFromParent = (await listDMs(arbi)).filter(
10003
- (n2) => n2.type === "user_message" && n2.read === false && n2.sender?.external_id === parentExtId
10295
+ const chats = (await listChats(arbi, "direct")).filter(
10296
+ (c2) => c2.unread_count > 0 && c2.members.some((m2) => m2.user.external_id === parentExtId)
10004
10297
  );
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(
10298
+ for (const chat of chats) {
10299
+ const me2 = chat.members.find((m2) => m2.user.external_id === crypto2.userExtId);
10300
+ const since = me2?.last_read_at ? Date.parse(me2.last_read_at) : 0;
10301
+ const unread = (await listChatMessages(arbi, chat.external_id, {
10302
+ limit: Math.min(chat.unread_count, BACKFILL_LIMIT)
10303
+ })).filter((m2) => m2.sender_ext_id === parentExtId && Date.parse(m2.created_at) > since).reverse();
10304
+ if (unread.length > 0) log(`Backfilling ${unread.length} unread message(s) from parent`);
10305
+ for (const m2 of unread) {
10306
+ await handleMessage(chat.external_id, m2).catch(
10009
10307
  (err) => logError("Backfill handler error", err)
10010
10308
  );
10011
10309
  }
10012
10310
  }
10013
10311
  } catch (err) {
10014
- logError("Failed to backfill unread DMs", err);
10312
+ logError("Failed to backfill unread messages", err);
10015
10313
  }
10016
10314
  const ws = await connectWithReconnect({
10017
10315
  baseUrl,
@@ -10020,14 +10318,9 @@ async function startDmListener(options) {
10020
10318
  refreshAuth: () => arbi.auth.relogin(),
10021
10319
  maxRetries: Infinity,
10022
10320
  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
- }
10321
+ if (msg.type !== "chat.message") return;
10322
+ const { chat_ext_id, message } = msg;
10323
+ handleMessage(chat_ext_id, message).catch((err) => logError("Message handler error", err));
10031
10324
  },
10032
10325
  onReconnecting: (attempt, max) => {
10033
10326
  const limit = Number.isFinite(max) ? `/${max}` : "";
@@ -10040,7 +10333,7 @@ async function startDmListener(options) {
10040
10333
  log(`WebSocket closed: ${reason || "no reason"}`);
10041
10334
  }
10042
10335
  });
10043
- log(`Listening for DMs (orchestrator: ${orchestrator.name}, parent: ${parentExtId})`);
10336
+ log(`Listening for messages (orchestrator: ${orchestrator.name}, parent: ${parentExtId})`);
10044
10337
  return {
10045
10338
  close() {
10046
10339
  ws.close();
@@ -10049,6 +10342,6 @@ async function startDmListener(options) {
10049
10342
  };
10050
10343
  }
10051
10344
 
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 };
10345
+ 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
10346
  //# sourceMappingURL=index.js.map
10054
10347
  //# sourceMappingURL=index.js.map