Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

📎 feat: Copy Chat Attachments into Attached Workspaces (#17376)

Danny Avila5e90cc45e4af
diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.js
index f65874a490..2f102f8f8d 100644
--- a/api/server/services/Endpoints/agents/initialize.js
+++ b/api/server/services/Endpoints/agents/initialize.js
@@ -10,6 +10,7 @@ const {
resolveInitializationProjectContext,
initializeAgent,
primeInvokedSkillsForProfiles,
+ createWorkspaceAttachmentPrimer,
validateAgentModel,
extractManualSkills,
GenerationJobManager,
@@ -100,6 +101,7 @@ const {
provisionToCodeEnv,
provisionToVectorDB,
checkSessionsAlive,
+ digestFile,
} = require('~/server/services/Files/provision');
const { createProvisionFilesCallback } = require('~/server/services/Files/provisionCallback');
const { getModelsConfig } = require('~/server/controllers/ModelController');
@@ -594,6 +596,21 @@ const initializeClientWithProvider = async ({
}),
};
+ const primeAttachments = createWorkspaceAttachmentPrimer({
+ toolContexts: agentToolContexts,
+ getProvisionFiles: () => toolExecuteOptions.provisionFiles,
+ deps: {
+ userId: req.user.id,
+ conversationId,
+ getAuthHeaders: (workerId) => getCodeApiAuthHeaders(req, workerId),
+ digestFile: (file, digestSignal) => digestFile({ req, file, signal: digestSignal }),
+ recordImport: db.recordFileWorkspaceImport,
+ codeApiMaxRetryWaitMs: appConfig?.endpoints?.agents?.codeApiMaxRetryWaitMs,
+ timeoutMs: appConfig?.endpoints?.agents?.workspaceAttachments?.timeoutMs,
+ concurrency: appConfig?.endpoints?.agents?.workspaceAttachments?.concurrency,
+ },
+ });
+
const summarizationOptions =
appConfig?.summarization?.enabled === false ? { enabled: false } : { enabled: true };
@@ -1480,14 +1497,22 @@ const initializeClientWithProvider = async ({
if (config.userMCPAuthMap) {
Object.assign(userMCPAuthMap, config.userMCPAuthMap);
}
+ const toolContext = buildAgentToolContext({ agent: routedAgent, config });
subagentCodeRouting.attach(agentToolContexts, {
agentId,
context,
placement,
codeExecutionContext: config.codeExecutionContext,
- toolContext: buildAgentToolContext({ agent: routedAgent, config }),
+ toolContext,
});
endpointTokenConfigByAgentId.set(agentId, config.endpointTokenConfig);
+ /** A routed execution keeps its own tool context, so provision against exactly that one. */
+ const ownToolContexts = new Map([[agentId, toolContext]]);
+ await primeAttachments([config], {
+ signal: context.signal,
+ toolContexts: ownToolContexts,
+ provisionFiles: createProvisionFilesCallback({ req, agentToolContexts: ownToolContexts }),
+ });
return config;
};
const initializeLazySubagent = async ({
@@ -2032,6 +2057,7 @@ const initializeClientWithProvider = async ({
toolExecuteOptions.provisionFiles = runFileBindings.wrapProvision(
toolExecuteOptions.provisionFiles,
);
+ await primeAttachments([primaryConfig, ...agentConfigs.values()], { signal });
const eventHandlers = getDefaultHandlers({
res,
diff --git a/api/server/services/Endpoints/agents/initialize.spec.js b/api/server/services/Endpoints/agents/initialize.spec.js
index 0b90e7aea8..bc354fbb6d 100644
--- a/api/server/services/Endpoints/agents/initialize.spec.js
+++ b/api/server/services/Endpoints/agents/initialize.spec.js
@@ -648,6 +648,47 @@ describe('initializeClient — processAgent ACL gate', () => {
});
});
+ it('rewrites the attached-workspace file note before the agent runs', async () => {
+ const config = makePrimaryConfig([]);
+ config.codeExecutionContext = {
+ baseUrl: 'https://code-attached.example.com',
+ codeSessionKey: 'execute_code',
+ executionProfile: 'stateful',
+ statefulSessions: true,
+ environmentType: 'attached',
+ environmentId: 'machine',
+ codeWorkspace: {
+ environmentId: 'machine',
+ workspaceId: 'primary',
+ operations: ['read_file'],
+ },
+ };
+ config.dynamicToolContextMap = { execute_code: 'programmatic-only note' };
+ config.codeContextEntries = [
+ {
+ file: { file_id: 'upload-1', filename: 'release.zip', user: testUser._id.toString() },
+ destination: 'release.zip',
+ agentScoped: false,
+ source: { storage_session_id: 'session-1', file_id: 'object-1' },
+ },
+ ];
+ mockInitializeAgent.mockResolvedValue(config);
+
+ await initializeClient({
+ req: makeReq(),
+ res: {},
+ signal: new AbortController().signal,
+ endpointOption: makeEndpointOption(),
+ });
+
+ expect(agentClientArgs.agent.dynamicToolContextMap.execute_code).toContain(
+ "release.zip (attached by user): this machine's LibreChat worker cannot receive attachments yet",
+ );
+ expect(agentClientArgs.agent.dynamicToolContextMap.execute_code).not.toContain(
+ '$LIBRECHAT_CODE_DATA_DIR',
+ );
+ });
+
it('binds foreground tool execution to the host-owned run signal', async () => {
mockInitializeAgent.mockResolvedValue(makePrimaryConfig([]));
const controller = new AbortController();
diff --git a/api/server/services/Files/Code/process.js b/api/server/services/Files/Code/process.js
index 405fdda029..81901e0c74 100644
--- a/api/server/services/Files/Code/process.js
+++ b/api/server/services/Files/Code/process.js
@@ -689,6 +689,7 @@ const getReuploadFailureCategory = (error) => {
* @returns {Promise<{
* files: Array<{ id: string; session_id: string; name: string }>,
* toolContext: string,
+ * contextFiles?: import('@librechat/api').CodeContextEntry[],
* }>}
*/
const primeFiles = async (options) => {
@@ -748,6 +749,8 @@ const primeFiles = async (options) => {
/** All stale-file reuploads in this prime share one live-turn wait cap. */
const uploadRateLimitBudget = createCodeApiRateLimitBudget(uploadOptions.retryWaitMs);
let toolContext = '';
+ /** An attached workspace rebuilds this note once attachments are copied in. */
+ const contextFiles = codeFileLocation === 'programmatic' ? [] : undefined;
const { selected, skippedNoRef, skippedSuperseded } = await selectCodeFiles({
files: dbFiles,
@@ -785,11 +788,24 @@ const primeFiles = async (options) => {
const pushFile = (overrideSessionId, overrideId, destination = sandboxName) => {
/* The sandbox holds the converted name, not the record's, so the mount path has
* to follow the same rule provisioning uploaded under. */
- toolContext = appendCodeFileContextLine(
- toolContext,
- getCodeFileContextLine(file, agentResourceIds, destination, codeFileLocation),
+ const contextLine = getCodeFileContextLine(
+ file,
+ agentResourceIds,
+ destination,
codeFileLocation,
);
+ toolContext = appendCodeFileContextLine(toolContext, contextLine, codeFileLocation);
+ if (contextFiles && contextLine) {
+ contextFiles.push({
+ file,
+ destination,
+ agentScoped: agentResourceIds.has(file.file_id),
+ source: {
+ storage_session_id: overrideSessionId ?? session_id,
+ file_id: overrideId ?? id,
+ },
+ });
+ }
/* `id` is the storage file_id (drives codeapi's upload-key
* existence check), `resource_id` is the entity that owns
* the storage session (drives sessionKey re-derivation). For
@@ -980,7 +996,7 @@ const primeFiles = async (options) => {
});
}
- return { files, toolContext };
+ return { files, toolContext, ...(contextFiles?.length ? { contextFiles } : {}) };
};
/**
diff --git a/api/server/services/Files/Code/process.spec.js b/api/server/services/Files/Code/process.spec.js
index a8a682a2d7..e4cf5db6f0 100644
--- a/api/server/services/Files/Code/process.spec.js
+++ b/api/server/services/Files/Code/process.spec.js
@@ -4123,6 +4123,30 @@ describe('Code Process', () => {
expect(result.toolContext).not.toContain('/mnt/data');
expect(result.toolContext).not.toContain('tool environment:');
expect(result.files).toHaveLength(1);
+ expect(result.contextFiles).toEqual([
+ {
+ file: expect.objectContaining({ file_id: 'fid-ready' }),
+ destination: 'data-ready.xlsx',
+ agentScoped: true,
+ source: {
+ storage_session_id: result.files[0].storage_session_id,
+ file_id: result.files[0].id,
+ },
+ },
+ ]);
+ });
+
+ it('returns no structured entries on a sandbox route', async () => {
+ setupSessionInfoOk();
+ getFiles.mockResolvedValue([makeFile({ status: 'ready' })]);
+
+ const result = await primeFiles({
+ req: { user: { id: 'user-123', role: 'USER' } },
+ tool_resources: { execute_code: { file_ids: ['fid-ready'], files: [] } },
+ agentId: 'agent-id',
+ });
+
+ expect(result.contextFiles).toBeUndefined();
});
it('annotates a pending file with "(preview not yet generated)"', async () => {
diff --git a/api/server/services/Files/provision.js b/api/server/services/Files/provision.js
index 8c2eb618bb..9cbbb20a47 100644
--- a/api/server/services/Files/provision.js
+++ b/api/server/services/Files/provision.js
@@ -18,5 +18,6 @@ module.exports = {
loadCodeApiKey: (...args) => getService().loadCodeApiKey(...args),
provisionToCodeEnv: (...args) => getService().provisionToCodeEnv(...args),
provisionToVectorDB: (...args) => getService().provisionToVectorDB(...args),
+ digestFile: (...args) => getService().digestFile(...args),
checkSessionsAlive: (...args) => getService().checkSessionsAlive(...args),
};
diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.js
index 6ed4d5bab5..ef1cfecd5b 100644
--- a/api/server/services/ToolService.js
+++ b/api/server/services/ToolService.js
@@ -1555,9 +1555,10 @@ async function loadToolDefinitionsWrapper({
* sandbox can't see the prior turn's generated artifacts on first read.
*/
let primedCodeFiles;
+ let codeContextEntries;
if (hasExecuteCode && tool_resources) {
try {
- const { toolContext, files } = await primeCodeFiles({
+ const { toolContext, files, contextFiles } = await primeCodeFiles({
req,
tool_resources,
agentId: agent.id,
@@ -1577,6 +1578,7 @@ async function loadToolDefinitionsWrapper({
if (files?.length) {
primedCodeFiles = files;
}
+ codeContextEntries = contextFiles;
} catch (error) {
if (isFatalAgentInitializationError(error, { signal })) {
throw error;
@@ -1648,6 +1650,7 @@ async function loadToolDefinitionsWrapper({
mcpToolAliases,
actionsEnabled,
primedCodeFiles,
+ codeContextEntries,
oauthActionToolNames,
codeExecutionContext: resolvedCodeExecutionContext,
repositoryInstructionSource: createRepositoryInstructionSource({
diff --git a/packages/api/src/agents/hitl/byom.ts b/packages/api/src/agents/hitl/byom.ts
index 12bc7e0191..59559ea87b 100644
--- a/packages/api/src/agents/hitl/byom.ts
+++ b/packages/api/src/agents/hitl/byom.ts
@@ -275,6 +275,16 @@ function permissionDecision(
return resolveCodePermissionDecision({ mode: effectiveMode, category, decision });
}
+/**
+ * Whether this machine denies file writes outright, before any turn mode applies. A chat
+ * upload is the user's consent where the policy only asks, never where it denies.
+ */
+export function isAttachedFileWriteDenied(
+ policy: AttachedCodeEnvironmentPolicySettings | undefined,
+): boolean {
+ return permissionDecision(policy, 'fileWrite') === 'deny';
+}
+
function isCodeApprovalMode(value: unknown): value is CodeApprovalMode {
return CODE_APPROVAL_MODES.some((mode) => mode === value);
}
diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.ts
index ccb4f54ab1..c0f13b696a 100644
--- a/packages/api/src/agents/initialize.ts
+++ b/packages/api/src/agents/initialize.ts
@@ -67,6 +67,7 @@ import type { ResolvedChatProjectContext } from '../projects/context';
import type { TextContentFragment } from '../protection/types';
import type { CheckAccessParams } from '../middleware/access';
import type { GetProjectFiles } from '../projects/resources';
+import type { CodeContextEntry } from '~/files/code/priming';
import type { MCPToolAlias } from '~/tools/classification';
import type { CodeExecutionContext } from './execution';
import type { AgentExecutionContext } from './runtime';
@@ -913,6 +914,9 @@ export type InitializedAgent = Agent & {
* call #1 the sandbox can't see the files at all.
*/
primedCodeFiles?: import('@librechat/agents').CodeEnvFile[];
+ /** Files the primed code-file note described on an attached workspace, so the note can be
+ * rebuilt once attachments are copied in (`primeWorkspaceAttachments`). */
+ codeContextEntries?: CodeContextEntry[];
/**
* Resolved token/pricing config for this agent's endpoint (admin static
* `tokenConfig` and/or fetched custom-endpoint config). Surfaced from the
@@ -999,6 +1003,8 @@ export interface InitializeAgentParams {
* artifacts don't reach the sandbox.
*/
primedCodeFiles?: import('@librechat/agents').CodeEnvFile[];
+ /** Structured form of the primed code-file note on an attached workspace. */
+ codeContextEntries?: CodeContextEntry[];
/** Live workspace binding resolved by the execution-side loader. */
codeExecutionContext?: CodeExecutionContext;
repositoryInstructionSource?: RepositoryInstructionSource;
@@ -2261,6 +2267,7 @@ export async function initializeAgent(
oauthActionToolNames,
tools: structuredTools,
primedCodeFiles,
+ codeContextEntries,
codeExecutionContext: loadedCodeExecutionContext,
repositoryInstructionSource,
} = loadToolsResult ?? {
@@ -2277,6 +2284,7 @@ export async function initializeAgent(
actionsEnabled: undefined,
oauthActionToolNames: undefined,
primedCodeFiles: undefined,
+ codeContextEntries: undefined,
codeExecutionContext: undefined,
repositoryInstructionSource: undefined,
};
@@ -2889,6 +2897,7 @@ export async function initializeAgent(
? maxContextTokens
: Math.max(1024, Math.round(baseContextTokens * (1 - DEFAULT_RESERVE_RATIO))),
primedCodeFiles,
+ codeContextEntries,
endpointTokenConfig: options.endpointTokenConfig,
instructionsPromptFacts,
};
diff --git a/packages/api/src/agents/resources.ts b/packages/api/src/agents/resources.ts
index 513ab5e694..560e2283a7 100644
--- a/packages/api/src/agents/resources.ts
+++ b/packages/api/src/agents/resources.ts
@@ -130,6 +130,9 @@ export type ProvisionState = {
* another agent's setup file to this conversation, and provisioning it here would put
* it in a namespace this agent's other users can read. */
agentScopedFileIds: Set<string>;
+ /** Files an attached workspace's attachment note already describes; the queued-file note
+ * leaves them out rather than pointing at a second location. */
+ describedFileIds?: Set<string>;
};
/**
diff --git a/packages/api/src/code/attachments.spec.ts b/packages/api/src/code/attachments.spec.ts
new file mode 100644
index 0000000000..08e8ba8687
--- /dev/null
+++ b/packages/api/src/code/attachments.spec.ts
@@ -0,0 +1,1001 @@
+import { createHash } from 'node:crypto';
+import { Tools, FileContext } from 'librechat-data-provider';
+import { Constants as AgentConstants } from '@librechat/agents';
+import type { TFile, TurnFileConsumers, CodeWorkspaceOperation } from 'librechat-data-provider';
+import type { CodeEnvFile } from '@librechat/agents';
+import type { WorkspaceAttachmentAgent, WorkspaceImportRecord } from './attachments';
+import type { CodeExecutionContext } from '~/agents/execution';
+import type { ProvisionState } from '~/agents/resources';
+import type { CodeBridgeFetch } from './bridge';
+import {
+ toAttachmentName,
+ ignoresWholeFolder,
+ createWorkspaceAttachmentPrimer,
+ assignAttachmentNames,
+ primeWorkspaceAttachments,
+ importWorkspaceAttachments,
+ createWorkspaceAttachmentTurn,
+} from './attachments';
+import { prepareQueuedCodeFileContext } from '~/files/code/queued';
+import { executeWorkspaceTool } from './workspace';
+
+const USER_ID = 'user-1';
+const CONVERSATION_ID = 'convo-1';
+
+const sha = (content: string) => createHash('sha256').update(content).digest('hex');
+
+type WorkspaceRequest = {
+ operation: string;
+ workspaceId: string;
+ workspaceInstanceId?: string;
+ path: string;
+ content?: string;
+ overwrite?: boolean;
+ source?: { storage_session_id: string; id: string };
+ bytes?: number;
+ sha256?: string;
+};
+
+/**
+ * In-memory stand-in for the Code API and its attached worker, implementing the
+ * `import_file` contract: stored objects are copied by reference, a same-digest file is left
+ * unchanged, a different file at the path is a conflict, `write_file` is create-only, and
+ * `read_file` returns what is stored.
+ */
+function createFakeWorker({
+ objects = new Map<string, string>(),
+ delayMs = 0,
+ denyWrites = false,
+ truncateReads = false,
+}: {
+ objects?: Map<string, string>;
+ delayMs?: number;
+ denyWrites?: boolean;
+ truncateReads?: boolean;
+} = {}) {
+ const files = new Map<string, string>();
+ const requests: WorkspaceRequest[] = [];
+ const reply = (status: number, body: object) =>
+ new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
+ const fetchImpl: CodeBridgeFetch = async (_input, init) => {
+ const request = JSON.parse(String(init?.body)) as WorkspaceRequest;
+ requests.push(request);
+ if (delayMs > 0) {
+ await new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(resolve, delayMs);
+ init?.signal?.addEventListener('abort', () => {
+ clearTimeout(timer);
+ reject(init.signal?.reason);
+ });
+ });
+ }
+ const key = `${request.workspaceInstanceId ?? 'root'}:${request.path}`;
+ if (request.operation === 'read_file') {
+ const content = files.get(key) ?? '';
+ return reply(200, {
+ protocolVersion: 1,
+ operation: 'read_file',
+ workspaceId: request.workspaceId,
+ path: request.path,
+ content,
+ startLine: 1,
+ endLine: content.split('\n').length,
+ truncated: truncateReads,
+ ...(truncateReads ? { nextStartLine: content.split('\n').length + 1 } : {}),
+ });
+ }
+ if (denyWrites) {
+ return reply(403, { code: 'WRITE_DISABLED', error: 'File writes are disabled' });
+ }
+ if (request.operation === 'write_file') {
+ if (files.has(key) && request.overwrite === false) {
+ return reply(409, { code: 'EDIT_CONFLICT', error: 'Workspace file already exists' });
+ }
+ files.set(key, request.content ?? '');
+ return reply(200, {
+ protocolVersion: 1,
+ operation: 'write_file',
+ workspaceId: request.workspaceId,
+ path: request.path,
+ created: true,
+ bytesWritten: Buffer.byteLength(request.content ?? ''),
+ });
+ }
+ const content = objects.get(`${request.source?.storage_session_id}/${request.source?.id}`);
+ if (content == null || sha(content) !== request.sha256) {
+ return reply(422, { code: 'INVALID_REQUEST', error: 'source mismatch' });
+ }
+ const existing = files.get(key);
+ if (existing != null && sha(existing) === request.sha256) {
+ return reply(200, {
+ protocolVersion: 1,
+ operation: 'import_file',
+ workspaceId: request.workspaceId,
+ path: request.path,
+ created: false,
+ unchanged: true,
+ bytesWritten: 0,
+ sha256: request.sha256,
+ });
+ }
+ if (existing != null) {
+ return reply(409, { code: 'EDIT_CONFLICT', error: 'A different file exists' });
+ }
+ files.set(key, content);
+ return reply(200, {
+ protocolVersion: 1,
+ operation: 'import_file',
+ workspaceId: request.workspaceId,
+ path: request.path,
+ created: true,
+ bytesWritten: Buffer.byteLength(content),
+ sha256: request.sha256,
+ });
+ };
+ return { fetchImpl, files, requests, objects };
+}
+
+function attachedContext(
+ operations: CodeWorkspaceOperation[] = ['read_file', 'write_file', 'import_file'],
+ overrides: Partial<CodeExecutionContext> = {},
+ workspaceInstanceId?: string,
+): CodeExecutionContext {
+ return {
+ baseUrl: 'https://code.example/v1',
+ codeSessionKey: 'session',
+ executionProfile: 'stateful',
+ executionRouteKey: 'stateful:machine',
+ statefulSessions: true,
+ environmentType: 'attached',
+ environmentId: 'machine',
+ bridgeWorkerId: 'worker',
+ codeWorkspace: {
+ environmentId: 'machine',
+ workspaceId: 'primary',
+ operations,
+ ...(workspaceInstanceId ? { workspaceInstanceId } : {}),
+ },
+ ...overrides,
+ };
+}
+
+let fileCounter = 0;
+function chatFile(
+ filename: string,
+ content: string,
+ objects: Map<string, string>,
+ overrides: Partial<TFile> = {},
+): {
+ file: TFile;
+ destination: string;
+ agentScoped: boolean;
+ source: { storage_session_id: string; file_id: string };
+} {
+ fileCounter += 1;
+ const source = { storage_session_id: `session${fileCounter}`, file_id: `object${fileCounter}` };
+ objects.set(`${source.storage_session_id}/${source.file_id}`, content);
+ return {
+ file: {
+ file_id: `file-${fileCounter}`,
+ user: USER_ID,
+ filename,
+ filepath: `/uploads/${filename}`,
+ type: 'application/octet-stream',
+ bytes: Buffer.byteLength(content),
+ object: 'file',
+ usage: 0,
+ createdAt: new Date(2026, 0, 1, 0, 0, fileCounter).toISOString(),
+ ...overrides,
+ } as TFile,
+ destination: filename,
+ agentScoped: false,
+ source,
+ };
+}
+
+function createDeps(worker: ReturnType<typeof createFakeWorker>) {
+ const records: WorkspaceImportRecord[] = [];
+ const digests: string[] = [];
+ return {
+ records,
+ digests,
+ deps: {
+ userId: USER_ID,
+ conversationId: CONVERSATION_ID,
+ getAuthHeaders: async () => ({ Authorization: 'Bearer token' }),
+ digestFile: async (file: TFile) => {
+ digests.push(file.file_id);
+ const content = worker.objects.get(sourceOf.get(file.file_id) ?? '') ?? '';
+ return { sha256: sha(content), bytes: Buffer.byteLength(content) };
+ },
+ recordImport: async (record: WorkspaceImportRecord) => {
+ records.push(record);
+ },
+ codeApiMaxRetryWaitMs: 0,
+ fetchImpl: worker.fetchImpl,
+ },
+ };
+}
+
+/** Which stored object each test file was primed from, so the digest reads the same bytes. */
+const sourceOf = new Map<string, string>();
+const consumers: TurnFileConsumers = { executeCode: true, fileSearch: false };
+function remember<
+ T extends { file: TFile; source: { storage_session_id: string; file_id: string } },
+>(entry: T): T {
+ sourceOf.set(entry.file.file_id, `${entry.source.storage_session_id}/${entry.source.file_id}`);
+ return entry;
+}
+
+function agentWith(
+ context: CodeExecutionContext,
+ entries: WorkspaceAttachmentAgent['codeContextEntries'],
+ extra: Partial<WorkspaceAttachmentAgent> = {},
+): WorkspaceAttachmentAgent {
+ return {
+ id: 'agent-1',
+ codeExecutionContext: context,
+ codeContextEntries: entries,
+ dynamicToolContextMap: { [Tools.execute_code]: 'stale programmatic note' },
+ toolDefinitions: [{ name: AgentConstants.BASH_TOOL }],
+ ...extra,
+ };
+}
+
+beforeEach(() => {
+ sourceOf.clear();
+});
+
+describe('attachment names', () => {
+ it('keeps a name that is already portable', () => {
+ expect(toAttachmentName('Release notes (final).pdf')).toBe('Release notes (final).pdf');
+ expect(toAttachmentName('données-été.csv')).toBe('données-été.csv');
+ });
+
+ it('removes directories, unsafe characters, leading dots and reserved device names', () => {
+ expect(toAttachmentName('../../etc/passwd')).toBe('passwd');
+ expect(toAttachmentName('C:\\Users\\me\\report.docx')).toBe('report.docx');
+ expect(toAttachmentName('a<b>c:d"e|f?g*h.txt')).toBe('a_b_c_d_e_f_g_h.txt');
+ expect(toAttachmentName('tab\there\u0000.txt')).toBe('tab_here_.txt');
+ expect(toAttachmentName('.env')).toBe('env');
+ expect(toAttachmentName('...hidden.tar.gz')).toBe('hidden.tar.gz');
+ expect(toAttachmentName('trailing. . ')).toBe('trailing');
+ expect(toAttachmentName('CON.txt')).toBe('_CON.txt');
+ expect(toAttachmentName('...')).toBe('attachment');
+ });
+
+ it('shortens an overlong name but keeps its extension', () => {
+ const name = toAttachmentName(`${'x'.repeat(300)}.zip`);
+ expect(name.length).toBe(120);
+ expect(name.endsWith('.zip')).toBe(true);
+ });
+
+ it('de-duplicates collisions deterministically, ignoring case', () => {
+ expect(
+ assignAttachmentNames(['data.csv', 'DATA.csv', 'data.csv', 'notes', 'notes', 'a/data.csv']),
+ ).toEqual(['data.csv', 'DATA (2).csv', 'data (3).csv', 'notes', 'notes (2)', 'data (4).csv']);
+ });
+});
+
+describe('import_file contract validation', () => {
+ it('rejects a result whose digest does not match the request', async () => {
+ const fetchImpl: CodeBridgeFetch = async () =>
+ new Response(
+ JSON.stringify({
+ protocolVersion: 1,
+ operation: 'import_file',
+ workspaceId: 'primary',
+ path: '.librechat/attachments/a.txt',
+ created: true,
+ bytesWritten: 1,
+ sha256: 'f'.repeat(64),
+ }),
+ { status: 200 },
+ );
+ await expect(
+ executeWorkspaceTool({
+ baseURL: 'https://code.example',
+ authHeaders: {},
+ fetchImpl,
+ request: {
+ protocolVersion: 1,
+ operation: 'import_file',
+ workspaceId: 'primary',
+ path: '.librechat/attachments/a.txt',
+ source: { storage_session_id: 's', id: 'o' },
+ bytes: 1,
+ sha256: 'a'.repeat(64),
+ },
+ }),
+ ).rejects.toMatchObject({ reason: 'invalid' });
+ });
+
+ it('accepts nanoid storage ids that start with a symbol', async () => {
+ const fetchImpl: CodeBridgeFetch = async (_input, init) => {
+ const request = JSON.parse(String(init?.body)) as WorkspaceRequest;
+ return new Response(
+ JSON.stringify({
+ protocolVersion: 1,
+ operation: 'import_file',
+ workspaceId: 'primary',
+ path: request.path,
+ created: false,
+ unchanged: true,
+ bytesWritten: 0,
+ sha256: request.sha256,
+ }),
+ { status: 200 },
+ );
+ };
+ await expect(
+ executeWorkspaceTool({
+ baseURL: 'https://code.example',
+ authHeaders: {},
+ fetchImpl,
+ request: {
+ protocolVersion: 1,
+ operation: 'import_file',
+ workspaceId: 'primary',
+ path: '.librechat/attachments/a.txt',
+ source: { storage_session_id: '-V1StGXR8_Z5jdHi6B-my', id: '_ZvTqYz0fN3pX8kLm2Qw1' },
+ bytes: 1,
+ sha256: 'a'.repeat(64),
+ },
+ }),
+ ).resolves.toMatchObject({ unchanged: true, bytesWritten: 0 });
+ });
+
+ it('refuses to send a path that escapes the workspace', async () => {
+ const fetchImpl = jest.fn<ReturnType<CodeBridgeFetch>, Parameters<CodeBridgeFetch>>();
+ await expect(
+ executeWorkspaceTool({
+ baseURL: 'https://code.example',
+ authHeaders: {},
+ fetchImpl,
+ request: {
+ protocolVersion: 1,
+ operation: 'import_file',
+ workspaceId: 'primary',
+ path: '../outside.txt',
+ source: { storage_session_id: 's', id: 'o' },
+ bytes: 1,
+ sha256: 'a'.repeat(64),
+ },
+ }),
+ ).rejects.toMatchObject({ reason: 'invalid' });
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+});
+
+describe('primeWorkspaceAttachments', () => {
+ it('copies chat files into .librechat/attachments and lists their workspace paths', async () => {
+ const worker = createFakeWorker();
+ const { deps, records } = createDeps(worker);
+ const zip = remember(chatFile('release prep.zip', 'zip-bytes', worker.objects));
+ const csv = remember(chatFile('data.csv', 'a,b\n1,2\n', worker.objects));
+ const agent = agentWith(attachedContext(), [zip, csv]);
+
+ await primeWorkspaceAttachments({ agents: [agent], deps });
+
+ expect(worker.files.get('root:.librechat/attachments/release prep.zip')).toBe('zip-bytes');
+ expect(worker.files.get('root:.librechat/attachments/data.csv')).toBe('a,b\n1,2\n');
+ expect(worker.files.get('root:.librechat/attachments/.gitignore')).toBe('*\n');
+ const imports = worker.requests.filter((request) => request.operation === 'import_file');
+ expect(imports).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ workspaceId: 'primary',
+ path: '.librechat/attachments/release prep.zip',
+ source: { storage_session_id: zip.source.storage_session_id, id: zip.source.file_id },
+ bytes: 9,
+ sha256: sha('zip-bytes'),
+ overwrite: false,
+ }),
+ ]),
+ );
+ const note = agent.dynamicToolContextMap?.[Tools.execute_code] as string;
+ expect(note).toContain('every workspace tool');
+ expect(note).toContain('.librechat/attachments/release prep.zip (attached by user)');
+ expect(note).toContain('.librechat/attachments/data.csv (attached by user)');
+ expect(note).not.toContain('$LIBRECHAT_CODE_DATA_DIR');
+ expect(records.map((record) => record.copy?.target.path).sort()).toEqual([
+ '.librechat/attachments/data.csv',
+ '.librechat/attachments/release prep.zip',
+ ]);
+ expect(records[0].digest).toEqual(
+ expect.objectContaining({ sha256: expect.stringMatching(/^[a-f0-9]{64}$/) }),
+ );
+ });
+
+ it('does not send a file again once this conversation recorded it in the workspace', async () => {
+ const worker = createFakeWorker();
+ const { deps, digests } = createDeps(worker);
+ const report = remember(chatFile('report.pdf', 'pdf', worker.objects));
+ const firstAgent = agentWith(attachedContext(), [report]);
+ await primeWorkspaceAttachments({ agents: [firstAgent], deps });
+ expect(worker.requests).toHaveLength(2);
+
+ const nextAgent = agentWith(attachedContext(), [report]);
+ await primeWorkspaceAttachments({ agents: [nextAgent], deps });
+
+ expect(worker.requests).toHaveLength(2);
+ expect(digests).toEqual([report.file.file_id]);
+ expect(nextAgent.dynamicToolContextMap?.[Tools.execute_code]).toContain(
+ '.librechat/attachments/report.pdf',
+ );
+ });
+
+ it('treats a same-digest file already in the workspace as imported', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const report = remember(chatFile('report.pdf', 'pdf', worker.objects));
+ worker.files.set('root:.librechat/attachments/report.pdf', 'pdf');
+
+ const agent = agentWith(attachedContext(), [report]);
+ await primeWorkspaceAttachments({
+ agents: [agent],
+ deps: { ...deps, conversationId: undefined },
+ });
+
+ expect(agent.dynamicToolContextMap?.[Tools.execute_code]).toContain(
+ '.librechat/attachments/report.pdf (attached by user)',
+ );
+ });
+
+ it('moves a file to the next free name when a different file holds its name', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const report = remember(chatFile('report.pdf', 'new pdf', worker.objects));
+ worker.files.set('root:.librechat/attachments/report.pdf', 'someone else');
+
+ const agent = agentWith(attachedContext(), [report]);
+ await primeWorkspaceAttachments({ agents: [agent], deps });
+
+ expect(worker.files.get('root:.librechat/attachments/report (2).pdf')).toBe('new pdf');
+ expect(agent.dynamicToolContextMap?.[Tools.execute_code]).toContain(
+ '.librechat/attachments/report (2).pdf (attached by user)',
+ );
+ });
+
+ it('gives same-named attachments distinct names in upload order', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const first = remember(chatFile('notes.txt', 'one', worker.objects));
+ const second = remember(chatFile('Notes.txt', 'two', worker.objects));
+
+ const agent = agentWith(attachedContext(), [second, first]);
+ await primeWorkspaceAttachments({ agents: [agent], deps });
+
+ expect(worker.files.get('root:.librechat/attachments/notes.txt')).toBe('one');
+ expect(worker.files.get('root:.librechat/attachments/Notes (2).txt')).toBe('two');
+ const note = agent.dynamicToolContextMap?.[Tools.execute_code] as string;
+ expect(note).toContain(
+ '.librechat/attachments/Notes (2).txt (attached by user) (uploaded as Notes.txt)',
+ );
+ });
+
+ it('creates the ignore file once and checks it again on a later turn', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const files = ['a.txt', 'b.txt', 'c.txt'].map((name) =>
+ remember(chatFile(name, name, worker.objects)),
+ );
+ await primeWorkspaceAttachments({ agents: [agentWith(attachedContext(), files)], deps });
+ const later = remember(chatFile('d.txt', 'd', worker.objects));
+ await primeWorkspaceAttachments({ agents: [agentWith(attachedContext(), [later])], deps });
+
+ expect(worker.requests.filter((request) => request.operation === 'write_file')).toHaveLength(2);
+ expect(worker.requests.filter((request) => request.operation === 'read_file')).toHaveLength(1);
+ expect(worker.requests.filter((request) => request.operation === 'import_file')).toHaveLength(
+ 4,
+ );
+ expect(worker.files.get('root:.librechat/attachments/.gitignore')).toBe('*\n');
+ });
+
+ it('stops copying once the user changes the ignore file', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const first = remember(chatFile('a.txt', 'a', worker.objects));
+ await primeWorkspaceAttachments({ agents: [agentWith(attachedContext(), [first])], deps });
+ worker.files.set('root:.librechat/attachments/.gitignore', '*.log\n');
+
+ const later = remember(chatFile('b.txt', 'b', worker.objects));
+ const agent = agentWith(attachedContext(), [later]);
+ await primeWorkspaceAttachments({ agents: [agent], deps });
+
+ expect(worker.files.has('root:.librechat/attachments/b.txt')).toBe(false);
+ expect(agent.dynamicToolContextMap?.[Tools.execute_code]).toContain(
+ 'b.txt (attached by user): the existing .librechat/attachments/.gitignore',
+ );
+ });
+
+ it('treats a truncated read of the ignore file as not ignored', async () => {
+ const worker = createFakeWorker({ truncateReads: true });
+ worker.files.set('root:.librechat/attachments/.gitignore', '*\n');
+ const { deps } = createDeps(worker);
+ const file = remember(chatFile('keep.txt', 'k', worker.objects));
+ const agent = agentWith(attachedContext(), [file]);
+
+ await primeWorkspaceAttachments({ agents: [agent], deps });
+
+ expect(worker.files.has('root:.librechat/attachments/keep.txt')).toBe(false);
+ });
+
+ it('names a converted image for the bytes it holds', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const photo = remember(chatFile('photo.heic', 'webp', worker.objects, { type: 'image/webp' }));
+ const agent = agentWith(attachedContext(), [photo]);
+
+ await primeWorkspaceAttachments({ agents: [agent], deps });
+
+ expect(worker.files.get('root:.librechat/attachments/photo.webp')).toBe('webp');
+ expect(agent.dynamicToolContextMap?.[Tools.execute_code]).toContain(
+ '.librechat/attachments/photo.webp (attached by user) (uploaded as photo.heic)',
+ );
+ });
+
+ it('caps workspace requests for the whole turn, across agents', async () => {
+ const worker = createFakeWorker({ delayMs: 20 });
+ const { deps } = createDeps(worker);
+ let inFlight = 0;
+ let peak = 0;
+ const counted: typeof worker.fetchImpl = async (input, init) => {
+ inFlight++;
+ peak = Math.max(peak, inFlight);
+ try {
+ return await worker.fetchImpl(input, init);
+ } finally {
+ inFlight--;
+ }
+ };
+ const firstFiles = ['a', 'b', 'c'].map((name) =>
+ remember(chatFile(`${name}.txt`, name, worker.objects)),
+ );
+ const secondFiles = ['d', 'e', 'f'].map((name) =>
+ remember(chatFile(`${name}.txt`, name, worker.objects)),
+ );
+ const first = agentWith(attachedContext(), firstFiles);
+ const second = { ...agentWith(attachedContext(), secondFiles), id: 'agent-2' };
+
+ await primeWorkspaceAttachments({
+ agents: [first, second],
+ deps: { ...deps, fetchImpl: counted, concurrency: 2 },
+ });
+
+ expect(worker.requests.filter((request) => request.operation === 'import_file')).toHaveLength(
+ 6,
+ );
+ expect(peak).toBeLessThanOrEqual(2);
+ });
+
+ it('admits no more tasks than the limit at once', async () => {
+ const turn = createWorkspaceAttachmentTurn(2);
+ let active = 0;
+ let peak = 0;
+ const task = () =>
+ turn.limit(async () => {
+ active++;
+ peak = Math.max(peak, active);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ active--;
+ });
+ await Promise.all(Array.from({ length: 7 }, task));
+ expect(peak).toBe(2);
+ });
+
+ it('keeps an ignore file the user already has when it ignores the folder', async () => {
+ const worker = createFakeWorker();
+ worker.files.set('root:.librechat/attachments/.gitignore', '# mine\n*\n');
+ const { deps } = createDeps(worker);
+ const file = remember(chatFile('a.txt', 'a', worker.objects));
+
+ await primeWorkspaceAttachments({ agents: [agentWith(attachedContext(), [file])], deps });
+
+ expect(worker.files.get('root:.librechat/attachments/.gitignore')).toBe('# mine\n*\n');
+ expect(worker.files.get('root:.librechat/attachments/a.txt')).toBe('a');
+ });
+
+ it('copies nothing into a folder whose existing ignore file does not ignore it', async () => {
+ const worker = createFakeWorker();
+ worker.files.set('root:.librechat/attachments/.gitignore', '# mine\n*.log\n');
+ const { deps } = createDeps(worker);
+ const file = remember(chatFile('a.txt', 'a', worker.objects));
+ const agent = agentWith(attachedContext(), [file]);
+
+ await primeWorkspaceAttachments({ agents: [agent], deps });
+
+ expect(worker.files.has('root:.librechat/attachments/a.txt')).toBe(false);
+ expect(worker.requests.some((request) => request.operation === 'import_file')).toBe(false);
+ expect(agent.dynamicToolContextMap?.[Tools.execute_code]).toContain(
+ 'a.txt (attached by user): the existing .librechat/attachments/.gitignore does not ignore the folder',
+ );
+ });
+
+ it('recognizes only rules that ignore the whole folder', () => {
+ expect(ignoresWholeFolder('*\n')).toBe(true);
+ expect(ignoresWholeFolder('# keep out\n/**\n')).toBe(true);
+ expect(ignoresWholeFolder('*.zip\n')).toBe(false);
+ expect(ignoresWholeFolder('*\n!keep.txt\n')).toBe(false);
+ expect(ignoresWholeFolder('')).toBe(false);
+ });
+
+ it('copies into the conversation checkout and keeps its marker apart from the root', async () => {
+ const worker = createFakeWorker();
+ const { deps, records } = createDeps(worker);
+ const instance = 'a'.repeat(64);
+ const file = remember(chatFile('lane.txt', 'lane', worker.objects));
+
+ const isolated = agentWith(attachedContext(undefined, {}, instance), [file]);
+ await primeWorkspaceAttachments({ agents: [isolated], deps });
+ const root = agentWith(attachedContext(), [file]);
+ await primeWorkspaceAttachments({ agents: [root], deps });
+
+ const imports = worker.requests.filter((request) => request.operation === 'import_file');
+ expect(imports.map((request) => request.workspaceInstanceId)).toEqual([instance, undefined]);
+ expect(worker.files.get(`${instance}:.librechat/attachments/lane.txt`)).toBe('lane');
+ expect(worker.files.get('root:.librechat/attachments/lane.txt')).toBe('lane');
+ expect(new Set(records.map((record) => record.copy?.key)).size).toBe(2);
+ });
+
+ it('says plainly that files are unavailable when the worker cannot import', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const file = remember(chatFile('report.pdf', 'pdf', worker.objects));
+ const agent = agentWith(attachedContext(['read_file', 'write_file']), [file]);
+
+ await primeWorkspaceAttachments({ agents: [agent], deps });
+
+ expect(worker.requests).toHaveLength(0);
+ const note = agent.dynamicToolContextMap?.[Tools.execute_code] as string;
+ expect(note).toContain('not available on this machine');
+ expect(note).toContain('report.pdf (attached by user)');
+ expect(note).toContain('cannot receive attachments yet');
+ expect(note).not.toContain('$LIBRECHAT_CODE_DATA_DIR');
+ });
+
+ it('offers the programmatic Bash path only to an agent that has that tool', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const file = remember(chatFile('report.pdf', 'pdf', worker.objects));
+ const agent = agentWith(attachedContext(['read_file']), [file], {
+ toolDefinitions: [{ name: AgentConstants.BASH_PROGRAMMATIC_TOOL_CALLING }],
+ });
+
+ await primeWorkspaceAttachments({ agents: [agent], deps });
+
+ expect(agent.dynamicToolContextMap?.[Tools.execute_code]).toContain(
+ 'programmatic Bash tool can read it at $LIBRECHAT_CODE_DATA_DIR/report.pdf',
+ );
+ });
+
+ it('skips imports when this machine denies file writes', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const file = remember(chatFile('report.pdf', 'pdf', worker.objects));
+ const context = attachedContext(undefined, {
+ codeEnvironmentConfigSchema: {
+ permissions: { fileWrite: { default: 'deny', allowed: ['deny'] } },
+ } as CodeExecutionContext['codeEnvironmentConfigSchema'],
+ });
+ const agent = agentWith(context, [file]);
+
+ await primeWorkspaceAttachments({ agents: [agent], deps });
+
+ expect(worker.requests).toHaveLength(0);
+ expect(agent.dynamicToolContextMap?.[Tools.execute_code]).toContain(
+ 'file writes are not allowed in this workspace',
+ );
+ });
+
+ it('imports under an ask policy, since the upload is the consent', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const file = remember(chatFile('report.pdf', 'pdf', worker.objects));
+ const context = attachedContext(undefined, {
+ codeEnvironmentConfigSchema: {
+ permissions: { fileWrite: { default: 'ask', allowed: ['ask', 'allow'] } },
+ } as CodeExecutionContext['codeEnvironmentConfigSchema'],
+ });
+
+ await primeWorkspaceAttachments({ agents: [agentWith(context, [file])], deps });
+
+ expect(worker.files.get('root:.librechat/attachments/report.pdf')).toBe('pdf');
+ });
+
+ it('reports a worker-side write refusal instead of a path', async () => {
+ const worker = createFakeWorker({ denyWrites: true });
+ const { deps } = createDeps(worker);
+ const file = remember(chatFile('report.pdf', 'pdf', worker.objects));
+ const agent = agentWith(attachedContext(), [file]);
+
+ await primeWorkspaceAttachments({ agents: [agent], deps });
+
+ expect(agent.dynamicToolContextMap?.[Tools.execute_code]).toContain(
+ 'report.pdf (attached by user): file writes are not allowed in this workspace',
+ );
+ });
+
+ it('keeps the digest of a refused file so the next turn does not hash it again', async () => {
+ const worker = createFakeWorker({ denyWrites: true });
+ const { deps, digests, records } = createDeps(worker);
+ const file = remember(chatFile('big.iso', 'iso', worker.objects));
+
+ await primeWorkspaceAttachments({ agents: [agentWith(attachedContext(), [file])], deps });
+ await primeWorkspaceAttachments({ agents: [agentWith(attachedContext(), [file])], deps });
+
+ expect(digests).toEqual([file.file.file_id]);
+ expect(records).toEqual([
+ expect.objectContaining({ digest: expect.objectContaining({ bytes: 3 }) }),
+ ]);
+ expect(records[0].copy).toBeUndefined();
+ });
+
+ it('never copies the agent’s own files or another user’s', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const agentFile = remember({
+ ...chatFile('setup.md', 'setup', worker.objects),
+ agentScoped: true,
+ });
+ const foreign = remember(
+ chatFile('shared.txt', 'shared', worker.objects, { user: 'someone-else' }),
+ );
+ const agent = agentWith(attachedContext(), [agentFile, foreign]);
+
+ await primeWorkspaceAttachments({ agents: [agent], deps });
+
+ expect(worker.requests).toHaveLength(0);
+ const note = agent.dynamicToolContextMap?.[Tools.execute_code] as string;
+ expect(note).toContain("setup.md: it is one of the agent's own files");
+ expect(note).toContain('shared.txt (attached by user): only files you uploaded yourself');
+ });
+
+ it('falls back to the unavailable note when the copy does not finish in time', async () => {
+ const worker = createFakeWorker({ delayMs: 5_000 });
+ const { deps, records } = createDeps(worker);
+ const file = remember(chatFile('big.zip', 'zip', worker.objects));
+ const agent = agentWith(attachedContext(), [file]);
+
+ const startedAt = Date.now();
+ await primeWorkspaceAttachments({ agents: [agent], deps: { ...deps, timeoutMs: 100 } });
+
+ expect(Date.now() - startedAt).toBeLessThan(2_000);
+ expect(records.map((record) => record.copy)).toEqual([undefined]);
+ expect(agent.dynamicToolContextMap?.[Tools.execute_code]).toContain(
+ 'big.zip (attached by user): copying it to this machine did not finish in time',
+ );
+ });
+
+ it('does not import without write_file, since the folder could not ignore itself', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const file = remember(chatFile('report.pdf', 'pdf', worker.objects));
+ const agent = agentWith(attachedContext(['read_file', 'import_file']), [file]);
+
+ await primeWorkspaceAttachments({ agents: [agent], deps });
+
+ expect(worker.requests).toHaveLength(0);
+ expect(agent.dynamicToolContextMap?.[Tools.execute_code]).toContain(
+ 'cannot receive attachments yet',
+ );
+ });
+
+ it('starts nothing when the turn is already cancelled', async () => {
+ const worker = createFakeWorker();
+ const { deps, digests } = createDeps(worker);
+ const file = remember(chatFile('report.pdf', 'pdf', worker.objects));
+ const controller = new AbortController();
+ controller.abort(new Error('cancelled'));
+
+ await expect(
+ primeWorkspaceAttachments({
+ agents: [agentWith(attachedContext(), [file])],
+ deps,
+ signal: controller.signal,
+ }),
+ ).rejects.toThrow('cancelled');
+ expect(digests).toHaveLength(0);
+ expect(worker.requests).toHaveLength(0);
+ });
+
+ it('does not hold the turn for a stalled metadata write', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const file = remember(chatFile('report.pdf', 'pdf', worker.objects));
+ const agent = agentWith(attachedContext(), [file]);
+
+ const startedAt = Date.now();
+ await primeWorkspaceAttachments({
+ agents: [agent],
+ deps: { ...deps, timeoutMs: 100, recordImport: () => new Promise<void>(() => undefined) },
+ });
+
+ expect(Date.now() - startedAt).toBeLessThan(2_000);
+ expect(agent.dynamicToolContextMap?.[Tools.execute_code]).toContain(
+ '.librechat/attachments/report.pdf',
+ );
+ });
+
+ it('copies again when the same environment id now names a different worker', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const file = remember(chatFile('report.pdf', 'pdf', worker.objects));
+
+ await primeWorkspaceAttachments({ agents: [agentWith(attachedContext(), [file])], deps });
+ const replaced = attachedContext(undefined, { bridgeWorkerId: 'replacement-worker' });
+ await primeWorkspaceAttachments({ agents: [agentWith(replaced, [file])], deps });
+
+ expect(worker.requests.filter((request) => request.operation === 'import_file')).toHaveLength(
+ 2,
+ );
+ });
+
+ it('primes each agent once, including a subagent that joins later', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const file = remember(chatFile('report.pdf', 'pdf', worker.objects));
+ const primary = agentWith(attachedContext(), [file]);
+ const lazy = { ...agentWith(attachedContext(), [file]), id: 'lazy-subagent' };
+ const provisionFiles = jest.fn(async () => []);
+ const prime = createWorkspaceAttachmentPrimer({
+ deps,
+ getProvisionFiles: () => provisionFiles,
+ });
+
+ await prime([primary]);
+ lazy.dynamicToolContextMap = { [Tools.execute_code]: 'stale programmatic note' };
+ await prime([lazy, primary], { toolContexts: new Map([[lazy.id, {}]]) });
+
+ expect(lazy.dynamicToolContextMap?.[Tools.execute_code]).toContain(
+ '.librechat/attachments/report.pdf',
+ );
+ expect(worker.requests.filter((request) => request.operation === 'import_file')).toHaveLength(
+ 1,
+ );
+ });
+
+ it('leaves sandbox routes and unselected attached machines alone', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const file = remember(chatFile('report.pdf', 'pdf', worker.objects));
+ const sandbox = agentWith({ ...attachedContext(), environmentType: undefined }, [file]);
+ const unselected = agentWith({ ...attachedContext(), codeWorkspace: undefined }, [file]);
+
+ await primeWorkspaceAttachments({ agents: [sandbox, unselected], deps });
+
+ expect(worker.requests).toHaveLength(0);
+ expect(sandbox.dynamicToolContextMap?.[Tools.execute_code]).toBe('stale programmatic note');
+ expect(unselected.dynamicToolContextMap?.[Tools.execute_code]).toBe('stale programmatic note');
+ });
+
+ it('stages queued uploads, copies them, and keeps the queued note from repeating them', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const queued = chatFile('fresh.zip', 'fresh', worker.objects);
+ remember(queued);
+ const provisionState: ProvisionState = {
+ codeEnvFiles: [queued.file],
+ codeEnvDestinations: new Map([[queued.file.file_id, 'fresh.zip']]),
+ vectorDBFiles: [],
+ aliveFileIds: new Set(),
+ agentScopedFileIds: new Set(),
+ };
+ const staged: CodeEnvFile = {
+ id: queued.source.file_id,
+ storage_session_id: queued.source.storage_session_id,
+ name: 'fresh.zip',
+ } as CodeEnvFile;
+ const provisionFiles = jest.fn(async (toolNames: string[]) => {
+ expect(toolNames).toEqual([AgentConstants.READ_FILE]);
+ queued.file.metadata = {
+ codeEnvRefs: {
+ 'stateful:machine': {
+ kind: 'user',
+ id: USER_ID,
+ storage_session_id: queued.source.storage_session_id,
+ file_id: queued.source.file_id,
+ sandboxFilename: 'fresh.zip',
+ },
+ },
+ };
+ provisionState.codeEnvFiles = [];
+ return [staged];
+ });
+ const agent = agentWith(attachedContext(), [], {
+ provisionState,
+ fileConsumers: consumers,
+ dynamicToolContextMap: { queued_code_files: 'stale queued note' },
+ });
+
+ await primeWorkspaceAttachments({ agents: [agent], deps, provisionFiles });
+
+ expect(provisionFiles).toHaveBeenCalledTimes(1);
+ expect(agent.primedCodeFiles).toEqual([staged]);
+ expect(worker.files.get('root:.librechat/attachments/fresh.zip')).toBe('fresh');
+ expect(agent.dynamicToolContextMap?.queued_code_files).toBeUndefined();
+ expect(agent.dynamicToolContextMap?.[Tools.execute_code]).toContain(
+ '.librechat/attachments/fresh.zip (attached by user)',
+ );
+
+ provisionState.codeEnvFiles = [queued.file];
+ prepareQueuedCodeFileContext(
+ { ...agent, provisionState, fileConsumers: consumers },
+ [],
+ USER_ID,
+ );
+ expect(agent.dynamicToolContextMap?.queued_code_files).toBeUndefined();
+ });
+
+ it('hands late provisioning refs to the first code tool call', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const queued = remember(chatFile('slow.zip', 'slow', worker.objects));
+ let finish: (files: CodeEnvFile[]) => void = () => undefined;
+ const provisionFiles = jest.fn(
+ () => new Promise<CodeEnvFile[]>((resolve) => (finish = resolve)),
+ );
+ const toolContext: { pendingProvisionedCodeFiles?: CodeEnvFile[] } = {};
+ const agent = agentWith(attachedContext(), [], {
+ provisionState: {
+ codeEnvFiles: [queued.file],
+ codeEnvDestinations: new Map([[queued.file.file_id, 'slow.zip']]),
+ vectorDBFiles: [],
+ aliveFileIds: new Set(),
+ agentScopedFileIds: new Set(),
+ },
+ fileConsumers: consumers,
+ });
+
+ await primeWorkspaceAttachments({
+ agents: [agent],
+ toolContexts: new Map([[agent.id, toolContext]]),
+ provisionFiles,
+ deps: { ...deps, timeoutMs: 50 },
+ });
+
+ expect(agent.dynamicToolContextMap?.[Tools.execute_code]).toContain(
+ 'slow.zip (attached by user): copying it to this machine did not finish in time',
+ );
+ const late = { id: 'late', storage_session_id: 's', name: 'slow.zip' } as CodeEnvFile;
+ finish([late]);
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(toolContext.pendingProvisionedCodeFiles).toEqual([late]);
+ expect(agent.primedCodeFiles).toBeUndefined();
+ });
+
+ it('copies a file shared by two agents on the same workspace once', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const file = remember(chatFile('shared.csv', 'x', worker.objects));
+ const first = agentWith(attachedContext(), [file]);
+ const second = { ...agentWith(attachedContext(), [file]), id: 'agent-2' };
+
+ await primeWorkspaceAttachments({ agents: [first, second], deps });
+
+ expect(worker.requests.filter((request) => request.operation === 'import_file')).toHaveLength(
+ 1,
+ );
+ expect(second.dynamicToolContextMap?.[Tools.execute_code]).toContain(
+ '.librechat/attachments/shared.csv',
+ );
+ });
+
+ it('copies a displaced code output under its original name', async () => {
+ const worker = createFakeWorker();
+ const { deps } = createDeps(worker);
+ const output = remember(
+ chatFile('chart.png', 'png', worker.objects, { context: FileContext.execute_code }),
+ );
+ const result = await importWorkspaceAttachments({
+ context: attachedContext(),
+ candidates: [{ ...output, destination: 'chart-1.png' }],
+ deps,
+ signal: new AbortController().signal,
+ });
+ expect(result.get(output.file.file_id)).toEqual({
+ status: 'imported',
+ path: '.librechat/attachments/chart.png',
+ });
+ });
+});
diff --git a/packages/api/src/code/attachments.ts b/packages/api/src/code/attachments.ts
new file mode 100644
index 0000000000..347921ea8d
--- /dev/null
+++ b/packages/api/src/code/attachments.ts
@@ -0,0 +1,1078 @@
+import { createHash } from 'node:crypto';
+import { logger } from '@librechat/data-schemas';
+import { Constants as AgentConstants } from '@librechat/agents';
+import {
+ Tools,
+ Constants,
+ getCodeEnvRefForProfile,
+ resolveSandboxFilename,
+} from 'librechat-data-provider';
+import type {
+ TFile,
+ TurnFileConsumers,
+ TFileWorkspaceImport,
+ TFileWorkspaceImports,
+} from 'librechat-data-provider';
+import type { CodeEnvFile } from '@librechat/agents';
+import type { AttachedCodeEnvironmentPolicySettings } from '~/agents/hitl/byom';
+import type { StoredFileDigest } from '~/files/provision/service';
+import type { CodeExecutionContext } from '~/agents/execution';
+import type { CodeContextEntry } from '~/files/code/priming';
+import type { ProvisionState } from '~/agents/resources';
+import type { CodeBridgeFetch } from './bridge';
+import {
+ executeWorkspaceTool,
+ WorkspaceToolHttpError,
+ resolveAttachedWorkspaceAdmissionOptions,
+} from './workspace';
+import {
+ isDescribedCodeFile,
+ getCodeFileLocation,
+ getCodeFileContextSuffix,
+} from '~/files/code/priming';
+import { codeExecutionAuthHeaders, getCodeExecutionRouteKey } from '~/agents/execution';
+import { isAttachedFileWriteDenied } from '~/agents/hitl/byom';
+import { getSafeErrorMetadata } from '~/utils/errors';
+
+/** Workspace-relative folder chat attachments are copied into. */
+export const WORKSPACE_ATTACHMENTS_DIRECTORY = '.librechat/attachments';
+/** The whole import phase, provisioning included, never holds a turn longer than this. */
+export const WORKSPACE_ATTACHMENT_IMPORT_TIMEOUT_MS = 10_000;
+/** Workspace requests in flight for the whole turn, across every agent it primes. */
+export const WORKSPACE_ATTACHMENT_IMPORT_CONCURRENCY = 3;
+const WORKSPACE_ATTACHMENTS_GITIGNORE = `${WORKSPACE_ATTACHMENTS_DIRECTORY}/.gitignore`;
+const MAX_ATTACHMENT_NAME_LENGTH = 120;
+const MAX_EXTENSION_LENGTH = 16;
+/** Conflicting names tried after the first before a file is reported as unavailable. */
+const MAX_CONFLICT_RETRIES = 3;
+const QUEUED_CODE_FILES_CONTEXT_KEY = 'queued_code_files';
+const PROGRAMMATIC_TOOL_NAMES: ReadonlySet<string> = new Set([
+ AgentConstants.PROGRAMMATIC_TOOL_CALLING,
+ AgentConstants.BASH_PROGRAMMATIC_TOOL_CALLING,
+]);
+const UNSAFE_NAME_CHARACTERS: ReadonlySet<string> = new Set('<>:"/\\|?*');
+const RESERVED_WINDOWS_NAME = /^(?:con|prn|aux|nul|com\d|lpt\d)(?:\.|$)/i;
+
+export type WorkspaceAttachmentUnavailableReason =
+ | 'unsupported'
+ | 'denied'
+ | 'agent_file'
+ | 'not_owned'
+ | 'not_staged'
+ | 'too_large'
+ | 'conflict'
+ | 'not_ignored'
+ | 'timeout'
+ | 'failed';
+
+export type WorkspaceAttachmentOutcome =
+ | { status: 'imported'; path: string }
+ | { status: 'unavailable'; reason: WorkspaceAttachmentUnavailableReason };
+
+const UNAVAILABLE_REASONS: Record<WorkspaceAttachmentUnavailableReason, string> = {
+ unsupported:
+ "this machine's LibreChat worker cannot receive attachments yet; updating the worker enables it",
+ denied: 'file writes are not allowed in this workspace',
+ agent_file: "it is one of the agent's own files, not one attached in this chat",
+ not_owned: 'only files you uploaded yourself are copied to your machine',
+ not_staged: 'it could not be prepared for transfer to this machine',
+ too_large: "it is larger than this machine's file size limit",
+ conflict: `a different file already uses that name in ${WORKSPACE_ATTACHMENTS_DIRECTORY}`,
+ not_ignored: `the existing ${WORKSPACE_ATTACHMENTS_DIRECTORY}/.gitignore does not ignore the folder, so a copy could end up in the repository; adding a line with * to it enables copies`,
+ timeout: 'copying it to this machine did not finish in time; it is retried next turn',
+ failed: 'copying it to this machine failed',
+};
+
+/** One code-environment object a workspace copy is read from. */
+interface AttachmentSource {
+ storage_session_id: string;
+ file_id: string;
+}
+
+/**
+ * Persists a copy and/or a freshly computed digest, so a later turn skips the copy without a
+ * workspace call and never hashes the same stored object twice.
+ */
+export interface WorkspaceImportRecord {
+ file_id: string;
+ user: string;
+ tenantId?: string | null;
+ copy?: { key: string; target: TFileWorkspaceImport };
+ digest?: NonNullable<TFileWorkspaceImports['digest']>;
+}
+
+export interface WorkspaceAttachmentDeps {
+ userId: string;
+ conversationId?: string | null;
+ getAuthHeaders: (bridgeWorkerId?: string) => Promise<Record<string, string>>;
+ /** SHA-256 and length of the stored bytes, or null when storage cannot be streamed. */
+ digestFile: (file: TFile, signal: AbortSignal) => Promise<StoredFileDigest | null>;
+ recordImport: (record: WorkspaceImportRecord) => Promise<unknown>;
+ codeApiMaxRetryWaitMs?: number;
+ fetchImpl?: CodeBridgeFetch;
+ timeoutMs?: number;
+ /** Workspace requests in flight for the turn; defaults to three. */
+ concurrency?: number;
+}
+
+export interface WorkspaceAttachmentCandidate {
+ file: TFile;
+ /** Name under `$LIBRECHAT_CODE_DATA_DIR`, for programmatic Bash. */
+ destination: string;
+ agentScoped: boolean;
+ source?: AttachmentSource;
+}
+
+/**
+ * A portable single path segment for `filename`: directories, control and reserved
+ * characters, leading dots and trailing dots or spaces are removed, a reserved Windows device
+ * name is prefixed, and an overlong name keeps its extension. A safe name is returned as is.
+ */
+export function toAttachmentName(filename: string): string {
+ const base = filename.split(/[\\/]/).pop() ?? '';
+ const cleaned = replaceUnsafeCharacters(base.normalize('NFC'))
+ .replace(/\s+/g, ' ')
+ .replace(/^[.\s]+/, '')
+ .replace(/[.\s]+$/, '');
+ const name = cleaned === '' ? 'attachment' : cleaned;
+ const portable = RESERVED_WINDOWS_NAME.test(name) ? `_${name}` : name;
+ if (portable.length <= MAX_ATTACHMENT_NAME_LENGTH) {
+ return portable;
+ }
+ const { stem, extension } = splitExtension(portable);
+ return `${stem.slice(0, MAX_ATTACHMENT_NAME_LENGTH - extension.length).trimEnd()}${extension}`;
+}
+
+/** Collapses each run of control or path-reserved characters to one underscore. */
+function replaceUnsafeCharacters(value: string): string {
+ let result = '';
+ let replacing = false;
+ for (const character of value) {
+ const code = character.codePointAt(0) ?? 0;
+ if (code <= 0x1f || code === 0x7f || UNSAFE_NAME_CHARACTERS.has(character)) {
+ result += replacing ? '' : '_';
+ replacing = true;
+ continue;
+ }
+ result += character;
+ replacing = false;
+ }
+ return result;
+}
+
+function splitExtension(name: string): { stem: string; extension: string } {
+ const dot = name.lastIndexOf('.');
+ if (dot <= 0 || name.length - dot > MAX_EXTENSION_LENGTH) {
+ return { stem: name, extension: '' };
+ }
+ return { stem: name.slice(0, dot), extension: name.slice(dot) };
+}
+
+/** The `index`-th name for `name`: the name itself, then `name (2).ext`, `name (3).ext`… */
+export function getAttachmentNameVariant(name: string, index: number): string {
+ if (index <= 1) {
+ return name;
+ }
+ const { stem, extension } = splitExtension(name);
+ return `${stem} (${index})${extension}`;
+}
+
+/**
+ * Claims the first variant of `name` not yet taken, comparing case-insensitively because
+ * the target may be a Windows or macOS checkout.
+ */
+function claimAttachmentName(taken: Set<string>, name: string, start = 1): string {
+ for (let index = start; ; index++) {
+ const candidate = getAttachmentNameVariant(name, index);
+ const key = candidate.toLowerCase();
+ if (!taken.has(key)) {
+ taken.add(key);
+ return candidate;
+ }
+ }
+}
+
+/** Assigns distinct portable names in order, so the earliest file keeps the bare name. */
+export function assignAttachmentNames(filenames: readonly string[]): string[] {
+ const taken = new Set<string>();
+ return filenames.map((filename) => claimAttachmentName(taken, toAttachmentName(filename)));
+}
+
+/**
+ * Whether LibreChat may copy chat attachments into the selected workspace, or why not. The
+ * upload is the user's consent, so an `ask` file-write policy still allows it; only `deny`
+ * on this machine, or a worker without `import_file`, stops it.
+ */
+export function resolveWorkspaceAttachmentPolicy(
+ context: CodeExecutionContext,
+): { eligible: true } | { eligible: false; reason: 'unsupported' | 'denied' } {
+ const operations = context.codeWorkspace?.operations;
+ /** Without `write_file` the folder could not ignore itself, and copies would surface as
+ * untracked repository content. */
+ if (operations?.includes('import_file') !== true || !operations.includes('write_file')) {
+ return { eligible: false, reason: 'unsupported' };
+ }
+ const policy: AttachedCodeEnvironmentPolicySettings = {
+ configSchema: context.codeEnvironmentConfigSchema,
+ settings: context.codeEnvironmentSettings,
+ };
+ if (isAttachedFileWriteDenied(policy)) {
+ return { eligible: false, reason: 'denied' };
+ }
+ return { eligible: true };
+}
+
+/**
+ * Opaque key for one conversation's copies in one workspace checkout on one live worker. The
+ * Code API route and worker are part of it, so a machine replaced under the same environment
+ * id never inherits the previous machine's copies.
+ */
+export function getWorkspaceAttachmentTargetKey(
+ context: CodeExecutionContext,
+ conversationId: string,
+): string | undefined {
+ const workspace = context.codeWorkspace;
+ if (workspace == null) {
+ return undefined;
+ }
+ return createHash('sha256')
+ .update(
+ JSON.stringify([
+ conversationId,
+ context.baseUrl.trim().replace(/\/+$/, ''),
+ context.bridgeWorkerId ?? null,
+ context.environmentId ?? workspace.environmentId,
+ workspace.workspaceId,
+ workspace.workspaceInstanceId ?? null,
+ ]),
+ )
+ .digest('hex')
+ .slice(0, 32);
+}
+
+/** A create-only write found different bytes at the path; older workers say `FILE_EXISTS`. */
+const CONFLICT_CODES: ReadonlySet<string> = new Set(['EDIT_CONFLICT', 'FILE_EXISTS']);
+
+function classifyImportFailure(error: unknown): WorkspaceAttachmentUnavailableReason {
+ if (!(error instanceof WorkspaceToolHttpError)) {
+ return 'failed';
+ }
+ if (error.reason === 'timeout' || error.reason === 'insufficient_time') {
+ return 'timeout';
+ }
+ if (error.reason !== 'rejected') {
+ return 'failed';
+ }
+ const code = error.upstreamCode ?? '';
+ if (error.upstreamStatus === 409 && CONFLICT_CODES.has(code)) {
+ return 'conflict';
+ }
+ if (error.upstreamStatus === 403 && code === 'WRITE_DISABLED') {
+ return 'denied';
+ }
+ if (error.upstreamStatus === 413) {
+ return 'too_large';
+ }
+ return 'failed';
+}
+
+/** Admits at most `limit` tasks at once; a finishing task hands its slot to the next waiter. */
+function createLimiter(limit: number): <T>(task: () => Promise<T>) => Promise<T> {
+ let active = 0;
+ const waiting: Array<() => void> = [];
+ return async <T>(task: () => Promise<T>): Promise<T> => {
+ if (active >= limit) {
+ await new Promise<void>((resolve) => waiting.push(resolve));
+ } else {
+ active++;
+ }
+ try {
+ return await task();
+ } finally {
+ const next = waiting.shift();
+ if (next) {
+ next();
+ } else {
+ active--;
+ }
+ }
+ };
+}
+
+/**
+ * What one turn shares across the agents it primes: copies and ignore checks already started,
+ * so each file and each folder is handled once, and one cap on concurrent workspace requests.
+ */
+export interface WorkspaceAttachmentTurn {
+ imports: Map<string, Promise<WorkspaceAttachmentOutcome>>;
+ ignores: Map<string, Promise<WorkspaceAttachmentUnavailableReason | null>>;
+ limit: <T>(task: () => Promise<T>) => Promise<T>;
+}
+
+export function createWorkspaceAttachmentTurn(
+ concurrency: number = WORKSPACE_ATTACHMENT_IMPORT_CONCURRENCY,
+): WorkspaceAttachmentTurn {
+ return {
+ imports: new Map(),
+ ignores: new Map(),
+ limit: createLimiter(Math.max(1, Math.floor(concurrency))),
+ };
+}
+
+/** Resolves when `signal` aborts; never rejects, so it can bound a race. */
+function whenAborted(signal: AbortSignal): Promise<void> {
+ return new Promise((resolve) => {
+ if (signal.aborted) {
+ resolve();
+ return;
+ }
+ signal.addEventListener('abort', () => resolve(), { once: true });
+ });
+}
+
+interface ImportTarget {
+ context: CodeExecutionContext;
+ workspaceId: string;
+ workspaceInstanceId?: string;
+ key?: string;
+}
+
+/**
+ * Copies chat attachments into one workspace and reports where each landed. Copies already
+ * recorded for this conversation and workspace with the same digest are not sent again, the
+ * worker's own digest check makes a resend harmless, and anything unfinished when `signal`
+ * aborts is reported as timed out rather than holding the turn.
+ */
+export async function importWorkspaceAttachments({
+ context,
+ candidates,
+ deps,
+ signal,
+ turn = createWorkspaceAttachmentTurn(deps.concurrency),
+}: {
+ context: CodeExecutionContext;
+ candidates: readonly WorkspaceAttachmentCandidate[];
+ deps: WorkspaceAttachmentDeps;
+ signal: AbortSignal;
+ turn?: WorkspaceAttachmentTurn;
+}): Promise<Map<string, WorkspaceAttachmentOutcome>> {
+ const outcomes = new Map<string, WorkspaceAttachmentOutcome>();
+ const workspace = context.codeWorkspace;
+ if (workspace == null) {
+ return outcomes;
+ }
+ const target: ImportTarget = {
+ context,
+ workspaceId: workspace.workspaceId,
+ ...(workspace.workspaceInstanceId
+ ? { workspaceInstanceId: workspace.workspaceInstanceId }
+ : {}),
+ ...(deps.conversationId && deps.conversationId !== Constants.NEW_CONVO
+ ? { key: getWorkspaceAttachmentTargetKey(context, deps.conversationId) }
+ : {}),
+ };
+ const ordered = [...candidates].sort(compareCandidates);
+ const recordedNames = ordered.map((candidate) => getRecordedName(candidate.file, target.key));
+ const taken = new Set(
+ recordedNames.flatMap((name) => (name == null ? [] : [name.toLowerCase()])),
+ );
+ const pending = ordered.map((candidate, index) => ({
+ candidate,
+ name: recordedNames[index] ?? claimAttachmentName(taken, getAttachmentBaseName(candidate.file)),
+ }));
+
+ const workspaceKey = JSON.stringify([
+ context.baseUrl,
+ context.bridgeWorkerId ?? null,
+ target.workspaceId,
+ target.workspaceInstanceId ?? null,
+ ]);
+ /** Checked once per turn and folder, never cached longer: the user may edit the file. */
+ const ensureIgnored = (): Promise<WorkspaceAttachmentUnavailableReason | null> => {
+ let check = turn.ignores.get(workspaceKey);
+ if (check == null) {
+ check = ensureAttachmentsIgnored({ target, deps, signal });
+ turn.ignores.set(workspaceKey, check);
+ }
+ return check;
+ };
+
+ await Promise.all(
+ pending.map(async (item) => {
+ const importKey = JSON.stringify([workspaceKey, item.candidate.file.file_id]);
+ let outcome = turn.imports.get(importKey);
+ if (outcome == null) {
+ outcome = turn.limit(() =>
+ importOne({ ...item, target, taken, deps, signal, ensureIgnored }),
+ );
+ turn.imports.set(importKey, outcome);
+ }
+ outcomes.set(item.candidate.file.file_id, await outcome);
+ }),
+ );
+ return outcomes;
+}
+
+/** The portable name for a file's stored bytes: a converted image takes its stored type's
+ * extension, as the sandbox copy does, so tools decode what is actually there. */
+function getAttachmentBaseName(file: TFile): string {
+ return toAttachmentName(resolveSandboxFilename(file.filename, file.type));
+}
+
+/** The name an earlier turn copied this file under, kept so its path never moves. */
+function getRecordedName(file: TFile, key: string | undefined): string | undefined {
+ const path = key ? file.metadata?.workspaceImports?.targets?.[key]?.path : undefined;
+ const prefix = `${WORKSPACE_ATTACHMENTS_DIRECTORY}/`;
+ if (path == null || !path.startsWith(prefix) || path.slice(prefix.length).includes('/')) {
+ return undefined;
+ }
+ return path.slice(prefix.length);
+}
+
+function compareCandidates(
+ left: WorkspaceAttachmentCandidate,
+ right: WorkspaceAttachmentCandidate,
+): number {
+ const leftTime = new Date(left.file.createdAt ?? 0).getTime() || 0;
+ const rightTime = new Date(right.file.createdAt ?? 0).getTime() || 0;
+ if (leftTime !== rightTime) {
+ return leftTime - rightTime;
+ }
+ if (left.file.file_id === right.file.file_id) {
+ return 0;
+ }
+ return left.file.file_id < right.file.file_id ? -1 : 1;
+}
+
+async function importOne({
+ candidate,
+ name,
+ target,
+ taken,
+ deps,
+ signal,
+ ensureIgnored,
+}: {
+ candidate: WorkspaceAttachmentCandidate;
+ name: string;
+ target: ImportTarget;
+ taken: Set<string>;
+ deps: WorkspaceAttachmentDeps;
+ signal: AbortSignal;
+ /** Null once the folder is known to ignore itself, else why copies cannot go there. */
+ ensureIgnored: () => Promise<WorkspaceAttachmentUnavailableReason | null>;
+}): Promise<WorkspaceAttachmentOutcome> {
+ const { file, source } = candidate;
+ if (source == null) {
+ return { status: 'unavailable', reason: 'not_staged' };
+ }
+ let freshDigest: NonNullable<TFileWorkspaceImports['digest']> | undefined;
+ let copy: TFileWorkspaceImport | undefined;
+ try {
+ const sourceKey = `${source.storage_session_id}/${source.file_id}`;
+ const stored = file.metadata?.workspaceImports?.digest;
+ const digest =
+ stored?.source === sourceKey
+ ? { sha256: stored.sha256, bytes: stored.bytes }
+ : await deps.digestFile(file, signal);
+ if (digest == null) {
+ return { status: 'unavailable', reason: 'not_staged' };
+ }
+ if (stored?.source !== sourceKey) {
+ freshDigest = { source: sourceKey, ...digest };
+ }
+ const recorded = target.key
+ ? file.metadata?.workspaceImports?.targets?.[target.key]
+ : undefined;
+ if (recorded?.sha256 === digest.sha256) {
+ return { status: 'imported', path: recorded.path };
+ }
+ const notIgnored = await ensureIgnored();
+ if (notIgnored != null) {
+ return { status: 'unavailable', reason: signal.aborted ? 'timeout' : notIgnored };
+ }
+ let attemptName = name;
+ for (let attempt = 0; ; attempt++) {
+ try {
+ const path = await sendImport({
+ target,
+ deps,
+ signal,
+ path: `${WORKSPACE_ATTACHMENTS_DIRECTORY}/${attemptName}`,
+ source,
+ digest,
+ });
+ copy = { sha256: digest.sha256, path };
+ return { status: 'imported', path };
+ } catch (error) {
+ const reason = classifyImportFailure(error);
+ if (reason !== 'conflict' || attempt >= MAX_CONFLICT_RETRIES || signal.aborted) {
+ throw error;
+ }
+ attemptName = claimAttachmentName(taken, getAttachmentBaseName(file), 2);
+ }
+ }
+ } catch (error) {
+ if (signal.aborted) {
+ return { status: 'unavailable', reason: 'timeout' };
+ }
+ const reason = classifyImportFailure(error);
+ logger.warn(
+ `[workspaceAttachments] Import of file ${file.file_id} into workspace ${target.workspaceId} failed: ${reason}`,
+ );
+ return { status: 'unavailable', reason };
+ } finally {
+ /** Bookkeeping only: past the deadline the turn goes on and the write lands when it can. */
+ await Promise.race([
+ persistImport({ file, target, deps, copy, digest: freshDigest }),
+ whenAborted(signal),
+ ]);
+ }
+}
+
+async function sendImport({
+ target,
+ deps,
+ signal,
+ path,
+ source,
+ digest,
+}: {
+ target: ImportTarget;
+ deps: WorkspaceAttachmentDeps;
+ signal: AbortSignal;
+ path: string;
+ source: AttachmentSource;
+ digest: StoredFileDigest;
+}): Promise<string> {
+ const result = await executeWorkspaceTool({
+ ...workspaceRequestOptions(target, deps, signal),
+ request: {
+ protocolVersion: 1,
+ operation: 'import_file',
+ workspaceId: target.workspaceId,
+ ...(target.workspaceInstanceId ? { workspaceInstanceId: target.workspaceInstanceId } : {}),
+ path,
+ source: { storage_session_id: source.storage_session_id, id: source.file_id },
+ bytes: digest.bytes,
+ sha256: digest.sha256,
+ overwrite: false,
+ },
+ });
+ if (result.operation !== 'import_file') {
+ throw new WorkspaceToolHttpError('invalid');
+ }
+ return result.path;
+}
+
+function workspaceRequestOptions(
+ target: ImportTarget,
+ deps: WorkspaceAttachmentDeps,
+ signal: AbortSignal,
+): Omit<Parameters<typeof executeWorkspaceTool>[0], 'request'> {
+ return {
+ baseURL: target.context.baseUrl,
+ authHeaders: () => codeExecutionAuthHeaders(deps.getAuthHeaders, target.context),
+ signal,
+ ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),
+ ...(deps.codeApiMaxRetryWaitMs == null
+ ? {}
+ : { codeApiMaxRetryWaitMs: deps.codeApiMaxRetryWaitMs }),
+ ...resolveAttachedWorkspaceAdmissionOptions(target.context.codeEnvironmentConfigSchema),
+ };
+}
+
+async function persistImport({
+ file,
+ target,
+ deps,
+ copy,
+ digest,
+}: {
+ file: TFile;
+ target: ImportTarget;
+ deps: WorkspaceAttachmentDeps;
+ copy?: TFileWorkspaceImport;
+ digest?: NonNullable<TFileWorkspaceImports['digest']>;
+}): Promise<void> {
+ const key = target.key;
+ const recordedCopy = copy != null && key != null ? { key, target: copy } : undefined;
+ if (recordedCopy == null && digest == null) {
+ return;
+ }
+ try {
+ await deps.recordImport({
+ file_id: file.file_id,
+ user: deps.userId,
+ tenantId: file.tenantId ?? null,
+ ...(recordedCopy ? { copy: recordedCopy } : {}),
+ ...(digest ? { digest } : {}),
+ });
+ const imports = file.metadata?.workspaceImports;
+ file.metadata = {
+ ...file.metadata,
+ workspaceImports: {
+ ...imports,
+ ...(digest ? { digest } : {}),
+ ...(recordedCopy
+ ? { targets: { ...imports?.targets, [recordedCopy.key]: recordedCopy.target } }
+ : {}),
+ },
+ };
+ } catch (error) {
+ logger.warn(
+ `[workspaceAttachments] Could not record the import of file ${file.file_id}; it is resent next turn`,
+ getSafeErrorMetadata(error),
+ );
+ }
+}
+
+/** Rules that ignore every entry of the folder they sit in. */
+const IGNORE_ALL_RULES: ReadonlySet<string> = new Set(['*', '/*', '**', '/**']);
+
+/** Whether a `.gitignore` ignores everything beside it, with no negation re-including a file. */
+export function ignoresWholeFolder(content: string): boolean {
+ const rules = content
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter((line) => line !== '' && !line.startsWith('#'));
+ return (
+ rules.some((rule) => IGNORE_ALL_RULES.has(rule)) && !rules.some((rule) => rule.startsWith('!'))
+ );
+}
+
+/**
+ * Copies go only where they cannot surface as repository content: the folder's `.gitignore` is
+ * created with `*`, never replaced, and an existing one must already ignore the whole folder.
+ * Resolves to null when that holds, otherwise to why copies cannot be placed.
+ */
+async function ensureAttachmentsIgnored({
+ target,
+ deps,
+ signal,
+}: {
+ target: ImportTarget;
+ deps: WorkspaceAttachmentDeps;
+ signal: AbortSignal;
+}): Promise<WorkspaceAttachmentUnavailableReason | null> {
+ const workspace = {
+ workspaceId: target.workspaceId,
+ ...(target.workspaceInstanceId ? { workspaceInstanceId: target.workspaceInstanceId } : {}),
+ };
+ try {
+ await executeWorkspaceTool({
+ ...workspaceRequestOptions(target, deps, signal),
+ request: {
+ protocolVersion: 1,
+ operation: 'write_file',
+ ...workspace,
+ path: WORKSPACE_ATTACHMENTS_GITIGNORE,
+ content: '*\n',
+ overwrite: false,
+ },
+ });
+ } catch (error) {
+ if (classifyImportFailure(error) !== 'conflict') {
+ logger.warn(
+ '[workspaceAttachments] Could not create the attachments .gitignore',
+ getSafeErrorMetadata(error),
+ );
+ return classifyImportFailure(error);
+ }
+ if (target.context.codeWorkspace?.operations.includes('read_file') !== true) {
+ return 'not_ignored';
+ }
+ try {
+ const existing = await executeWorkspaceTool({
+ ...workspaceRequestOptions(target, deps, signal),
+ request: {
+ protocolVersion: 1,
+ operation: 'read_file',
+ ...workspace,
+ path: WORKSPACE_ATTACHMENTS_GITIGNORE,
+ maxLines: 200,
+ },
+ });
+ /** A rule past the part read could re-include a file, so only a whole read counts. */
+ if (
+ existing.operation !== 'read_file' ||
+ existing.truncated ||
+ !ignoresWholeFolder(existing.content)
+ ) {
+ return 'not_ignored';
+ }
+ } catch (readError) {
+ logger.warn(
+ '[workspaceAttachments] Could not read the attachments .gitignore',
+ getSafeErrorMetadata(readError),
+ );
+ return classifyImportFailure(readError);
+ }
+ }
+ return null;
+}
+
+/**
+ * The code-file note for an attached workspace: copied attachments by their workspace path,
+ * which every workspace tool can open, and plainly why any other file is not on the machine.
+ * The `$LIBRECHAT_CODE_DATA_DIR` path is offered only to an agent that has programmatic Bash.
+ */
+export function buildWorkspaceAttachmentContext({
+ candidates,
+ outcomes,
+ programmaticBash,
+}: {
+ candidates: readonly WorkspaceAttachmentCandidate[];
+ outcomes: ReadonlyMap<string, WorkspaceAttachmentOutcome>;
+ programmaticBash: boolean;
+}): string {
+ let imported = '';
+ let unavailable = '';
+ for (const { file, destination, agentScoped } of candidates) {
+ const outcome = outcomes.get(file.file_id);
+ if (outcome?.status === 'imported') {
+ const name = outcome.path.slice(outcome.path.lastIndexOf('/') + 1);
+ imported += `\n\t- ${outcome.path}${getCodeFileContextSuffix(file, agentScoped, name)}`;
+ continue;
+ }
+ const reason = UNAVAILABLE_REASONS[outcome?.reason ?? 'unsupported'];
+ const programmatic = programmaticBash
+ ? `; scripts run by the programmatic Bash tool can read it at $LIBRECHAT_CODE_DATA_DIR/${destination} during that run`
+ : '';
+ unavailable += `\n\t- ${file.filename}${getCodeFileContextSuffix(
+ file,
+ agentScoped,
+ file.filename,
+ )}: ${reason}${programmatic}`;
+ }
+ const sections: string[] = [];
+ if (imported) {
+ sections.push(
+ `- Note: Attached files are in the workspace at these paths, so every workspace tool (shell, read, search) can open them:${imported}`,
+ );
+ }
+ if (unavailable) {
+ sections.push(`- Note: These files are not available on this machine:${unavailable}`);
+ }
+ return sections.join('\n');
+}
+
+export interface WorkspaceAttachmentAgent {
+ id: string;
+ codeExecutionContext?: CodeExecutionContext;
+ /** Files the primed code-file note described, kept structured so it can be rebuilt. */
+ codeContextEntries?: CodeContextEntry[];
+ provisionState?: ProvisionState;
+ fileConsumers?: TurnFileConsumers;
+ dynamicToolContextMap?: Record<string, unknown>;
+ toolDefinitions?: ReadonlyArray<{ name?: string }>;
+ primedCodeFiles?: CodeEnvFile[];
+}
+
+/** Late provisioning refs go here so the first code tool call still receives them. */
+export interface WorkspaceAttachmentToolContext {
+ pendingProvisionedCodeFiles?: CodeEnvFile[];
+}
+
+export type ProvisionFiles = (
+ toolNames: string[],
+ agentId?: string,
+ signal?: AbortSignal,
+) => Promise<CodeEnvFile[] | void>;
+
+function mergeCodeEnvFiles(
+ current: readonly CodeEnvFile[] | undefined,
+ added: readonly CodeEnvFile[],
+): CodeEnvFile[] {
+ const merged = [...(current ?? [])];
+ for (const file of added) {
+ if (!merged.some((existing) => existing.id === file.id && existing.name === file.name)) {
+ merged.push(file);
+ }
+ }
+ return merged;
+}
+
+function collectQueuedCandidates(agent: WorkspaceAttachmentAgent): WorkspaceAttachmentCandidate[] {
+ const state = agent.provisionState;
+ if (state == null || agent.fileConsumers?.executeCode !== true) {
+ return [];
+ }
+ return state.codeEnvFiles.flatMap((file) => {
+ const destination = state.codeEnvDestinations?.get(file.file_id) ?? file.filename;
+ return isDescribedCodeFile(file, destination)
+ ? [{ file, destination, agentScoped: state.agentScopedFileIds.has(file.file_id) }]
+ : [];
+ });
+}
+
+/** Reads the route's stored ref after provisioning wrote it onto the shared record. */
+function withProvisionedSource(
+ candidate: WorkspaceAttachmentCandidate,
+ routeKey: string,
+): WorkspaceAttachmentCandidate {
+ if (candidate.source != null) {
+ return candidate;
+ }
+ const ref = getCodeEnvRefForProfile(candidate.file.metadata, routeKey);
+ if (ref?.storage_session_id == null || ref.file_id == null) {
+ return candidate;
+ }
+ return {
+ ...candidate,
+ destination: ref.sandboxFilename ?? candidate.destination,
+ source: { storage_session_id: ref.storage_session_id, file_id: ref.file_id },
+ };
+}
+
+/**
+ * Uploads queued attachments to the Code API so they can be copied, bounded by `signal`.
+ * Refs that arrive in time seed the run's sessions; later ones wait for the first code tool
+ * call, exactly as lazily provisioned files do.
+ */
+async function provisionQueued({
+ agent,
+ toolContext,
+ provisionFiles,
+ turnSignal,
+ deadline,
+}: {
+ agent: WorkspaceAttachmentAgent;
+ toolContext?: WorkspaceAttachmentToolContext;
+ provisionFiles: ProvisionFiles;
+ turnSignal?: AbortSignal;
+ deadline: AbortSignal;
+}): Promise<void> {
+ const provisioning = provisionFiles([AgentConstants.READ_FILE], agent.id, turnSignal).then(
+ (files) => files ?? [],
+ );
+ const onTime = await Promise.race([
+ provisioning.then(
+ (files) => files,
+ (error: unknown) => {
+ logger.warn(
+ `[workspaceAttachments] Provisioning attachments for agent ${agent.id} failed`,
+ getSafeErrorMetadata(error),
+ );
+ return [];
+ },
+ ),
+ whenAborted(deadline).then(() => undefined),
+ ]);
+ if (onTime != null) {
+ agent.primedCodeFiles = mergeCodeEnvFiles(agent.primedCodeFiles, onTime);
+ return;
+ }
+ provisioning
+ .then((files) => {
+ if (toolContext && files.length > 0) {
+ toolContext.pendingProvisionedCodeFiles = mergeCodeEnvFiles(
+ toolContext.pendingProvisionedCodeFiles,
+ files,
+ );
+ }
+ })
+ .catch(() => undefined);
+}
+
+/** Overrides for one priming call: a routed subagent brings the exact tool context it runs
+ * in, and a provisioning callback bound to it, rather than the turn's per-agent defaults. */
+export interface WorkspaceAttachmentPrimeOptions {
+ signal?: AbortSignal;
+ toolContexts?: ReadonlyMap<string, WorkspaceAttachmentToolContext>;
+ provisionFiles?: ProvisionFiles;
+}
+
+/**
+ * Primes every agent once per turn, whether it is initialized with the turn or joins later as
+ * a lazily selected subagent. `getProvisionFiles` is read at call time, so a callback wrapped
+ * after the primer was created is the one used.
+ */
+export function createWorkspaceAttachmentPrimer({
+ toolContexts,
+ getProvisionFiles,
+ deps,
+}: {
+ toolContexts?: ReadonlyMap<string, WorkspaceAttachmentToolContext>;
+ getProvisionFiles?: () => ProvisionFiles | undefined;
+ deps: WorkspaceAttachmentDeps;
+}): (
+ agents: ReadonlyArray<WorkspaceAttachmentAgent | null | undefined>,
+ options?: WorkspaceAttachmentPrimeOptions,
+) => Promise<void> {
+ const primed = new WeakSet<WorkspaceAttachmentAgent>();
+ const turn = createWorkspaceAttachmentTurn(deps.concurrency);
+ return (agents, options = {}) => {
+ const pending = agents.filter(
+ (agent): agent is WorkspaceAttachmentAgent => agent != null && !primed.has(agent),
+ );
+ for (const agent of pending) {
+ primed.add(agent);
+ }
+ return primeWorkspaceAttachments({
+ agents: pending,
+ toolContexts: options.toolContexts ?? toolContexts,
+ provisionFiles: options.provisionFiles ?? getProvisionFiles?.(),
+ signal: options.signal,
+ turn,
+ deps,
+ });
+ };
+}
+
+/**
+ * For agents on an attached workspace, copies the chat's own attachments into
+ * `.librechat/attachments/` before the model runs and replaces the code-file note with
+ * where they are. Agents that cannot receive them get a note saying so instead of a path
+ * only programmatic Bash could open. The whole phase is bounded; whatever is unfinished
+ * falls back to that note, and the copy is retried next turn.
+ */
+export async function primeWorkspaceAttachments({
+ agents,
+ toolContexts,
+ provisionFiles,
+ signal,
+ deps,
+ turn = createWorkspaceAttachmentTurn(deps.concurrency),
+}: {
+ agents: ReadonlyArray<WorkspaceAttachmentAgent | null | undefined>;
+ toolContexts?: ReadonlyMap<string, WorkspaceAttachmentToolContext>;
+ provisionFiles?: ProvisionFiles;
+ signal?: AbortSignal;
+ /** Shared with later priming of the same turn, such as a lazily selected subagent. */
+ turn?: WorkspaceAttachmentTurn;
+ deps: WorkspaceAttachmentDeps;
+}): Promise<void> {
+ const eligibleAgents = agents.flatMap((agent) =>
+ agent?.codeExecutionContext != null &&
+ getCodeFileLocation(agent.codeExecutionContext) === 'programmatic'
+ ? [{ agent, context: agent.codeExecutionContext }]
+ : [],
+ );
+ if (eligibleAgents.length === 0) {
+ return;
+ }
+ signal?.throwIfAborted();
+ const deadline = new AbortController();
+ const timeoutMs = deps.timeoutMs ?? WORKSPACE_ATTACHMENT_IMPORT_TIMEOUT_MS;
+ const timer = setTimeout(() => deadline.abort(), timeoutMs);
+ const abortOnTurn = () => deadline.abort(signal?.reason);
+ signal?.addEventListener('abort', abortOnTurn, { once: true });
+ try {
+ await Promise.all(
+ eligibleAgents.map(({ agent, context }) =>
+ primeAgentAttachments({
+ agent,
+ context,
+ toolContext: toolContexts?.get(agent.id),
+ provisionFiles,
+ turnSignal: signal,
+ deadline: deadline.signal,
+ turn,
+ deps,
+ }).catch((error: unknown) => {
+ if (signal?.aborted) {
+ throw error;
+ }
+ /** The primed note still stands; only the copy is skipped this turn. */
+ logger.error(
+ `[workspaceAttachments] Preparing attachments for agent ${agent.id} failed`,
+ getSafeErrorMetadata(error),
+ );
+ }),
+ ),
+ );
+ } finally {
+ clearTimeout(timer);
+ signal?.removeEventListener('abort', abortOnTurn);
+ }
+ signal?.throwIfAborted();
+}
+
+async function primeAgentAttachments({
+ agent,
+ context,
+ toolContext,
+ provisionFiles,
+ turnSignal,
+ deadline,
+ turn,
+ deps,
+}: {
+ agent: WorkspaceAttachmentAgent;
+ context: CodeExecutionContext;
+ toolContext?: WorkspaceAttachmentToolContext;
+ provisionFiles?: ProvisionFiles;
+ turnSignal?: AbortSignal;
+ deadline: AbortSignal;
+ turn: WorkspaceAttachmentTurn;
+ deps: WorkspaceAttachmentDeps;
+}): Promise<void> {
+ const primed: WorkspaceAttachmentCandidate[] = agent.codeContextEntries ?? [];
+ const queued = collectQueuedCandidates(agent);
+ if (primed.length === 0 && queued.length === 0) {
+ return;
+ }
+ const policy = resolveWorkspaceAttachmentPolicy(context);
+ const owned = (candidate: WorkspaceAttachmentCandidate): boolean =>
+ !candidate.agentScoped && String(candidate.file.user) === deps.userId;
+ const notOwnedReason = (
+ candidate: WorkspaceAttachmentCandidate,
+ ): WorkspaceAttachmentUnavailableReason => (candidate.agentScoped ? 'agent_file' : 'not_owned');
+ if (policy.eligible && provisionFiles && queued.some(owned)) {
+ await provisionQueued({ agent, toolContext, provisionFiles, turnSignal, deadline });
+ }
+ const routeKey = getCodeExecutionRouteKey(context);
+ const candidates = [...primed, ...queued.map((item) => withProvisionedSource(item, routeKey))];
+ const outcomes = new Map<string, WorkspaceAttachmentOutcome>();
+ const importable: WorkspaceAttachmentCandidate[] = [];
+ for (const candidate of candidates) {
+ if (policy.eligible && owned(candidate) && candidate.source == null) {
+ outcomes.set(candidate.file.file_id, {
+ status: 'unavailable',
+ reason: deadline.aborted ? 'timeout' : 'not_staged',
+ });
+ } else if (!owned(candidate)) {
+ outcomes.set(candidate.file.file_id, {
+ status: 'unavailable',
+ reason: notOwnedReason(candidate),
+ });
+ } else if (!policy.eligible) {
+ outcomes.set(candidate.file.file_id, { status: 'unavailable', reason: policy.reason });
+ } else {
+ importable.push(candidate);
+ }
+ }
+ if (importable.length > 0) {
+ const imported = await importWorkspaceAttachments({
+ context,
+ candidates: importable,
+ deps,
+ signal: deadline,
+ turn,
+ });
+ for (const [fileId, outcome] of imported) {
+ outcomes.set(fileId, outcome);
+ }
+ }
+ const note = buildWorkspaceAttachmentContext({
+ candidates,
+ outcomes,
+ programmaticBash:
+ agent.toolDefinitions?.some(
+ (definition) => definition.name != null && PROGRAMMATIC_TOOL_NAMES.has(definition.name),
+ ) === true,
+ });
+ agent.dynamicToolContextMap ??= {};
+ delete agent.dynamicToolContextMap[QUEUED_CODE_FILES_CONTEXT_KEY];
+ if (note) {
+ agent.dynamicToolContextMap[Tools.execute_code] = note;
+ } else {
+ delete agent.dynamicToolContextMap[Tools.execute_code];
+ }
+ if (agent.provisionState) {
+ agent.provisionState.describedFileIds = new Set(
+ candidates.map((candidate) => candidate.file.file_id),
+ );
+ }
+}
diff --git a/packages/api/src/code/bridge.spec.ts b/packages/api/src/code/bridge.spec.ts
index d3847fff73..dba55d644d 100644
--- a/packages/api/src/code/bridge.spec.ts
+++ b/packages/api/src/code/bridge.spec.ts
@@ -351,6 +351,96 @@ describe('getCodeBridgeWorkerStatus', () => {
);
});
+ describe('workspace operations a newer worker advertises', () => {
+ const statusWith = (workspaceTools: object) =>
+ getCodeBridgeWorkerStatus({
+ baseURL: 'https://code.example.com/v1',
+ token: 'token',
+ workerId: 'personal-vm',
+ fetchImpl: jest.fn().mockResolvedValue(
+ Response.json({
+ protocolVersion: 1,
+ workerId: 'personal-vm',
+ online: true,
+ ready: true,
+ leaseExpiresInMs: 45_000,
+ capabilities: {
+ statefulWorkspace: false,
+ runtimes: [],
+ sandboxProfile: 'native-srt',
+ workspaceTools,
+ },
+ }),
+ ),
+ });
+
+ test('drops names this build does not know and keeps the workspace usable', async () => {
+ await expect(
+ statusWith({
+ protocolVersion: 1,
+ operations: ['read_file', 'stream_logs', 'write_file', 'import_file'],
+ workspaces: [
+ { id: 'project-a' },
+ { id: 'docs', operations: ['read_file', 'stream_logs'] },
+ { id: 'future', operations: ['stream_logs'] },
+ ],
+ }),
+ ).resolves.toEqual(
+ expect.objectContaining({
+ status: 'ready',
+ operations: ['read_file', 'write_file', 'import_file'],
+ workspaces: [
+ { id: 'project-a' },
+ { id: 'docs', operations: ['read_file'] },
+ { id: 'future', operations: [] },
+ ],
+ }),
+ );
+ });
+
+ test('drops unknown names from a legacy capability list too', async () => {
+ await expect(statusWith({ operations: ['read_file', 'stream_logs'] })).resolves.toEqual(
+ expect.objectContaining({ operations: ['read_file'] }),
+ );
+ });
+
+ test('treats a worker offering only unknown operations as offering no workspace tools', async () => {
+ const status = await statusWith({
+ protocolVersion: 1,
+ operations: ['stream_logs'],
+ workspaces: [{ id: 'project-a' }],
+ });
+ expect(status.status).toBe('ready');
+ expect(status.operations).toBeUndefined();
+ expect(status.workspaces).toBeUndefined();
+ });
+
+ test.each([
+ ['a non-string name', ['read_file', 42]],
+ ['a malformed name', ['read_file', 'Read File']],
+ ['a duplicate name', ['read_file', 'read_file']],
+ ['an unbounded list', ['read_file', ...Array.from({ length: 64 }, (_, i) => `op_${i}`)]],
+ ])('still rejects %s', async (_label, operations) => {
+ await expect(
+ statusWith({ protocolVersion: 1, operations, workspaces: [{ id: 'project-a' }] }),
+ ).rejects.toEqual(
+ expect.objectContaining<Partial<CodeBridgeStatusError>>({ reason: 'invalid' }),
+ );
+ });
+
+ test('still rejects a root claiming a known operation the worker does not offer', async () => {
+ await expect(
+ statusWith({
+ protocolVersion: 1,
+ operations: ['read_file', 'stream_logs'],
+ workspaces: [{ id: 'project-a', operations: ['execute_command'] }],
+ }),
+ ).rejects.toEqual(
+ expect.objectContaining<Partial<CodeBridgeStatusError>>({ reason: 'invalid' }),
+ );
+ });
+ });
+
test('rejects an upstream response before buffering more than 256 KiB', async () => {
const fetchImpl = jest
.fn()
diff --git a/packages/api/src/code/bridge.ts b/packages/api/src/code/bridge.ts
index dd40833e61..0e3d2d7003 100644
--- a/packages/api/src/code/bridge.ts
+++ b/packages/api/src/code/bridge.ts
@@ -245,18 +245,37 @@ function validStatusStringArray(value: unknown): value is string[] {
);
}
-function validWorkspaceOperations(value: unknown): value is CodeWorkspaceOperation[] {
- return (
- Array.isArray(value) &&
- value.length > 0 &&
- value.length <= CODE_WORKSPACE_OPERATIONS.length &&
- value.every((operation) =>
- CODE_WORKSPACE_OPERATIONS.includes(operation as CodeWorkspaceOperation),
- ) &&
- new Set(value).size === value.length
+/** Bound on advertised operation names, known or not, so a status cannot carry an unbounded list. */
+const MAX_ADVERTISED_WORKSPACE_OPERATIONS = 64;
+const WORKSPACE_OPERATION_NAME = /^[a-z][a-z0-9_]{0,63}$/;
+const KNOWN_WORKSPACE_OPERATIONS: ReadonlySet<string> = new Set(CODE_WORKSPACE_OPERATIONS);
+
+/**
+ * The operations this build knows from a well-formed advertised list, or undefined when the list
+ * itself is malformed. Workers gain operations before every LibreChat deployment knows them, so a
+ * well-formed name this build does not know is dropped rather than invalidating the worker.
+ */
+function knownWorkspaceOperations(value: unknown): CodeWorkspaceOperation[] | undefined {
+ if (
+ !Array.isArray(value) ||
+ value.length > MAX_ADVERTISED_WORKSPACE_OPERATIONS ||
+ new Set(value).size !== value.length ||
+ !value.every(
+ (operation) => typeof operation === 'string' && WORKSPACE_OPERATION_NAME.test(operation),
+ )
+ ) {
+ return undefined;
+ }
+ return value.filter((operation): operation is CodeWorkspaceOperation =>
+ KNOWN_WORKSPACE_OPERATIONS.has(operation),
);
}
+/** A worker-level list must still offer at least one operation this build can use. */
+function validWorkspaceOperations(value: unknown): boolean {
+ return (knownWorkspaceOperations(value)?.length ?? 0) > 0;
+}
+
function knownEditFileFeatures(value: unknown): WorkspaceEditFileFeature[] {
if (!Array.isArray(value)) {
return [];
@@ -266,8 +285,9 @@ function knownEditFileFeatures(value: unknown): WorkspaceEditFileFeature[] {
function validWorkspaceCapabilities(value: unknown): value is {
protocolVersion: 1;
- operations: CodeWorkspaceOperation[];
- workspaces: CodeWorkspaceDescriptor[];
+ /** Raw advertised names; read through `knownWorkspaceOperations`. */
+ operations: string[];
+ workspaces: Array<Omit<CodeWorkspaceDescriptor, 'operations'> & { operations?: string[] }>;
programmaticLanguages?: unknown;
editFileFeatures?: unknown;
} {
@@ -282,7 +302,7 @@ function validWorkspaceCapabilities(value: unknown): value is {
) {
return false;
}
- const operations = capabilities.operations;
+ const operations = knownWorkspaceOperations(capabilities.operations) ?? [];
const ids = new Set<string>();
return capabilities.workspaces.every((value) => {
if (value == null || typeof value !== 'object' || Array.isArray(value)) return false;
@@ -319,9 +339,7 @@ function validWorkspaceCapabilities(value: unknown): value is {
workspace.name.trim().length === 0 ||
workspace.name.length > 128)) ||
(workspace.operations !== undefined &&
- (!validWorkspaceOperations(workspace.operations) ||
- workspace.operations.length > operations.length ||
- workspace.operations.some((operation) => !operations.includes(operation))))
+ !isWorkspaceOperationSubset(workspace.operations, operations))
) {
return false;
}
@@ -330,11 +348,34 @@ function validWorkspaceCapabilities(value: unknown): value is {
});
}
+/** A root may narrow the worker's known operations; one only it knows is dropped, not refused. */
+function isWorkspaceOperationSubset(
+ value: unknown,
+ workerOperations: readonly CodeWorkspaceOperation[],
+): boolean {
+ const known = knownWorkspaceOperations(value);
+ return known != null && known.every((operation) => workerOperations.includes(operation));
+}
+
+/**
+ * A worker whose workspace tools are all newer than this build is still a valid worker; it
+ * simply offers no workspace tools here, exactly like one that advertises none.
+ */
+function offersOnlyUnknownWorkspaceOperations(value: unknown): boolean {
+ if (value == null || typeof value !== 'object' || Array.isArray(value)) return false;
+ const { operations } = value as { operations?: unknown };
+ return (
+ Array.isArray(operations) &&
+ operations.length > 0 &&
+ knownWorkspaceOperations(operations)?.length === 0
+ );
+}
+
/** Keep the status endpoint readable during worker-first rolling upgrades.
* Legacy capabilities remain non-selectable and are surfaced as an explicit
* update-required state; they never regain an implicit `primary` binding. */
function validLegacyWorkspaceCapabilities(value: unknown): value is {
- operations: CodeWorkspaceOperation[];
+ operations: string[];
} {
if (value == null || typeof value !== 'object' || Array.isArray(value)) return false;
const capabilities = value as Record<string, unknown>;
@@ -430,7 +471,8 @@ export async function getCodeBridgeWorkerStatus({
const validWorkspaceTools =
capabilities?.workspaceTools == null ||
validWorkspaceCapabilities(capabilities.workspaceTools) ||
- validLegacyWorkspaceCapabilities(capabilities.workspaceTools);
+ validLegacyWorkspaceCapabilities(capabilities.workspaceTools) ||
+ offersOnlyUnknownWorkspaceOperations(capabilities.workspaceTools);
if (
status.protocolVersion !== 1 ||
status.workerId !== workerId ||
@@ -459,11 +501,13 @@ export async function getCodeBridgeWorkerStatus({
> = {};
if (validWorkspaceCapabilities(capabilities?.workspaceTools)) {
workspaceStatus = {
- operations: [...capabilities.workspaceTools.operations],
- workspaces: capabilities.workspaceTools.workspaces.map((workspace) => ({
- ...workspace,
- ...(workspace.operations ? { operations: [...workspace.operations] } : {}),
- })),
+ operations: knownWorkspaceOperations(capabilities.workspaceTools.operations) ?? [],
+ workspaces: capabilities.workspaceTools.workspaces.map(
+ ({ operations, ...workspace }): CodeWorkspaceDescriptor => ({
+ ...workspace,
+ ...(operations ? { operations: knownWorkspaceOperations(operations) ?? [] } : {}),
+ }),
+ ),
};
if (
Array.isArray(capabilities.workspaceTools.programmaticLanguages) &&
@@ -479,7 +523,9 @@ export async function getCodeBridgeWorkerStatus({
workspaceStatus.editFileFeatures = editFileFeatures;
}
} else if (validLegacyWorkspaceCapabilities(capabilities?.workspaceTools)) {
- workspaceStatus = { operations: [...capabilities.workspaceTools.operations] };
+ workspaceStatus = {
+ operations: knownWorkspaceOperations(capabilities.workspaceTools.operations) ?? [],
+ };
}
return {
status: workerStatus,
diff --git a/packages/api/src/code/capabilities.spec.ts b/packages/api/src/code/capabilities.spec.ts
index fa10ef0379..818ac53d5d 100644
--- a/packages/api/src/code/capabilities.spec.ts
+++ b/packages/api/src/code/capabilities.spec.ts
@@ -356,6 +356,7 @@ describe('resolveCodeExecutionWorkspaceContext', () => {
workspaces: unknown[],
statefulWorkspace: boolean = true,
maxCommandTimeoutMs?: number,
+ operations: string[] = ['read_file', 'list_files', 'execute_command'],
): Response {
return new Response(
JSON.stringify({
@@ -371,7 +372,7 @@ describe('resolveCodeExecutionWorkspaceContext', () => {
runtimes: ['bash'],
workspaceTools: {
protocolVersion: 1,
- operations: ['read_file', 'list_files', 'execute_command'],
+ operations,
workspaces,
},
},
@@ -412,6 +413,33 @@ describe('resolveCodeExecutionWorkspaceContext', () => {
});
});
+ it('selects a workspace from a newer worker with only the operations this build knows', async () => {
+ jest
+ .spyOn(globalThis, 'fetch')
+ .mockResolvedValue(
+ workspaceStatus(
+ [{ id: 'docs', operations: ['read_file', 'stream_logs', 'import_file', 'write_file'] }],
+ true,
+ undefined,
+ ['read_file', 'write_file', 'import_file', 'stream_logs', 'execute_command'],
+ ),
+ );
+
+ await expect(
+ resolveCodeExecutionWorkspaceContext({
+ context,
+ requestedSelections: [{ environmentId: 'personal', workspaceId: 'docs' }],
+ environments,
+ getAppConfig,
+ }),
+ ).resolves.toMatchObject({
+ codeWorkspace: {
+ workspaceId: 'docs',
+ operations: ['read_file', 'import_file', 'write_file'],
+ },
+ });
+ });
+
it('carries the worker edit features into the selected workspace', async () => {
const response = workspaceStatus([{ id: 'docs' }]);
const body = await response.json();
diff --git a/packages/api/src/code/index.ts b/packages/api/src/code/index.ts
index 7ee2b2a5a8..08a5298812 100644
--- a/packages/api/src/code/index.ts
+++ b/packages/api/src/code/index.ts
@@ -11,6 +11,7 @@ export * from './decision';
export * from './inheritance';
export * from './errors';
export * from './instructions';
+export * from './attachments';
export * from './targets';
export * from './agent';
export { createCodeSetupRouter } from './setup/router';
diff --git a/packages/api/src/code/workspace.ts b/packages/api/src/code/workspace.ts
index f7ab968ae0..bb06ef5818 100644
--- a/packages/api/src/code/workspace.ts
+++ b/packages/api/src/code/workspace.ts
@@ -133,6 +133,19 @@ const PREVIEW_EDIT_RESULT_KEYS = new Set([
'bytesWritten',
'matches',
]);
+const IMPORT_RESULT_KEYS = new Set([
+ 'protocolVersion',
+ 'operation',
+ 'workspaceId',
+ 'path',
+ 'created',
+ 'unchanged',
+ 'bytesWritten',
+ 'sha256',
+]);
+/** Raw Code API storage identifiers are URL-safe nanoids. */
+const STORAGE_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
+const SHA256_PATTERN = /^[a-f0-9]{64}$/;
const TEXT_EDIT_KEYS = new Set(['oldText', 'newText', 'replaceAll']);
const EDIT_MATCH_KEYS = new Set(['strategy', 'occurrences']);
@@ -189,6 +202,26 @@ export interface WorkspaceWriteRequest {
overwrite?: boolean;
}
+/**
+ * Copies an object the Code API already stores for this user into the workspace. Additive to
+ * protocol v1: sent only to workspaces that advertise `import_file`. The Code API mints the
+ * read grant and checks ownership; LibreChat names only refs it already holds.
+ */
+export interface WorkspaceImportRequest {
+ protocolVersion: 1;
+ operation: 'import_file';
+ workspaceId: string;
+ workspaceInstanceId?: string;
+ /** Linked worktree (`.worktrees/<name>`) the path is relative to. */
+ worktree?: string;
+ path: string;
+ source: { storage_session_id: string; id: string };
+ bytes: number;
+ /** Lowercase hex digest of the object; an existing file with the same digest is left as is. */
+ sha256: string;
+ overwrite?: boolean;
+}
+
export interface WorkspaceTextEdit {
oldText: string;
newText: string;
@@ -226,7 +259,8 @@ export type WorkspaceToolRequest =
| WorkspaceWriteRequest
| WorkspacePreviewEditRequest
| WorkspaceEditRequest
- | WorkspaceExecuteCommandRequest;
+ | WorkspaceExecuteCommandRequest
+ | WorkspaceImportRequest;
export interface WorkspaceReadResult {
protocolVersion: 1;
@@ -286,6 +320,18 @@ export interface WorkspaceWriteResult {
bytesWritten: number;
}
+export interface WorkspaceImportResult {
+ protocolVersion: 1;
+ operation: 'import_file';
+ workspaceId: string;
+ path: string;
+ created: boolean;
+ /** The file already held these exact bytes, so nothing was written. */
+ unchanged?: boolean;
+ bytesWritten: number;
+ sha256: string;
+}
+
export interface WorkspaceEditResult {
protocolVersion: 1;
operation: 'edit_file';
@@ -316,7 +362,8 @@ export type WorkspaceToolResult =
| WorkspaceWriteResult
| WorkspacePreviewEditResult
| WorkspaceEditResult
- | WorkspaceExecuteCommandResult;
+ | WorkspaceExecuteCommandResult
+ | WorkspaceImportResult;
export class WorkspaceToolHttpError extends Error {
/**
@@ -832,6 +879,24 @@ function isValidRequest(request: WorkspaceToolRequest): boolean {
(request.overwrite === undefined || typeof request.overwrite === 'boolean')
);
}
+ if (request.operation === 'import_file') {
+ return (
+ isSafePath(request.path) &&
+ (request.worktree === undefined ||
+ (LINKED_WORKTREE_NAME_PATTERN.test(request.worktree) &&
+ !request.worktree.endsWith('.lock'))) &&
+ isRecord(request.source) &&
+ Object.keys(request.source).length === 2 &&
+ typeof request.source.storage_session_id === 'string' &&
+ STORAGE_ID_PATTERN.test(request.source.storage_session_id) &&
+ typeof request.source.id === 'string' &&
+ STORAGE_ID_PATTERN.test(request.source.id) &&
+ Number.isSafeInteger(request.bytes) &&
+ request.bytes >= 0 &&
+ SHA256_PATTERN.test(request.sha256) &&
+ (request.overwrite === undefined || typeof request.overwrite === 'boolean')
+ );
+ }
if (request.operation === 'preview_edit') {
return (
isSafePath(request.path) &&
@@ -980,6 +1045,19 @@ function isValidResult(
Number(value.bytesWritten) === new TextEncoder().encode(request.content).byteLength
);
}
+ if (request.operation === 'import_file') {
+ return (
+ hasOnlyKeys(value, IMPORT_RESULT_KEYS) &&
+ value.path === request.path &&
+ typeof value.created === 'boolean' &&
+ (value.unchanged === undefined || typeof value.unchanged === 'boolean') &&
+ !(value.created === true && value.unchanged === true) &&
+ value.sha256 === request.sha256 &&
+ Number.isSafeInteger(value.bytesWritten) &&
+ (Number(value.bytesWritten) === request.bytes ||
+ (value.unchanged === true && Number(value.bytesWritten) === 0))
+ );
+ }
if (request.operation === 'edit_file') {
return (
hasOnlyKeys(value, EDIT_RESULT_KEYS) &&
@@ -1164,6 +1242,8 @@ export function toLinkedWorktreeRequest(
},
};
}
+ case 'import_file':
+ return undefined;
case 'execute_command': {
if (request.environmentAction != null) return undefined;
const target = splitLinkedWorktreePath(request.cwd);
@@ -1191,6 +1271,7 @@ export function fromLinkedWorktreeResult(
case 'write_file':
case 'edit_file':
case 'preview_edit':
+ case 'import_file':
return { ...result, path: prefixed(worktree, result.path) };
case 'search_text':
return {
diff --git a/packages/api/src/files/code/priming.ts b/packages/api/src/files/code/priming.ts
index 0dba3389f0..4a21798687 100644
--- a/packages/api/src/files/code/priming.ts
+++ b/packages/api/src/files/code/priming.ts
@@ -208,6 +208,20 @@ export type CodeFileLocation = 'sandbox' | 'programmatic';
type CodeContextFile = Pick<TFile, 'file_id' | 'filename' | 'context' | 'status' | 'previewError'>;
+/**
+ * A file the code-file note describes, kept structured on routes where the note is rebuilt
+ * after priming: an attached workspace replaces it once attachments are copied in.
+ */
+export interface CodeContextEntry {
+ file: TFile;
+ /** Name under the code data directory. */
+ destination: string;
+ /** One of the agent's own files rather than something attached in this chat. */
+ agentScoped: boolean;
+ /** The code-environment object holding the bytes, when one is stored. */
+ source?: { storage_session_id: string; file_id: string };
+}
+
const CODE_FILE_CONTEXT_ROOTS: Record<CodeFileLocation, string> = {
sandbox: '/mnt/data',
programmatic: '$LIBRECHAT_CODE_DATA_DIR',
@@ -258,17 +272,34 @@ export function getCodeFileContextLine(
destination: string,
location: CodeFileLocation = 'sandbox',
): string {
- const displaced = destination !== file.filename;
- if (file.context === FileContext.execute_code && !displaced) {
+ if (!isDescribedCodeFile(file, destination)) {
return '';
}
+ return `\n\t- ${CODE_FILE_CONTEXT_ROOTS[location]}/${destination}${getCodeFileContextSuffix(
+ file,
+ agentResourceIds.has(file.file_id),
+ destination,
+ )}`;
+}
+
+/** Whether the code-file note mentions this file at `destination` at all. */
+export function isDescribedCodeFile(file: CodeContextFile, destination: string): boolean {
+ return file.context !== FileContext.execute_code || destination !== file.filename;
+}
+
+/** Provenance and preview state appended to a file shown under `shownName`. */
+export function getCodeFileContextSuffix(
+ file: CodeContextFile,
+ agentScoped: boolean,
+ shownName: string,
+): string {
const origin =
file.context === FileContext.execute_code
? ` (written earlier as ${file.filename})`
- : `${agentResourceIds.has(file.file_id) ? '' : ' (attached by user)'}${
- displaced ? ` (uploaded as ${file.filename})` : ''
+ : `${agentScoped ? '' : ' (attached by user)'}${
+ shownName !== file.filename ? ` (uploaded as ${file.filename})` : ''
}`;
- return `\n\t- ${CODE_FILE_CONTEXT_ROOTS[location]}/${destination}${origin}${getPreviewContextSuffix(file)}`;
+ return `${origin}${getPreviewContextSuffix(file)}`;
}
export function appendCodeFileContextLine(
diff --git a/packages/api/src/files/code/queued.ts b/packages/api/src/files/code/queued.ts
index 39a497f6d9..d30d9e0832 100644
--- a/packages/api/src/files/code/queued.ts
+++ b/packages/api/src/files/code/queued.ts
@@ -194,7 +194,9 @@ export function prepareQueuedCodeFileContext(
);
const location = getCodeFileLocation(agent.codeExecutionContext);
let context = '';
+ const described = agent.provisionState.describedFileIds;
for (const { file, destination } of uploads) {
+ if (described?.has(file.file_id)) continue;
context = appendCodeFileContextLine(
context,
getCodeFileContextLine(file, agent.provisionState.agentScopedFileIds, destination, location),
diff --git a/packages/api/src/files/provision/service.spec.ts b/packages/api/src/files/provision/service.spec.ts
index 253c97b8dd..18a1a9e4ff 100644
--- a/packages/api/src/files/provision/service.spec.ts
+++ b/packages/api/src/files/provision/service.spec.ts
@@ -1,6 +1,7 @@
import { Readable } from 'node:stream';
import { AxiosError, AxiosHeaders } from 'axios';
-import { generateKeyPairSync } from 'node:crypto';
+import { FileSources } from 'librechat-data-provider';
+import { createHash, generateKeyPairSync } from 'node:crypto';
import type { TFile } from 'librechat-data-provider';
import type { ServerRequest } from '~/types';
@@ -307,6 +308,45 @@ describe('createProvisionService', () => {
});
});
+ describe('digestFile', () => {
+ it('hashes the stored bytes a code-environment upload would send', async () => {
+ const getDownloadStream = jest
+ .fn()
+ .mockResolvedValue(Readable.from([Buffer.from('hello '), Buffer.from('world')]));
+ const { service } = buildService({
+ getStrategyFunctions: () => ({ getDownloadStream }),
+ });
+
+ await expect(service.digestFile({ req, file: makeFile() })).resolves.toEqual({
+ sha256: createHash('sha256').update('hello world').digest('hex'),
+ bytes: 11,
+ });
+ expect(getDownloadStream).toHaveBeenCalledWith(req, '/x/data.csv', { signal: undefined });
+ });
+
+ it('returns null for a source without a storage stream', async () => {
+ const { service } = buildService();
+ await expect(
+ service.digestFile({ req, file: makeFile({ source: FileSources.openai }) }),
+ ).resolves.toBeNull();
+ });
+
+ it('stops reading when the signal aborts', async () => {
+ const controller = new AbortController();
+ const stream = new Readable({ read() {} });
+ stream.push('partial');
+ const { service } = buildService({
+ getStrategyFunctions: () => ({ getDownloadStream: jest.fn().mockResolvedValue(stream) }),
+ });
+
+ const digest = service.digestFile({ req, file: makeFile(), signal: controller.signal });
+ setImmediate(() => controller.abort(new Error('deadline')));
+
+ await expect(digest).rejects.toThrow('deadline');
+ expect(stream.destroyed).toBe(true);
+ });
+ });
+
describe('checkSessionsAlive', () => {
const staleFile = (id: string) =>
makeFile({
diff --git a/packages/api/src/files/provision/service.ts b/packages/api/src/files/provision/service.ts
index b742d5a0b6..c38643abc8 100644
--- a/packages/api/src/files/provision/service.ts
+++ b/packages/api/src/files/provision/service.ts
@@ -1,10 +1,10 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { randomUUID } from 'node:crypto';
import { pipeline } from 'node:stream/promises';
import { logger } from '@librechat/data-schemas';
import { getCodeBaseURL } from '@librechat/agents';
+import { createHash, randomUUID } from 'node:crypto';
import {
FileSources,
getCodeEnvRefs,
@@ -90,6 +90,11 @@ export interface CodeEnvReferenceSetResult {
codeEnvRefs?: CodeEnvRefMap;
}
+export interface StoredFileDigest {
+ sha256: string;
+ bytes: number;
+}
+
export interface ProvisionService {
loadCodeApiKey: (userId: string) => Promise<string | undefined>;
provisionToCodeEnv: (params: {
@@ -115,6 +120,13 @@ export interface ProvisionService {
signal?: AbortSignal;
onUploadStart?: FileStorageUploadObserver;
}) => Promise<{ embedded: boolean; fileUpdate: ProvisionFileUpdate | null }>;
+ /** SHA-256 and length of the stored bytes, the same bytes a code-environment upload sends;
+ * null when the file's storage cannot be streamed. */
+ digestFile: (params: {
+ req: ServerRequest;
+ file: TFile;
+ signal?: AbortSignal;
+ }) => Promise<StoredFileDigest | null>;
checkSessionsAlive: (params: {
files: TFile[];
apiKey?: string;
@@ -626,10 +638,41 @@ export function createProvisionService({
await Promise.allSettled(sessionChecks);
return aliveFileIds;
}
+ async function digestFile({
+ req,
+ file,
+ signal,
+ }: {
+ req: ServerRequest;
+ file: TFile;
+ signal?: AbortSignal;
+ }): Promise<StoredFileDigest | null> {
+ const stream = await getStorageStream(file, req, signal);
+ if (stream == null) {
+ return null;
+ }
+ const hash = createHash('sha256');
+ let bytes = 0;
+ const abort = () => stream.destroy(signal?.reason instanceof Error ? signal.reason : undefined);
+ signal?.addEventListener('abort', abort, { once: true });
+ try {
+ for await (const chunk of stream) {
+ const buffer: Buffer = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
+ hash.update(buffer);
+ bytes += buffer.byteLength;
+ }
+ } finally {
+ signal?.removeEventListener('abort', abort);
+ }
+ signal?.throwIfAborted();
+ return { sha256: hash.digest('hex'), bytes };
+ }
+
return {
loadCodeApiKey,
provisionToCodeEnv,
provisionToVectorDB,
+ digestFile,
checkSessionsAlive,
};
}
diff --git a/packages/data-provider/src/code/workspace.ts b/packages/data-provider/src/code/workspace.ts
index 6b7da4bbce..bdb6854ba0 100644
--- a/packages/data-provider/src/code/workspace.ts
+++ b/packages/data-provider/src/code/workspace.ts
@@ -52,6 +52,8 @@ export const CODE_WORKSPACE_OPERATIONS = [
'preview_edit',
'edit_file',
'execute_command',
+ /** Copies a Code API stored object into the workspace; sent only when advertised. */
+ 'import_file',
] as const;
export const CODE_WORKSPACE_INSTANCE_TYPES = ['git_worktree'] as const;
export const CODE_WORKSPACE_CHECKOUT_MODES = ['source', 'isolated'] as const;
diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.ts
index bcb68263df..09afd487bd 100644
--- a/packages/data-provider/src/config.spec.ts
+++ b/packages/data-provider/src/config.spec.ts
@@ -259,6 +259,30 @@ describe('repository instruction configuration', () => {
});
});
+describe('workspace attachment configuration', () => {
+ it('defaults the copy budget to ten seconds and bounds operator overrides', () => {
+ expect(agentsEndpointSchema.parse({}).workspaceAttachments).toBeUndefined();
+ expect(agentsEndpointSchema.parse({ workspaceAttachments: {} }).workspaceAttachments).toEqual({
+ timeoutMs: 10_000,
+ concurrency: 3,
+ });
+ expect(
+ agentsEndpointSchema.parse({ workspaceAttachments: { timeoutMs: 30_000 } })
+ .workspaceAttachments,
+ ).toEqual({ timeoutMs: 30_000, concurrency: 3 });
+ for (const concurrency of [0, 17, 1.5]) {
+ expect(
+ agentsEndpointSchema.safeParse({ workspaceAttachments: { concurrency } }).success,
+ ).toBe(false);
+ }
+ for (const timeoutMs of [0, 999, 120_001, 1.5]) {
+ expect(agentsEndpointSchema.safeParse({ workspaceAttachments: { timeoutMs } }).success).toBe(
+ false,
+ );
+ }
+ });
+});
+
describe('inactive history payload budget', () => {
it('defaults the budget with and without an interface block', () => {
expect(interfaceSchema.parse({}).historyCacheMaxBytes).toBe(DEFAULT_HISTORY_CACHE_MAX_BYTES);
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index cbf47e0daa..9329263d23 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -1617,6 +1617,15 @@ export const agentsEndpointSchema = baseEndpointSchema
timeoutMs: z.number().int().min(100).max(30_000).optional().default(2000),
})
.optional(),
+ /** How long a turn on an attached workspace may spend copying chat attachments into it
+ * before the model runs; unfinished copies fall back to a note and retry next turn. */
+ workspaceAttachments: z
+ .object({
+ timeoutMs: z.number().int().min(1_000).max(120_000).optional().default(10_000),
+ /** Workspace requests in flight for the turn, across every agent it primes. */
+ concurrency: z.number().int().min(1).max(16).optional().default(3),
+ })
+ .optional(),
/** Budget and cache configuration for resolving an agent's linked prompt-group
* instructions. Omitting the block applies the defaults below. */
linkedInstructions: z
diff --git a/packages/data-provider/src/types/files.ts b/packages/data-provider/src/types/files.ts
index c304a99413..457ee5e3c8 100644
--- a/packages/data-provider/src/types/files.ts
+++ b/packages/data-provider/src/types/files.ts
@@ -227,12 +227,32 @@ export type TFile = {
destinationChosen?: boolean;
/** The type the delivery route was resolved against, when conversion changed it. */
routingMimeType?: string;
+ /** Copies already placed in attached workspaces; see `TFileWorkspaceImports`. */
+ workspaceImports?: TFileWorkspaceImports;
};
llmDeliveryPath?: 'provider' | 'text' | 'none';
createdAt?: string | Date;
updatedAt?: string | Date;
};
+/** One copy of a file placed in an attached workspace. */
+export interface TFileWorkspaceImport {
+ sha256: string;
+ /** Workspace-relative path the copy was written to. */
+ path: string;
+}
+
+/**
+ * Lets a later turn skip files an attached workspace already holds without another read.
+ * `digest` describes the stored code-environment object the copies were made from, keyed by
+ * that object so a re-upload is hashed again; `targets` is keyed by an opaque digest of the
+ * conversation, machine, workspace and checkout the copy was written to.
+ */
+export interface TFileWorkspaceImports {
+ digest?: { source: string; sha256: string; bytes: number };
+ targets?: Record<string, TFileWorkspaceImport>;
+}
+
export type TFileUpload = TFile & {
temp_file_id: string;
};
diff --git a/packages/data-schemas/src/methods/file.spec.ts b/packages/data-schemas/src/methods/file.spec.ts
index 385b1a8d0f..637b844496 100644
--- a/packages/data-schemas/src/methods/file.spec.ts
+++ b/packages/data-schemas/src/methods/file.spec.ts
@@ -3085,6 +3085,118 @@ describe('File Methods', () => {
});
});
+ describe('recordFileWorkspaceImport', () => {
+ const makeFile = (fileId: string, ownerId: mongoose.Types.ObjectId, tenantId = 'tenant-a') =>
+ runAsSystem(() =>
+ fileMethods.createFile({
+ file_id: fileId,
+ user: ownerId,
+ tenantId,
+ filename: 'report.pdf',
+ filepath: '/uploads/report.pdf',
+ source: 'local',
+ type: 'application/pdf',
+ bytes: 3,
+ context: FileContext.message_attachment,
+ metadata: { routingMimeType: 'application/pdf' },
+ }),
+ );
+ const keyA = 'a'.repeat(32);
+ const keyB = 'b'.repeat(32);
+ const copy = (path: string) => ({ sha256: 'c'.repeat(64), path });
+
+ it('records copies and the digest without replacing sibling targets or metadata', async () => {
+ const ownerId = new mongoose.Types.ObjectId();
+ const fileId = uuidv4();
+ await makeFile(fileId, ownerId);
+
+ await Promise.all([
+ runAsSystem(() =>
+ fileMethods.recordFileWorkspaceImport({
+ file_id: fileId,
+ user: ownerId.toString(),
+ tenantId: 'tenant-a',
+ copy: { key: keyA, target: copy('.librechat/attachments/report.pdf') },
+ }),
+ ),
+ runAsSystem(() =>
+ fileMethods.recordFileWorkspaceImport({
+ file_id: fileId,
+ user: ownerId.toString(),
+ tenantId: 'tenant-a',
+ copy: { key: keyB, target: copy('.librechat/attachments/report (2).pdf') },
+ }),
+ ),
+ runAsSystem(() =>
+ fileMethods.recordFileWorkspaceImport({
+ file_id: fileId,
+ user: ownerId.toString(),
+ tenantId: 'tenant-a',
+ digest: { source: 's/o', sha256: 'c'.repeat(64), bytes: 3 },
+ }),
+ ),
+ ]);
+
+ const stored = await runAsSystem(() => fileMethods.findFileById(fileId));
+ expect(stored?.metadata?.workspaceImports).toEqual({
+ digest: { source: 's/o', sha256: 'c'.repeat(64), bytes: 3 },
+ targets: {
+ [keyA]: copy('.librechat/attachments/report.pdf'),
+ [keyB]: copy('.librechat/attachments/report (2).pdf'),
+ },
+ });
+ expect(stored?.metadata?.routingMimeType).toBe('application/pdf');
+ });
+
+ it("never marks another user's file", async () => {
+ const ownerId = new mongoose.Types.ObjectId();
+ const fileId = uuidv4();
+ await makeFile(fileId, ownerId);
+
+ const matched = await runAsSystem(() =>
+ fileMethods.recordFileWorkspaceImport({
+ file_id: fileId,
+ user: new mongoose.Types.ObjectId().toString(),
+ tenantId: 'tenant-a',
+ copy: { key: keyA, target: copy('.librechat/attachments/report.pdf') },
+ }),
+ );
+
+ expect(matched).toBe(false);
+ const stored = await runAsSystem(() => fileMethods.findFileById(fileId));
+ expect(stored?.metadata?.workspaceImports).toBeUndefined();
+ });
+
+ it("never marks the same user's record in another tenant", async () => {
+ const ownerId = new mongoose.Types.ObjectId();
+ const fileId = uuidv4();
+ await makeFile(fileId, ownerId, 'tenant-b');
+
+ const matched = await runAsSystem(() =>
+ fileMethods.recordFileWorkspaceImport({
+ file_id: fileId,
+ user: ownerId.toString(),
+ tenantId: 'tenant-a',
+ copy: { key: keyA, target: copy('.librechat/attachments/report.pdf') },
+ }),
+ );
+
+ expect(matched).toBe(false);
+ const stored = await runAsSystem(() => fileMethods.findFileById(fileId));
+ expect(stored?.metadata?.workspaceImports).toBeUndefined();
+ });
+
+ it('rejects a key that would address another metadata path', async () => {
+ await expect(
+ fileMethods.recordFileWorkspaceImport({
+ file_id: uuidv4(),
+ user: new mongoose.Types.ObjectId().toString(),
+ copy: { key: 'targets.$where', target: copy('.librechat/attachments/report.pdf') },
+ }),
+ ).rejects.toThrow('hex digests');
+ });
+ });
+
describe('getUserCodeFiles', () => {
it('returns only authenticated owner code-env uploads', async () => {
const ownerId = new mongoose.Types.ObjectId();
diff --git a/packages/data-schemas/src/methods/file.ts b/packages/data-schemas/src/methods/file.ts
index c467de3347..e14c4a4871 100644
--- a/packages/data-schemas/src/methods/file.ts
+++ b/packages/data-schemas/src/methods/file.ts
@@ -1,7 +1,12 @@
import { Types } from 'mongoose';
import { createHash } from 'crypto';
import { EToolResources, FileContext, FileSources, getCodeEnvRefs } from 'librechat-data-provider';
-import type { CodeEnvRef, TFile } from 'librechat-data-provider';
+import type {
+ TFile,
+ CodeEnvRef,
+ TFileWorkspaceImport,
+ TFileWorkspaceImports,
+} from 'librechat-data-provider';
import type { FilterQuery, SortOrder, Model } from 'mongoose';
import type {
IMongoFile,
@@ -28,6 +33,17 @@ export type LegacySearchFileRef = {
tenantId?: string;
};
+/** A user's file's freshly computed digest, the copy placed in one workspace, or both. */
+export type WorkspaceImportRecord = {
+ file_id: string;
+ user: string;
+ /** The record's own tenant; an untenanted record is matched as untenanted. */
+ tenantId?: string | null;
+ /** `key` is an opaque hex digest of the conversation and workspace the copy went to. */
+ copy?: { key: string; target: TFileWorkspaceImport };
+ digest?: NonNullable<TFileWorkspaceImports['digest']>;
+};
+
export type ClearFileEmbeddingsParams = {
file_id: string;
userId: string;
@@ -453,6 +469,7 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {
file_id: string;
entityId: string;
}) => Promise<IMongoFile | null>;
+ recordFileWorkspaceImport: (data: WorkspaceImportRecord) => Promise<boolean>;
adoptLegacySearchEmbeddings: (data: {
files: LegacySearchFileRef[];
agentId: string;
@@ -1462,6 +1479,48 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {
);
}
+ /**
+ * Records a workspace copy of a user's file and/or the digest of the stored bytes, without
+ * rewriting sibling targets another turn wrote in between. A digest is kept even when the
+ * copy fails, so a refused file is not hashed again every turn. The target key becomes a
+ * dotted path, so only an opaque hex digest is accepted; the owner filter keeps a caller
+ * from marking another user's record.
+ *
+ * @returns Whether a record matched.
+ */
+ async function recordFileWorkspaceImport({
+ file_id,
+ user,
+ tenantId,
+ copy,
+ digest,
+ }: WorkspaceImportRecord): Promise<boolean> {
+ if (copy != null && !/^[a-f0-9]{32,64}$/.test(copy.key)) {
+ throw new Error('Workspace import keys must be hex digests');
+ }
+ const update: Record<
+ string,
+ TFileWorkspaceImport | NonNullable<TFileWorkspaceImports['digest']>
+ > = {};
+ if (copy != null) {
+ update[`metadata.workspaceImports.targets.${copy.key}`] = copy.target;
+ }
+ if (digest != null) {
+ update['metadata.workspaceImports.digest'] = digest;
+ }
+ if (Object.keys(update).length === 0) {
+ return false;
+ }
+ const File = mongoose.models.File as Model<IMongoFile>;
+ const result = await File.updateOne(
+ { file_id, user, tenantId: tenantId ?? null },
+ { $set: update },
+ /** Bookkeeping, not a content change: project resource versions include `updatedAt`. */
+ { timestamps: false },
+ );
+ return result.matchedCount > 0;
+ }
+
/**
* Records that a file has been embedded into one vector namespace, without disturbing
* the namespaces already recorded. Agents that share a file record, as a duplicate does
@@ -1942,6 +2001,7 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {
updateFileCodeEnvRef,
clearFileCodeEnvRefs,
addFileEmbeddedEntity,
+ recordFileWorkspaceImport,
clearFileEmbeddings,
isFileStorageClean,
adoptLegacySearchEmbeddings,
diff --git a/packages/data-schemas/src/schema/file.ts b/packages/data-schemas/src/schema/file.ts
index 3e2fc7a644..e4cb53f57f 100644
--- a/packages/data-schemas/src/schema/file.ts
+++ b/packages/data-schemas/src/schema/file.ts
@@ -192,6 +192,13 @@ const file: Schema<IMongoFile> = new Schema(
type: String,
default: undefined,
},
+ /** Copies placed in attached workspaces, keyed by opaque target digests; written only
+ * through `recordFileWorkspaceImport`. Mixed for the same dotted-key reason as
+ * `codeEnvRefs`. */
+ workspaceImports: {
+ type: Schema.Types.Mixed,
+ default: undefined,
+ },
},
llmDeliveryPath: {
/* What upload time inferred about delivery, from the endpoint and MIME type it saw.
diff --git a/packages/data-schemas/src/types/file.ts b/packages/data-schemas/src/types/file.ts
index 4b9d243f74..0a2ecf4017 100644
--- a/packages/data-schemas/src/types/file.ts
+++ b/packages/data-schemas/src/types/file.ts
@@ -5,6 +5,7 @@ import type {
FileContext,
RunFileProvenance,
TFile,
+ TFileWorkspaceImports,
} from 'librechat-data-provider';
export type FileStorageScope = {
@@ -229,6 +230,8 @@ export interface IMongoFile extends Omit<Document, 'model'> {
destinationChosen?: boolean;
/** The type the delivery route was resolved against, when conversion changed it. */
routingMimeType?: string;
+ /** Copies placed in attached workspaces. */
+ workspaceImports?: TFileWorkspaceImports;
};
/** Upload-time inference, not a durable contract. See the schema field for why. */
llmDeliveryPath?: string;