@arbidocs/sdk 0.4.159 → 0.4.161

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, unwrapWorkspaceKey, sealKeyForSession, buildWebSocketUrl, createAuthMessage, parseServerMessage, isMessageType, createContentHash, encryptFile, initSodium, bytesToBase64, encryptWithChatKey, decryptWithChatKey, decryptFile, encryptionKeypairFromSigningKey, deriveDirectChatKey, openSealedChatKey, generateChatKey, sealChatKey, encryptMessage, sealedBoxDecrypt, decodeSecureMailKey, openSecureMail, secureMailClaim, changePassword } from '@arbidocs/client';
4
+ import { createArbiClient, base64ToBytes, unwrapWorkspaceKey, sealKeyForSession, buildWebSocketUrl, createAuthMessage, parseServerMessage, isMessageType, createContentHash, encryptFile, initSodium, bytesToBase64, encryptWithChatKey, decryptWithChatKey, decryptFile, encryptionKeypairFromSigningKey, deriveDirectChatKey, openSealedChatKey, generateChatKey, sealChatKey, sealCallKey, encryptMessage, sealedBoxDecrypt, decodeSecureMailKey, openSecureMail, secureMailClaim, changePassword, readSessionClaims } from '@arbidocs/client';
5
5
  import { execSync, spawn } from 'child_process';
6
6
  import { createHash } from 'crypto';
7
7
  import { fileURLToPath } from 'url';
@@ -3524,6 +3524,14 @@ var ArbiApiError = class extends ArbiError {
3524
3524
  this.detail = apiErrorDetail(apiError);
3525
3525
  }
3526
3526
  };
3527
+ var DuplicateContactError = class extends ArbiApiError {
3528
+ contactId;
3529
+ constructor(message, contactId, apiError) {
3530
+ super(message, apiError ?? { detail: message }, 409);
3531
+ this.name = "DuplicateContactError";
3532
+ this.contactId = contactId;
3533
+ }
3534
+ };
3527
3535
  function refusalReason(err, fallback) {
3528
3536
  if (err instanceof ArbiApiError) return err.detail || fallback;
3529
3537
  return apiErrorDetail(err) || fallback;
@@ -5018,8 +5026,20 @@ var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([
5018
5026
  function sanitizeFolderPath(folderPath) {
5019
5027
  return folderPath.replace(/[\x00-\x1f\x7f]/g, "").replace(/\\/g, "/").replace(/\/{2,}/g, "/").replace(/^\/|\/$/g, "").trim();
5020
5028
  }
5021
- async function listDocuments(arbi) {
5022
- return requireData(await arbi.fetch.GET("/v1/document/list"), "Failed to fetch documents");
5029
+ async function listDocuments(arbi, workspaceExtId) {
5030
+ if (!workspaceExtId) {
5031
+ return requireData(await arbi.fetch.GET("/v1/document/list"), "Failed to fetch documents");
5032
+ }
5033
+ const docs = requireData(
5034
+ await arbi.fetch.GET("/v1/document/list", {
5035
+ params: { query: { workspace_ext_id: workspaceExtId } }
5036
+ }),
5037
+ "Failed to fetch documents"
5038
+ );
5039
+ if (docs.some((doc) => doc.workspace_ext_id !== workspaceExtId)) {
5040
+ throw new ArbiError(`This server cannot list workspace ${workspaceExtId} without opening it`);
5041
+ }
5042
+ return docs;
5023
5043
  }
5024
5044
  async function* listPaginated(arbi, options = {}) {
5025
5045
  const {
@@ -5666,10 +5686,13 @@ async function grantTemporaryWorkspaceAccess(arbi, params) {
5666
5686
  "Failed to grant temporary access"
5667
5687
  );
5668
5688
  }
5669
- async function removeWorkspaceUsers(arbi, userIds) {
5689
+ async function removeWorkspaceUsers(arbi, userIds, workspaceExtId) {
5670
5690
  requireOk(
5671
5691
  await arbi.fetch.DELETE("/v1/workspace/users", {
5672
- body: { users: userIds.map((id) => ({ user_ext_id: id })) }
5692
+ body: {
5693
+ users: userIds.map((id) => ({ user_ext_id: id })),
5694
+ ...workspaceExtId ? { workspace_ext_id: workspaceExtId } : {}
5695
+ }
5673
5696
  }),
5674
5697
  "Failed to remove users"
5675
5698
  );
@@ -5976,7 +5999,7 @@ async function listSkills(arbi, options) {
5976
5999
  return result.skills;
5977
6000
  }
5978
6001
  function isSharedSkill(skill) {
5979
- return skill.is_owner !== false && skill.visibility === "global";
6002
+ return (skill.is_owner ?? true) && skill.visibility === "global";
5980
6003
  }
5981
6004
  function uploadSkill(auth, slug, markdown, options) {
5982
6005
  return uploadFile(auth, new Blob([markdown], { type: "text/markdown" }), "SKILL.md", {
@@ -6248,11 +6271,23 @@ __export(contacts_exports, {
6248
6271
  createContact: () => createContact,
6249
6272
  deleteContact: () => deleteContact,
6250
6273
  groupContactsByStatus: () => groupContactsByStatus,
6274
+ importContacts: () => importContacts,
6251
6275
  inviteContacts: () => inviteContacts,
6276
+ linkContact: () => linkContact,
6252
6277
  listContacts: () => listContacts,
6253
6278
  searchContacts: () => searchContacts,
6254
6279
  updateContact: () => updateContact
6255
6280
  });
6281
+ function requireContact(result, message) {
6282
+ const error = result.error;
6283
+ if (result.response?.status === 409 && error && typeof error === "object" && "contact_id" in error)
6284
+ throw new DuplicateContactError(
6285
+ apiErrorDetail(error) ?? "This person is already in your contacts",
6286
+ error.contact_id || null,
6287
+ error
6288
+ );
6289
+ return requireData(result, message);
6290
+ }
6256
6291
  async function listContacts(arbi) {
6257
6292
  return requireData(await arbi.fetch.GET("/v1/contacts/"), "Failed to fetch contacts");
6258
6293
  }
@@ -6263,10 +6298,13 @@ async function inviteContacts(arbi, emails) {
6263
6298
  );
6264
6299
  }
6265
6300
  async function createContact(arbi, body) {
6266
- return requireData(await arbi.fetch.POST("/v1/contacts/", { body }), "Failed to create contact");
6301
+ return requireContact(
6302
+ await arbi.fetch.POST("/v1/contacts/", { body }),
6303
+ "Failed to create contact"
6304
+ );
6267
6305
  }
6268
6306
  async function updateContact(arbi, contactId, card) {
6269
- return requireData(
6307
+ return requireContact(
6270
6308
  await arbi.fetch.PATCH("/v1/contacts/{cnt_id}", {
6271
6309
  params: { path: { cnt_id: contactId } },
6272
6310
  body: { card, invite: false }
@@ -6274,12 +6312,32 @@ async function updateContact(arbi, contactId, card) {
6274
6312
  "Failed to update contact"
6275
6313
  );
6276
6314
  }
6315
+ async function linkContact(arbi, contactId, email, card) {
6316
+ return requireContact(
6317
+ await arbi.fetch.PATCH("/v1/contacts/{cnt_id}", {
6318
+ params: { path: { cnt_id: contactId } },
6319
+ body: { card, email, invite: true }
6320
+ }),
6321
+ "Failed to link contact"
6322
+ );
6323
+ }
6277
6324
  async function deleteContact(arbi, contactId) {
6278
6325
  requireOk(
6279
6326
  await arbi.fetch.DELETE("/v1/contacts/{cnt_id}", { params: { path: { cnt_id: contactId } } }),
6280
6327
  "Failed to delete contact"
6281
6328
  );
6282
6329
  }
6330
+ async function importContacts(arbi, file) {
6331
+ const form = new FormData();
6332
+ form.append("file", file);
6333
+ return requireData(
6334
+ await arbi.fetch.POST("/v1/contacts/import", {
6335
+ body: { file: "" },
6336
+ bodySerializer: () => form
6337
+ }),
6338
+ "Failed to import contacts"
6339
+ );
6340
+ }
6283
6341
  async function searchContacts(arbi, q2) {
6284
6342
  return requireData(
6285
6343
  await arbi.fetch.GET("/v1/contacts/search", { params: { query: { q: q2 } } }),
@@ -6351,8 +6409,11 @@ var chats_exports = {};
6351
6409
  __export(chats_exports, {
6352
6410
  CHAT_ATTACHMENT_MAX_BYTES: () => CHAT_ATTACHMENT_MAX_BYTES,
6353
6411
  CHAT_ATTACHMENT_MAX_FILES: () => CHAT_ATTACHMENT_MAX_FILES,
6412
+ CHAT_PAGE_SIZE: () => CHAT_PAGE_SIZE,
6354
6413
  DECRYPTION_FAILED: () => DECRYPTION_FAILED,
6414
+ ENCRYPTED_PREVIEW: () => ENCRYPTED_PREVIEW,
6355
6415
  addChatMembers: () => addChatMembers,
6416
+ chatMessagePreview: () => chatMessagePreview,
6356
6417
  chatMessageTombstone: () => chatMessageTombstone,
6357
6418
  checkChatAttachmentLimits: () => checkChatAttachmentLimits,
6358
6419
  createChatCryptoContext: () => createChatCryptoContext,
@@ -6369,6 +6430,7 @@ __export(chats_exports, {
6369
6430
  getChat: () => getChat,
6370
6431
  hasRead: () => hasRead,
6371
6432
  isAgentExtId: () => isAgentExtId,
6433
+ isTranscriptMessage: () => isTranscriptMessage,
6372
6434
  listChatMessages: () => listChatMessages,
6373
6435
  listChats: () => listChats,
6374
6436
  loadDecryptedChat: () => loadDecryptedChat,
@@ -6376,6 +6438,8 @@ __export(chats_exports, {
6376
6438
  openChatKeyRing: () => openChatKeyRing,
6377
6439
  openDirectChat: () => openDirectChat,
6378
6440
  parseChatAttachmentManifest: () => parseChatAttachmentManifest,
6441
+ parseTranscriptContent: () => parseTranscriptContent,
6442
+ readByOthers: () => readByOthers,
6379
6443
  removeChatMember: () => removeChatMember,
6380
6444
  renameChat: () => renameChat,
6381
6445
  resolveRecipient: () => resolveRecipient,
@@ -6672,6 +6736,39 @@ function chatMessageTombstone(message) {
6672
6736
  delete row.attachmentsError;
6673
6737
  return row;
6674
6738
  }
6739
+ function isTranscriptMessage(message) {
6740
+ return message.kind === "transcript";
6741
+ }
6742
+ function parseTranscriptContent(content) {
6743
+ if (!content) return null;
6744
+ try {
6745
+ const parsed = JSON.parse(content);
6746
+ if (!parsed || typeof parsed !== "object") return null;
6747
+ const p2 = parsed;
6748
+ if (typeof p2.text !== "string") return null;
6749
+ return {
6750
+ text: p2.text,
6751
+ speaker_identity: typeof p2.speaker_identity === "string" ? p2.speaker_identity : "",
6752
+ speaker_name: typeof p2.speaker_name === "string" ? p2.speaker_name : "",
6753
+ started_at: typeof p2.started_at === "string" ? p2.started_at : null
6754
+ };
6755
+ } catch {
6756
+ return null;
6757
+ }
6758
+ }
6759
+ var ENCRYPTED_PREVIEW = "[Encrypted]";
6760
+ function chatMessagePreview(message) {
6761
+ if (message.deleted) return null;
6762
+ if (message.kind === "call") return "Call";
6763
+ if (message.kind === "recording") return "Recording";
6764
+ if (message.decryptFailed) return ENCRYPTED_PREVIEW;
6765
+ const transcript = isTranscriptMessage(message) ? parseTranscriptContent(message.content) : null;
6766
+ if (transcript) {
6767
+ return `Transcript \xB7 ${transcript.speaker_name ? `${transcript.speaker_name}: ` : ""}${transcript.text}`;
6768
+ }
6769
+ if (message.content) return message.content;
6770
+ return message.attachmentFiles?.length ? `\u{1F4CE} ${message.attachmentFiles.map((f2) => f2.name).join(", ")}` : null;
6771
+ }
6675
6772
  async function decryptChatMessage(ring, message) {
6676
6773
  if (message.deleted) return chatMessageTombstone(message);
6677
6774
  const key = ring.keys.get(message.key_version);
@@ -6772,12 +6869,18 @@ async function renameChat(arbi, ring, title) {
6772
6869
  "Failed to rename chat"
6773
6870
  );
6774
6871
  }
6775
- async function addChatMembers(arbi, ring, members) {
6872
+ async function addChatMembers(arbi, ring, members, options = {}) {
6776
6873
  if (ring.kind === "direct") {
6777
6874
  throw new Error("A direct chat cannot gain members: create a group instead");
6778
6875
  }
6779
6876
  if (members.some((m2) => isAgentExtId(m2.external_id))) {
6780
- throw new Error("Personal agents cannot join a group chat");
6877
+ throw new Error(
6878
+ ring.kind === "meeting" ? "Personal agents cannot join a meeting chat" : "Personal agents cannot join a group chat"
6879
+ );
6880
+ }
6881
+ const callKey = options.callKey ?? null;
6882
+ if (ring.kind === "meeting" && !callKey) {
6883
+ throw new Error("You do not hold this meeting\u2019s call key");
6781
6884
  }
6782
6885
  const key = keyFor(ring, ring.currentVersion);
6783
6886
  return requireData(
@@ -6787,7 +6890,8 @@ async function addChatMembers(arbi, ring, members) {
6787
6890
  members: await Promise.all(
6788
6891
  members.map(async (m2) => ({
6789
6892
  user_ext_id: m2.external_id,
6790
- sealed_key: await sealChatKey(key, m2.encryption_public_key)
6893
+ sealed_key: await sealChatKey(key, m2.encryption_public_key),
6894
+ ...callKey ? { call_sealed_key: await sealCallKey(callKey, m2.encryption_public_key) } : {}
6791
6895
  }))
6792
6896
  )
6793
6897
  }
@@ -6840,6 +6944,7 @@ async function ensureChatKeyCurrent(arbi, chat, crypto2) {
6840
6944
  throw err;
6841
6945
  }
6842
6946
  }
6947
+ var CHAT_PAGE_SIZE = 50;
6843
6948
  async function listChatMessages(arbi, chatExtId, options) {
6844
6949
  return requireData(
6845
6950
  await arbi.fetch.GET("/v1/chats/{chat_ext_id}/messages", {
@@ -6902,6 +7007,10 @@ function hasRead(member, message) {
6902
7007
  if (!member?.last_read_at) return false;
6903
7008
  return Date.parse(member.last_read_at) >= Date.parse(message.created_at);
6904
7009
  }
7010
+ function readByOthers(chat, myExtId, message) {
7011
+ const others = chat.members.filter((m2) => m2.user.external_id !== myExtId);
7012
+ return others.every((m2) => hasRead(m2, message));
7013
+ }
6905
7014
  async function resolveRecipient(arbi, ref) {
6906
7015
  const isEmail = ref.includes("@");
6907
7016
  const matchKey = isEmail ? "email" : "external_id";
@@ -7443,7 +7552,6 @@ async function getFileContent(auth, fileId) {
7443
7552
  // src/operations/sessions.ts
7444
7553
  var sessions_exports = {};
7445
7554
  __export(sessions_exports, {
7446
- currentSessionId: () => currentSessionId,
7447
7555
  listSessions: () => listSessions,
7448
7556
  logoutAllSessions: () => logoutAllSessions,
7449
7557
  terminateSession: () => terminateSession
@@ -7466,16 +7574,6 @@ async function logoutAllSessions(arbi) {
7466
7574
  "Failed to sign out of all sessions"
7467
7575
  );
7468
7576
  }
7469
- function currentSessionId(accessToken) {
7470
- const payload = accessToken?.split(".")[1];
7471
- if (!payload) return null;
7472
- try {
7473
- const claims = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/")));
7474
- return typeof claims.sk === "string" ? claims.sk.slice(0, 12) : null;
7475
- } catch {
7476
- return null;
7477
- }
7478
- }
7479
7577
 
7480
7578
  // src/operations/profile.ts
7481
7579
  var profile_exports = {};
@@ -7513,9 +7611,13 @@ async function topUpFirmPool(arbi, aiAddons) {
7513
7611
  var account_exports = {};
7514
7612
  __export(account_exports, {
7515
7613
  confirmEmailChange: () => confirmEmailChange,
7614
+ getEntitlements: () => getEntitlements,
7516
7615
  requestDeletion: () => requestDeletion,
7517
7616
  requestEmailChange: () => requestEmailChange
7518
7617
  });
7618
+ async function getEntitlements(arbi) {
7619
+ return requireData(await arbi.fetch.GET("/v1/user/entitlements"), "Failed to load entitlements");
7620
+ }
7519
7621
  async function requestEmailChange(arbi, newEmail) {
7520
7622
  requireOk(
7521
7623
  await arbi.fetch.POST("/v1/user/request-email-change", { body: { new_email: newEmail } }),
@@ -9422,15 +9524,8 @@ async function cancelPublicBooking(baseUrl, slug, token) {
9422
9524
 
9423
9525
  // src/arbi.ts
9424
9526
  function tokenExpiresWithin(token, seconds) {
9425
- const payload = token?.split(".")[1];
9426
- if (!payload) return false;
9427
- try {
9428
- const json2 = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
9429
- const { exp } = JSON.parse(json2);
9430
- return typeof exp === "number" && exp * 1e3 - Date.now() < seconds * 1e3;
9431
- } catch {
9432
- return false;
9433
- }
9527
+ const expiresAt = readSessionClaims(token)?.expiresAt;
9528
+ return expiresAt != null && expiresAt - Date.now() < seconds * 1e3;
9434
9529
  }
9435
9530
  var Arbi = class {
9436
9531
  client = null;
@@ -9440,7 +9535,12 @@ var Arbi = class {
9440
9535
  currentWorkspaceId = null;
9441
9536
  /** Wrapped workspace keys seen in the last list/create, so selecting needs no re-fetch. */
9442
9537
  wrappedKeys = /* @__PURE__ */ new Map();
9538
+ /** Workspaces whose key this server session holds (`workspaces.open`), keyed per session key. */
9539
+ openedWorkspaces = /* @__PURE__ */ new Map();
9540
+ openedForSessionKey = null;
9443
9541
  chatCryptoContext = null;
9542
+ /** The chat keys I hold, opened once per set of epochs (`chatRingSignature`). */
9543
+ chatRings = /* @__PURE__ */ new Map();
9444
9544
  sessionExpiredListeners = /* @__PURE__ */ new Set();
9445
9545
  options;
9446
9546
  constructor(options) {
@@ -9576,9 +9676,41 @@ var Arbi = class {
9576
9676
  );
9577
9677
  }
9578
9678
  /**
9579
- * Select a workspace by ID. Uses the wrapped key from the last workspace list or create (the
9580
- * list is fetched only when the workspace is not known yet), decrypts it, and opens the
9581
- * workspace on the server.
9679
+ * Make a workspace usable for requests that name it, WITHOUT changing the current workspace (on
9680
+ * the server or here): its key, sealed to this server session, is deposited with `/prime-key`.
9681
+ * Idempotent: cached per server session (a re-login rotates it), concurrent calls share one
9682
+ * request, and the current workspace is already open.
9683
+ */
9684
+ openWorkspace(workspaceId) {
9685
+ if (workspaceId === this.currentWorkspaceId) return Promise.resolve();
9686
+ const lr2 = this.requireLogin();
9687
+ if (this.openedForSessionKey !== lr2.serverSessionKey) {
9688
+ this.openedWorkspaces.clear();
9689
+ this.openedForSessionKey = lr2.serverSessionKey;
9690
+ }
9691
+ const cached = this.openedWorkspaces.get(workspaceId);
9692
+ if (cached) return cached;
9693
+ const opening = this.sealWorkspaceKey(workspaceId).then(
9694
+ (sealedKey) => primeWorkspaceKey(this.requireClient(), workspaceId, sealedKey)
9695
+ );
9696
+ this.openedWorkspaces.set(workspaceId, opening);
9697
+ opening.catch(() => {
9698
+ if (this.openedWorkspaces.get(workspaceId) === opening)
9699
+ this.openedWorkspaces.delete(workspaceId);
9700
+ });
9701
+ return opening;
9702
+ }
9703
+ /** The workspace a call names, opened for this session; `undefined` for the current one. */
9704
+ async targetWorkspace(workspaceId) {
9705
+ if (!workspaceId || workspaceId === this.currentWorkspaceId) return void 0;
9706
+ await this.openWorkspace(workspaceId);
9707
+ return workspaceId;
9708
+ }
9709
+ /**
9710
+ * Make a workspace the CURRENT one: decrypt its key, open it on the server (which makes it the
9711
+ * session's active workspace) and record it in the session. This is navigation: only the host's
9712
+ * workspace switch calls it. Package code that needs another workspace calls
9713
+ * `workspaces.open(id)` and passes the workspace to the request instead.
9582
9714
  */
9583
9715
  async selectWorkspace(workspaceId) {
9584
9716
  const client = this.requireClient();
@@ -9619,6 +9751,7 @@ var Arbi = class {
9619
9751
  this.currentWorkspaceId = null;
9620
9752
  this.wrappedKeys.clear();
9621
9753
  this.chatCryptoContext = null;
9754
+ this.chatRings.clear();
9622
9755
  this.client?.session.clear();
9623
9756
  for (const listener of [...this.sessionExpiredListeners]) listener();
9624
9757
  }
@@ -9665,6 +9798,7 @@ var Arbi = class {
9665
9798
  this.currentWorkspaceId = null;
9666
9799
  this.wrappedKeys.clear();
9667
9800
  this.chatCryptoContext = null;
9801
+ this.chatRings.clear();
9668
9802
  }
9669
9803
  // ── Accessors ─────────────────────────────────────────────────────────
9670
9804
  /** Get the underlying ArbiClient (throws if not initialized). */
@@ -9805,6 +9939,8 @@ var Arbi = class {
9805
9939
  };
9806
9940
  // ── Account ───────────────────────────────────────────────────────────
9807
9941
  account = {
9942
+ /** Which paid features (native mail, the calendar, hosting calls) this person may use, and why not. */
9943
+ entitlements: () => getEntitlements(this.requireClient()),
9808
9944
  /** Send a verification code to the new address (not for SSO accounts). */
9809
9945
  requestEmailChange: (newEmail) => requestEmailChange(this.requireClient(), newEmail),
9810
9946
  /** Confirm the email change with the emailed code; the session and profile follow. */
@@ -9885,6 +10021,13 @@ var Arbi = class {
9885
10021
  }
9886
10022
  // ── Workspaces ────────────────────────────────────────────────────────
9887
10023
  workspaces = {
10024
+ /**
10025
+ * Make a workspace usable for requests that name it, WITHOUT changing the current workspace
10026
+ * (on the server or in the host). `removeUsers` and `documents.list` open the workspace they
10027
+ * are given themselves; `documents.upload` with `workspaceExtId` needs it opened first.
10028
+ * Idempotent and cached per server session. Navigation uses `selectWorkspace`.
10029
+ */
10030
+ open: (workspaceId) => this.openWorkspace(workspaceId),
9888
10031
  /** Hand this server session a workspace's key (sealed to the session) without opening it. */
9889
10032
  primeKey: (workspaceExtId, sessionSealedKey) => primeWorkspaceKey(this.requireClient(), workspaceExtId, sessionSealedKey),
9890
10033
  list: async () => this.rememberWorkspaces(await listWorkspaces(this.requireClient())),
@@ -9952,7 +10095,12 @@ var Arbi = class {
9952
10095
  workspaceExtId: params.workspaceId,
9953
10096
  workspaceKey: await this.sealWorkspaceKey(params.workspaceId)
9954
10097
  }),
9955
- removeUsers: (userIds) => removeWorkspaceUsers(this.requireClient(), userIds),
10098
+ /** Remove users (or agents) from the current workspace, or from `options.workspaceId`. */
10099
+ removeUsers: async (userIds, options) => removeWorkspaceUsers(
10100
+ this.requireClient(),
10101
+ userIds,
10102
+ await this.targetWorkspace(options?.workspaceId)
10103
+ ),
9956
10104
  setUserRole: (userIds, role) => setUserRole(this.requireClient(), userIds, role),
9957
10105
  /**
9958
10106
  * Ask another user to grant you workspace access. Builds the E2E-encrypted
@@ -9982,7 +10130,11 @@ var Arbi = class {
9982
10130
  };
9983
10131
  // ── Documents ─────────────────────────────────────────────────────────
9984
10132
  documents = {
9985
- list: () => listDocuments(this.requireClient()),
10133
+ /** The current workspace's documents, or `options.workspaceId`'s (opened, not switched to). */
10134
+ list: async (options) => listDocuments(
10135
+ this.requireClient(),
10136
+ await this.targetWorkspace(options?.workspaceId)
10137
+ ),
9986
10138
  /**
9987
10139
  * Async iterator that yields pages of documents sequentially.
9988
10140
  * Use this for large workspaces to stream output as pages arrive.
@@ -10235,6 +10387,16 @@ var Arbi = class {
10235
10387
  respond: (assistantMessageExtId, answer) => respondToAgent(this.requireClient(), assistantMessageExtId, answer),
10236
10388
  /** The skills the caller can run (own + shared marketplace), metadata only. */
10237
10389
  listSkills: (options) => listSkills(this.requireClient(), options),
10390
+ /**
10391
+ * Save a SKILL.md as the caller's skill ``slug``: private unless ``shared`` (pass
10392
+ * ``shared: isSharedSkill(skill)`` when changing an existing skill, so a shared one stays shared).
10393
+ */
10394
+ uploadSkill: (slug, markdown, options) => {
10395
+ this.requireWorkspace();
10396
+ return this.recovering(
10397
+ () => uploadSkill(this.getAuthHeaders(), slug, markdown, options)
10398
+ );
10399
+ },
10238
10400
  /**
10239
10401
  * Search documents without LLM generation (retrieval only). No `docIds` searches the whole
10240
10402
  * workspace; `searchChunks(result)` ranks the passages found.
@@ -10292,7 +10454,11 @@ var Arbi = class {
10292
10454
  invite: (emails) => inviteContacts(this.requireClient(), emails),
10293
10455
  create: (body) => this.withCalendarKeys((c2) => createContact(c2, body)),
10294
10456
  update: (contactId, card) => this.withCalendarKeys((c2) => updateContact(c2, contactId, card)),
10457
+ /** Link a card-only contact to `email` (invites it, or links the account at once). */
10458
+ link: (contactId, email, card) => this.withCalendarKeys((c2) => linkContact(c2, contactId, email, card)),
10295
10459
  delete: (contactId) => this.withCalendarKeys((c2) => deleteContact(c2, contactId)),
10460
+ /** Import one .vcf file (Pro). */
10461
+ import: (file) => this.withCalendarKeys((c2) => importContacts(c2, file)),
10296
10462
  search: (q2) => this.withCalendarKeys((c2) => searchContacts(c2, q2)),
10297
10463
  groupByStatus: groupContactsByStatus
10298
10464
  };
@@ -10395,14 +10561,36 @@ var Arbi = class {
10395
10561
  return this.chatCryptoContext;
10396
10562
  }
10397
10563
  /** Fetch a chat, sealing a new epoch first when it is `rotation_required`. */
10398
- async readyChat(chatExtId) {
10564
+ async readyChat(chat) {
10399
10565
  const client = this.requireClient();
10400
10566
  return ensureChatKeyCurrent(
10401
10567
  client,
10402
- await getChat(client, chatExtId),
10568
+ typeof chat === "string" ? await getChat(client, chat) : chat,
10403
10569
  await this.requireChatCrypto()
10404
10570
  );
10405
10571
  }
10572
+ /**
10573
+ * The keys of `chat` I hold, opened once per set of epochs: a direct chat's pair key depends on
10574
+ * the members' public keys, a group's on the epochs sealed to me.
10575
+ */
10576
+ chatRing(chat) {
10577
+ const sig = chat.kind === "direct" ? `d:${chat.members.map((m2) => `${m2.user.external_id}=${m2.user.encryption_public_key}`).join(",")}` : `g:${chat.key_version}:${(chat.my_keys ?? []).map((k2) => `${k2.version}=${k2.sealed_key}`).join(",")}`;
10578
+ const cached = this.chatRings.get(chat.external_id);
10579
+ if (cached && cached.sig === sig) return cached.ring;
10580
+ const ring = this.requireChatCrypto().then((crypto2) => openChatKeyRing(chat, crypto2));
10581
+ ring.catch(() => {
10582
+ if (this.chatRings.get(chat.external_id)?.ring === ring)
10583
+ this.chatRings.delete(chat.external_id);
10584
+ });
10585
+ this.chatRings.set(chat.external_id, { sig, ring });
10586
+ return ring;
10587
+ }
10588
+ /**
10589
+ * Chats: direct (a person, myself, or my own agent), group and meeting. Every message, title and
10590
+ * attachment is end-to-end encrypted under the chat key in this process; a caller passes and
10591
+ * gets plaintext and never handles keys. Operations on an open chat take the `ChatResponse`
10592
+ * (no refetch); the by-id forms fetch it first.
10593
+ */
10406
10594
  chats = {
10407
10595
  /** My chats, most recently active first (raw: titles/last messages are ciphertext). */
10408
10596
  list: (kind) => listChats(this.requireClient(), kind),
@@ -10411,6 +10599,33 @@ var Arbi = class {
10411
10599
  openDirect: (peerExtId) => openDirectChat(this.requireClient(), peerExtId),
10412
10600
  /** Create a group (epoch 1 sealed to every member). Agents are refused. */
10413
10601
  createGroup: async (params) => createGroupChat(this.requireClient(), await this.requireChatCrypto(), params),
10602
+ /** Who I am in chats: my external id and the X25519 public key chat keys are sealed to. */
10603
+ identity: async () => {
10604
+ const crypto2 = await this.requireChatCrypto();
10605
+ return {
10606
+ externalId: crypto2.userExtId,
10607
+ publicKey: bytesToBase64(crypto2.encryptionKeypair.publicKey)
10608
+ };
10609
+ },
10610
+ /** The keys of a chat I hold (cached per set of epochs). */
10611
+ ring: (chat) => this.chatRing(chat),
10612
+ /** Make a chat postable: seal the next epoch when it is `rotation_required`. */
10613
+ ready: (chat) => this.readyChat(chat),
10614
+ /** One page of messages decrypted, oldest first; page back with `before` (the oldest id). */
10615
+ page: async (chat, options = {}) => {
10616
+ const limit = options.limit ?? CHAT_PAGE_SIZE;
10617
+ const raw = await listChatMessages(this.requireClient(), chat.external_id, {
10618
+ before: options.before,
10619
+ limit
10620
+ });
10621
+ const ring = await this.chatRing(chat);
10622
+ const messages = (await decryptChatMessages(ring, raw)).reverse();
10623
+ return { messages, hasMore: raw.length === limit };
10624
+ },
10625
+ /** Decrypt one message of `chat` (never throws: a failure is marked on the row). */
10626
+ decrypt: async (chat, message) => decryptChatMessage(await this.chatRing(chat), message),
10627
+ /** A group's title in plaintext; null when it has none or it does not open. */
10628
+ title: async (chat) => chat.title ? decryptChatTitle(await this.chatRing(chat), chat) : null,
10414
10629
  /** A chat with its keys opened, title and newest messages decrypted (oldest first). */
10415
10630
  load: async (chatExtId, options) => {
10416
10631
  const chat = await this.readyChat(chatExtId);
@@ -10421,30 +10636,50 @@ var Arbi = class {
10421
10636
  options
10422
10637
  );
10423
10638
  },
10424
- /** Post plaintext to a chat (encrypted under its current epoch). */
10425
- send: async (chatExtId, text, options) => {
10426
- const chat = await this.readyChat(chatExtId);
10427
- const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
10428
- return sendChatMessage(this.requireClient(), ring, text, options);
10639
+ /** Post plaintext to a chat (encrypted under its current epoch). Returns it decrypted. */
10640
+ send: async (chat, text, options) => {
10641
+ const ready = await this.readyChat(chat);
10642
+ return sendChatMessage(
10643
+ this.requireClient(),
10644
+ await this.chatRing(ready),
10645
+ text,
10646
+ options
10647
+ );
10429
10648
  },
10430
- rename: async (chatExtId, title) => {
10431
- const chat = await this.readyChat(chatExtId);
10432
- const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
10433
- return renameChat(this.requireClient(), ring, title);
10649
+ rename: async (chat, title) => {
10650
+ const ready = await this.readyChat(chat);
10651
+ return renameChat(this.requireClient(), await this.chatRing(ready), title);
10434
10652
  },
10435
- addMembers: async (chatExtId, members) => {
10436
- const chat = await this.readyChat(chatExtId);
10437
- const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
10438
- return addChatMembers(this.requireClient(), ring, members);
10653
+ /** Add people; a meeting chat also needs its call key, sealed to each (`callKey`). */
10654
+ addMembers: async (chat, members, options) => {
10655
+ const ready = await this.readyChat(chat);
10656
+ return addChatMembers(
10657
+ this.requireClient(),
10658
+ await this.chatRing(ready),
10659
+ members,
10660
+ options
10661
+ );
10439
10662
  },
10440
- /** Remove a member (owner) or leave (own id); a remaining member seals the next epoch. */
10441
- removeMember: async (chatExtId, userExtId) => {
10663
+ /**
10664
+ * Remove a member (owner) or leave (own id). Removing someone seals the next epoch to the rest
10665
+ * straight away; when that fails, the next member to open the chat does it.
10666
+ */
10667
+ removeMember: async (chat, userExtId) => {
10668
+ const chatExtId = typeof chat === "string" ? chat : chat.external_id;
10442
10669
  await removeChatMember(this.requireClient(), chatExtId, userExtId);
10443
10670
  const crypto2 = await this.requireChatCrypto();
10444
- if (userExtId !== crypto2.userExtId) await this.readyChat(chatExtId);
10671
+ if (userExtId === crypto2.userExtId) return;
10672
+ try {
10673
+ await this.readyChat(chatExtId);
10674
+ } catch {
10675
+ }
10445
10676
  },
10446
10677
  markRead: (chatExtId, messageExtId) => markChatRead(this.requireClient(), chatExtId, messageExtId),
10447
- deleteMessage: (chatExtId, messageExtId) => deleteChatMessage(this.requireClient(), chatExtId, messageExtId)
10678
+ deleteMessage: (chatExtId, messageExtId) => deleteChatMessage(this.requireClient(), chatExtId, messageExtId),
10679
+ /** Encrypt each file with its own key and upload the ciphertext (limits checked first). */
10680
+ uploadAttachments: (files) => uploadChatAttachments(this.requireClient(), files),
10681
+ /** Fetch, decrypt and size-check one attachment. */
10682
+ downloadAttachment: (file) => downloadChatAttachment(this.requireClient(), file)
10448
10683
  };
10449
10684
  /** Direct-chat conveniences addressed by peer (email or `usr-`/`agt-` id). */
10450
10685
  dm = {
@@ -10651,7 +10886,7 @@ var Arbi = class {
10651
10886
  sessions = {
10652
10887
  list: () => listSessions(this.requireClient()),
10653
10888
  /** The id this device's session is listed under in `list()`; `null` when unknown. */
10654
- currentId: () => currentSessionId(this.client?.session.getState().accessToken),
10889
+ currentId: () => readSessionClaims(this.client?.session.getState().accessToken)?.sessionId ?? null,
10655
10890
  /** End one of your own sessions now (not the one this device is on: that is `logout`). */
10656
10891
  terminate: (sessionId) => terminateSession(this.requireClient(), sessionId),
10657
10892
  /** Sign out of every device on the server, then clear this instance. */
@@ -11864,6 +12099,6 @@ async function startDmListener(options) {
11864
12099
  };
11865
12100
  }
11866
12101
 
11867
- export { ACCOUNT_VENDOR, Arbi, ArbiApiError, ArbiError, ArbiSessionExpiredError, ClaudeOrchestrator, DEFAULT_AI_USD_PER_GBP, DOC_TERMINAL_STATUSES, DRIVE_SYNC_VENDORS, ENTITY_KINDS, FLAT_TAG_KINDS, FileConfigStore, GOOGLE_VENDORS, IMANAGE_VENDORS, MAILBOX_SYNC_VENDORS, MAX_RETRIEVE_DOC_IDS, MICROSOFT_VENDORS, OpenClawOrchestrator, PRESENCE_KINDS, PlanStepsError, PublicBookingError, SHAREPOINT_VENDORS, STEP_FIELD_OPTION_TONES, TAG_KINDS, TAG_NESTING_MAX_DEPTH, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, agents_exports as agents, assistant_exports as assistant, authenticatedFetch, bookPublicSlot, buildCitationChunkData, buildDocNameMap, buildFactsContextTool, buildRetrievalChunkTool, buildRetrievalFullContextTool, buildRetrievalTocTool, calendar_exports as calendar, canTagHaveParent, cancelPublicBooking, chats_exports as chats, connectErrorMessage, connectWebSocket, connectWithReconnect, connectors_exports as connectors, consumeSSEStream, contacts_exports as contacts, conversations_exports as conversations, countCitations, createAuthenticatedClient, createDocumentWaiter, defaultKindForFormat, 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, filterDocumentTags, filterSkills, firm_exports as firm, flattenTagTree, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatStreamSummary, formatUserName, formatWorkspaceChoices, formatWsMessage, generateEncryptedWorkspaceKey, generateNewWorkspaceKey, getChildTags, getEligibleParentTags, getErrorCode, getErrorMessage, getPublicBookingPage, getRawWorkspaceKey, getTagDescendantIds, health_exports as health, house_template_exports as houseTemplates, identityErrorCode, identity_exports as identityVerification, isAnnotationTag, isConnectorVendorVisible, isDriveSyncVendor, isEntityTag, isFlatKind, isLabelTag, isMailboxSyncVendor, isPresenceTag, isSharePointVendor, isSharedSkill, 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, progressFetch, projects_exports as projects, refusalReason, requireData, requireOk, resolveAuth, resolveCitations, resolveWorkspace, responses_exports as responses, searchChunks, selectWorkspace, selectWorkspaceById, sessions_exports as sessions, settings_exports as settings, signature_requests_exports as signatureRequests, startDmListener, streamSSE, stripCitationMarkdown, summarizeCitations, tagUseCount, tags_exports as tags, tagsForScope, tagsOfGroup, uploadSkill, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaces_exports as workspaces, wouldCreateTagCycle };
12102
+ export { ACCOUNT_VENDOR, Arbi, ArbiApiError, ArbiError, ArbiSessionExpiredError, ClaudeOrchestrator, DEFAULT_AI_USD_PER_GBP, DOC_TERMINAL_STATUSES, DRIVE_SYNC_VENDORS, DuplicateContactError, ENTITY_KINDS, FLAT_TAG_KINDS, FileConfigStore, GOOGLE_VENDORS, IMANAGE_VENDORS, MAILBOX_SYNC_VENDORS, MAX_RETRIEVE_DOC_IDS, MICROSOFT_VENDORS, OpenClawOrchestrator, PRESENCE_KINDS, PlanStepsError, PublicBookingError, SHAREPOINT_VENDORS, STEP_FIELD_OPTION_TONES, TAG_KINDS, TAG_NESTING_MAX_DEPTH, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, agents_exports as agents, assistant_exports as assistant, authenticatedFetch, bookPublicSlot, buildCitationChunkData, buildDocNameMap, buildFactsContextTool, buildRetrievalChunkTool, buildRetrievalFullContextTool, buildRetrievalTocTool, calendar_exports as calendar, canTagHaveParent, cancelPublicBooking, chats_exports as chats, connectErrorMessage, connectWebSocket, connectWithReconnect, connectors_exports as connectors, consumeSSEStream, contacts_exports as contacts, conversations_exports as conversations, countCitations, createAuthenticatedClient, createDocumentWaiter, defaultKindForFormat, 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, filterDocumentTags, filterSkills, firm_exports as firm, flattenTagTree, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatStreamSummary, formatUserName, formatWorkspaceChoices, formatWsMessage, generateEncryptedWorkspaceKey, generateNewWorkspaceKey, getChildTags, getEligibleParentTags, getErrorCode, getErrorMessage, getPublicBookingPage, getRawWorkspaceKey, getTagDescendantIds, health_exports as health, house_template_exports as houseTemplates, identityErrorCode, identity_exports as identityVerification, isAnnotationTag, isConnectorVendorVisible, isDriveSyncVendor, isEntityTag, isFlatKind, isLabelTag, isMailboxSyncVendor, isPresenceTag, isSharePointVendor, isSharedSkill, 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, progressFetch, projects_exports as projects, refusalReason, requireData, requireOk, resolveAuth, resolveCitations, resolveWorkspace, responses_exports as responses, searchChunks, selectWorkspace, selectWorkspaceById, sessions_exports as sessions, settings_exports as settings, signature_requests_exports as signatureRequests, startDmListener, streamSSE, stripCitationMarkdown, summarizeCitations, tagUseCount, tags_exports as tags, tagsForScope, tagsOfGroup, uploadSkill, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaces_exports as workspaces, wouldCreateTagCycle };
11868
12103
  //# sourceMappingURL=index.js.map
11869
12104
  //# sourceMappingURL=index.js.map