@arbidocs/sdk 0.4.158 → 0.4.160

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/browser.js CHANGED
@@ -1,4 +1,4 @@
1
- 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';
1
+ 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';
2
2
 
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -3518,6 +3518,14 @@ var ArbiApiError = class extends ArbiError {
3518
3518
  this.detail = apiErrorDetail(apiError);
3519
3519
  }
3520
3520
  };
3521
+ var DuplicateContactError = class extends ArbiApiError {
3522
+ contactId;
3523
+ constructor(message, contactId, apiError) {
3524
+ super(message, apiError ?? { detail: message }, 409);
3525
+ this.name = "DuplicateContactError";
3526
+ this.contactId = contactId;
3527
+ }
3528
+ };
3521
3529
  function refusalReason(err, fallback) {
3522
3530
  if (err instanceof ArbiApiError) return err.detail || fallback;
3523
3531
  return apiErrorDetail(err) || fallback;
@@ -4470,8 +4478,20 @@ var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([
4470
4478
  function sanitizeFolderPath(folderPath) {
4471
4479
  return folderPath.replace(/[\x00-\x1f\x7f]/g, "").replace(/\\/g, "/").replace(/\/{2,}/g, "/").replace(/^\/|\/$/g, "").trim();
4472
4480
  }
4473
- async function listDocuments(arbi) {
4474
- return requireData(await arbi.fetch.GET("/v1/document/list"), "Failed to fetch documents");
4481
+ async function listDocuments(arbi, workspaceExtId) {
4482
+ if (!workspaceExtId) {
4483
+ return requireData(await arbi.fetch.GET("/v1/document/list"), "Failed to fetch documents");
4484
+ }
4485
+ const docs = requireData(
4486
+ await arbi.fetch.GET("/v1/document/list", {
4487
+ params: { query: { workspace_ext_id: workspaceExtId } }
4488
+ }),
4489
+ "Failed to fetch documents"
4490
+ );
4491
+ if (docs.some((doc) => doc.workspace_ext_id !== workspaceExtId)) {
4492
+ throw new ArbiError(`This server cannot list workspace ${workspaceExtId} without opening it`);
4493
+ }
4494
+ return docs;
4475
4495
  }
4476
4496
  async function* listPaginated(arbi, options = {}) {
4477
4497
  const {
@@ -5095,10 +5115,13 @@ async function grantTemporaryWorkspaceAccess(arbi, params) {
5095
5115
  "Failed to grant temporary access"
5096
5116
  );
5097
5117
  }
5098
- async function removeWorkspaceUsers(arbi, userIds) {
5118
+ async function removeWorkspaceUsers(arbi, userIds, workspaceExtId) {
5099
5119
  requireOk(
5100
5120
  await arbi.fetch.DELETE("/v1/workspace/users", {
5101
- body: { users: userIds.map((id) => ({ user_ext_id: id })) }
5121
+ body: {
5122
+ users: userIds.map((id) => ({ user_ext_id: id })),
5123
+ ...workspaceExtId ? { workspace_ext_id: workspaceExtId } : {}
5124
+ }
5102
5125
  }),
5103
5126
  "Failed to remove users"
5104
5127
  );
@@ -5405,7 +5428,7 @@ async function listSkills(arbi, options) {
5405
5428
  return result.skills;
5406
5429
  }
5407
5430
  function isSharedSkill(skill) {
5408
- return skill.is_owner !== false && skill.visibility === "global";
5431
+ return (skill.is_owner ?? true) && skill.visibility === "global";
5409
5432
  }
5410
5433
  function uploadSkill(auth, slug, markdown, options) {
5411
5434
  return uploadFile(auth, new Blob([markdown], { type: "text/markdown" }), "SKILL.md", {
@@ -5677,11 +5700,23 @@ __export(contacts_exports, {
5677
5700
  createContact: () => createContact,
5678
5701
  deleteContact: () => deleteContact,
5679
5702
  groupContactsByStatus: () => groupContactsByStatus,
5703
+ importContacts: () => importContacts,
5680
5704
  inviteContacts: () => inviteContacts,
5705
+ linkContact: () => linkContact,
5681
5706
  listContacts: () => listContacts,
5682
5707
  searchContacts: () => searchContacts,
5683
5708
  updateContact: () => updateContact
5684
5709
  });
5710
+ function requireContact(result, message) {
5711
+ const error = result.error;
5712
+ if (result.response?.status === 409 && error && typeof error === "object" && "contact_id" in error)
5713
+ throw new DuplicateContactError(
5714
+ apiErrorDetail(error) ?? "This person is already in your contacts",
5715
+ error.contact_id || null,
5716
+ error
5717
+ );
5718
+ return requireData(result, message);
5719
+ }
5685
5720
  async function listContacts(arbi) {
5686
5721
  return requireData(await arbi.fetch.GET("/v1/contacts/"), "Failed to fetch contacts");
5687
5722
  }
@@ -5692,10 +5727,13 @@ async function inviteContacts(arbi, emails) {
5692
5727
  );
5693
5728
  }
5694
5729
  async function createContact(arbi, body) {
5695
- return requireData(await arbi.fetch.POST("/v1/contacts/", { body }), "Failed to create contact");
5730
+ return requireContact(
5731
+ await arbi.fetch.POST("/v1/contacts/", { body }),
5732
+ "Failed to create contact"
5733
+ );
5696
5734
  }
5697
5735
  async function updateContact(arbi, contactId, card) {
5698
- return requireData(
5736
+ return requireContact(
5699
5737
  await arbi.fetch.PATCH("/v1/contacts/{cnt_id}", {
5700
5738
  params: { path: { cnt_id: contactId } },
5701
5739
  body: { card, invite: false }
@@ -5703,12 +5741,32 @@ async function updateContact(arbi, contactId, card) {
5703
5741
  "Failed to update contact"
5704
5742
  );
5705
5743
  }
5744
+ async function linkContact(arbi, contactId, email, card) {
5745
+ return requireContact(
5746
+ await arbi.fetch.PATCH("/v1/contacts/{cnt_id}", {
5747
+ params: { path: { cnt_id: contactId } },
5748
+ body: { card, email, invite: true }
5749
+ }),
5750
+ "Failed to link contact"
5751
+ );
5752
+ }
5706
5753
  async function deleteContact(arbi, contactId) {
5707
5754
  requireOk(
5708
5755
  await arbi.fetch.DELETE("/v1/contacts/{cnt_id}", { params: { path: { cnt_id: contactId } } }),
5709
5756
  "Failed to delete contact"
5710
5757
  );
5711
5758
  }
5759
+ async function importContacts(arbi, file) {
5760
+ const form = new FormData();
5761
+ form.append("file", file);
5762
+ return requireData(
5763
+ await arbi.fetch.POST("/v1/contacts/import", {
5764
+ body: { file: "" },
5765
+ bodySerializer: () => form
5766
+ }),
5767
+ "Failed to import contacts"
5768
+ );
5769
+ }
5712
5770
  async function searchContacts(arbi, q2) {
5713
5771
  return requireData(
5714
5772
  await arbi.fetch.GET("/v1/contacts/search", { params: { query: { q: q2 } } }),
@@ -5780,8 +5838,11 @@ var chats_exports = {};
5780
5838
  __export(chats_exports, {
5781
5839
  CHAT_ATTACHMENT_MAX_BYTES: () => CHAT_ATTACHMENT_MAX_BYTES,
5782
5840
  CHAT_ATTACHMENT_MAX_FILES: () => CHAT_ATTACHMENT_MAX_FILES,
5841
+ CHAT_PAGE_SIZE: () => CHAT_PAGE_SIZE,
5783
5842
  DECRYPTION_FAILED: () => DECRYPTION_FAILED,
5843
+ ENCRYPTED_PREVIEW: () => ENCRYPTED_PREVIEW,
5784
5844
  addChatMembers: () => addChatMembers,
5845
+ chatMessagePreview: () => chatMessagePreview,
5785
5846
  chatMessageTombstone: () => chatMessageTombstone,
5786
5847
  checkChatAttachmentLimits: () => checkChatAttachmentLimits,
5787
5848
  createChatCryptoContext: () => createChatCryptoContext,
@@ -5798,6 +5859,7 @@ __export(chats_exports, {
5798
5859
  getChat: () => getChat,
5799
5860
  hasRead: () => hasRead,
5800
5861
  isAgentExtId: () => isAgentExtId,
5862
+ isTranscriptMessage: () => isTranscriptMessage,
5801
5863
  listChatMessages: () => listChatMessages,
5802
5864
  listChats: () => listChats,
5803
5865
  loadDecryptedChat: () => loadDecryptedChat,
@@ -5805,6 +5867,8 @@ __export(chats_exports, {
5805
5867
  openChatKeyRing: () => openChatKeyRing,
5806
5868
  openDirectChat: () => openDirectChat,
5807
5869
  parseChatAttachmentManifest: () => parseChatAttachmentManifest,
5870
+ parseTranscriptContent: () => parseTranscriptContent,
5871
+ readByOthers: () => readByOthers,
5808
5872
  removeChatMember: () => removeChatMember,
5809
5873
  renameChat: () => renameChat,
5810
5874
  resolveRecipient: () => resolveRecipient,
@@ -6085,6 +6149,39 @@ function chatMessageTombstone(message) {
6085
6149
  delete row.attachmentsError;
6086
6150
  return row;
6087
6151
  }
6152
+ function isTranscriptMessage(message) {
6153
+ return message.kind === "transcript";
6154
+ }
6155
+ function parseTranscriptContent(content) {
6156
+ if (!content) return null;
6157
+ try {
6158
+ const parsed = JSON.parse(content);
6159
+ if (!parsed || typeof parsed !== "object") return null;
6160
+ const p2 = parsed;
6161
+ if (typeof p2.text !== "string") return null;
6162
+ return {
6163
+ text: p2.text,
6164
+ speaker_identity: typeof p2.speaker_identity === "string" ? p2.speaker_identity : "",
6165
+ speaker_name: typeof p2.speaker_name === "string" ? p2.speaker_name : "",
6166
+ started_at: typeof p2.started_at === "string" ? p2.started_at : null
6167
+ };
6168
+ } catch {
6169
+ return null;
6170
+ }
6171
+ }
6172
+ var ENCRYPTED_PREVIEW = "[Encrypted]";
6173
+ function chatMessagePreview(message) {
6174
+ if (message.deleted) return null;
6175
+ if (message.kind === "call") return "Call";
6176
+ if (message.kind === "recording") return "Recording";
6177
+ if (message.decryptFailed) return ENCRYPTED_PREVIEW;
6178
+ const transcript = isTranscriptMessage(message) ? parseTranscriptContent(message.content) : null;
6179
+ if (transcript) {
6180
+ return `Transcript \xB7 ${transcript.speaker_name ? `${transcript.speaker_name}: ` : ""}${transcript.text}`;
6181
+ }
6182
+ if (message.content) return message.content;
6183
+ return message.attachmentFiles?.length ? `\u{1F4CE} ${message.attachmentFiles.map((f2) => f2.name).join(", ")}` : null;
6184
+ }
6088
6185
  async function decryptChatMessage(ring, message) {
6089
6186
  if (message.deleted) return chatMessageTombstone(message);
6090
6187
  const key = ring.keys.get(message.key_version);
@@ -6185,12 +6282,18 @@ async function renameChat(arbi, ring, title) {
6185
6282
  "Failed to rename chat"
6186
6283
  );
6187
6284
  }
6188
- async function addChatMembers(arbi, ring, members) {
6285
+ async function addChatMembers(arbi, ring, members, options = {}) {
6189
6286
  if (ring.kind === "direct") {
6190
6287
  throw new Error("A direct chat cannot gain members: create a group instead");
6191
6288
  }
6192
6289
  if (members.some((m2) => isAgentExtId(m2.external_id))) {
6193
- throw new Error("Personal agents cannot join a group chat");
6290
+ throw new Error(
6291
+ ring.kind === "meeting" ? "Personal agents cannot join a meeting chat" : "Personal agents cannot join a group chat"
6292
+ );
6293
+ }
6294
+ const callKey = options.callKey ?? null;
6295
+ if (ring.kind === "meeting" && !callKey) {
6296
+ throw new Error("You do not hold this meeting\u2019s call key");
6194
6297
  }
6195
6298
  const key = keyFor(ring, ring.currentVersion);
6196
6299
  return requireData(
@@ -6200,7 +6303,8 @@ async function addChatMembers(arbi, ring, members) {
6200
6303
  members: await Promise.all(
6201
6304
  members.map(async (m2) => ({
6202
6305
  user_ext_id: m2.external_id,
6203
- sealed_key: await sealChatKey(key, m2.encryption_public_key)
6306
+ sealed_key: await sealChatKey(key, m2.encryption_public_key),
6307
+ ...callKey ? { call_sealed_key: await sealCallKey(callKey, m2.encryption_public_key) } : {}
6204
6308
  }))
6205
6309
  )
6206
6310
  }
@@ -6253,6 +6357,7 @@ async function ensureChatKeyCurrent(arbi, chat, crypto2) {
6253
6357
  throw err;
6254
6358
  }
6255
6359
  }
6360
+ var CHAT_PAGE_SIZE = 50;
6256
6361
  async function listChatMessages(arbi, chatExtId, options) {
6257
6362
  return requireData(
6258
6363
  await arbi.fetch.GET("/v1/chats/{chat_ext_id}/messages", {
@@ -6315,6 +6420,10 @@ function hasRead(member, message) {
6315
6420
  if (!member?.last_read_at) return false;
6316
6421
  return Date.parse(member.last_read_at) >= Date.parse(message.created_at);
6317
6422
  }
6423
+ function readByOthers(chat, myExtId, message) {
6424
+ const others = chat.members.filter((m2) => m2.user.external_id !== myExtId);
6425
+ return others.every((m2) => hasRead(m2, message));
6426
+ }
6318
6427
  async function resolveRecipient(arbi, ref) {
6319
6428
  const isEmail = ref.includes("@");
6320
6429
  const matchKey = isEmail ? "email" : "external_id";
@@ -6856,7 +6965,6 @@ async function getFileContent(auth, fileId) {
6856
6965
  // src/operations/sessions.ts
6857
6966
  var sessions_exports = {};
6858
6967
  __export(sessions_exports, {
6859
- currentSessionId: () => currentSessionId,
6860
6968
  listSessions: () => listSessions,
6861
6969
  logoutAllSessions: () => logoutAllSessions,
6862
6970
  terminateSession: () => terminateSession
@@ -6879,16 +6987,6 @@ async function logoutAllSessions(arbi) {
6879
6987
  "Failed to sign out of all sessions"
6880
6988
  );
6881
6989
  }
6882
- function currentSessionId(accessToken) {
6883
- const payload = accessToken?.split(".")[1];
6884
- if (!payload) return null;
6885
- try {
6886
- const claims = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/")));
6887
- return typeof claims.sk === "string" ? claims.sk.slice(0, 12) : null;
6888
- } catch {
6889
- return null;
6890
- }
6891
- }
6892
6990
 
6893
6991
  // src/operations/profile.ts
6894
6992
  var profile_exports = {};
@@ -6921,9 +7019,13 @@ async function topUpFirmPool(arbi, aiAddons) {
6921
7019
  var account_exports = {};
6922
7020
  __export(account_exports, {
6923
7021
  confirmEmailChange: () => confirmEmailChange,
7022
+ getEntitlements: () => getEntitlements,
6924
7023
  requestDeletion: () => requestDeletion,
6925
7024
  requestEmailChange: () => requestEmailChange
6926
7025
  });
7026
+ async function getEntitlements(arbi) {
7027
+ return requireData(await arbi.fetch.GET("/v1/user/entitlements"), "Failed to load entitlements");
7028
+ }
6927
7029
  async function requestEmailChange(arbi, newEmail) {
6928
7030
  requireOk(
6929
7031
  await arbi.fetch.POST("/v1/user/request-email-change", { body: { new_email: newEmail } }),
@@ -8830,15 +8932,8 @@ async function cancelPublicBooking(baseUrl, slug, token) {
8830
8932
 
8831
8933
  // src/arbi.ts
8832
8934
  function tokenExpiresWithin(token, seconds) {
8833
- const payload = token?.split(".")[1];
8834
- if (!payload) return false;
8835
- try {
8836
- const json2 = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
8837
- const { exp } = JSON.parse(json2);
8838
- return typeof exp === "number" && exp * 1e3 - Date.now() < seconds * 1e3;
8839
- } catch {
8840
- return false;
8841
- }
8935
+ const expiresAt = readSessionClaims(token)?.expiresAt;
8936
+ return expiresAt != null && expiresAt - Date.now() < seconds * 1e3;
8842
8937
  }
8843
8938
  var Arbi = class {
8844
8939
  client = null;
@@ -8848,7 +8943,12 @@ var Arbi = class {
8848
8943
  currentWorkspaceId = null;
8849
8944
  /** Wrapped workspace keys seen in the last list/create, so selecting needs no re-fetch. */
8850
8945
  wrappedKeys = /* @__PURE__ */ new Map();
8946
+ /** Workspaces whose key this server session holds (`workspaces.open`), keyed per session key. */
8947
+ openedWorkspaces = /* @__PURE__ */ new Map();
8948
+ openedForSessionKey = null;
8851
8949
  chatCryptoContext = null;
8950
+ /** The chat keys I hold, opened once per set of epochs (`chatRingSignature`). */
8951
+ chatRings = /* @__PURE__ */ new Map();
8852
8952
  sessionExpiredListeners = /* @__PURE__ */ new Set();
8853
8953
  options;
8854
8954
  constructor(options) {
@@ -8984,9 +9084,41 @@ var Arbi = class {
8984
9084
  );
8985
9085
  }
8986
9086
  /**
8987
- * Select a workspace by ID. Uses the wrapped key from the last workspace list or create (the
8988
- * list is fetched only when the workspace is not known yet), decrypts it, and opens the
8989
- * workspace on the server.
9087
+ * Make a workspace usable for requests that name it, WITHOUT changing the current workspace (on
9088
+ * the server or here): its key, sealed to this server session, is deposited with `/prime-key`.
9089
+ * Idempotent: cached per server session (a re-login rotates it), concurrent calls share one
9090
+ * request, and the current workspace is already open.
9091
+ */
9092
+ openWorkspace(workspaceId) {
9093
+ if (workspaceId === this.currentWorkspaceId) return Promise.resolve();
9094
+ const lr2 = this.requireLogin();
9095
+ if (this.openedForSessionKey !== lr2.serverSessionKey) {
9096
+ this.openedWorkspaces.clear();
9097
+ this.openedForSessionKey = lr2.serverSessionKey;
9098
+ }
9099
+ const cached = this.openedWorkspaces.get(workspaceId);
9100
+ if (cached) return cached;
9101
+ const opening = this.sealWorkspaceKey(workspaceId).then(
9102
+ (sealedKey) => primeWorkspaceKey(this.requireClient(), workspaceId, sealedKey)
9103
+ );
9104
+ this.openedWorkspaces.set(workspaceId, opening);
9105
+ opening.catch(() => {
9106
+ if (this.openedWorkspaces.get(workspaceId) === opening)
9107
+ this.openedWorkspaces.delete(workspaceId);
9108
+ });
9109
+ return opening;
9110
+ }
9111
+ /** The workspace a call names, opened for this session; `undefined` for the current one. */
9112
+ async targetWorkspace(workspaceId) {
9113
+ if (!workspaceId || workspaceId === this.currentWorkspaceId) return void 0;
9114
+ await this.openWorkspace(workspaceId);
9115
+ return workspaceId;
9116
+ }
9117
+ /**
9118
+ * Make a workspace the CURRENT one: decrypt its key, open it on the server (which makes it the
9119
+ * session's active workspace) and record it in the session. This is navigation: only the host's
9120
+ * workspace switch calls it. Package code that needs another workspace calls
9121
+ * `workspaces.open(id)` and passes the workspace to the request instead.
8990
9122
  */
8991
9123
  async selectWorkspace(workspaceId) {
8992
9124
  const client = this.requireClient();
@@ -9027,6 +9159,7 @@ var Arbi = class {
9027
9159
  this.currentWorkspaceId = null;
9028
9160
  this.wrappedKeys.clear();
9029
9161
  this.chatCryptoContext = null;
9162
+ this.chatRings.clear();
9030
9163
  this.client?.session.clear();
9031
9164
  for (const listener of [...this.sessionExpiredListeners]) listener();
9032
9165
  }
@@ -9073,6 +9206,7 @@ var Arbi = class {
9073
9206
  this.currentWorkspaceId = null;
9074
9207
  this.wrappedKeys.clear();
9075
9208
  this.chatCryptoContext = null;
9209
+ this.chatRings.clear();
9076
9210
  }
9077
9211
  // ── Accessors ─────────────────────────────────────────────────────────
9078
9212
  /** Get the underlying ArbiClient (throws if not initialized). */
@@ -9213,6 +9347,8 @@ var Arbi = class {
9213
9347
  };
9214
9348
  // ── Account ───────────────────────────────────────────────────────────
9215
9349
  account = {
9350
+ /** Which paid features (native mail, the calendar, hosting calls) this person may use, and why not. */
9351
+ entitlements: () => getEntitlements(this.requireClient()),
9216
9352
  /** Send a verification code to the new address (not for SSO accounts). */
9217
9353
  requestEmailChange: (newEmail) => requestEmailChange(this.requireClient(), newEmail),
9218
9354
  /** Confirm the email change with the emailed code; the session and profile follow. */
@@ -9293,6 +9429,13 @@ var Arbi = class {
9293
9429
  }
9294
9430
  // ── Workspaces ────────────────────────────────────────────────────────
9295
9431
  workspaces = {
9432
+ /**
9433
+ * Make a workspace usable for requests that name it, WITHOUT changing the current workspace
9434
+ * (on the server or in the host). `removeUsers` and `documents.list` open the workspace they
9435
+ * are given themselves; `documents.upload` with `workspaceExtId` needs it opened first.
9436
+ * Idempotent and cached per server session. Navigation uses `selectWorkspace`.
9437
+ */
9438
+ open: (workspaceId) => this.openWorkspace(workspaceId),
9296
9439
  /** Hand this server session a workspace's key (sealed to the session) without opening it. */
9297
9440
  primeKey: (workspaceExtId, sessionSealedKey) => primeWorkspaceKey(this.requireClient(), workspaceExtId, sessionSealedKey),
9298
9441
  list: async () => this.rememberWorkspaces(await listWorkspaces(this.requireClient())),
@@ -9360,7 +9503,12 @@ var Arbi = class {
9360
9503
  workspaceExtId: params.workspaceId,
9361
9504
  workspaceKey: await this.sealWorkspaceKey(params.workspaceId)
9362
9505
  }),
9363
- removeUsers: (userIds) => removeWorkspaceUsers(this.requireClient(), userIds),
9506
+ /** Remove users (or agents) from the current workspace, or from `options.workspaceId`. */
9507
+ removeUsers: async (userIds, options) => removeWorkspaceUsers(
9508
+ this.requireClient(),
9509
+ userIds,
9510
+ await this.targetWorkspace(options?.workspaceId)
9511
+ ),
9364
9512
  setUserRole: (userIds, role) => setUserRole(this.requireClient(), userIds, role),
9365
9513
  /**
9366
9514
  * Ask another user to grant you workspace access. Builds the E2E-encrypted
@@ -9390,7 +9538,11 @@ var Arbi = class {
9390
9538
  };
9391
9539
  // ── Documents ─────────────────────────────────────────────────────────
9392
9540
  documents = {
9393
- list: () => listDocuments(this.requireClient()),
9541
+ /** The current workspace's documents, or `options.workspaceId`'s (opened, not switched to). */
9542
+ list: async (options) => listDocuments(
9543
+ this.requireClient(),
9544
+ await this.targetWorkspace(options?.workspaceId)
9545
+ ),
9394
9546
  /**
9395
9547
  * Async iterator that yields pages of documents sequentially.
9396
9548
  * Use this for large workspaces to stream output as pages arrive.
@@ -9643,6 +9795,16 @@ var Arbi = class {
9643
9795
  respond: (assistantMessageExtId, answer) => respondToAgent(this.requireClient(), assistantMessageExtId, answer),
9644
9796
  /** The skills the caller can run (own + shared marketplace), metadata only. */
9645
9797
  listSkills: (options) => listSkills(this.requireClient(), options),
9798
+ /**
9799
+ * Save a SKILL.md as the caller's skill ``slug``: private unless ``shared`` (pass
9800
+ * ``shared: isSharedSkill(skill)`` when changing an existing skill, so a shared one stays shared).
9801
+ */
9802
+ uploadSkill: (slug, markdown, options) => {
9803
+ this.requireWorkspace();
9804
+ return this.recovering(
9805
+ () => uploadSkill(this.getAuthHeaders(), slug, markdown, options)
9806
+ );
9807
+ },
9646
9808
  /**
9647
9809
  * Search documents without LLM generation (retrieval only). No `docIds` searches the whole
9648
9810
  * workspace; `searchChunks(result)` ranks the passages found.
@@ -9700,7 +9862,11 @@ var Arbi = class {
9700
9862
  invite: (emails) => inviteContacts(this.requireClient(), emails),
9701
9863
  create: (body) => this.withCalendarKeys((c2) => createContact(c2, body)),
9702
9864
  update: (contactId, card) => this.withCalendarKeys((c2) => updateContact(c2, contactId, card)),
9865
+ /** Link a card-only contact to `email` (invites it, or links the account at once). */
9866
+ link: (contactId, email, card) => this.withCalendarKeys((c2) => linkContact(c2, contactId, email, card)),
9703
9867
  delete: (contactId) => this.withCalendarKeys((c2) => deleteContact(c2, contactId)),
9868
+ /** Import one .vcf file (Pro). */
9869
+ import: (file) => this.withCalendarKeys((c2) => importContacts(c2, file)),
9704
9870
  search: (q2) => this.withCalendarKeys((c2) => searchContacts(c2, q2)),
9705
9871
  groupByStatus: groupContactsByStatus
9706
9872
  };
@@ -9803,14 +9969,36 @@ var Arbi = class {
9803
9969
  return this.chatCryptoContext;
9804
9970
  }
9805
9971
  /** Fetch a chat, sealing a new epoch first when it is `rotation_required`. */
9806
- async readyChat(chatExtId) {
9972
+ async readyChat(chat) {
9807
9973
  const client = this.requireClient();
9808
9974
  return ensureChatKeyCurrent(
9809
9975
  client,
9810
- await getChat(client, chatExtId),
9976
+ typeof chat === "string" ? await getChat(client, chat) : chat,
9811
9977
  await this.requireChatCrypto()
9812
9978
  );
9813
9979
  }
9980
+ /**
9981
+ * The keys of `chat` I hold, opened once per set of epochs: a direct chat's pair key depends on
9982
+ * the members' public keys, a group's on the epochs sealed to me.
9983
+ */
9984
+ chatRing(chat) {
9985
+ 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(",")}`;
9986
+ const cached = this.chatRings.get(chat.external_id);
9987
+ if (cached && cached.sig === sig) return cached.ring;
9988
+ const ring = this.requireChatCrypto().then((crypto2) => openChatKeyRing(chat, crypto2));
9989
+ ring.catch(() => {
9990
+ if (this.chatRings.get(chat.external_id)?.ring === ring)
9991
+ this.chatRings.delete(chat.external_id);
9992
+ });
9993
+ this.chatRings.set(chat.external_id, { sig, ring });
9994
+ return ring;
9995
+ }
9996
+ /**
9997
+ * Chats: direct (a person, myself, or my own agent), group and meeting. Every message, title and
9998
+ * attachment is end-to-end encrypted under the chat key in this process; a caller passes and
9999
+ * gets plaintext and never handles keys. Operations on an open chat take the `ChatResponse`
10000
+ * (no refetch); the by-id forms fetch it first.
10001
+ */
9814
10002
  chats = {
9815
10003
  /** My chats, most recently active first (raw: titles/last messages are ciphertext). */
9816
10004
  list: (kind) => listChats(this.requireClient(), kind),
@@ -9819,6 +10007,33 @@ var Arbi = class {
9819
10007
  openDirect: (peerExtId) => openDirectChat(this.requireClient(), peerExtId),
9820
10008
  /** Create a group (epoch 1 sealed to every member). Agents are refused. */
9821
10009
  createGroup: async (params) => createGroupChat(this.requireClient(), await this.requireChatCrypto(), params),
10010
+ /** Who I am in chats: my external id and the X25519 public key chat keys are sealed to. */
10011
+ identity: async () => {
10012
+ const crypto2 = await this.requireChatCrypto();
10013
+ return {
10014
+ externalId: crypto2.userExtId,
10015
+ publicKey: bytesToBase64(crypto2.encryptionKeypair.publicKey)
10016
+ };
10017
+ },
10018
+ /** The keys of a chat I hold (cached per set of epochs). */
10019
+ ring: (chat) => this.chatRing(chat),
10020
+ /** Make a chat postable: seal the next epoch when it is `rotation_required`. */
10021
+ ready: (chat) => this.readyChat(chat),
10022
+ /** One page of messages decrypted, oldest first; page back with `before` (the oldest id). */
10023
+ page: async (chat, options = {}) => {
10024
+ const limit = options.limit ?? CHAT_PAGE_SIZE;
10025
+ const raw = await listChatMessages(this.requireClient(), chat.external_id, {
10026
+ before: options.before,
10027
+ limit
10028
+ });
10029
+ const ring = await this.chatRing(chat);
10030
+ const messages = (await decryptChatMessages(ring, raw)).reverse();
10031
+ return { messages, hasMore: raw.length === limit };
10032
+ },
10033
+ /** Decrypt one message of `chat` (never throws: a failure is marked on the row). */
10034
+ decrypt: async (chat, message) => decryptChatMessage(await this.chatRing(chat), message),
10035
+ /** A group's title in plaintext; null when it has none or it does not open. */
10036
+ title: async (chat) => chat.title ? decryptChatTitle(await this.chatRing(chat), chat) : null,
9822
10037
  /** A chat with its keys opened, title and newest messages decrypted (oldest first). */
9823
10038
  load: async (chatExtId, options) => {
9824
10039
  const chat = await this.readyChat(chatExtId);
@@ -9829,30 +10044,50 @@ var Arbi = class {
9829
10044
  options
9830
10045
  );
9831
10046
  },
9832
- /** Post plaintext to a chat (encrypted under its current epoch). */
9833
- send: async (chatExtId, text, options) => {
9834
- const chat = await this.readyChat(chatExtId);
9835
- const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
9836
- return sendChatMessage(this.requireClient(), ring, text, options);
10047
+ /** Post plaintext to a chat (encrypted under its current epoch). Returns it decrypted. */
10048
+ send: async (chat, text, options) => {
10049
+ const ready = await this.readyChat(chat);
10050
+ return sendChatMessage(
10051
+ this.requireClient(),
10052
+ await this.chatRing(ready),
10053
+ text,
10054
+ options
10055
+ );
9837
10056
  },
9838
- rename: async (chatExtId, title) => {
9839
- const chat = await this.readyChat(chatExtId);
9840
- const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
9841
- return renameChat(this.requireClient(), ring, title);
10057
+ rename: async (chat, title) => {
10058
+ const ready = await this.readyChat(chat);
10059
+ return renameChat(this.requireClient(), await this.chatRing(ready), title);
9842
10060
  },
9843
- addMembers: async (chatExtId, members) => {
9844
- const chat = await this.readyChat(chatExtId);
9845
- const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
9846
- return addChatMembers(this.requireClient(), ring, members);
10061
+ /** Add people; a meeting chat also needs its call key, sealed to each (`callKey`). */
10062
+ addMembers: async (chat, members, options) => {
10063
+ const ready = await this.readyChat(chat);
10064
+ return addChatMembers(
10065
+ this.requireClient(),
10066
+ await this.chatRing(ready),
10067
+ members,
10068
+ options
10069
+ );
9847
10070
  },
9848
- /** Remove a member (owner) or leave (own id); a remaining member seals the next epoch. */
9849
- removeMember: async (chatExtId, userExtId) => {
10071
+ /**
10072
+ * Remove a member (owner) or leave (own id). Removing someone seals the next epoch to the rest
10073
+ * straight away; when that fails, the next member to open the chat does it.
10074
+ */
10075
+ removeMember: async (chat, userExtId) => {
10076
+ const chatExtId = typeof chat === "string" ? chat : chat.external_id;
9850
10077
  await removeChatMember(this.requireClient(), chatExtId, userExtId);
9851
10078
  const crypto2 = await this.requireChatCrypto();
9852
- if (userExtId !== crypto2.userExtId) await this.readyChat(chatExtId);
10079
+ if (userExtId === crypto2.userExtId) return;
10080
+ try {
10081
+ await this.readyChat(chatExtId);
10082
+ } catch {
10083
+ }
9853
10084
  },
9854
10085
  markRead: (chatExtId, messageExtId) => markChatRead(this.requireClient(), chatExtId, messageExtId),
9855
- deleteMessage: (chatExtId, messageExtId) => deleteChatMessage(this.requireClient(), chatExtId, messageExtId)
10086
+ deleteMessage: (chatExtId, messageExtId) => deleteChatMessage(this.requireClient(), chatExtId, messageExtId),
10087
+ /** Encrypt each file with its own key and upload the ciphertext (limits checked first). */
10088
+ uploadAttachments: (files) => uploadChatAttachments(this.requireClient(), files),
10089
+ /** Fetch, decrypt and size-check one attachment. */
10090
+ downloadAttachment: (file) => downloadChatAttachment(this.requireClient(), file)
9856
10091
  };
9857
10092
  /** Direct-chat conveniences addressed by peer (email or `usr-`/`agt-` id). */
9858
10093
  dm = {
@@ -10059,7 +10294,7 @@ var Arbi = class {
10059
10294
  sessions = {
10060
10295
  list: () => listSessions(this.requireClient()),
10061
10296
  /** The id this device's session is listed under in `list()`; `null` when unknown. */
10062
- currentId: () => currentSessionId(this.client?.session.getState().accessToken),
10297
+ currentId: () => readSessionClaims(this.client?.session.getState().accessToken)?.sessionId ?? null,
10063
10298
  /** End one of your own sessions now (not the one this device is on: that is `logout`). */
10064
10299
  terminate: (sessionId) => terminateSession(this.requireClient(), sessionId),
10065
10300
  /** Sign out of every device on the server, then clear this instance. */
@@ -10199,6 +10434,6 @@ function canTagHaveParent(tags, tagId) {
10199
10434
  return getChildTags(tags, tagId).length === 0;
10200
10435
  }
10201
10436
 
10202
- export { ACCOUNT_VENDOR, Arbi, ArbiApiError, ArbiError, DEFAULT_AI_USD_PER_GBP, DRIVE_SYNC_VENDORS, ENTITY_KINDS, FLAT_TAG_KINDS, GOOGLE_VENDORS, IMANAGE_VENDORS, MAILBOX_SYNC_VENDORS, MAX_RETRIEVE_DOC_IDS, MICROSOFT_VENDORS, PRESENCE_KINDS, PlanStepsError, PublicBookingError, SHAREPOINT_VENDORS, TAG_KINDS, TAG_NESTING_MAX_DEPTH, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, assistant_exports as assistant, authenticatedFetch, bookPublicSlot, buildCitationChunkData, 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, defaultKindForFormat, doctags_exports as doctags, documents_exports as documents, facts_exports as facts, files_exports as files, filterDocumentTags, filterSkills, flattenTagTree, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatUserName, formatWorkspaceChoices, getChildTags, getEligibleParentTags, 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, mail_exports as mail, notifications_exports as notifications, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, performPasswordLogin, 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, streamSSE, stripCitationMarkdown, summarizeCitations, tagUseCount, tags_exports as tags, tagsForScope, tagsOfGroup, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaces_exports as workspaces, wouldCreateTagCycle };
10437
+ export { ACCOUNT_VENDOR, Arbi, ArbiApiError, ArbiError, DEFAULT_AI_USD_PER_GBP, DRIVE_SYNC_VENDORS, DuplicateContactError, ENTITY_KINDS, FLAT_TAG_KINDS, GOOGLE_VENDORS, IMANAGE_VENDORS, MAILBOX_SYNC_VENDORS, MAX_RETRIEVE_DOC_IDS, MICROSOFT_VENDORS, PRESENCE_KINDS, PlanStepsError, PublicBookingError, SHAREPOINT_VENDORS, TAG_KINDS, TAG_NESTING_MAX_DEPTH, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, assistant_exports as assistant, authenticatedFetch, bookPublicSlot, buildCitationChunkData, 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, defaultKindForFormat, doctags_exports as doctags, documents_exports as documents, facts_exports as facts, files_exports as files, filterDocumentTags, filterSkills, flattenTagTree, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatUserName, formatWorkspaceChoices, getChildTags, getEligibleParentTags, 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, mail_exports as mail, notifications_exports as notifications, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, performPasswordLogin, 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, streamSSE, stripCitationMarkdown, summarizeCitations, tagUseCount, tags_exports as tags, tagsForScope, tagsOfGroup, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaces_exports as workspaces, wouldCreateTagCycle };
10203
10438
  //# sourceMappingURL=browser.js.map
10204
10439
  //# sourceMappingURL=browser.js.map