@arbidocs/sdk 0.4.49 → 0.4.51

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.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { t as ConfigStore, q as CliConfig, r as CliCredentials, C as ChatSession, ao as SkippedFile, az as UploadResult, m as AuthHeaders, av as UploadBatchResult, ay as UploadOptions, aw as UploadDirectOptions, ax as UploadDirectResult, am as SUPPORTED_EXTENSIONS, T as MailAttachment, E as DmCryptoContext } from './browser-CQ3lohen.cjs';
2
- export { A as ActivityKind, a as ActivityResponse, d as AgentStepEvent, e as Arbi, f as ArbiApiError, g as ArbiError, i as ArbiOptions, j as ArbiSessionExpiredError, k as ArtifactEvent, l as AuthContext, n as AuthMode, o as AuthenticatedClient, p as CitationSummary, s as CommandDescriptor, u as ConnectOptions, v as ConversationResponse, y as CreateWorkRequest, z as CreateWorkflowRequest, D as DOC_TERMINAL_STATUSES, F as DocNameMap, G as DocumentAutomationAction, H as DocumentListFields, I as DocumentListOrder, J as DocumentSelector, K as DocumentWaiter, L as DocumentWaiterOptions, P as FormattedWsMessage, Q as ListAllOptions, S as ListPaginatedOptions, U as MessageLevel, V as MessageMetadataPayload, W as MessageQueuedEvent, X as OutputTokensDetails, Y as ParsedSlashCommand, Z as PendingAuthResponse, _ as PlanWorkRequest, a0 as ProjectInvoicesResponse, a1 as ProjectUsageResponse, a2 as QueryOptions, a3 as ReconnectOptions, a4 as ReconnectableWsConnection, a5 as RequestApprovalRequest, a6 as ResolvedCitation, a7 as ResolvedRecipient, 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, 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, aO as agents, aP as assistant, aQ as authenticatedFetch, aR as buildDocNameMap, 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, b0 as createDocumentWaiter, 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, ba as formatStreamSummary, bb as formatUserName, bc as formatWorkspaceChoices, bd as formatWsMessage, be as generateEncryptedWorkspaceKey, bf as generateNewWorkspaceKey, bg as getErrorCode, bh as getErrorMessage, bi as getRawWorkspaceKey, bj as health, bk as mail, bl as parseSSEEvents, bm as parseSlashCommand, bn as parseSlashTokenInProgress, bo as performPasswordLogin, bp as performSigningKeyLogin, bq as performSsoDeviceFlowLogin, 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
+ import { t as ConfigStore, q as CliConfig, r as CliCredentials, C as ChatSession, ar as SkippedFile, aC as UploadResult, m as AuthHeaders, ay as UploadBatchResult, aB as UploadOptions, az as UploadDirectOptions, aA as UploadDirectResult, ap as SUPPORTED_EXTENSIONS, W as MailAttachment, H as DmCryptoContext } from './browser-ottmzMPY.cjs';
2
+ export { A as ActivityKind, a as ActivityResponse, d as AgentStepEvent, e as Arbi, f as ArbiApiError, g as ArbiError, i as ArbiOptions, j as ArbiSessionExpiredError, k as ArtifactEvent, l as AuthContext, n as AuthMode, o as AuthenticatedClient, p as CitationSummary, s as CommandDescriptor, u as ConnectOptions, v as ConversationResponse, y as CreateWorkRequest, z as CreateWorkflowRequest, D as DOC_TERMINAL_STATUSES, B as DecryptedDmNotification, F as DmAttachmentFile, G as DmAttachmentInput, I as DocNameMap, J as DocumentAutomationAction, K as DocumentListFields, L as DocumentListOrder, M as DocumentSelector, N as DocumentWaiter, O as DocumentWaiterOptions, S as FormattedWsMessage, T as ListAllOptions, V as ListPaginatedOptions, X as MessageLevel, Y as MessageMetadataPayload, Z as MessageQueuedEvent, _ as OutputTokensDetails, $ as ParsedSlashCommand, a0 as PendingAuthResponse, a1 as PlanWorkRequest, a3 as ProjectInvoicesResponse, a4 as ProjectUsageResponse, a5 as QueryOptions, a6 as ReconnectOptions, a7 as ReconnectableWsConnection, a8 as RequestApprovalRequest, a9 as ResolvedCitation, aa as ResolvedRecipient, 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, 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, aR as agents, aS as assistant, aT as authenticatedFetch, aU as buildDocNameMap, 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, b3 as createDocumentWaiter, 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, bd as formatStreamSummary, be as formatUserName, bf as formatWorkspaceChoices, bg as formatWsMessage, bh as generateEncryptedWorkspaceKey, bi as generateNewWorkspaceKey, bj as getErrorCode, bk as getErrorMessage, bl as getRawWorkspaceKey, bm as health, bn as mail, bo as parseSSEEvents, bp as parseSlashCommand, bq as parseSlashTokenInProgress, br as performPasswordLogin, bs as performSigningKeyLogin, bt as performSsoDeviceFlowLogin, 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';
3
3
  import { SessionStorageProvider, ArbiClient } from '@arbidocs/client';
4
4
  export { LoginProfile } from '@arbidocs/client';
5
5
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { t as ConfigStore, q as CliConfig, r as CliCredentials, C as ChatSession, ao as SkippedFile, az as UploadResult, m as AuthHeaders, av as UploadBatchResult, ay as UploadOptions, aw as UploadDirectOptions, ax as UploadDirectResult, am as SUPPORTED_EXTENSIONS, T as MailAttachment, E as DmCryptoContext } from './browser-CQ3lohen.js';
2
- export { A as ActivityKind, a as ActivityResponse, d as AgentStepEvent, e as Arbi, f as ArbiApiError, g as ArbiError, i as ArbiOptions, j as ArbiSessionExpiredError, k as ArtifactEvent, l as AuthContext, n as AuthMode, o as AuthenticatedClient, p as CitationSummary, s as CommandDescriptor, u as ConnectOptions, v as ConversationResponse, y as CreateWorkRequest, z as CreateWorkflowRequest, D as DOC_TERMINAL_STATUSES, F as DocNameMap, G as DocumentAutomationAction, H as DocumentListFields, I as DocumentListOrder, J as DocumentSelector, K as DocumentWaiter, L as DocumentWaiterOptions, P as FormattedWsMessage, Q as ListAllOptions, S as ListPaginatedOptions, U as MessageLevel, V as MessageMetadataPayload, W as MessageQueuedEvent, X as OutputTokensDetails, Y as ParsedSlashCommand, Z as PendingAuthResponse, _ as PlanWorkRequest, a0 as ProjectInvoicesResponse, a1 as ProjectUsageResponse, a2 as QueryOptions, a3 as ReconnectOptions, a4 as ReconnectableWsConnection, a5 as RequestApprovalRequest, a6 as ResolvedCitation, a7 as ResolvedRecipient, 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, 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, aO as agents, aP as assistant, aQ as authenticatedFetch, aR as buildDocNameMap, 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, b0 as createDocumentWaiter, 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, ba as formatStreamSummary, bb as formatUserName, bc as formatWorkspaceChoices, bd as formatWsMessage, be as generateEncryptedWorkspaceKey, bf as generateNewWorkspaceKey, bg as getErrorCode, bh as getErrorMessage, bi as getRawWorkspaceKey, bj as health, bk as mail, bl as parseSSEEvents, bm as parseSlashCommand, bn as parseSlashTokenInProgress, bo as performPasswordLogin, bp as performSigningKeyLogin, bq as performSsoDeviceFlowLogin, 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
+ import { t as ConfigStore, q as CliConfig, r as CliCredentials, C as ChatSession, ar as SkippedFile, aC as UploadResult, m as AuthHeaders, ay as UploadBatchResult, aB as UploadOptions, az as UploadDirectOptions, aA as UploadDirectResult, ap as SUPPORTED_EXTENSIONS, W as MailAttachment, H as DmCryptoContext } from './browser-ottmzMPY.js';
2
+ export { A as ActivityKind, a as ActivityResponse, d as AgentStepEvent, e as Arbi, f as ArbiApiError, g as ArbiError, i as ArbiOptions, j as ArbiSessionExpiredError, k as ArtifactEvent, l as AuthContext, n as AuthMode, o as AuthenticatedClient, p as CitationSummary, s as CommandDescriptor, u as ConnectOptions, v as ConversationResponse, y as CreateWorkRequest, z as CreateWorkflowRequest, D as DOC_TERMINAL_STATUSES, B as DecryptedDmNotification, F as DmAttachmentFile, G as DmAttachmentInput, I as DocNameMap, J as DocumentAutomationAction, K as DocumentListFields, L as DocumentListOrder, M as DocumentSelector, N as DocumentWaiter, O as DocumentWaiterOptions, S as FormattedWsMessage, T as ListAllOptions, V as ListPaginatedOptions, X as MessageLevel, Y as MessageMetadataPayload, Z as MessageQueuedEvent, _ as OutputTokensDetails, $ as ParsedSlashCommand, a0 as PendingAuthResponse, a1 as PlanWorkRequest, a3 as ProjectInvoicesResponse, a4 as ProjectUsageResponse, a5 as QueryOptions, a6 as ReconnectOptions, a7 as ReconnectableWsConnection, a8 as RequestApprovalRequest, a9 as ResolvedCitation, aa as ResolvedRecipient, 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, 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, aR as agents, aS as assistant, aT as authenticatedFetch, aU as buildDocNameMap, 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, b3 as createDocumentWaiter, 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, bd as formatStreamSummary, be as formatUserName, bf as formatWorkspaceChoices, bg as formatWsMessage, bh as generateEncryptedWorkspaceKey, bi as generateNewWorkspaceKey, bj as getErrorCode, bk as getErrorMessage, bl as getRawWorkspaceKey, bm as health, bn as mail, bo as parseSSEEvents, bp as parseSlashCommand, bq as parseSlashTokenInProgress, br as performPasswordLogin, bs as performSigningKeyLogin, bt as performSsoDeviceFlowLogin, 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';
3
3
  import { SessionStorageProvider, ArbiClient } from '@arbidocs/client';
4
4
  export { LoginProfile } from '@arbidocs/client';
5
5
 
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, deriveEncryptionKeypairFromSigning, sealedBoxDecrypt, sealKeyForSession, buildWebSocketUrl, createAuthMessage, parseServerMessage, isMessageType, createContentHash, encryptFile, changePasswordWithRekey, initSodium } from '@arbidocs/client';
4
+ import { createArbiClient, base64ToBytes, deriveEncryptionKeypairFromSigning, sealedBoxDecrypt, sealKeyForSession, buildWebSocketUrl, createAuthMessage, parseServerMessage, isMessageType, createContentHash, encryptFile, initSodium, bytesToBase64, decryptFile, changePasswordWithRekey } from '@arbidocs/client';
5
5
  import { execSync, spawn } from 'child_process';
6
6
  import { createHash } from 'crypto';
7
7
  import { fileURLToPath } from 'url';
@@ -5786,19 +5786,29 @@ async function generateDocTags(arbi, tagIds, docIds, options) {
5786
5786
  // src/operations/dm.ts
5787
5787
  var dm_exports = {};
5788
5788
  __export(dm_exports, {
5789
+ DM_ATTACHMENT_MAX_BYTES: () => DM_ATTACHMENT_MAX_BYTES,
5790
+ DM_ATTACHMENT_MAX_FILES: () => DM_ATTACHMENT_MAX_FILES,
5791
+ checkDmAttachmentLimits: () => checkDmAttachmentLimits,
5789
5792
  createDmCryptoContext: () => createDmCryptoContext,
5793
+ decryptDmAttachments: () => decryptDmAttachments,
5790
5794
  decryptDmBatch: () => decryptDmBatch,
5791
5795
  decryptDmContent: () => decryptDmContent,
5792
5796
  deleteDMs: () => deleteDMs,
5797
+ downloadDmAttachment: () => downloadDmAttachment,
5798
+ encryptDmAttachmentManifest: () => encryptDmAttachmentManifest,
5793
5799
  encryptDmContent: () => encryptDmContent,
5794
5800
  listActivity: () => listActivity,
5795
5801
  listDMs: () => listDMs,
5796
5802
  listDecryptedDMs: () => listDecryptedDMs,
5797
5803
  markRead: () => markRead,
5804
+ parseDmAttachmentManifest: () => parseDmAttachmentManifest,
5798
5805
  requestWorkspaceAccess: () => requestWorkspaceAccess,
5799
5806
  resolveRecipient: () => resolveRecipient,
5800
5807
  sendDM: () => sendDM,
5801
- sendEncryptedDM: () => sendEncryptedDM
5808
+ sendEncryptedDM: () => sendEncryptedDM,
5809
+ serializeDmAttachmentManifest: () => serializeDmAttachmentManifest,
5810
+ uploadDmAttachment: () => uploadDmAttachment,
5811
+ uploadDmAttachments: () => uploadDmAttachments
5802
5812
  });
5803
5813
 
5804
5814
  // src/operations/agents.ts
@@ -5905,6 +5915,138 @@ async function stageAgentFile(auth, agentId, file, name) {
5905
5915
  });
5906
5916
  return response.json();
5907
5917
  }
5918
+ var DM_ATTACHMENT_MAX_BYTES = 15 * 1024 * 1024;
5919
+ var DM_ATTACHMENT_MAX_FILES = 10;
5920
+ var ATTACHMENT_ID = /^att-[a-zA-Z0-9]{8}$/;
5921
+ var MANIFEST_VERSION = 1;
5922
+ var MB = 1024 * 1024;
5923
+ function checkDmAttachmentLimits(files) {
5924
+ if (files.length > DM_ATTACHMENT_MAX_FILES) {
5925
+ throw new Error(
5926
+ `You can attach at most ${DM_ATTACHMENT_MAX_FILES} files to a message (this one has ${files.length}).`
5927
+ );
5928
+ }
5929
+ for (const file of files) {
5930
+ if (file.size > DM_ATTACHMENT_MAX_BYTES) {
5931
+ throw new Error(
5932
+ `${file.name} is too large (${(file.size / MB).toFixed(1)} MB). Files can be at most ${DM_ATTACHMENT_MAX_BYTES / MB} MB.`
5933
+ );
5934
+ }
5935
+ }
5936
+ }
5937
+ async function uploadDmAttachment(arbi, input) {
5938
+ checkDmAttachmentLimits([{ name: input.name, size: input.bytes.length }]);
5939
+ await initSodium();
5940
+ const key = globalThis.crypto.getRandomValues(new Uint8Array(32));
5941
+ try {
5942
+ const ciphertext = encryptFile(input.bytes, key);
5943
+ const form = new FormData();
5944
+ form.append(
5945
+ "file",
5946
+ new Blob([ciphertext], { type: "application/octet-stream" }),
5947
+ "attachment.bin"
5948
+ );
5949
+ const result = await arbi.fetch.POST("/v1/notifications/attachments", {
5950
+ body: { file: "" },
5951
+ bodySerializer: () => form
5952
+ });
5953
+ if (result.response?.status === 413) {
5954
+ throw new ArbiApiError(
5955
+ `${input.name} is too large. Files can be at most ${DM_ATTACHMENT_MAX_BYTES / MB} MB.`,
5956
+ result.error,
5957
+ 413
5958
+ );
5959
+ }
5960
+ const uploaded = requireData(result, `Failed to upload ${input.name}`);
5961
+ return {
5962
+ id: uploaded.external_id,
5963
+ name: input.name,
5964
+ type: input.type || "application/octet-stream",
5965
+ size: input.bytes.length,
5966
+ key: bytesToBase64(key)
5967
+ };
5968
+ } finally {
5969
+ key.fill(0);
5970
+ }
5971
+ }
5972
+ async function uploadDmAttachments(arbi, inputs) {
5973
+ checkDmAttachmentLimits(inputs.map((i2) => ({ name: i2.name, size: i2.bytes.length })));
5974
+ const files = [];
5975
+ for (const input of inputs) files.push(await uploadDmAttachment(arbi, input));
5976
+ return files;
5977
+ }
5978
+ function serializeDmAttachmentManifest(files) {
5979
+ return JSON.stringify({
5980
+ v: MANIFEST_VERSION,
5981
+ files: files.map(({ id, name, type, size, key }) => ({ id, name, type, size, key }))
5982
+ });
5983
+ }
5984
+ function parseDmAttachmentManifest(json2) {
5985
+ const manifest = JSON.parse(json2);
5986
+ if (manifest?.v !== MANIFEST_VERSION || !Array.isArray(manifest.files)) {
5987
+ throw new Error("Unsupported attachment manifest");
5988
+ }
5989
+ return manifest.files.map((entry) => {
5990
+ const f2 = entry;
5991
+ 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") {
5992
+ throw new Error("Malformed attachment manifest");
5993
+ }
5994
+ return {
5995
+ id: f2.id,
5996
+ name: f2.name,
5997
+ type: typeof f2.type === "string" && f2.type ? f2.type : "application/octet-stream",
5998
+ size: f2.size,
5999
+ key: f2.key
6000
+ };
6001
+ });
6002
+ }
6003
+ async function encryptDmAttachmentManifest(arbi, files, recipientEncryptionPubKeyBase64, senderEncryptionSecretKey) {
6004
+ return arbi.crypto.encryptMessage(
6005
+ serializeDmAttachmentManifest(files),
6006
+ recipientEncryptionPubKeyBase64,
6007
+ senderEncryptionSecretKey
6008
+ );
6009
+ }
6010
+ async function decryptDmAttachments(arbi, notification, crypto2) {
6011
+ if (!notification.attachments) return [];
6012
+ const isSent = notification.sender.external_id === crypto2.userExtId;
6013
+ const otherParty = isSent ? notification.recipient : notification.sender;
6014
+ const json2 = await arbi.crypto.decryptMessage(
6015
+ notification.attachments,
6016
+ otherParty.encryption_public_key,
6017
+ crypto2.encryptionKeypair.secretKey
6018
+ );
6019
+ return parseDmAttachmentManifest(json2);
6020
+ }
6021
+ async function downloadDmAttachment(arbi, file) {
6022
+ if (!ATTACHMENT_ID.test(file.id)) throw new Error(`Invalid attachment id: ${file.id}`);
6023
+ const result = await arbi.fetch.GET("/v1/notifications/attachments/{external_id}", {
6024
+ params: { path: { external_id: file.id } },
6025
+ parseAs: "arrayBuffer"
6026
+ });
6027
+ if (result.response?.status === 404) {
6028
+ throw new ArbiApiError(`${file.name} is no longer available`, result.error, 404);
6029
+ }
6030
+ const ciphertext = requireData(
6031
+ result,
6032
+ `Failed to download ${file.name}`
6033
+ );
6034
+ await initSodium();
6035
+ const key = base64ToBytes(file.key);
6036
+ let plain;
6037
+ try {
6038
+ if (key.length !== 32) throw new Error("bad key");
6039
+ plain = decryptFile(new Uint8Array(ciphertext), key);
6040
+ } catch {
6041
+ throw new Error(`Could not decrypt ${file.name}: the file was altered or the key is wrong`);
6042
+ } finally {
6043
+ key.fill(0);
6044
+ }
6045
+ if (plain.length !== file.size) {
6046
+ throw new Error(`${file.name} is ${plain.length} bytes, expected ${file.size} bytes`);
6047
+ }
6048
+ return plain;
6049
+ }
5908
6050
 
5909
6051
  // src/operations/dm.ts
5910
6052
  function createDmCryptoContext(arbi, signingPrivateKeyBytes, userExtId) {
@@ -5935,16 +6077,25 @@ async function decryptDmContent(arbi, notification, crypto2) {
5935
6077
  async function decryptDmBatch(arbi, notifications, crypto2) {
5936
6078
  const results = [];
5937
6079
  for (const n2 of notifications) {
5938
- if (n2.type !== "user_message" || !n2.content) {
6080
+ if (n2.type !== "user_message" || !n2.content && !n2.attachments) {
5939
6081
  results.push(n2);
5940
6082
  continue;
5941
6083
  }
6084
+ let row;
5942
6085
  try {
5943
- const plaintext = await decryptDmContent(arbi, n2, crypto2);
5944
- results.push({ ...n2, content: plaintext });
6086
+ row = { ...n2, content: await decryptDmContent(arbi, n2, crypto2) };
5945
6087
  } catch {
5946
- results.push({ ...n2, content: "[Decryption failed]" });
6088
+ row = { ...n2, content: "[Decryption failed]" };
5947
6089
  }
6090
+ if (n2.attachments) {
6091
+ try {
6092
+ row.attachmentFiles = await decryptDmAttachments(arbi, n2, crypto2);
6093
+ } catch {
6094
+ row.attachmentFiles = [];
6095
+ row.attachmentsError = "The attachments could not be decrypted";
6096
+ }
6097
+ }
6098
+ results.push(row);
5948
6099
  }
5949
6100
  return results;
5950
6101
  }
@@ -6000,7 +6151,9 @@ async function resolveRecipient(arbi, ref) {
6000
6151
  }
6001
6152
  return null;
6002
6153
  }
6003
- async function sendEncryptedDM(arbi, messages, crypto2) {
6154
+ async function sendEncryptedDM(arbi, messages, crypto2, options) {
6155
+ const attachments = options?.attachments ?? [];
6156
+ checkDmAttachmentLimits(attachments);
6004
6157
  const plaintextFor = new Map(messages.map((m2) => [m2.recipient_ext_id, m2.content]));
6005
6158
  const encrypted = await Promise.all(
6006
6159
  messages.map(async (msg) => ({
@@ -6010,18 +6163,31 @@ async function sendEncryptedDM(arbi, messages, crypto2) {
6010
6163
  msg.content,
6011
6164
  msg.recipient_encryption_public_key,
6012
6165
  crypto2.encryptionKeypair.secretKey
6013
- )
6166
+ ),
6167
+ ...attachments.length ? {
6168
+ attachments: await encryptDmAttachmentManifest(
6169
+ arbi,
6170
+ attachments,
6171
+ msg.recipient_encryption_public_key,
6172
+ crypto2.encryptionKeypair.secretKey
6173
+ )
6174
+ } : {}
6014
6175
  }))
6015
6176
  );
6016
6177
  const created = requireData(
6017
6178
  await arbi.fetch.POST("/v1/notifications/", {
6018
- body: { messages: encrypted, context_only: false }
6179
+ body: {
6180
+ messages: encrypted,
6181
+ context_only: false,
6182
+ ...attachments.length ? { attachment_ext_ids: attachments.map((f2) => f2.id) } : {}
6183
+ }
6019
6184
  }),
6020
6185
  "Failed to send message"
6021
6186
  );
6022
6187
  return created.map((n2) => ({
6023
6188
  ...n2,
6024
- content: plaintextFor.get(n2.recipient.external_id) ?? n2.content
6189
+ content: plaintextFor.get(n2.recipient.external_id) ?? n2.content,
6190
+ ...attachments.length ? { attachmentFiles: attachments } : {}
6025
6191
  }));
6026
6192
  }
6027
6193
  async function requestWorkspaceAccess(arbi, params, crypto2) {
@@ -8245,10 +8411,10 @@ function attachmentFromBytes(name, contentType, bytes) {
8245
8411
  name,
8246
8412
  content_type: contentType,
8247
8413
  size: bytes.length,
8248
- content_base64: bytesToBase64(bytes)
8414
+ content_base64: bytesToBase642(bytes)
8249
8415
  };
8250
8416
  }
8251
- function bytesToBase64(bytes) {
8417
+ function bytesToBase642(bytes) {
8252
8418
  let binary = "";
8253
8419
  for (let i2 = 0; i2 < bytes.length; i2 += 32768) {
8254
8420
  binary += String.fromCharCode(...bytes.subarray(i2, i2 + 32768));