@arbidocs/sdk 0.4.49 → 0.4.50

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.
@@ -1,2 +1,2 @@
1
- export { A as ActivityKind, a as ActivityResponse, b as AgentControlStateEvent, c as AgentStepDeltaEvent, d as AgentStepEvent, e as Arbi, f as ArbiApiError, g as ArbiError, h as ArbiErrorEvent, i as ArbiOptions, k as ArtifactEvent, l as AuthContext, m as AuthHeaders, n as AuthMode, o as AuthenticatedClient, C as ChatSession, p as CitationSummary, q as CliConfig, r as CliCredentials, s as CommandDescriptor, t as ConfigStore, u as ConnectOptions, v as ConversationResponse, w as CreateFactRequest, x as CreateFactsRequest, y as CreateWorkRequest, z as CreateWorkflowRequest, B as DeferredInterjectionEvent, G as DocumentAutomationAction, J as DocumentSelector, M as FactResponse, N as FactSearchRequest, O as FactSearchResponse, R as ListFactsOptions, V as MessageMetadataPayload, W as MessageQueuedEvent, X as OutputTokensDetails, Y as ParsedSlashCommand, Z as PendingAuthResponse, _ as PlanWorkRequest, $ as ProbeAnswerEvent, a0 as ProjectInvoicesResponse, a1 as ProjectUsageResponse, a2 as QueryOptions, a3 as ReconnectOptions, a4 as ReconnectableWsConnection, a5 as RequestApprovalRequest, a6 as ResolvedCitation, a8 as ResponseCompletedEvent, a9 as ResponseContentPartAddedEvent, aa as ResponseCreatedEvent, ab as ResponseFailedEvent, ac as ResponseOutputItemAddedEvent, ad as ResponseOutputItemDoneEvent, ae as ResponseOutputTextDeltaEvent, af as ResponseOutputTextDoneEvent, ag as ResponseUsage, ah as ReviewWorkRequest, ai as SSEEvent, aj as SSEStreamCallbacks, ak as SSEStreamResult, al as SSEStreamStartData, an as SkillSummary, ap as SubmitBackgroundQueryOptions, aq as TaskPlan, ar as TokenBudgetContext, as as UpdateConversationRequest, at as UpdateFactRequest, au as UpdateWorkflowRequest, aA as UserDailyUsageResponse, aB as UserInfo, aC as UserInputRequestEvent, aD as UserMessageEvent, aE as WebSocketAuthError, aF as WorkStatus, aG as WorkflowAuthMode, aH as WorkflowResponse, aI as WorkflowRunHistoryResponse, aJ as WorkflowRunResponse, aK as WorkspaceContext, aL as WsConnection, aM as account, aN as agentconfig, aP as assistant, aQ as authenticatedFetch, aS as buildRetrievalChunkTool, aT as buildRetrievalFullContextTool, aU as buildRetrievalTocTool, aV as connectWebSocket, aW as connectWithReconnect, aX as consumeSSEStream, aY as contacts, aZ as conversations, a_ as countCitations, a$ as createAuthenticatedClient, b1 as dm, b2 as doctags, b3 as documents, b4 as facts, b5 as files, b6 as filterSkills, b7 as formatAgentStepLabel, b8 as formatFileSize, b9 as formatItemLabel, bb as formatUserName, bc as formatWorkspaceChoices, bh as getErrorMessage, bi as getRawWorkspaceKey, bj as health, bk as mail, bl as parseSSEEvents, bm as parseSlashCommand, bn as parseSlashTokenInProgress, bo as performPasswordLogin, br as profile, bs as projects, bt as requireData, bu as requireOk, bv as resolveAuth, bw as resolveCitations, bx as resolveWorkspace, by as responses, bz as selectWorkspace, bA as selectWorkspaceById, bB as sessions, bC as settings, bD as streamSSE, bE as stripCitationMarkdown, bF as summarizeCitations, bG as tags, bH as work, bI as workflows, bJ as workspaces } from './browser-CQ3lohen.cjs';
1
+ export { A as ActivityKind, a as ActivityResponse, b as AgentControlStateEvent, c as AgentStepDeltaEvent, d as AgentStepEvent, e as Arbi, f as ArbiApiError, g as ArbiError, h as ArbiErrorEvent, i as ArbiOptions, k as ArtifactEvent, l as AuthContext, m as AuthHeaders, n as AuthMode, o as AuthenticatedClient, C as ChatSession, p as CitationSummary, q as CliConfig, r as CliCredentials, s as CommandDescriptor, t as ConfigStore, u as ConnectOptions, v as ConversationResponse, w as CreateFactRequest, x as CreateFactsRequest, y as CreateWorkRequest, z as CreateWorkflowRequest, B as DecryptedDmNotification, E as DeferredInterjectionEvent, F as DmAttachmentFile, G as DmAttachmentInput, J as DocumentAutomationAction, M as DocumentSelector, P as FactResponse, Q as FactSearchRequest, R as FactSearchResponse, U as ListFactsOptions, Y as MessageMetadataPayload, Z as MessageQueuedEvent, _ as OutputTokensDetails, $ as ParsedSlashCommand, a0 as PendingAuthResponse, a1 as PlanWorkRequest, a2 as ProbeAnswerEvent, a3 as ProjectInvoicesResponse, a4 as ProjectUsageResponse, a5 as QueryOptions, a6 as ReconnectOptions, a7 as ReconnectableWsConnection, a8 as RequestApprovalRequest, a9 as ResolvedCitation, ab as ResponseCompletedEvent, ac as ResponseContentPartAddedEvent, ad as ResponseCreatedEvent, ae as ResponseFailedEvent, af as ResponseOutputItemAddedEvent, ag as ResponseOutputItemDoneEvent, ah as ResponseOutputTextDeltaEvent, ai as ResponseOutputTextDoneEvent, aj as ResponseUsage, ak as ReviewWorkRequest, al as SSEEvent, am as SSEStreamCallbacks, an as SSEStreamResult, ao as SSEStreamStartData, aq as SkillSummary, as as SubmitBackgroundQueryOptions, at as TaskPlan, au as TokenBudgetContext, av as UpdateConversationRequest, aw as UpdateFactRequest, ax as UpdateWorkflowRequest, aD as UserDailyUsageResponse, aE as UserInfo, aF as UserInputRequestEvent, aG as UserMessageEvent, aH as WebSocketAuthError, aI as WorkStatus, aJ as WorkflowAuthMode, aK as WorkflowResponse, aL as WorkflowRunHistoryResponse, aM as WorkflowRunResponse, aN as WorkspaceContext, aO as WsConnection, aP as account, aQ as agentconfig, aS as assistant, aT as authenticatedFetch, aV as buildRetrievalChunkTool, aW as buildRetrievalFullContextTool, aX as buildRetrievalTocTool, aY as connectWebSocket, aZ as connectWithReconnect, a_ as consumeSSEStream, a$ as contacts, b0 as conversations, b1 as countCitations, b2 as createAuthenticatedClient, b4 as dm, b5 as doctags, b6 as documents, b7 as facts, b8 as files, b9 as filterSkills, ba as formatAgentStepLabel, bb as formatFileSize, bc as formatItemLabel, be as formatUserName, bf as formatWorkspaceChoices, bk as getErrorMessage, bl as getRawWorkspaceKey, bm as health, bn as mail, bo as parseSSEEvents, bp as parseSlashCommand, bq as parseSlashTokenInProgress, br as performPasswordLogin, bu as profile, bv as projects, bw as requireData, bx as requireOk, by as resolveAuth, bz as resolveCitations, bA as resolveWorkspace, bB as responses, bC as selectWorkspace, bD as selectWorkspaceById, bE as sessions, bF as settings, bG as streamSSE, bH as stripCitationMarkdown, bI as summarizeCitations, bJ as tags, bK as work, bL as workflows, bM as workspaces } from './browser-ottmzMPY.cjs';
2
2
  export { LoginProfile } from '@arbidocs/client';
package/dist/browser.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { A as ActivityKind, a as ActivityResponse, b as AgentControlStateEvent, c as AgentStepDeltaEvent, d as AgentStepEvent, e as Arbi, f as ArbiApiError, g as ArbiError, h as ArbiErrorEvent, i as ArbiOptions, k as ArtifactEvent, l as AuthContext, m as AuthHeaders, n as AuthMode, o as AuthenticatedClient, C as ChatSession, p as CitationSummary, q as CliConfig, r as CliCredentials, s as CommandDescriptor, t as ConfigStore, u as ConnectOptions, v as ConversationResponse, w as CreateFactRequest, x as CreateFactsRequest, y as CreateWorkRequest, z as CreateWorkflowRequest, B as DeferredInterjectionEvent, G as DocumentAutomationAction, J as DocumentSelector, M as FactResponse, N as FactSearchRequest, O as FactSearchResponse, R as ListFactsOptions, V as MessageMetadataPayload, W as MessageQueuedEvent, X as OutputTokensDetails, Y as ParsedSlashCommand, Z as PendingAuthResponse, _ as PlanWorkRequest, $ as ProbeAnswerEvent, a0 as ProjectInvoicesResponse, a1 as ProjectUsageResponse, a2 as QueryOptions, a3 as ReconnectOptions, a4 as ReconnectableWsConnection, a5 as RequestApprovalRequest, a6 as ResolvedCitation, a8 as ResponseCompletedEvent, a9 as ResponseContentPartAddedEvent, aa as ResponseCreatedEvent, ab as ResponseFailedEvent, ac as ResponseOutputItemAddedEvent, ad as ResponseOutputItemDoneEvent, ae as ResponseOutputTextDeltaEvent, af as ResponseOutputTextDoneEvent, ag as ResponseUsage, ah as ReviewWorkRequest, ai as SSEEvent, aj as SSEStreamCallbacks, ak as SSEStreamResult, al as SSEStreamStartData, an as SkillSummary, ap as SubmitBackgroundQueryOptions, aq as TaskPlan, ar as TokenBudgetContext, as as UpdateConversationRequest, at as UpdateFactRequest, au as UpdateWorkflowRequest, aA as UserDailyUsageResponse, aB as UserInfo, aC as UserInputRequestEvent, aD as UserMessageEvent, aE as WebSocketAuthError, aF as WorkStatus, aG as WorkflowAuthMode, aH as WorkflowResponse, aI as WorkflowRunHistoryResponse, aJ as WorkflowRunResponse, aK as WorkspaceContext, aL as WsConnection, aM as account, aN as agentconfig, aP as assistant, aQ as authenticatedFetch, aS as buildRetrievalChunkTool, aT as buildRetrievalFullContextTool, aU as buildRetrievalTocTool, aV as connectWebSocket, aW as connectWithReconnect, aX as consumeSSEStream, aY as contacts, aZ as conversations, a_ as countCitations, a$ as createAuthenticatedClient, b1 as dm, b2 as doctags, b3 as documents, b4 as facts, b5 as files, b6 as filterSkills, b7 as formatAgentStepLabel, b8 as formatFileSize, b9 as formatItemLabel, bb as formatUserName, bc as formatWorkspaceChoices, bh as getErrorMessage, bi as getRawWorkspaceKey, bj as health, bk as mail, bl as parseSSEEvents, bm as parseSlashCommand, bn as parseSlashTokenInProgress, bo as performPasswordLogin, br as profile, bs as projects, bt as requireData, bu as requireOk, bv as resolveAuth, bw as resolveCitations, bx as resolveWorkspace, by as responses, bz as selectWorkspace, bA as selectWorkspaceById, bB as sessions, bC as settings, bD as streamSSE, bE as stripCitationMarkdown, bF as summarizeCitations, bG as tags, bH as work, bI as workflows, bJ as workspaces } from './browser-CQ3lohen.js';
1
+ export { A as ActivityKind, a as ActivityResponse, b as AgentControlStateEvent, c as AgentStepDeltaEvent, d as AgentStepEvent, e as Arbi, f as ArbiApiError, g as ArbiError, h as ArbiErrorEvent, i as ArbiOptions, k as ArtifactEvent, l as AuthContext, m as AuthHeaders, n as AuthMode, o as AuthenticatedClient, C as ChatSession, p as CitationSummary, q as CliConfig, r as CliCredentials, s as CommandDescriptor, t as ConfigStore, u as ConnectOptions, v as ConversationResponse, w as CreateFactRequest, x as CreateFactsRequest, y as CreateWorkRequest, z as CreateWorkflowRequest, B as DecryptedDmNotification, E as DeferredInterjectionEvent, F as DmAttachmentFile, G as DmAttachmentInput, J as DocumentAutomationAction, M as DocumentSelector, P as FactResponse, Q as FactSearchRequest, R as FactSearchResponse, U as ListFactsOptions, Y as MessageMetadataPayload, Z as MessageQueuedEvent, _ as OutputTokensDetails, $ as ParsedSlashCommand, a0 as PendingAuthResponse, a1 as PlanWorkRequest, a2 as ProbeAnswerEvent, a3 as ProjectInvoicesResponse, a4 as ProjectUsageResponse, a5 as QueryOptions, a6 as ReconnectOptions, a7 as ReconnectableWsConnection, a8 as RequestApprovalRequest, a9 as ResolvedCitation, ab as ResponseCompletedEvent, ac as ResponseContentPartAddedEvent, ad as ResponseCreatedEvent, ae as ResponseFailedEvent, af as ResponseOutputItemAddedEvent, ag as ResponseOutputItemDoneEvent, ah as ResponseOutputTextDeltaEvent, ai as ResponseOutputTextDoneEvent, aj as ResponseUsage, ak as ReviewWorkRequest, al as SSEEvent, am as SSEStreamCallbacks, an as SSEStreamResult, ao as SSEStreamStartData, aq as SkillSummary, as as SubmitBackgroundQueryOptions, at as TaskPlan, au as TokenBudgetContext, av as UpdateConversationRequest, aw as UpdateFactRequest, ax as UpdateWorkflowRequest, aD as UserDailyUsageResponse, aE as UserInfo, aF as UserInputRequestEvent, aG as UserMessageEvent, aH as WebSocketAuthError, aI as WorkStatus, aJ as WorkflowAuthMode, aK as WorkflowResponse, aL as WorkflowRunHistoryResponse, aM as WorkflowRunResponse, aN as WorkspaceContext, aO as WsConnection, aP as account, aQ as agentconfig, aS as assistant, aT as authenticatedFetch, aV as buildRetrievalChunkTool, aW as buildRetrievalFullContextTool, aX as buildRetrievalTocTool, aY as connectWebSocket, aZ as connectWithReconnect, a_ as consumeSSEStream, a$ as contacts, b0 as conversations, b1 as countCitations, b2 as createAuthenticatedClient, b4 as dm, b5 as doctags, b6 as documents, b7 as facts, b8 as files, b9 as filterSkills, ba as formatAgentStepLabel, bb as formatFileSize, bc as formatItemLabel, be as formatUserName, bf as formatWorkspaceChoices, bk as getErrorMessage, bl as getRawWorkspaceKey, bm as health, bn as mail, bo as parseSSEEvents, bp as parseSlashCommand, bq as parseSlashTokenInProgress, br as performPasswordLogin, bu as profile, bv as projects, bw as requireData, bx as requireOk, by as resolveAuth, bz as resolveCitations, bA as resolveWorkspace, bB as responses, bC as selectWorkspace, bD as selectWorkspaceById, bE as sessions, bF as settings, bG as streamSSE, bH as stripCitationMarkdown, bI as summarizeCitations, bJ as tags, bK as work, bL as workflows, bM as workspaces } from './browser-ottmzMPY.js';
2
2
  export { LoginProfile } from '@arbidocs/client';
package/dist/browser.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createArbiClient, base64ToBytes, deriveEncryptionKeypairFromSigning, sealedBoxDecrypt, sealKeyForSession, buildWebSocketUrl, createAuthMessage, parseServerMessage, isMessageType, createContentHash, encryptFile, changePasswordWithRekey, initSodium } from '@arbidocs/client';
1
+ import { createArbiClient, base64ToBytes, deriveEncryptionKeypairFromSigning, sealedBoxDecrypt, sealKeyForSession, buildWebSocketUrl, createAuthMessage, parseServerMessage, isMessageType, createContentHash, encryptFile, initSodium, bytesToBase64, decryptFile, changePasswordWithRekey } from '@arbidocs/client';
2
2
 
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -5243,19 +5243,29 @@ async function generateDocTags(arbi, tagIds, docIds, options) {
5243
5243
  // src/operations/dm.ts
5244
5244
  var dm_exports = {};
5245
5245
  __export(dm_exports, {
5246
+ DM_ATTACHMENT_MAX_BYTES: () => DM_ATTACHMENT_MAX_BYTES,
5247
+ DM_ATTACHMENT_MAX_FILES: () => DM_ATTACHMENT_MAX_FILES,
5248
+ checkDmAttachmentLimits: () => checkDmAttachmentLimits,
5246
5249
  createDmCryptoContext: () => createDmCryptoContext,
5250
+ decryptDmAttachments: () => decryptDmAttachments,
5247
5251
  decryptDmBatch: () => decryptDmBatch,
5248
5252
  decryptDmContent: () => decryptDmContent,
5249
5253
  deleteDMs: () => deleteDMs,
5254
+ downloadDmAttachment: () => downloadDmAttachment,
5255
+ encryptDmAttachmentManifest: () => encryptDmAttachmentManifest,
5250
5256
  encryptDmContent: () => encryptDmContent,
5251
5257
  listActivity: () => listActivity,
5252
5258
  listDMs: () => listDMs,
5253
5259
  listDecryptedDMs: () => listDecryptedDMs,
5254
5260
  markRead: () => markRead,
5261
+ parseDmAttachmentManifest: () => parseDmAttachmentManifest,
5255
5262
  requestWorkspaceAccess: () => requestWorkspaceAccess,
5256
5263
  resolveRecipient: () => resolveRecipient,
5257
5264
  sendDM: () => sendDM,
5258
- sendEncryptedDM: () => sendEncryptedDM
5265
+ sendEncryptedDM: () => sendEncryptedDM,
5266
+ serializeDmAttachmentManifest: () => serializeDmAttachmentManifest,
5267
+ uploadDmAttachment: () => uploadDmAttachment,
5268
+ uploadDmAttachments: () => uploadDmAttachments
5259
5269
  });
5260
5270
 
5261
5271
  // src/operations/agents.ts
@@ -5347,6 +5357,138 @@ async function stageAgentFile(auth, agentId, file, name) {
5347
5357
  });
5348
5358
  return response.json();
5349
5359
  }
5360
+ var DM_ATTACHMENT_MAX_BYTES = 15 * 1024 * 1024;
5361
+ var DM_ATTACHMENT_MAX_FILES = 10;
5362
+ var ATTACHMENT_ID = /^att-[a-zA-Z0-9]{8}$/;
5363
+ var MANIFEST_VERSION = 1;
5364
+ var MB = 1024 * 1024;
5365
+ function checkDmAttachmentLimits(files) {
5366
+ if (files.length > DM_ATTACHMENT_MAX_FILES) {
5367
+ throw new Error(
5368
+ `You can attach at most ${DM_ATTACHMENT_MAX_FILES} files to a message (this one has ${files.length}).`
5369
+ );
5370
+ }
5371
+ for (const file of files) {
5372
+ if (file.size > DM_ATTACHMENT_MAX_BYTES) {
5373
+ throw new Error(
5374
+ `${file.name} is too large (${(file.size / MB).toFixed(1)} MB). Files can be at most ${DM_ATTACHMENT_MAX_BYTES / MB} MB.`
5375
+ );
5376
+ }
5377
+ }
5378
+ }
5379
+ async function uploadDmAttachment(arbi, input) {
5380
+ checkDmAttachmentLimits([{ name: input.name, size: input.bytes.length }]);
5381
+ await initSodium();
5382
+ const key = globalThis.crypto.getRandomValues(new Uint8Array(32));
5383
+ try {
5384
+ const ciphertext = encryptFile(input.bytes, key);
5385
+ const form = new FormData();
5386
+ form.append(
5387
+ "file",
5388
+ new Blob([ciphertext], { type: "application/octet-stream" }),
5389
+ "attachment.bin"
5390
+ );
5391
+ const result = await arbi.fetch.POST("/v1/notifications/attachments", {
5392
+ body: { file: "" },
5393
+ bodySerializer: () => form
5394
+ });
5395
+ if (result.response?.status === 413) {
5396
+ throw new ArbiApiError(
5397
+ `${input.name} is too large. Files can be at most ${DM_ATTACHMENT_MAX_BYTES / MB} MB.`,
5398
+ result.error,
5399
+ 413
5400
+ );
5401
+ }
5402
+ const uploaded = requireData(result, `Failed to upload ${input.name}`);
5403
+ return {
5404
+ id: uploaded.external_id,
5405
+ name: input.name,
5406
+ type: input.type || "application/octet-stream",
5407
+ size: input.bytes.length,
5408
+ key: bytesToBase64(key)
5409
+ };
5410
+ } finally {
5411
+ key.fill(0);
5412
+ }
5413
+ }
5414
+ async function uploadDmAttachments(arbi, inputs) {
5415
+ checkDmAttachmentLimits(inputs.map((i2) => ({ name: i2.name, size: i2.bytes.length })));
5416
+ const files = [];
5417
+ for (const input of inputs) files.push(await uploadDmAttachment(arbi, input));
5418
+ return files;
5419
+ }
5420
+ function serializeDmAttachmentManifest(files) {
5421
+ return JSON.stringify({
5422
+ v: MANIFEST_VERSION,
5423
+ files: files.map(({ id, name, type, size, key }) => ({ id, name, type, size, key }))
5424
+ });
5425
+ }
5426
+ function parseDmAttachmentManifest(json2) {
5427
+ const manifest = JSON.parse(json2);
5428
+ if (manifest?.v !== MANIFEST_VERSION || !Array.isArray(manifest.files)) {
5429
+ throw new Error("Unsupported attachment manifest");
5430
+ }
5431
+ return manifest.files.map((entry) => {
5432
+ const f2 = entry;
5433
+ if (typeof f2.id !== "string" || !ATTACHMENT_ID.test(f2.id) || typeof f2.name !== "string" || typeof f2.size !== "number" || !Number.isInteger(f2.size) || f2.size < 0 || typeof f2.key !== "string") {
5434
+ throw new Error("Malformed attachment manifest");
5435
+ }
5436
+ return {
5437
+ id: f2.id,
5438
+ name: f2.name,
5439
+ type: typeof f2.type === "string" && f2.type ? f2.type : "application/octet-stream",
5440
+ size: f2.size,
5441
+ key: f2.key
5442
+ };
5443
+ });
5444
+ }
5445
+ async function encryptDmAttachmentManifest(arbi, files, recipientEncryptionPubKeyBase64, senderEncryptionSecretKey) {
5446
+ return arbi.crypto.encryptMessage(
5447
+ serializeDmAttachmentManifest(files),
5448
+ recipientEncryptionPubKeyBase64,
5449
+ senderEncryptionSecretKey
5450
+ );
5451
+ }
5452
+ async function decryptDmAttachments(arbi, notification, crypto2) {
5453
+ if (!notification.attachments) return [];
5454
+ const isSent = notification.sender.external_id === crypto2.userExtId;
5455
+ const otherParty = isSent ? notification.recipient : notification.sender;
5456
+ const json2 = await arbi.crypto.decryptMessage(
5457
+ notification.attachments,
5458
+ otherParty.encryption_public_key,
5459
+ crypto2.encryptionKeypair.secretKey
5460
+ );
5461
+ return parseDmAttachmentManifest(json2);
5462
+ }
5463
+ async function downloadDmAttachment(arbi, file) {
5464
+ if (!ATTACHMENT_ID.test(file.id)) throw new Error(`Invalid attachment id: ${file.id}`);
5465
+ const result = await arbi.fetch.GET("/v1/notifications/attachments/{external_id}", {
5466
+ params: { path: { external_id: file.id } },
5467
+ parseAs: "arrayBuffer"
5468
+ });
5469
+ if (result.response?.status === 404) {
5470
+ throw new ArbiApiError(`${file.name} is no longer available`, result.error, 404);
5471
+ }
5472
+ const ciphertext = requireData(
5473
+ result,
5474
+ `Failed to download ${file.name}`
5475
+ );
5476
+ await initSodium();
5477
+ const key = base64ToBytes(file.key);
5478
+ let plain;
5479
+ try {
5480
+ if (key.length !== 32) throw new Error("bad key");
5481
+ plain = decryptFile(new Uint8Array(ciphertext), key);
5482
+ } catch {
5483
+ throw new Error(`Could not decrypt ${file.name}: the file was altered or the key is wrong`);
5484
+ } finally {
5485
+ key.fill(0);
5486
+ }
5487
+ if (plain.length !== file.size) {
5488
+ throw new Error(`${file.name} is ${plain.length} bytes, expected ${file.size} bytes`);
5489
+ }
5490
+ return plain;
5491
+ }
5350
5492
 
5351
5493
  // src/operations/dm.ts
5352
5494
  function createDmCryptoContext(arbi, signingPrivateKeyBytes, userExtId) {
@@ -5377,16 +5519,25 @@ async function decryptDmContent(arbi, notification, crypto2) {
5377
5519
  async function decryptDmBatch(arbi, notifications, crypto2) {
5378
5520
  const results = [];
5379
5521
  for (const n2 of notifications) {
5380
- if (n2.type !== "user_message" || !n2.content) {
5522
+ if (n2.type !== "user_message" || !n2.content && !n2.attachments) {
5381
5523
  results.push(n2);
5382
5524
  continue;
5383
5525
  }
5526
+ let row;
5384
5527
  try {
5385
- const plaintext = await decryptDmContent(arbi, n2, crypto2);
5386
- results.push({ ...n2, content: plaintext });
5528
+ row = { ...n2, content: await decryptDmContent(arbi, n2, crypto2) };
5387
5529
  } catch {
5388
- results.push({ ...n2, content: "[Decryption failed]" });
5530
+ row = { ...n2, content: "[Decryption failed]" };
5389
5531
  }
5532
+ if (n2.attachments) {
5533
+ try {
5534
+ row.attachmentFiles = await decryptDmAttachments(arbi, n2, crypto2);
5535
+ } catch {
5536
+ row.attachmentFiles = [];
5537
+ row.attachmentsError = "The attachments could not be decrypted";
5538
+ }
5539
+ }
5540
+ results.push(row);
5390
5541
  }
5391
5542
  return results;
5392
5543
  }
@@ -5442,7 +5593,9 @@ async function resolveRecipient(arbi, ref) {
5442
5593
  }
5443
5594
  return null;
5444
5595
  }
5445
- async function sendEncryptedDM(arbi, messages, crypto2) {
5596
+ async function sendEncryptedDM(arbi, messages, crypto2, options) {
5597
+ const attachments = options?.attachments ?? [];
5598
+ checkDmAttachmentLimits(attachments);
5446
5599
  const plaintextFor = new Map(messages.map((m2) => [m2.recipient_ext_id, m2.content]));
5447
5600
  const encrypted = await Promise.all(
5448
5601
  messages.map(async (msg) => ({
@@ -5452,18 +5605,31 @@ async function sendEncryptedDM(arbi, messages, crypto2) {
5452
5605
  msg.content,
5453
5606
  msg.recipient_encryption_public_key,
5454
5607
  crypto2.encryptionKeypair.secretKey
5455
- )
5608
+ ),
5609
+ ...attachments.length ? {
5610
+ attachments: await encryptDmAttachmentManifest(
5611
+ arbi,
5612
+ attachments,
5613
+ msg.recipient_encryption_public_key,
5614
+ crypto2.encryptionKeypair.secretKey
5615
+ )
5616
+ } : {}
5456
5617
  }))
5457
5618
  );
5458
5619
  const created = requireData(
5459
5620
  await arbi.fetch.POST("/v1/notifications/", {
5460
- body: { messages: encrypted, context_only: false }
5621
+ body: {
5622
+ messages: encrypted,
5623
+ context_only: false,
5624
+ ...attachments.length ? { attachment_ext_ids: attachments.map((f2) => f2.id) } : {}
5625
+ }
5461
5626
  }),
5462
5627
  "Failed to send message"
5463
5628
  );
5464
5629
  return created.map((n2) => ({
5465
5630
  ...n2,
5466
- content: plaintextFor.get(n2.recipient.external_id) ?? n2.content
5631
+ content: plaintextFor.get(n2.recipient.external_id) ?? n2.content,
5632
+ ...attachments.length ? { attachmentFiles: attachments } : {}
5467
5633
  }));
5468
5634
  }
5469
5635
  async function requestWorkspaceAccess(arbi, params, crypto2) {
@@ -6942,10 +7108,10 @@ function attachmentFromBytes(name, contentType, bytes) {
6942
7108
  name,
6943
7109
  content_type: contentType,
6944
7110
  size: bytes.length,
6945
- content_base64: bytesToBase64(bytes)
7111
+ content_base64: bytesToBase642(bytes)
6946
7112
  };
6947
7113
  }
6948
- function bytesToBase64(bytes) {
7114
+ function bytesToBase642(bytes) {
6949
7115
  let binary = "";
6950
7116
  for (let i2 = 0; i2 < bytes.length; i2 += 32768) {
6951
7117
  binary += String.fromCharCode(...bytes.subarray(i2, i2 + 32768));