@arbidocs/sdk 0.5.68 → 0.5.70

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 path3, { dirname, resolve } from 'path';
3
3
  import os2 from 'os';
4
- import { createArbiClient, base64ToBytes, unwrapWorkspaceKey, sealKeyForSession, buildWebSocketUrl, createAuthMessage, parseServerMessage, isMessageType, createContentHash, encryptFile, initSodium, encryptionKeypairFromSigningKey, sealedBoxEncrypt, sealedBoxDecrypt, bytesToBase64, encryptWithChatKey, decryptWithChatKey, decryptFile, deriveDirectChatKey, openSealedChatKey, generateChatKey, sealChatKey, sealCallKey, encryptMessage, decodeSecureMailKey, openSecureMail, secureMailClaim, createSessionManager, authRequestError, isAbortError, changePassword, openCallKeyOf, decryptCallTitle, generateCallKey, encryptCallTitle, sealCallKeyForPeers, openSealedCallKey, readSessionClaims } from '@arbidocs/client';
4
+ import { createArbiClient, base64ToBytes, unwrapWorkspaceKey, sealKeyForSession, buildWebSocketUrl, createAuthMessage, parseServerMessage, isMessageType, createContentHash, encryptFile, initSodium, encryptionKeypairFromSigningKey, sealedBoxEncrypt, sealedBoxDecrypt, bytesToBase64, sealSecureMail, decodeSecureMailKey, openSecureMail, secureMailClaim, encryptWithChatKey, decryptWithChatKey, decryptFile, deriveDirectChatKey, openSealedChatKey, generateChatKey, sealChatKey, sealCallKey, encryptMessage, createSessionManager, authRequestError, isAbortError, changePassword, openCallKeyOf, decryptCallTitle, generateCallKey, encryptCallTitle, sealCallKeyForPeers, openSealedCallKey, readSessionClaims } from '@arbidocs/client';
5
5
  import { execSync, spawn } from 'child_process';
6
6
  import { createHash } from 'crypto';
7
7
  import { fileURLToPath } from 'url';
@@ -6013,16 +6013,40 @@ async function updateDocuments(arbi, documents) {
6013
6013
  "Failed to update documents"
6014
6014
  );
6015
6015
  }
6016
- async function uploadUrl(arbi, urls, shared = false, configExtId) {
6017
- return requireData(
6016
+ async function uploadUrl(arbi, urls, options) {
6017
+ return requireUploadData(
6018
6018
  await arbi.fetch.POST("/v1/document/upload-url", {
6019
6019
  params: {
6020
- query: { urls, shared, ...configExtId ? { config_ext_id: configExtId } : {} }
6020
+ query: {
6021
+ urls,
6022
+ shared: options.shared ?? false,
6023
+ workspace_ext_id: options.workspaceExtId,
6024
+ ...options.configExtId ? { config_ext_id: options.configExtId } : {}
6025
+ }
6021
6026
  }
6022
6027
  }),
6023
6028
  "Failed to upload from URLs"
6024
6029
  );
6025
6030
  }
6031
+ var UPLOAD_WORKSPACE_CONFLICT_MESSAGES = {
6032
+ workspace_mismatch: "These files were prepared for another workspace, so they were not saved. Upload them again.",
6033
+ workspace_key_required: "The workspace couldn't be unlocked for this upload, so the files were not saved."
6034
+ };
6035
+ function requireUploadData(result, message) {
6036
+ const status = result.response?.status;
6037
+ const conflict = result.error && status === 409 ? workspaceConflictOf(result.error) : null;
6038
+ if (conflict) {
6039
+ throw new ArbiApiError(
6040
+ UPLOAD_WORKSPACE_CONFLICT_MESSAGES[conflict.code],
6041
+ result.error,
6042
+ status,
6043
+ {
6044
+ code: conflict.code
6045
+ }
6046
+ );
6047
+ }
6048
+ return requireData(result, message);
6049
+ }
6026
6050
  async function uploadDocuments(arbi, files, options = {}) {
6027
6051
  const query2 = {};
6028
6052
  if (options.shared !== void 0) query2.shared = options.shared;
@@ -6047,7 +6071,7 @@ async function uploadDocuments(arbi, files, options = {}) {
6047
6071
  return form;
6048
6072
  }
6049
6073
  });
6050
- return requireData(result, "Failed to upload documents");
6074
+ return requireUploadData(result, "Failed to upload documents");
6051
6075
  }
6052
6076
  async function similarDocuments(arbi, options = {}) {
6053
6077
  return requireData(
@@ -6204,6 +6228,9 @@ async function presignedPut(url, body, onProgress, headers) {
6204
6228
  }
6205
6229
  }
6206
6230
  async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
6231
+ if (!options?.workspaceExtId) {
6232
+ throw new ArbiError("uploadDocumentsDirect needs options.workspaceExtId (the key's workspace)");
6233
+ }
6207
6234
  if (files.length === 0) return { doc_ext_ids: [], skipped: [] };
6208
6235
  const SECRETBOX_ENVELOPE_OVERHEAD = 40;
6209
6236
  const declared = files.map((f2) => ({
@@ -6215,21 +6242,19 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
6215
6242
  }));
6216
6243
  const initBody = {
6217
6244
  files: declared,
6218
- shared: options?.shared !== false,
6219
- config_ext_id: options?.configExtId ?? null,
6245
+ shared: options.shared !== false,
6246
+ config_ext_id: options.configExtId ?? null,
6220
6247
  // Only sent when set, so a plain upload is accepted by any server version.
6221
- ...options?.versionOf ? { version_of: options.versionOf } : {},
6222
- wp_type: options?.wpType ?? null,
6223
- tag_ext_id: options?.tagExtId ?? null,
6224
- folder: options?.folder ? sanitizeFolderPath(options.folder) : null,
6225
- presign_expires_in: options?.presignExpiresIn ?? 3600
6248
+ ...options.versionOf ? { version_of: options.versionOf } : {},
6249
+ wp_type: options.wpType ?? null,
6250
+ tag_ext_id: options.tagExtId ?? null,
6251
+ folder: options.folder ? sanitizeFolderPath(options.folder) : null,
6252
+ presign_expires_in: options.presignExpiresIn ?? 3600
6226
6253
  };
6227
- const guarded = options?.inWorkspace ?? ((send) => send());
6228
- const initResult = await guarded(
6229
- async () => requireData(
6230
- await arbi.fetch.POST("/v1/document/upload-init", { body: initBody }),
6231
- "Failed to initialize direct upload"
6232
- )
6254
+ const query2 = { workspace_ext_id: options.workspaceExtId };
6255
+ const initResult = requireUploadData(
6256
+ await arbi.fetch.POST("/v1/document/upload-init", { params: { query: query2 }, body: initBody }),
6257
+ "Failed to initialize direct upload"
6233
6258
  );
6234
6259
  const items = initResult.items ?? [];
6235
6260
  const bytesByName = /* @__PURE__ */ new Map();
@@ -6263,7 +6288,7 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
6263
6288
  const total = ciphertext.length;
6264
6289
  try {
6265
6290
  await presignedPut(item.upload_url, ciphertext, (loaded, putTotal) => {
6266
- options?.onBytesProgress?.({
6291
+ options.onBytesProgress?.({
6267
6292
  fileIndex,
6268
6293
  fileName: item.file_name,
6269
6294
  loaded,
@@ -6275,7 +6300,7 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
6275
6300
  `Presigned PUT for ${item.doc_ext_id} failed: ${err instanceof Error ? err.message : String(err)}`
6276
6301
  );
6277
6302
  }
6278
- options?.onBytesProgress?.({
6303
+ options.onBytesProgress?.({
6279
6304
  fileIndex,
6280
6305
  fileName: item.file_name,
6281
6306
  loaded: total,
@@ -6286,16 +6311,15 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
6286
6311
  if (toCommit.length === 0) {
6287
6312
  return { doc_ext_ids: [], skipped };
6288
6313
  }
6289
- const commitResult = await guarded(
6290
- async () => requireData(
6291
- await arbi.fetch.POST("/v1/document/upload-commit", {
6292
- body: {
6293
- doc_ext_ids: toCommit,
6294
- tag_ext_id: options?.tagExtId ?? null
6295
- }
6296
- }),
6297
- "Failed to commit direct upload"
6298
- )
6314
+ const commitResult = requireUploadData(
6315
+ await arbi.fetch.POST("/v1/document/upload-commit", {
6316
+ params: { query: query2 },
6317
+ body: {
6318
+ doc_ext_ids: toCommit,
6319
+ tag_ext_id: options.tagExtId ?? null
6320
+ }
6321
+ }),
6322
+ "Failed to commit direct upload"
6299
6323
  );
6300
6324
  return {
6301
6325
  doc_ext_ids: commitResult.doc_ext_ids ?? [],
@@ -6543,6 +6567,130 @@ async function unlockModelConnections(arbi, keys, onlyId) {
6543
6567
  }
6544
6568
  }
6545
6569
 
6570
+ // src/operations/secure-mail.ts
6571
+ var secure_mail_exports = {};
6572
+ __export(secure_mail_exports, {
6573
+ claimSecureMail: () => claimSecureMail,
6574
+ prepareSecureMail: () => prepareSecureMail,
6575
+ secureMime: () => secureMime
6576
+ });
6577
+ var MAX_MESSAGE_BYTES = 25 * 1024 * 1024;
6578
+ var utf8 = new TextEncoder();
6579
+ var encodedWord = (value) => `=?UTF-8?B?${bytesToBase64(utf8.encode(value))}?=`;
6580
+ var folded = (value) => value.match(/.{1,76}/g)?.join("\r\n") ?? "";
6581
+ var safeHeader = (value) => {
6582
+ if (/[\r\n\0]/.test(value)) throw new Error("Email headers cannot contain newlines");
6583
+ return value;
6584
+ };
6585
+ function secureMime(compose, sender) {
6586
+ const address = (r2) => `${r2.name ? encodedWord(safeHeader(r2.name)) + " " : ""}<${safeHeader(r2.email)}>`;
6587
+ const boundary = "arbi-" + crypto.randomUUID();
6588
+ const headers = [
6589
+ `From: ${address({ email: sender.email, name: sender.display_name })}`,
6590
+ ...compose.to.length ? [`To: ${compose.to.map(address).join(", ")}`] : [],
6591
+ ...compose.cc.length ? [`Cc: ${compose.cc.map(address).join(", ")}`] : [],
6592
+ `Subject: ${encodedWord(safeHeader(compose.subject))}`,
6593
+ `Date: ${(/* @__PURE__ */ new Date()).toUTCString()}`,
6594
+ `Message-ID: <${crypto.randomUUID()}@${sender.email.split("@")[1]}>`,
6595
+ ...compose.in_reply_to ? [`In-Reply-To: ${safeHeader(compose.in_reply_to)}`] : [],
6596
+ ...compose.references?.length ? [`References: ${compose.references.map(safeHeader).join(" ")}`] : [],
6597
+ "MIME-Version: 1.0",
6598
+ "X-ARBI-Secure-Delivery: 1",
6599
+ `Content-Type: multipart/mixed; boundary="${boundary}"`
6600
+ ];
6601
+ const alternative = "alternative-" + crypto.randomUUID();
6602
+ const plainPart = `Content-Type: text/plain; charset="utf-8"\r
6603
+ Content-Transfer-Encoding: base64\r
6604
+ \r
6605
+ ${folded(bytesToBase64(utf8.encode(compose.text)))}`;
6606
+ const bodyPart = compose.html ? `Content-Type: multipart/alternative; boundary="${alternative}"\r
6607
+ \r
6608
+ --${alternative}\r
6609
+ ${plainPart}\r
6610
+ --${alternative}\r
6611
+ Content-Type: text/html; charset="utf-8"\r
6612
+ Content-Transfer-Encoding: base64\r
6613
+ \r
6614
+ ${folded(bytesToBase64(utf8.encode(compose.html)))}\r
6615
+ --${alternative}--\r
6616
+ ` : plainPart;
6617
+ const parts = [
6618
+ `--${boundary}\r
6619
+ ${bodyPart}`,
6620
+ ...compose.attachments.map((a2) => {
6621
+ if (!a2.content_base64) throw new Error("Attachment content is missing");
6622
+ const name = encodeURIComponent(safeHeader(a2.name)).replace(/'/g, "%27");
6623
+ return `--${boundary}\r
6624
+ Content-Type: ${safeHeader(a2.content_type || "application/octet-stream")}\r
6625
+ Content-Disposition: attachment; filename*=UTF-8''${name}\r
6626
+ Content-Transfer-Encoding: base64\r
6627
+ \r
6628
+ ${folded(a2.content_base64)}`;
6629
+ }),
6630
+ `--${boundary}--\r
6631
+ `
6632
+ ];
6633
+ return utf8.encode(headers.join("\r\n") + "\r\n\r\n" + parts.join("\r\n"));
6634
+ }
6635
+ async function prepareSecureMail(compose, sender, { requestId, senderPublicKey, frontendOrigin }) {
6636
+ const raw = secureMime(compose, sender);
6637
+ try {
6638
+ if (raw.length > MAX_MESSAGE_BYTES) throw new Error("Email exceeds the message size limit");
6639
+ const metadata = {
6640
+ secure_delivery: true,
6641
+ id: "",
6642
+ subject: compose.subject,
6643
+ sender: [{ email: sender.email, name: sender.display_name }],
6644
+ to: compose.to,
6645
+ cc: compose.cc,
6646
+ bcc: [],
6647
+ received_at: (/* @__PURE__ */ new Date()).toISOString(),
6648
+ preview: compose.text.slice(0, 220),
6649
+ unread: false,
6650
+ text: "",
6651
+ references: compose.references ?? [],
6652
+ attachments: compose.attachments.map((a2, i2) => ({
6653
+ ...a2,
6654
+ id: String(i2),
6655
+ content_base64: null
6656
+ }))
6657
+ };
6658
+ const recipients = [
6659
+ ...new Set([...compose.to, ...compose.cc, ...compose.bcc].map((r2) => r2.email.toLowerCase()))
6660
+ ];
6661
+ const sealed = await sealSecureMail(raw, metadata, senderPublicKey);
6662
+ return {
6663
+ request_id: requestId,
6664
+ draft_id: compose.draft_id,
6665
+ recipients: recipients.map((email) => ({
6666
+ id: crypto.randomUUID(),
6667
+ email,
6668
+ fragment_key: sealed.fragment_key
6669
+ })),
6670
+ ciphertext: sealed.ciphertext,
6671
+ metadata_ciphertext: sealed.metadata_ciphertext,
6672
+ sender_wrapped_key: sealed.sender_wrapped_key,
6673
+ frontend_origin: frontendOrigin
6674
+ };
6675
+ } finally {
6676
+ raw.fill(0);
6677
+ }
6678
+ }
6679
+ async function claimSecureMail(mail, id, fragmentKey, recipientPublicKey) {
6680
+ const key = decodeSecureMailKey(fragmentKey);
6681
+ try {
6682
+ const path5 = `/secure/${encodeURIComponent(id)}`;
6683
+ const response = await mail(path5);
6684
+ const { raw } = await openSecureMail(await response.json(), key);
6685
+ raw.fill(0);
6686
+ const claim = await secureMailClaim(key, recipientPublicKey);
6687
+ const claimed = await mail(`${path5}/claim`, { method: "POST", body: JSON.stringify(claim) });
6688
+ return await claimed.json();
6689
+ } finally {
6690
+ key.fill(0);
6691
+ }
6692
+ }
6693
+
6546
6694
  // src/operations/workspaces.ts
6547
6695
  var workspaces_exports = {};
6548
6696
  __export(workspaces_exports, {
@@ -10201,7 +10349,6 @@ __export(mail_exports, {
10201
10349
  NATIVE_ACCOUNT: () => NATIVE_ACCOUNT,
10202
10350
  attachmentFromBytes: () => attachmentFromBytes,
10203
10351
  claimNativeAlias: () => claimNativeAlias,
10204
- claimSecureMail: () => claimSecureMail,
10205
10352
  createMailFetch: () => createMailFetch,
10206
10353
  downloadAttachment: () => downloadAttachment,
10207
10354
  getMailPolicy: () => getMailPolicy,
@@ -10307,28 +10454,16 @@ async function unlockNativeMail(mail, keys) {
10307
10454
  secretKey.fill(0);
10308
10455
  }
10309
10456
  }
10310
- async function claimSecureMail(mail, id, fragmentKey, recipientPublicKey) {
10311
- const key = decodeSecureMailKey(fragmentKey);
10312
- try {
10313
- const path5 = `/secure/${encodeURIComponent(id)}`;
10314
- const { raw } = await openSecureMail(await json(mail(path5)), key);
10315
- raw.fill(0);
10316
- const claim = await secureMailClaim(key, recipientPublicKey);
10317
- return await json(mail(`${path5}/claim`, { method: "POST", body: JSON.stringify(claim) }));
10318
- } finally {
10319
- key.fill(0);
10320
- }
10321
- }
10322
10457
  function attachmentFromBytes(name, contentType, bytes) {
10323
10458
  return {
10324
10459
  id: "",
10325
10460
  name,
10326
10461
  content_type: contentType,
10327
10462
  size: bytes.length,
10328
- content_base64: bytesToBase643(bytes)
10463
+ content_base64: bytesToBase644(bytes)
10329
10464
  };
10330
10465
  }
10331
- function bytesToBase643(bytes) {
10466
+ function bytesToBase644(bytes) {
10332
10467
  let binary = "";
10333
10468
  for (let i2 = 0; i2 < bytes.length; i2 += 32768) {
10334
10469
  binary += String.fromCharCode(...bytes.subarray(i2, i2 + 32768));
@@ -11790,6 +11925,10 @@ var Arbi = class {
11790
11925
  if (target) await this.openWorkspace(target);
11791
11926
  return target;
11792
11927
  }
11928
+ /** {@link targetWorkspace} for a call that cannot go without one: throws when none is known. */
11929
+ async requireTargetWorkspace(workspaceId) {
11930
+ return await this.targetWorkspace(workspaceId) ?? this.requireWorkspace();
11931
+ }
11793
11932
  /**
11794
11933
  * Make a workspace the CURRENT one: decrypt its key, open it on the server (which makes it the
11795
11934
  * session's active workspace) and record it in the session. This is navigation: only the host's
@@ -12403,20 +12542,23 @@ var Arbi = class {
12403
12542
  finaliseTranslation: (docId) => finaliseTranslation(this.requireClient(), docId),
12404
12543
  delete: (externalIds) => deleteDocuments(this.requireClient(), externalIds),
12405
12544
  update: (documents) => updateDocuments(this.requireClient(), documents),
12406
- uploadUrl: (urls, options) => {
12407
- this.requireWorkspace();
12408
- return uploadUrl(
12409
- this.requireClient(),
12410
- urls,
12411
- options?.shared,
12412
- options?.configExtId
12413
- );
12545
+ /** Make documents from web addresses in the current workspace, or `options.workspaceId`. */
12546
+ uploadUrl: async (urls, options) => {
12547
+ const { workspaceId, ...rest } = options ?? {};
12548
+ return uploadUrl(this.requireClient(), urls, {
12549
+ workspaceExtId: await this.requireTargetWorkspace(workspaceId),
12550
+ ...rest
12551
+ });
12414
12552
  },
12415
12553
  /**
12416
- * Upload files in one request (the open workspace, or `options.workspaceExtId`): folder, tag,
12417
- * sharing, config, a new version of a document.
12554
+ * Upload files in one request into the current workspace, or `options.workspaceExtId`: folder,
12555
+ * tag, sharing, config, a new version of a document. The request names the workspace either
12556
+ * way, so a switch while it is in flight cannot move it.
12418
12557
  */
12419
- upload: (files, options) => uploadDocuments(this.requireClient(), files, options),
12558
+ upload: async (files, options) => uploadDocuments(this.requireClient(), files, {
12559
+ ...options,
12560
+ workspaceExtId: await this.requireTargetWorkspace(options?.workspaceExtId ?? void 0)
12561
+ }),
12420
12562
  /** Near-duplicate pairs at or above `threshold` (or one document's, `docId`). */
12421
12563
  similar: (options) => similarDocuments(this.requireClient(), options),
12422
12564
  /**
@@ -12441,19 +12583,15 @@ var Arbi = class {
12441
12583
  },
12442
12584
  /**
12443
12585
  * Upload files straight to storage, encrypted here with `workspaceKey` (`uploadDocumentsDirect`),
12444
- * into `workspaceId`, which must be the workspace open NOW. `upload-init` and `upload-commit`
12445
- * name no workspace yet (they act on the session's open one), so each runs under
12446
- * `readInWorkspace`: it is not sent, or its answer not kept, unless `workspaceId` is open when
12447
- * it is sent and still when it returns. A switch refuses the upload
12448
- * (`ArbiWorkspaceChangedError`) instead of storing files encrypted with one workspace's key in
12449
- * another. For any other workspace use `upload` with `workspaceExtId`, which names it.
12586
+ * into `workspaceId`, whose key it must be. `upload-init` and `upload-commit` name that
12587
+ * workspace (made usable for this session first, not switched to), so a switch while the
12588
+ * upload runs cannot move the files into another workspace.
12450
12589
  */
12451
- uploadDirect: (workspaceId, workspaceKey, files, options) => {
12452
- if (this.currentWorkspaceId !== workspaceId)
12453
- return Promise.reject(new ArbiWorkspaceChangedError(workspaceId, "uploading to"));
12590
+ uploadDirect: async (workspaceId, workspaceKey, files, options) => {
12591
+ const workspaceExtId = await this.requireTargetWorkspace(workspaceId);
12454
12592
  return uploadDocumentsDirect(this.requireClient(), workspaceKey, files, {
12455
12593
  ...options,
12456
- inWorkspace: (send) => this.readInWorkspace(workspaceId, send)
12594
+ workspaceExtId
12457
12595
  });
12458
12596
  },
12459
12597
  /** Download a document's original file — its current version, or `version`. */
@@ -12610,6 +12748,42 @@ var Arbi = class {
12610
12748
  });
12611
12749
  }
12612
12750
  };
12751
+ // ── Secure mail ─────────────────────────────────────────────────────
12752
+ /**
12753
+ * Mail to anyone, sealed in this browser under a key that travels only in the link's fragment
12754
+ * (see `operations/secure-mail`). Both sides use the signed-in user's encryption key: the
12755
+ * login's, or (a new tab not signed in to the server yet) the one kept on this device.
12756
+ */
12757
+ secureMail = {
12758
+ /**
12759
+ * The `/secure/send` payload for `compose` from `account`, shown with the user's own name.
12760
+ * Links open on `frontendOrigin` (default: this page's origin).
12761
+ */
12762
+ prepare: async (compose, account, requestId, frontendOrigin = globalThis.location?.origin ?? "") => {
12763
+ const user = this.client?.session.getState().user;
12764
+ const name = user ? [user.given_name, user.family_name] : [this.userProfile?.givenName, this.userProfile?.familyName];
12765
+ const senderName = name.filter(Boolean).join(" ");
12766
+ return prepareSecureMail(
12767
+ compose,
12768
+ { ...account, display_name: senderName || account.display_name },
12769
+ { requestId, senderPublicKey: await this.encryptionPublicKey(), frontendOrigin }
12770
+ );
12771
+ },
12772
+ /**
12773
+ * Claim the secure message `id` with the key from its link into the user's native inbox, over
12774
+ * `mail` (default: this session's mail transport). Resolves to the message's id there.
12775
+ */
12776
+ claim: async (id, fragmentKey, mail = this.mail.fetch) => claimSecureMail(mail, id, fragmentKey, await this.encryptionPublicKey())
12777
+ };
12778
+ /** The signed-in user's X25519 public key (from the identity key; its secret half is wiped). */
12779
+ async encryptionPublicKey() {
12780
+ const signingKey = this.loginResult?.signingPrivateKey ?? (await this.client?.storage.getSession().catch(() => null))?.signingPrivateKey;
12781
+ if (!signingKey) throw new ArbiError("Sign in again to unlock your encryption key");
12782
+ await initSodium();
12783
+ const pair = encryptionKeypairFromSigningKey(signingKey);
12784
+ pair.secretKey.fill(0);
12785
+ return pair.publicKey;
12786
+ }
12613
12787
  async openResponseHandle(open, options, id, bufferEvents = false) {
12614
12788
  const controller = new AbortController();
12615
12789
  const abort = () => controller.abort();
@@ -13820,7 +13994,8 @@ async function runGroupedDirectUpload(arbi, workspaceKey, groups, options) {
13820
13994
  options?.onBatchStart?.(progress);
13821
13995
  const result = await uploadDocumentsDirect(arbi, workspaceKey, group.files, {
13822
13996
  folder: group.folder || void 0,
13823
- configExtId: options?.configExtId
13997
+ configExtId: options.configExtId,
13998
+ workspaceExtId: options.workspaceExtId
13824
13999
  });
13825
14000
  const skipped = result.skipped ?? [];
13826
14001
  allDocIds.push(...result.doc_ext_ids);
@@ -15505,6 +15680,6 @@ function composeTools(base, next, mode) {
15505
15680
  return structuredClone(mode === "add" ? { ...base, ...next } : next);
15506
15681
  }
15507
15682
 
15508
- export { ACCOUNT_VENDOR, Arbi, ArbiApiError, ArbiError, ArbiSessionExpiredError, ArbiStructuredOutputError, ArbiTransportError, ArbiWorkspaceChangedError, ArbiWorkspaceSupersededError, ArbiWorkspaceUnavailableError, CallApiError, 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, PROMPT_CONTEXT_CHARS, PlanStepsError, PublicBookingError, ResponseStream, SHAREPOINT_VENDORS, STEP_FIELD_OPTION_TONES, STOP_ID_WAIT_MS, STOP_REPEAT_WINDOW_MS, TAG_KINDS, TAG_NESTING_MAX_DEPTH, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, agents_exports as agents, appendTranscriptionHints, assistant_exports as assistant, authenticatedFetch, bookPublicSlot, buildCitationChunkData, buildDocNameMap, buildDocumentTools, buildFactsContextTool, buildRetrievalChunkTool, buildRetrievalFullContextTool, buildRetrievalTocTool, buildTurnRequest, calendar_exports as calendar, calls_exports as calls, canTagHaveParent, cancelPublicBooking, capabilities, chats_exports as chats, composeConfiguration, composeTools, computeRunStats, connectErrorMessage, connectWebSocket, connectWithReconnect, connectors_exports as connectors, contacts_exports as contacts, continuityPrompt, conversations_exports as conversations, countCitations, createAuthenticatedClient, createDocumentWaiter, createIndexAssigner, databases_exports as databases, defaultKindForFormat, device_flow_exports as deviceFlow, doctags_exports as doctags, documentTools, documents_exports as documents, documents_node_exports as documentsNode, estimateDraftTokens, extractDocumentIdsFromMessages, extractFactIdsFromMessages, extractSubagentLanes, facts_exports as facts, files_exports as files, filterDocumentTags, filterSkills, findLeafForTaskMessage, findMainSiblingLeaf, findReplyTarget, findSubagentRunId, firm_exports as firm, flattenTagTree, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatStreamSummary, formatTokens, formatUserName, formatWorkspaceChoices, formatWsMessage, generateEncryptedWorkspaceKey, generateNewWorkspaceKey, getAgentStepLabel, getAttachableRunId, getChildTags, getContextRemainingPercent, getContextUsedPercent, getContextUsedTokens, getCurrentStep, getEligibleParentTags, getErrorCode, getErrorMessage, getPublicBookingPage, getRawWorkspaceKey, getRunToAttach, getRunToCancel, getStepDisplay, getStepTool, getSubagentBranchRecord, getTagDescendantIds, health_exports as health, house_template_exports as houseTemplates, hydrateAgentSteps, identityErrorCode, identity_exports as identityVerification, instructions, isAnnotationTag, isConnectorVendorVisible, isDriveSyncVendor, isEntityTag, isFlatKind, isLabelTag, isMailboxSyncVendor, isNearAiUsageBudget, isPresenceTag, isSharePointVendor, isSharedSkill, isTraceItem, listen_exports as listen, mail_exports as mail, mail_node_exports as mailNode, mcpTools, mergeAgentSteps, model_connections_exports as modelConnections, notifications_exports as notifications, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, parseStructuredResponse, performPasswordLogin, performSigningKeyLogin, performSsoDeviceFlowLogin, pickMainThread, profile_exports as profile, progressFetch, projects_exports as projects, quotaExceededFrom, quotaFromStreamError, reduceOutputItem, refusalReason, requireData, requireOk, resolveAuth, resolveCitations, resolveSummary, resolveWorkspace, responses_exports as responses, searchChunks, selectFullContextDocument, selectWorkspace, selectWorkspaceById, sessions_exports as sessions, settings_exports as settings, signature_requests_exports as signatureRequests, sliceToSubagentThread, startDmListener, streamSSE, stripCitationMarkdown, subagentJobLabel, summarizeCitations, tagUseCount, tags_exports as tags, tagsForScope, tagsOfGroup, topLevelAgentSteps, uploadSkill, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaceConflictOf, workspaces_exports as workspaces, wouldCreateTagCycle };
15683
+ export { ACCOUNT_VENDOR, Arbi, ArbiApiError, ArbiError, ArbiSessionExpiredError, ArbiStructuredOutputError, ArbiTransportError, ArbiWorkspaceChangedError, ArbiWorkspaceSupersededError, ArbiWorkspaceUnavailableError, CallApiError, 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, PROMPT_CONTEXT_CHARS, PlanStepsError, PublicBookingError, ResponseStream, SHAREPOINT_VENDORS, STEP_FIELD_OPTION_TONES, STOP_ID_WAIT_MS, STOP_REPEAT_WINDOW_MS, TAG_KINDS, TAG_NESTING_MAX_DEPTH, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, agents_exports as agents, appendTranscriptionHints, assistant_exports as assistant, authenticatedFetch, bookPublicSlot, buildCitationChunkData, buildDocNameMap, buildDocumentTools, buildFactsContextTool, buildRetrievalChunkTool, buildRetrievalFullContextTool, buildRetrievalTocTool, buildTurnRequest, calendar_exports as calendar, calls_exports as calls, canTagHaveParent, cancelPublicBooking, capabilities, chats_exports as chats, composeConfiguration, composeTools, computeRunStats, connectErrorMessage, connectWebSocket, connectWithReconnect, connectors_exports as connectors, contacts_exports as contacts, continuityPrompt, conversations_exports as conversations, countCitations, createAuthenticatedClient, createDocumentWaiter, createIndexAssigner, databases_exports as databases, defaultKindForFormat, device_flow_exports as deviceFlow, doctags_exports as doctags, documentTools, documents_exports as documents, documents_node_exports as documentsNode, estimateDraftTokens, extractDocumentIdsFromMessages, extractFactIdsFromMessages, extractSubagentLanes, facts_exports as facts, files_exports as files, filterDocumentTags, filterSkills, findLeafForTaskMessage, findMainSiblingLeaf, findReplyTarget, findSubagentRunId, firm_exports as firm, flattenTagTree, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatStreamSummary, formatTokens, formatUserName, formatWorkspaceChoices, formatWsMessage, generateEncryptedWorkspaceKey, generateNewWorkspaceKey, getAgentStepLabel, getAttachableRunId, getChildTags, getContextRemainingPercent, getContextUsedPercent, getContextUsedTokens, getCurrentStep, getEligibleParentTags, getErrorCode, getErrorMessage, getPublicBookingPage, getRawWorkspaceKey, getRunToAttach, getRunToCancel, getStepDisplay, getStepTool, getSubagentBranchRecord, getTagDescendantIds, health_exports as health, house_template_exports as houseTemplates, hydrateAgentSteps, identityErrorCode, identity_exports as identityVerification, instructions, isAnnotationTag, isConnectorVendorVisible, isDriveSyncVendor, isEntityTag, isFlatKind, isLabelTag, isMailboxSyncVendor, isNearAiUsageBudget, isPresenceTag, isSharePointVendor, isSharedSkill, isTraceItem, listen_exports as listen, mail_exports as mail, mail_node_exports as mailNode, mcpTools, mergeAgentSteps, model_connections_exports as modelConnections, notifications_exports as notifications, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, parseStructuredResponse, performPasswordLogin, performSigningKeyLogin, performSsoDeviceFlowLogin, pickMainThread, profile_exports as profile, progressFetch, projects_exports as projects, quotaExceededFrom, quotaFromStreamError, reduceOutputItem, refusalReason, requireData, requireOk, resolveAuth, resolveCitations, resolveSummary, resolveWorkspace, responses_exports as responses, searchChunks, secure_mail_exports as secureMail, selectFullContextDocument, selectWorkspace, selectWorkspaceById, sessions_exports as sessions, settings_exports as settings, signature_requests_exports as signatureRequests, sliceToSubagentThread, startDmListener, streamSSE, stripCitationMarkdown, subagentJobLabel, summarizeCitations, tagUseCount, tags_exports as tags, tagsForScope, tagsOfGroup, topLevelAgentSteps, uploadSkill, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaceConflictOf, workspaces_exports as workspaces, wouldCreateTagCycle };
15509
15684
  //# sourceMappingURL=index.js.map
15510
15685
  //# sourceMappingURL=index.js.map