@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/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 {
@@ -5465,12 +5485,14 @@ async function suggestSignatureFields(arbi, docId, version) {
5465
5485
  return data.fields;
5466
5486
  }
5467
5487
  function assignSuggestions(suggestions, signers) {
5468
- const groups = [...new Set(suggestions.map((s2) => s2.group))];
5488
+ const groups = [...new Set(suggestions.filter((s2) => !s2.signer_email).map((s2) => s2.group))];
5469
5489
  return suggestions.flatMap((s2, i2) => {
5470
- const signer = signers[groups.indexOf(s2.group)];
5490
+ const signer = s2.signer_email ?? signers[groups.indexOf(s2.group)];
5471
5491
  if (!signer) return [];
5472
5492
  const { type, page, x: x2, y: y2, width, height } = s2;
5473
- return [{ id: `s${i2 + 1}`, type, page, x: x2, y: y2, width, height, signer, required: true }];
5493
+ return [
5494
+ { id: `s${i2 + 1}`, type, page, x: x2, y: y2, width, height, signer, required: s2.required ?? true }
5495
+ ];
5474
5496
  });
5475
5497
  }
5476
5498
  async function createSignatureRequest(arbi, docId, { fields, version, message, send = true }) {
@@ -5664,10 +5686,13 @@ async function grantTemporaryWorkspaceAccess(arbi, params) {
5664
5686
  "Failed to grant temporary access"
5665
5687
  );
5666
5688
  }
5667
- async function removeWorkspaceUsers(arbi, userIds) {
5689
+ async function removeWorkspaceUsers(arbi, userIds, workspaceExtId) {
5668
5690
  requireOk(
5669
5691
  await arbi.fetch.DELETE("/v1/workspace/users", {
5670
- 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
+ }
5671
5696
  }),
5672
5697
  "Failed to remove users"
5673
5698
  );
@@ -5974,7 +5999,7 @@ async function listSkills(arbi, options) {
5974
5999
  return result.skills;
5975
6000
  }
5976
6001
  function isSharedSkill(skill) {
5977
- return skill.is_owner !== false && skill.visibility === "global";
6002
+ return (skill.is_owner ?? true) && skill.visibility === "global";
5978
6003
  }
5979
6004
  function uploadSkill(auth, slug, markdown, options) {
5980
6005
  return uploadFile(auth, new Blob([markdown], { type: "text/markdown" }), "SKILL.md", {
@@ -6246,11 +6271,23 @@ __export(contacts_exports, {
6246
6271
  createContact: () => createContact,
6247
6272
  deleteContact: () => deleteContact,
6248
6273
  groupContactsByStatus: () => groupContactsByStatus,
6274
+ importContacts: () => importContacts,
6249
6275
  inviteContacts: () => inviteContacts,
6276
+ linkContact: () => linkContact,
6250
6277
  listContacts: () => listContacts,
6251
6278
  searchContacts: () => searchContacts,
6252
6279
  updateContact: () => updateContact
6253
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
+ }
6254
6291
  async function listContacts(arbi) {
6255
6292
  return requireData(await arbi.fetch.GET("/v1/contacts/"), "Failed to fetch contacts");
6256
6293
  }
@@ -6261,10 +6298,13 @@ async function inviteContacts(arbi, emails) {
6261
6298
  );
6262
6299
  }
6263
6300
  async function createContact(arbi, body) {
6264
- 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
+ );
6265
6305
  }
6266
6306
  async function updateContact(arbi, contactId, card) {
6267
- return requireData(
6307
+ return requireContact(
6268
6308
  await arbi.fetch.PATCH("/v1/contacts/{cnt_id}", {
6269
6309
  params: { path: { cnt_id: contactId } },
6270
6310
  body: { card, invite: false }
@@ -6272,12 +6312,32 @@ async function updateContact(arbi, contactId, card) {
6272
6312
  "Failed to update contact"
6273
6313
  );
6274
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
+ }
6275
6324
  async function deleteContact(arbi, contactId) {
6276
6325
  requireOk(
6277
6326
  await arbi.fetch.DELETE("/v1/contacts/{cnt_id}", { params: { path: { cnt_id: contactId } } }),
6278
6327
  "Failed to delete contact"
6279
6328
  );
6280
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
+ }
6281
6341
  async function searchContacts(arbi, q2) {
6282
6342
  return requireData(
6283
6343
  await arbi.fetch.GET("/v1/contacts/search", { params: { query: { q: q2 } } }),
@@ -6349,8 +6409,11 @@ var chats_exports = {};
6349
6409
  __export(chats_exports, {
6350
6410
  CHAT_ATTACHMENT_MAX_BYTES: () => CHAT_ATTACHMENT_MAX_BYTES,
6351
6411
  CHAT_ATTACHMENT_MAX_FILES: () => CHAT_ATTACHMENT_MAX_FILES,
6412
+ CHAT_PAGE_SIZE: () => CHAT_PAGE_SIZE,
6352
6413
  DECRYPTION_FAILED: () => DECRYPTION_FAILED,
6414
+ ENCRYPTED_PREVIEW: () => ENCRYPTED_PREVIEW,
6353
6415
  addChatMembers: () => addChatMembers,
6416
+ chatMessagePreview: () => chatMessagePreview,
6354
6417
  chatMessageTombstone: () => chatMessageTombstone,
6355
6418
  checkChatAttachmentLimits: () => checkChatAttachmentLimits,
6356
6419
  createChatCryptoContext: () => createChatCryptoContext,
@@ -6367,6 +6430,7 @@ __export(chats_exports, {
6367
6430
  getChat: () => getChat,
6368
6431
  hasRead: () => hasRead,
6369
6432
  isAgentExtId: () => isAgentExtId,
6433
+ isTranscriptMessage: () => isTranscriptMessage,
6370
6434
  listChatMessages: () => listChatMessages,
6371
6435
  listChats: () => listChats,
6372
6436
  loadDecryptedChat: () => loadDecryptedChat,
@@ -6374,6 +6438,8 @@ __export(chats_exports, {
6374
6438
  openChatKeyRing: () => openChatKeyRing,
6375
6439
  openDirectChat: () => openDirectChat,
6376
6440
  parseChatAttachmentManifest: () => parseChatAttachmentManifest,
6441
+ parseTranscriptContent: () => parseTranscriptContent,
6442
+ readByOthers: () => readByOthers,
6377
6443
  removeChatMember: () => removeChatMember,
6378
6444
  renameChat: () => renameChat,
6379
6445
  resolveRecipient: () => resolveRecipient,
@@ -6670,6 +6736,39 @@ function chatMessageTombstone(message) {
6670
6736
  delete row.attachmentsError;
6671
6737
  return row;
6672
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
+ }
6673
6772
  async function decryptChatMessage(ring, message) {
6674
6773
  if (message.deleted) return chatMessageTombstone(message);
6675
6774
  const key = ring.keys.get(message.key_version);
@@ -6770,12 +6869,18 @@ async function renameChat(arbi, ring, title) {
6770
6869
  "Failed to rename chat"
6771
6870
  );
6772
6871
  }
6773
- async function addChatMembers(arbi, ring, members) {
6872
+ async function addChatMembers(arbi, ring, members, options = {}) {
6774
6873
  if (ring.kind === "direct") {
6775
6874
  throw new Error("A direct chat cannot gain members: create a group instead");
6776
6875
  }
6777
6876
  if (members.some((m2) => isAgentExtId(m2.external_id))) {
6778
- 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");
6779
6884
  }
6780
6885
  const key = keyFor(ring, ring.currentVersion);
6781
6886
  return requireData(
@@ -6785,7 +6890,8 @@ async function addChatMembers(arbi, ring, members) {
6785
6890
  members: await Promise.all(
6786
6891
  members.map(async (m2) => ({
6787
6892
  user_ext_id: m2.external_id,
6788
- 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) } : {}
6789
6895
  }))
6790
6896
  )
6791
6897
  }
@@ -6838,6 +6944,7 @@ async function ensureChatKeyCurrent(arbi, chat, crypto2) {
6838
6944
  throw err;
6839
6945
  }
6840
6946
  }
6947
+ var CHAT_PAGE_SIZE = 50;
6841
6948
  async function listChatMessages(arbi, chatExtId, options) {
6842
6949
  return requireData(
6843
6950
  await arbi.fetch.GET("/v1/chats/{chat_ext_id}/messages", {
@@ -6900,6 +7007,10 @@ function hasRead(member, message) {
6900
7007
  if (!member?.last_read_at) return false;
6901
7008
  return Date.parse(member.last_read_at) >= Date.parse(message.created_at);
6902
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
+ }
6903
7014
  async function resolveRecipient(arbi, ref) {
6904
7015
  const isEmail = ref.includes("@");
6905
7016
  const matchKey = isEmail ? "email" : "external_id";
@@ -7441,7 +7552,6 @@ async function getFileContent(auth, fileId) {
7441
7552
  // src/operations/sessions.ts
7442
7553
  var sessions_exports = {};
7443
7554
  __export(sessions_exports, {
7444
- currentSessionId: () => currentSessionId,
7445
7555
  listSessions: () => listSessions,
7446
7556
  logoutAllSessions: () => logoutAllSessions,
7447
7557
  terminateSession: () => terminateSession
@@ -7464,16 +7574,6 @@ async function logoutAllSessions(arbi) {
7464
7574
  "Failed to sign out of all sessions"
7465
7575
  );
7466
7576
  }
7467
- function currentSessionId(accessToken) {
7468
- const payload = accessToken?.split(".")[1];
7469
- if (!payload) return null;
7470
- try {
7471
- const claims = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/")));
7472
- return typeof claims.sk === "string" ? claims.sk.slice(0, 12) : null;
7473
- } catch {
7474
- return null;
7475
- }
7476
- }
7477
7577
 
7478
7578
  // src/operations/profile.ts
7479
7579
  var profile_exports = {};
@@ -7511,9 +7611,13 @@ async function topUpFirmPool(arbi, aiAddons) {
7511
7611
  var account_exports = {};
7512
7612
  __export(account_exports, {
7513
7613
  confirmEmailChange: () => confirmEmailChange,
7614
+ getEntitlements: () => getEntitlements,
7514
7615
  requestDeletion: () => requestDeletion,
7515
7616
  requestEmailChange: () => requestEmailChange
7516
7617
  });
7618
+ async function getEntitlements(arbi) {
7619
+ return requireData(await arbi.fetch.GET("/v1/user/entitlements"), "Failed to load entitlements");
7620
+ }
7517
7621
  async function requestEmailChange(arbi, newEmail) {
7518
7622
  requireOk(
7519
7623
  await arbi.fetch.POST("/v1/user/request-email-change", { body: { new_email: newEmail } }),
@@ -9420,15 +9524,8 @@ async function cancelPublicBooking(baseUrl, slug, token) {
9420
9524
 
9421
9525
  // src/arbi.ts
9422
9526
  function tokenExpiresWithin(token, seconds) {
9423
- const payload = token?.split(".")[1];
9424
- if (!payload) return false;
9425
- try {
9426
- const json2 = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
9427
- const { exp } = JSON.parse(json2);
9428
- return typeof exp === "number" && exp * 1e3 - Date.now() < seconds * 1e3;
9429
- } catch {
9430
- return false;
9431
- }
9527
+ const expiresAt = readSessionClaims(token)?.expiresAt;
9528
+ return expiresAt != null && expiresAt - Date.now() < seconds * 1e3;
9432
9529
  }
9433
9530
  var Arbi = class {
9434
9531
  client = null;
@@ -9438,7 +9535,12 @@ var Arbi = class {
9438
9535
  currentWorkspaceId = null;
9439
9536
  /** Wrapped workspace keys seen in the last list/create, so selecting needs no re-fetch. */
9440
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;
9441
9541
  chatCryptoContext = null;
9542
+ /** The chat keys I hold, opened once per set of epochs (`chatRingSignature`). */
9543
+ chatRings = /* @__PURE__ */ new Map();
9442
9544
  sessionExpiredListeners = /* @__PURE__ */ new Set();
9443
9545
  options;
9444
9546
  constructor(options) {
@@ -9574,9 +9676,41 @@ var Arbi = class {
9574
9676
  );
9575
9677
  }
9576
9678
  /**
9577
- * Select a workspace by ID. Uses the wrapped key from the last workspace list or create (the
9578
- * list is fetched only when the workspace is not known yet), decrypts it, and opens the
9579
- * 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.
9580
9714
  */
9581
9715
  async selectWorkspace(workspaceId) {
9582
9716
  const client = this.requireClient();
@@ -9617,6 +9751,7 @@ var Arbi = class {
9617
9751
  this.currentWorkspaceId = null;
9618
9752
  this.wrappedKeys.clear();
9619
9753
  this.chatCryptoContext = null;
9754
+ this.chatRings.clear();
9620
9755
  this.client?.session.clear();
9621
9756
  for (const listener of [...this.sessionExpiredListeners]) listener();
9622
9757
  }
@@ -9663,6 +9798,7 @@ var Arbi = class {
9663
9798
  this.currentWorkspaceId = null;
9664
9799
  this.wrappedKeys.clear();
9665
9800
  this.chatCryptoContext = null;
9801
+ this.chatRings.clear();
9666
9802
  }
9667
9803
  // ── Accessors ─────────────────────────────────────────────────────────
9668
9804
  /** Get the underlying ArbiClient (throws if not initialized). */
@@ -9803,6 +9939,8 @@ var Arbi = class {
9803
9939
  };
9804
9940
  // ── Account ───────────────────────────────────────────────────────────
9805
9941
  account = {
9942
+ /** Which paid features (native mail, the calendar, hosting calls) this person may use, and why not. */
9943
+ entitlements: () => getEntitlements(this.requireClient()),
9806
9944
  /** Send a verification code to the new address (not for SSO accounts). */
9807
9945
  requestEmailChange: (newEmail) => requestEmailChange(this.requireClient(), newEmail),
9808
9946
  /** Confirm the email change with the emailed code; the session and profile follow. */
@@ -9883,6 +10021,13 @@ var Arbi = class {
9883
10021
  }
9884
10022
  // ── Workspaces ────────────────────────────────────────────────────────
9885
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),
9886
10031
  /** Hand this server session a workspace's key (sealed to the session) without opening it. */
9887
10032
  primeKey: (workspaceExtId, sessionSealedKey) => primeWorkspaceKey(this.requireClient(), workspaceExtId, sessionSealedKey),
9888
10033
  list: async () => this.rememberWorkspaces(await listWorkspaces(this.requireClient())),
@@ -9950,7 +10095,12 @@ var Arbi = class {
9950
10095
  workspaceExtId: params.workspaceId,
9951
10096
  workspaceKey: await this.sealWorkspaceKey(params.workspaceId)
9952
10097
  }),
9953
- 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
+ ),
9954
10104
  setUserRole: (userIds, role) => setUserRole(this.requireClient(), userIds, role),
9955
10105
  /**
9956
10106
  * Ask another user to grant you workspace access. Builds the E2E-encrypted
@@ -9980,7 +10130,11 @@ var Arbi = class {
9980
10130
  };
9981
10131
  // ── Documents ─────────────────────────────────────────────────────────
9982
10132
  documents = {
9983
- 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
+ ),
9984
10138
  /**
9985
10139
  * Async iterator that yields pages of documents sequentially.
9986
10140
  * Use this for large workspaces to stream output as pages arrive.
@@ -10233,6 +10387,16 @@ var Arbi = class {
10233
10387
  respond: (assistantMessageExtId, answer) => respondToAgent(this.requireClient(), assistantMessageExtId, answer),
10234
10388
  /** The skills the caller can run (own + shared marketplace), metadata only. */
10235
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
+ },
10236
10400
  /**
10237
10401
  * Search documents without LLM generation (retrieval only). No `docIds` searches the whole
10238
10402
  * workspace; `searchChunks(result)` ranks the passages found.
@@ -10290,7 +10454,11 @@ var Arbi = class {
10290
10454
  invite: (emails) => inviteContacts(this.requireClient(), emails),
10291
10455
  create: (body) => this.withCalendarKeys((c2) => createContact(c2, body)),
10292
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)),
10293
10459
  delete: (contactId) => this.withCalendarKeys((c2) => deleteContact(c2, contactId)),
10460
+ /** Import one .vcf file (Pro). */
10461
+ import: (file) => this.withCalendarKeys((c2) => importContacts(c2, file)),
10294
10462
  search: (q2) => this.withCalendarKeys((c2) => searchContacts(c2, q2)),
10295
10463
  groupByStatus: groupContactsByStatus
10296
10464
  };
@@ -10393,14 +10561,36 @@ var Arbi = class {
10393
10561
  return this.chatCryptoContext;
10394
10562
  }
10395
10563
  /** Fetch a chat, sealing a new epoch first when it is `rotation_required`. */
10396
- async readyChat(chatExtId) {
10564
+ async readyChat(chat) {
10397
10565
  const client = this.requireClient();
10398
10566
  return ensureChatKeyCurrent(
10399
10567
  client,
10400
- await getChat(client, chatExtId),
10568
+ typeof chat === "string" ? await getChat(client, chat) : chat,
10401
10569
  await this.requireChatCrypto()
10402
10570
  );
10403
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
+ */
10404
10594
  chats = {
10405
10595
  /** My chats, most recently active first (raw: titles/last messages are ciphertext). */
10406
10596
  list: (kind) => listChats(this.requireClient(), kind),
@@ -10409,6 +10599,33 @@ var Arbi = class {
10409
10599
  openDirect: (peerExtId) => openDirectChat(this.requireClient(), peerExtId),
10410
10600
  /** Create a group (epoch 1 sealed to every member). Agents are refused. */
10411
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,
10412
10629
  /** A chat with its keys opened, title and newest messages decrypted (oldest first). */
10413
10630
  load: async (chatExtId, options) => {
10414
10631
  const chat = await this.readyChat(chatExtId);
@@ -10419,30 +10636,50 @@ var Arbi = class {
10419
10636
  options
10420
10637
  );
10421
10638
  },
10422
- /** Post plaintext to a chat (encrypted under its current epoch). */
10423
- send: async (chatExtId, text, options) => {
10424
- const chat = await this.readyChat(chatExtId);
10425
- const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
10426
- 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
+ );
10427
10648
  },
10428
- rename: async (chatExtId, title) => {
10429
- const chat = await this.readyChat(chatExtId);
10430
- const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
10431
- 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);
10432
10652
  },
10433
- addMembers: async (chatExtId, members) => {
10434
- const chat = await this.readyChat(chatExtId);
10435
- const ring = await openChatKeyRing(chat, await this.requireChatCrypto());
10436
- 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
+ );
10437
10662
  },
10438
- /** Remove a member (owner) or leave (own id); a remaining member seals the next epoch. */
10439
- 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;
10440
10669
  await removeChatMember(this.requireClient(), chatExtId, userExtId);
10441
10670
  const crypto2 = await this.requireChatCrypto();
10442
- if (userExtId !== crypto2.userExtId) await this.readyChat(chatExtId);
10671
+ if (userExtId === crypto2.userExtId) return;
10672
+ try {
10673
+ await this.readyChat(chatExtId);
10674
+ } catch {
10675
+ }
10443
10676
  },
10444
10677
  markRead: (chatExtId, messageExtId) => markChatRead(this.requireClient(), chatExtId, messageExtId),
10445
- 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)
10446
10683
  };
10447
10684
  /** Direct-chat conveniences addressed by peer (email or `usr-`/`agt-` id). */
10448
10685
  dm = {
@@ -10649,7 +10886,7 @@ var Arbi = class {
10649
10886
  sessions = {
10650
10887
  list: () => listSessions(this.requireClient()),
10651
10888
  /** The id this device's session is listed under in `list()`; `null` when unknown. */
10652
- currentId: () => currentSessionId(this.client?.session.getState().accessToken),
10889
+ currentId: () => readSessionClaims(this.client?.session.getState().accessToken)?.sessionId ?? null,
10653
10890
  /** End one of your own sessions now (not the one this device is on: that is `logout`). */
10654
10891
  terminate: (sessionId) => terminateSession(this.requireClient(), sessionId),
10655
10892
  /** Sign out of every device on the server, then clear this instance. */
@@ -11862,6 +12099,6 @@ async function startDmListener(options) {
11862
12099
  };
11863
12100
  }
11864
12101
 
11865
- 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 };
11866
12103
  //# sourceMappingURL=index.js.map
11867
12104
  //# sourceMappingURL=index.js.map