Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(sandbox): sync user-uploaded files into the cloud sandbox (#15550)

LiJian251e2ede5e99
diff --git a/packages/builtin-tool-cloud-sandbox/src/index.ts b/packages/builtin-tool-cloud-sandbox/src/index.ts
index 899947fb185..f017b83bbc7 100644
--- a/packages/builtin-tool-cloud-sandbox/src/index.ts
+++ b/packages/builtin-tool-cloud-sandbox/src/index.ts
@@ -2,3 +2,4 @@ export * from './ExecutionRuntime';
export * from './manifest';
export * from './systemRole';
export * from './types';
+export * from './uploadedFiles';
diff --git a/packages/builtin-tool-cloud-sandbox/src/systemRole.ts b/packages/builtin-tool-cloud-sandbox/src/systemRole.ts
index 294667a5d91..36972b4d560 100644
--- a/packages/builtin-tool-cloud-sandbox/src/systemRole.ts
+++ b/packages/builtin-tool-cloud-sandbox/src/systemRole.ts
@@ -1,3 +1,5 @@
+import { SANDBOX_UPLOADED_FILES_DIR } from './uploadedFiles';
+
export const systemPrompt = `You have access to a Cloud Sandbox that provides a secure, isolated environment for executing code and file operations. This sandbox runs on AWS Bedrock AgentCore and is completely separate from the user's local system.
@@ -16,6 +18,12 @@ export const systemPrompt = `You have access to a Cloud Sandbox that provides a
</sandbox_environment>
+<uploaded_files>
+Files the user uploaded in this conversation (attachments and session files) are automatically synced into \`${SANDBOX_UPLOADED_FILES_DIR}\` when your sandbox session starts. If the user refers to a file they shared, look there first β€” do NOT ask them to re-upload. Run \`listFiles\` on \`${SANDBOX_UPLOADED_FILES_DIR}\` to see everything that is available.
+{{sandbox_uploaded_files}}
+</uploaded_files>
+
+
<preinstalled_software>
**IMPORTANT: Prefer Pre-installed Software**
The sandbox comes with pre-installed software and libraries. **Always prioritize using these pre-installed tools** when they can solve the user's problem, rather than installing additional packages.
diff --git a/packages/builtin-tool-cloud-sandbox/src/uploadedFiles.ts b/packages/builtin-tool-cloud-sandbox/src/uploadedFiles.ts
new file mode 100644
index 00000000000..af4fd1c0259
--- /dev/null
+++ b/packages/builtin-tool-cloud-sandbox/src/uploadedFiles.ts
@@ -0,0 +1,89 @@
+/**
+ * Directory inside the cloud sandbox where user-uploaded files (attached to the
+ * conversation topic / session) are synced when the sandbox session starts.
+ */
+export const SANDBOX_UPLOADED_FILES_DIR = '/mnt/data';
+
+/** Skip individual files larger than this when syncing into the sandbox. */
+export const SANDBOX_INIT_MAX_FILE_SIZE = 100 * 1024 * 1024;
+
+/** Hard cap on how many uploaded files are synced into the sandbox. */
+export const SANDBOX_INIT_MAX_FILES = 50;
+
+export interface SandboxUploadedFileMeta {
+ name: string;
+ size?: number;
+}
+
+/**
+ * Select the files that the sandbox bootstrap will actually sync, applying the
+ * per-file size cap and the total count cap. Shared by the bootstrap (what gets
+ * downloaded) and the prompt (what the agent is told exists) so the two never
+ * drift apart. Items with an unknown size are kept (we cannot rule them out).
+ */
+export const selectSandboxInitFiles = <T extends { size?: number }>(files: T[]): T[] =>
+ files
+ .filter((file) => file.size == null || file.size <= SANDBOX_INIT_MAX_FILE_SIZE)
+ .slice(0, SANDBOX_INIT_MAX_FILES);
+
+const formatBytes = (size?: number): string => {
+ if (typeof size !== 'number' || !Number.isFinite(size) || size <= 0) return '';
+ const units = ['B', 'KB', 'MB', 'GB'];
+ let value = size;
+ let unit = 0;
+ while (value >= 1024 && unit < units.length - 1) {
+ value /= 1024;
+ unit += 1;
+ }
+ const rounded = unit === 0 ? value : Math.round(value * 10) / 10;
+ return ` (${rounded}${units[unit]})`;
+};
+
+/**
+ * Reduce an uploaded file name to a safe, flat basename so it cannot escape the
+ * sandbox upload directory (no path traversal) or carry control characters.
+ */
+export const sanitizeSandboxFileName = (name: string): string => {
+ const base = name.split(/[/\\]/).pop() ?? '';
+ const cleaned = [...base]
+ .filter((char) => {
+ const code = char.codePointAt(0) ?? 0;
+ return code > 0x1f && code !== 0x7f;
+ })
+ .join('')
+ .trim();
+ return cleaned.length > 0 ? cleaned : 'file';
+};
+
+/**
+ * Build the absolute sandbox path for an uploaded file.
+ */
+export const sandboxUploadedFilePath = (name: string): string =>
+ `${SANDBOX_UPLOADED_FILES_DIR}/${sanitizeSandboxFileName(name)}`;
+
+/**
+ * Render the dynamic `{{sandbox_uploaded_files}}` section listing the files that
+ * are pre-loaded into the sandbox. Returns an empty string when there are no
+ * files so the surrounding system prompt renders cleanly.
+ *
+ * Applies the same size/count caps as the bootstrap and de-dupes by resolved
+ * sandbox path, so the listed files match exactly what is written to disk.
+ */
+export const formatUploadedFilesPrompt = (files: SandboxUploadedFileMeta[]): string => {
+ if (!files || files.length === 0) return '';
+
+ const seen = new Set<string>();
+ const lines: string[] = [];
+
+ for (const file of selectSandboxInitFiles(files)) {
+ if (!file?.name) continue;
+ const path = sandboxUploadedFilePath(file.name);
+ if (seen.has(path)) continue;
+ seen.add(path);
+ lines.push(`- ${path}${formatBytes(file.size)}`);
+ }
+
+ if (lines.length === 0) return '';
+
+ return ['These user-uploaded files are pre-loaded and ready to use:', ...lines].join('\n');
+};
diff --git a/packages/database/src/models/__tests__/file.test.ts b/packages/database/src/models/__tests__/file.test.ts
index 27c1684d850..2bb788df85a 100644
--- a/packages/database/src/models/__tests__/file.test.ts
+++ b/packages/database/src/models/__tests__/file.test.ts
@@ -11,9 +11,14 @@ import {
embeddings,
fileChunks,
files,
+ filesToSessions,
globalFiles,
knowledgeBaseFiles,
knowledgeBases,
+ messages,
+ messagesFiles,
+ sessions,
+ topics,
users,
} from '../../schemas';
import type { LobeChatDatabase } from '../../type';
@@ -1602,4 +1607,87 @@ describe('FileModel', () => {
expect(result).toHaveLength(0);
});
});
+
+ describe('findFilesToInitInSandbox', () => {
+ const sessionId = 'sandbox-session-1';
+ const topicId = 'sandbox-topic-1';
+
+ beforeEach(async () => {
+ await serverDB.insert(sessions).values({ id: sessionId, userId });
+ await serverDB.insert(topics).values([
+ { id: topicId, sessionId, userId },
+ { id: 'sandbox-topic-2', sessionId, userId },
+ ]);
+ await serverDB.insert(messages).values([
+ { id: 'sandbox-msg-1', role: 'user', topicId, userId },
+ { id: 'sandbox-msg-2', role: 'user', topicId: 'sandbox-topic-2', userId },
+ ]);
+ await serverDB.insert(files).values([
+ { fileType: 'text/csv', id: 'sf-msg', name: 'msg.csv', size: 1, url: 'k-msg', userId },
+ {
+ fileType: 'application/pdf',
+ id: 'sf-sess',
+ name: 's.pdf',
+ size: 2,
+ url: 'k-sess',
+ userId,
+ },
+ { fileType: 'text/plain', id: 'sf-both', name: 'both.txt', size: 3, url: 'k-both', userId },
+ { fileType: 'text/plain', id: 'sf-other', name: 'o.txt', size: 4, url: 'k-other', userId },
+ ]);
+ });
+
+ it('merges topic message files and session files, de-duped by id', async () => {
+ await serverDB.insert(messagesFiles).values([
+ { fileId: 'sf-msg', messageId: 'sandbox-msg-1', userId },
+ { fileId: 'sf-both', messageId: 'sandbox-msg-1', userId },
+ // attached to a different topic β†’ must be excluded
+ { fileId: 'sf-other', messageId: 'sandbox-msg-2', userId },
+ ]);
+ await serverDB.insert(filesToSessions).values([
+ { fileId: 'sf-sess', sessionId, userId },
+ // also referenced via message β†’ must be de-duped
+ { fileId: 'sf-both', sessionId, userId },
+ ]);
+
+ const result = await fileModel.findFilesToInitInSandbox(topicId);
+
+ expect(result.map((file) => file.id).sort()).toEqual(['sf-both', 'sf-msg', 'sf-sess']);
+ expect(result.find((file) => file.id === 'sf-both')).toEqual({
+ fileType: 'text/plain',
+ id: 'sf-both',
+ name: 'both.txt',
+ size: 3,
+ url: 'k-both',
+ });
+ });
+
+ it('returns an empty array when the topic has no associated files', async () => {
+ const result = await fileModel.findFilesToInitInSandbox(topicId);
+ expect(result).toEqual([]);
+ });
+
+ it('does not return files belonging to another user', async () => {
+ await serverDB.insert(messages).values({
+ id: 'sandbox-msg-other',
+ role: 'user',
+ topicId,
+ userId: 'user2',
+ });
+ await serverDB.insert(files).values({
+ fileType: 'text/plain',
+ id: 'sf-user2',
+ name: 'u2.txt',
+ size: 5,
+ url: 'k-u2',
+ userId: 'user2',
+ });
+ await serverDB
+ .insert(messagesFiles)
+ .values({ fileId: 'sf-user2', messageId: 'sandbox-msg-other', userId: 'user2' });
+
+ const result = await fileModel.findFilesToInitInSandbox(topicId);
+ expect(result).toEqual([]);
+ });
+ });
});
diff --git a/packages/database/src/models/file.ts b/packages/database/src/models/file.ts
index ae81f774c76..1a4f56aa4c6 100644
--- a/packages/database/src/models/file.ts
+++ b/packages/database/src/models/file.ts
@@ -12,11 +12,27 @@ import {
embeddings,
fileChunks,
files,
+ filesToSessions,
globalFiles,
knowledgeBaseFiles,
+ messages,
+ messagesFiles,
+ topics,
} from '../schemas';
import type { LobeChatDatabase, Transaction } from '../type';
+/**
+ * Minimal file descriptor used to bootstrap user-uploaded files into a sandbox.
+ */
+export interface SandboxInitFileItem {
+ fileType: string;
+ id: string;
+ name: string;
+ size: number;
+ /** S3 key / storage url, needs to be turned into a download url before use */
+ url: string;
+}
+
export class FileModel {
private readonly userId: string;
private db: LobeChatDatabase;
@@ -360,6 +376,44 @@ export class FileModel {
});
};
+ /**
+ * Collect the user-uploaded files that should be pre-loaded into a sandbox for
+ * the given topic. Combines two associations and de-duplicates by file id:
+ * - files attached to messages inside the topic (`messages_files`)
+ * - files attached to the session that owns the topic (`files_to_sessions`)
+ */
+ findFilesToInitInSandbox = async (topicId: string): Promise<SandboxInitFileItem[]> => {
+ const columns = {
+ fileType: files.fileType,
+ id: files.id,
+ name: files.name,
+ size: files.size,
+ url: files.url,
+ };
+
+ const [messageFiles, sessionFiles] = await Promise.all([
+ this.db
+ .select(columns)
+ .from(messagesFiles)
+ .innerJoin(messages, eq(messagesFiles.messageId, messages.id))
+ .innerJoin(files, eq(messagesFiles.fileId, files.id))
+ .where(and(eq(messages.topicId, topicId), eq(messagesFiles.userId, this.userId))),
+ this.db
+ .select(columns)
+ .from(filesToSessions)
+ .innerJoin(topics, eq(topics.sessionId, filesToSessions.sessionId))
+ .innerJoin(files, eq(filesToSessions.fileId, files.id))
+ .where(and(eq(topics.id, topicId), eq(filesToSessions.userId, this.userId))),
+ ]);
+
+ const deduped = new Map<string, SandboxInitFileItem>();
+ for (const file of [...messageFiles, ...sessionFiles]) {
+ if (!deduped.has(file.id)) deduped.set(file.id, file);
+ }
+
+ return [...deduped.values()];
+ };
+
countFilesByHash = async (hash: string) => {
const result = await this.db
.select({
diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
index 0f52d8ce405..97c5576b93e 100644
--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
@@ -790,6 +790,23 @@ export const createRuntimeExecutors = (
// {{sandbox_enabled}} β€” mirrors client-side check for lobe-cloud-sandbox.
const sandboxEnabled = String(resolved.enabledToolIds.includes('lobe-cloud-sandbox'));
+ // {{sandbox_uploaded_files}} β€” lists the topic/session files that are
+ // synced into the sandbox upload dir, so the agent knows they exist.
+ // Mirrors the bootstrap query in SandboxMiddlewareService.
+ let sandboxUploadedFiles = '';
+ if (sandboxEnabled === 'true' && ctx.serverDB && ctx.userId && lobehubSkillTopicId) {
+ try {
+ const { FileModel } = await import('@/database/models/file');
+ const { formatUploadedFilesPrompt } =
+ await import('@lobechat/builtin-tool-cloud-sandbox');
+ const fileModel = new FileModel(ctx.serverDB, ctx.userId);
+ const uploadedFiles = await fileModel.findFilesToInitInSandbox(lobehubSkillTopicId);
+ sandboxUploadedFiles = formatUploadedFilesPrompt(uploadedFiles);
+ } catch (error) {
+ log('Failed to resolve files for {{sandbox_uploaded_files}} substitution: %O', error);
+ }
+ }
+
// {{session_date}} β€” current date formatted for user's timezone.
const sessionDate = new Intl.DateTimeFormat('en-US', {
day: 'numeric',
@@ -879,6 +896,7 @@ export const createRuntimeExecutors = (
session_date: sessionDate,
// Creds tool variables
sandbox_enabled: sandboxEnabled,
+ sandbox_uploaded_files: sandboxUploadedFiles,
CREDS_LIST: credsListStr,
KLAVIS_SERVICES_LIST: klavisServicesListStr,
// Memory tool variables
diff --git a/src/server/routers/tools/market.ts b/src/server/routers/tools/market.ts
index 3cff4ce0956..7ef6297d319 100644
--- a/src/server/routers/tools/market.ts
+++ b/src/server/routers/tools/market.ts
@@ -233,6 +233,7 @@ const execInSandboxHandler = async ({
const sandboxService = createSandboxService({
fileService: ctx.fileService,
marketService: ctx.marketService,
+ serverDB: ctx.serverDB,
topicId,
userId,
});
diff --git a/src/server/services/sandbox/__tests__/bootstrap.test.ts b/src/server/services/sandbox/__tests__/bootstrap.test.ts
new file mode 100644
index 00000000000..4e995452500
--- /dev/null
+++ b/src/server/services/sandbox/__tests__/bootstrap.test.ts
@@ -0,0 +1,44 @@
+import { SANDBOX_UPLOADED_FILES_DIR } from '@lobechat/builtin-tool-cloud-sandbox';
+import { describe, expect, it } from 'vitest';
+
+import { buildSandboxFilesInitCommand, SANDBOX_FILES_INIT_MARKER } from '../bootstrap';
+
+describe('buildSandboxFilesInitCommand', () => {
+ it('only ensures the dir when there is nothing to download', () => {
+ expect(buildSandboxFilesInitCommand([])).toBe(`mkdir -p '${SANDBOX_UPLOADED_FILES_DIR}'`);
+ });
+
+ it('wraps downloads in an idempotent marker guard', () => {
+ const command = buildSandboxFilesInitCommand([
+ { name: 'data.csv', url: 'https://files.example.com/a' },
+ ]);
+
+ expect(command).toContain(`if [ ! -f '${SANDBOX_FILES_INIT_MARKER}' ]; then`);
+ expect(command).toContain(
+ `curl -fsSL 'https://files.example.com/a' -o '${SANDBOX_UPLOADED_FILES_DIR}/data.csv' || true`,
+ );
+ expect(command).toContain(`touch '${SANDBOX_FILES_INIT_MARKER}'`);
+ });
+
+ it('de-dupes downloads that resolve to the same sandbox path', () => {
+ const command = buildSandboxFilesInitCommand([
+ { name: 'a/data.csv', url: 'https://files.example.com/a' },
+ { name: 'b/data.csv', url: 'https://files.example.com/b' },
+ ]);
+
+ const curlCount = command.split('curl ').length - 1;
+ expect(curlCount).toBe(1);
+ });
+
+ it('skips entries without a download url', () => {
+ const command = buildSandboxFilesInitCommand([{ name: 'data.csv', url: '' }]);
+ expect(command).toBe(`mkdir -p '${SANDBOX_UPLOADED_FILES_DIR}'`);
+ });
+
+ it('escapes single quotes in names and urls', () => {
+ const command = buildSandboxFilesInitCommand([{ name: "o'brien.txt", url: "https://x/a'b" }]);
+
+ expect(command).toContain(String.raw`o'\''brien.txt`);
+ expect(command).toContain(String.raw`'https://x/a'\''b'`);
+ });
+});
diff --git a/src/server/services/sandbox/__tests__/serviceInit.test.ts b/src/server/services/sandbox/__tests__/serviceInit.test.ts
new file mode 100644
index 00000000000..38f471d1ef2
--- /dev/null
+++ b/src/server/services/sandbox/__tests__/serviceInit.test.ts
@@ -0,0 +1,136 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { LobeChatDatabase } from '@/database/type';
+import type { FileService } from '@/server/services/file';
+import type { MarketService } from '@/server/services/market';
+
+import { SandboxMiddlewareService } from '../service';
+import type { SandboxProvider } from '../types';
+
+const findFilesToInitInSandbox = vi.fn();
+
+vi.mock('@/database/models/file', () => ({
+ FileModel: vi.fn().mockImplementation(() => ({ findFilesToInitInSandbox })),
+}));
+
+const createProvider = (): SandboxProvider =>
+ ({
+ capabilities: {
+ backgroundCommands: true,
+ exportFile: true,
+ files: true,
+ languages: ['python'],
+ persistentSession: true,
+ shell: true,
+ skillScripts: true,
+ },
+ callTool: vi.fn(async () => ({ result: {}, success: true })),
+ exportFileToUploadUrl: vi.fn(),
+ kind: 'onlyboxes',
+ }) satisfies SandboxProvider;
+
+const createFileService = (): FileService =>
+ ({
+ createCachedPreSignedUrlForPreview: vi.fn(async () => 'https://download.example.com/x'),
+ }) as unknown as FileService;
+
+const baseOptions = () => ({
+ fileService: createFileService(),
+ marketService: {} as MarketService,
+ serverDB: {} as LobeChatDatabase,
+ topicId: 'topic-1',
+ userId: 'user-1',
+});
+
+describe('SandboxMiddlewareService file initialization', () => {
+ beforeEach(() => {
+ findFilesToInitInSandbox.mockReset();
+ findFilesToInitInSandbox.mockResolvedValue([
+ { fileType: 'text/csv', id: 'f1', name: 'data.csv', size: 10, url: 'key-1' },
+ ]);
+ });
+
+ it('syncs uploaded files into the sandbox before the first tool call', async () => {
+ const provider = createProvider();
+ const service = new SandboxMiddlewareService(provider, baseOptions());
+
+ await service.callTool('listFiles', { directoryPath: '/mnt/data' });
+
+ expect(findFilesToInitInSandbox).toHaveBeenCalledWith('topic-1');
+ expect(provider.callTool).toHaveBeenNthCalledWith(
+ 1,
+ 'runCommand',
+ expect.objectContaining({ command: expect.stringContaining('curl') }),
+ );
+ expect(provider.callTool).toHaveBeenNthCalledWith(2, 'listFiles', {
+ directoryPath: '/mnt/data',
+ });
+ });
+
+ it('only runs the sync once per service instance', async () => {
+ const provider = createProvider();
+ const service = new SandboxMiddlewareService(provider, baseOptions());
+
+ await service.callTool('listFiles', {});
+ await service.callTool('readFile', { path: '/mnt/data/data.csv' });
+
+ const runCommandCalls = (provider.callTool as ReturnType<typeof vi.fn>).mock.calls.filter(
+ ([tool]) => tool === 'runCommand',
+ );
+ expect(runCommandCalls).toHaveLength(1);
+ });
+
+ it('skips the sync when there is no serverDB', async () => {
+ const provider = createProvider();
+ const service = new SandboxMiddlewareService(provider, {
+ ...baseOptions(),
+ serverDB: undefined,
+ });
+
+ await service.callTool('listFiles', {});
+
+ expect(findFilesToInitInSandbox).not.toHaveBeenCalled();
+ expect(provider.callTool).toHaveBeenCalledTimes(1);
+ expect(provider.callTool).toHaveBeenCalledWith('listFiles', {});
+ });
+
+ it('does not sync when there are no uploaded files', async () => {
+ findFilesToInitInSandbox.mockResolvedValue([]);
+ const provider = createProvider();
+ const service = new SandboxMiddlewareService(provider, baseOptions());
+
+ await service.callTool('listFiles', {});
+
+ expect(provider.callTool).toHaveBeenCalledTimes(1);
+ expect(provider.callTool).toHaveBeenCalledWith('listFiles', {});
+ });
+
+ it('never blocks the tool call when the sync fails', async () => {
+ findFilesToInitInSandbox.mockRejectedValue(new Error('db down'));
+ const provider = createProvider();
+ const service = new SandboxMiddlewareService(provider, baseOptions());
+
+ await expect(service.callTool('listFiles', {})).resolves.toMatchObject({ success: true });
+ expect(provider.callTool).toHaveBeenCalledWith('listFiles', {});
+ });
+
+ it('skips files exceeding the size cap, matching what the prompt advertises', async () => {
+ findFilesToInitInSandbox.mockResolvedValue([
+ {
+ fileType: 'application/zip',
+ id: 'big',
+ name: 'huge.zip',
+ size: 200 * 1024 * 1024,
+ url: 'k',
+ },
+ ]);
+ const provider = createProvider();
+ const service = new SandboxMiddlewareService(provider, baseOptions());
+
+ await service.callTool('listFiles', {});
+
+ // oversized file is filtered out β†’ nothing to download β†’ only the real tool runs
+ expect(provider.callTool).toHaveBeenCalledTimes(1);
+ expect(provider.callTool).toHaveBeenCalledWith('listFiles', {});
+ });
+});
diff --git a/src/server/services/sandbox/__tests__/uploadedFiles.test.ts b/src/server/services/sandbox/__tests__/uploadedFiles.test.ts
new file mode 100644
index 00000000000..eae671e0bc3
Binary files /dev/null and b/src/server/services/sandbox/__tests__/uploadedFiles.test.ts differ
diff --git a/src/server/services/sandbox/bootstrap.ts b/src/server/services/sandbox/bootstrap.ts
new file mode 100644
index 00000000000..46cd183f508
--- /dev/null
+++ b/src/server/services/sandbox/bootstrap.ts
@@ -0,0 +1,48 @@
+import {
+ SANDBOX_UPLOADED_FILES_DIR,
+ sandboxUploadedFilePath,
+} from '@lobechat/builtin-tool-cloud-sandbox';
+
+/** Marker file written once the uploaded files have been synced for a session. */
+export const SANDBOX_FILES_INIT_MARKER = `${SANDBOX_UPLOADED_FILES_DIR}/.lobe-files-initialized`;
+
+/** Timeout (ms) for the bootstrap download command. */
+export const SANDBOX_INIT_TIMEOUT_MS = 120_000;
+
+export interface SandboxInitDownload {
+ name: string;
+ /** A download URL (e.g. presigned) the sandbox can fetch with curl. */
+ url: string;
+}
+
+const shellQuote = (value: string): string => `'${value.replaceAll("'", String.raw`'\''`)}'`;
+
+/**
+ * Build an idempotent shell command that downloads the given uploaded files into
+ * the sandbox upload directory. A marker file guards re-runs, so the command is
+ * a cheap no-op once the files have been synced for the current session.
+ *
+ * Downloads are best-effort: a single failed fetch does not abort the rest, and
+ * the marker is always written so the sync is not retried on every tool call.
+ */
+export const buildSandboxFilesInitCommand = (downloads: SandboxInitDownload[]): string => {
+ const dir = shellQuote(SANDBOX_UPLOADED_FILES_DIR);
+ const marker = shellQuote(SANDBOX_FILES_INIT_MARKER);
+
+ const seen = new Set<string>();
+ const curls: string[] = [];
+
+ for (const { name, url } of downloads) {
+ if (!url) continue;
+ const path = sandboxUploadedFilePath(name);
+ if (seen.has(path)) continue;
+ seen.add(path);
+ curls.push(`curl -fsSL ${shellQuote(url)} -o ${shellQuote(path)} || true`);
+ }
+
+ if (curls.length === 0) return `mkdir -p ${dir}`;
+
+ const body = [...curls, `touch ${marker}`].join('; ');
+
+ return `mkdir -p ${dir}; if [ ! -f ${marker} ]; then ${body}; fi`;
+};
diff --git a/src/server/services/sandbox/service.ts b/src/server/services/sandbox/service.ts
index cc97e5d2828..780ad26072f 100644
--- a/src/server/services/sandbox/service.ts
+++ b/src/server/services/sandbox/service.ts
@@ -1,10 +1,18 @@
-import type {
- SandboxCallToolResult,
- SandboxExportFileResult,
+import {
+ type SandboxCallToolResult,
+ type SandboxExportFileResult,
+ selectSandboxInitFiles,
} from '@lobechat/builtin-tool-cloud-sandbox';
import debug from 'debug';
import { sha256 } from 'js-sha256';
+import { FileModel } from '@/database/models/file';
+
+import {
+ buildSandboxFilesInitCommand,
+ SANDBOX_INIT_TIMEOUT_MS,
+ type SandboxInitDownload,
+} from './bootstrap';
import type {
SandboxCommandResult,
SandboxProvider,
@@ -20,6 +28,8 @@ export class SandboxMiddlewareService implements SandboxService {
readonly capabilities: SandboxProviderCapabilities;
readonly kind: SandboxProviderKind;
+ private filesInitialized = false;
+
constructor(
private readonly provider: SandboxProvider,
private readonly options: SandboxServiceOptions,
@@ -28,10 +38,70 @@ export class SandboxMiddlewareService implements SandboxService {
this.kind = provider.kind;
}
- callTool(toolName: string, params: Record<string, unknown>): Promise<SandboxCallToolResult> {
+ async callTool(
+ toolName: string,
+ params: Record<string, unknown>,
+ ): Promise<SandboxCallToolResult> {
+ await this.ensureFilesInitialized();
return this.provider.callTool(toolName, params);
}
+ /**
+ * Sync the files the user uploaded in this topic/session into the sandbox the
+ * first time this service instance is used. Best-effort: any failure is
+ * swallowed so it never blocks the actual tool call.
+ *
+ * The downloaded command is guarded by an in-sandbox marker file, which is the
+ * single source of truth for idempotency: it is a cheap no-op once synced, and
+ * if the sandbox session is recycled the marker disappears so the next call
+ * re-syncs automatically. We intentionally do NOT cache the "done" state out of
+ * band (e.g. in Redis), because that could skip the re-sync after a recycle and
+ * leave the agent believing files exist when /mnt/data is empty.
+ */
+ private async ensureFilesInitialized(): Promise<void> {
+ if (this.filesInitialized) return;
+ this.filesInitialized = true;
+
+ const { fileService, serverDB, topicId, userId } = this.options;
+ if (!serverDB || !fileService || !topicId || !userId) return;
+ if (!this.provider.capabilities.shell) return;
+
+ try {
+ const fileModel = new FileModel(serverDB, userId);
+ const files = selectSandboxInitFiles(await fileModel.findFilesToInitInSandbox(topicId));
+
+ if (files.length === 0) return;
+
+ const downloads = (
+ await Promise.all(
+ files.map(async (file): Promise<SandboxInitDownload | null> => {
+ const url = await fileService
+ .createCachedPreSignedUrlForPreview(file.url)
+ .catch(() => '');
+ return url ? { name: file.name, url } : null;
+ }),
+ )
+ ).filter((item): item is SandboxInitDownload => item !== null);
+
+ if (downloads.length === 0) return;
+
+ const command = buildSandboxFilesInitCommand(downloads);
+ const result = await this.provider.callTool('runCommand', {
+ command,
+ timeout: SANDBOX_INIT_TIMEOUT_MS,
+ });
+
+ log(
+ 'Sandbox file init for topic %s: %d files, success=%s',
+ topicId,
+ downloads.length,
+ result.success,
+ );
+ } catch (error) {
+ log('Sandbox file init failed for topic %s: %O', topicId, error);
+ }
+ }
+
async exportAndUploadFile(path: string, filename: string): Promise<SandboxExportFileResult> {
const { fileService, topicId } = this.options;
diff --git a/src/server/services/sandbox/types.ts b/src/server/services/sandbox/types.ts
index ecf71d8f92e..0c6e95c0a7b 100644
--- a/src/server/services/sandbox/types.ts
+++ b/src/server/services/sandbox/types.ts
@@ -2,6 +2,7 @@ import type {
ISandboxService,
SandboxExportFileResult,
} from '@lobechat/builtin-tool-cloud-sandbox';
+import type { LobeChatDatabase } from '@lobechat/database';
import type { FileService } from '@/server/services/file';
import type { MarketService } from '@/server/services/market';
@@ -16,6 +17,8 @@ export interface SandboxSessionContext {
export interface SandboxServiceOptions extends SandboxSessionContext {
fileService?: FileService;
marketService: MarketService;
+ /** Used to look up topic/session files when bootstrapping the sandbox. */
+ serverDB?: LobeChatDatabase;
}
export interface SandboxProviderCapabilities {
diff --git a/src/server/services/toolExecution/serverRuntimes/cloudSandbox.ts b/src/server/services/toolExecution/serverRuntimes/cloudSandbox.ts
index 74e46b18b88..024b0444932 100644
--- a/src/server/services/toolExecution/serverRuntimes/cloudSandbox.ts
+++ b/src/server/services/toolExecution/serverRuntimes/cloudSandbox.ts
@@ -28,6 +28,7 @@ export const cloudSandboxRuntime: ServerRuntimeRegistration = {
const sandboxService = createSandboxService({
fileService,
marketService,
+ serverDB: context.serverDB,
topicId: context.topicId,
userId: context.userId,
});
diff --git a/src/server/services/toolExecution/serverRuntimes/skills.ts b/src/server/services/toolExecution/serverRuntimes/skills.ts
index 0c203bd519f..abf61776e41 100644
--- a/src/server/services/toolExecution/serverRuntimes/skills.ts
+++ b/src/server/services/toolExecution/serverRuntimes/skills.ts
@@ -19,6 +19,7 @@ import debug from 'debug';
import { AgentSkillModel } from '@/database/models/agentSkill';
import { FileModel } from '@/database/models/file';
import { UserModel } from '@/database/models/user';
+import type { LobeChatDatabase } from '@/database/type';
import { filterBuiltinSkills } from '@/helpers/skillFilters';
import { AgentDocumentsService } from '@/server/services/agentDocuments';
import { deviceGateway } from '@/server/services/deviceGateway';
@@ -44,6 +45,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {
private marketService: MarketService;
private fileService: FileService;
private fileModel: FileModel;
+ private serverDB: LobeChatDatabase;
private topicId?: string;
private userId: string;
@@ -52,6 +54,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {
fileService: FileService;
marketService: MarketService;
resourceService: SkillResourceService;
+ serverDB: LobeChatDatabase;
skillModel: AgentSkillModel;
topicId?: string;
userId: string;
@@ -61,6 +64,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {
this.marketService = options.marketService;
this.fileService = options.fileService;
this.fileModel = options.fileModel;
+ this.serverDB = options.serverDB;
this.topicId = options.topicId;
this.userId = options.userId;
}
@@ -99,6 +103,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {
const sandboxService = createSandboxService({
fileService: this.fileService,
marketService: this.marketService,
+ serverDB: this.serverDB,
topicId: this.topicId,
userId: this.userId,
});
@@ -181,6 +186,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {
const sandboxService = createSandboxService({
fileService: this.fileService,
marketService: this.marketService,
+ serverDB: this.serverDB,
topicId: this.topicId,
userId: this.userId,
});
@@ -284,6 +290,7 @@ export const skillsRuntime: ServerRuntimeRegistration = {
fileService,
marketService,
resourceService,
+ serverDB: context.serverDB,
skillModel,
topicId: context.topicId,
userId: context.userId,
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index 6e405f7e72a..1414dc8c599 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -1,6 +1,7 @@
import { LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';
import { AgentBuilderIdentifier } from '@lobechat/builtin-tool-agent-builder';
import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';
+import { formatUploadedFilesPrompt } from '@lobechat/builtin-tool-cloud-sandbox';
import {
CredsIdentifier,
type CredSummary,
@@ -57,7 +58,7 @@ import { getChatGroupStoreState } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
import { getAiInfraStoreState } from '@/store/aiInfra';
import { getChatStoreState } from '@/store/chat';
-import { topicSelectors } from '@/store/chat/selectors';
+import { chatSelectors, topicSelectors } from '@/store/chat/selectors';
import { getToolStoreState } from '@/store/tool';
import {
builtinToolSelectors,
@@ -735,6 +736,13 @@ export const contextEngineering = async ({
year: 'numeric',
}).format(new Date()),
sandbox_enabled: () => String(tools?.includes('lobe-cloud-sandbox') ?? false),
+ // NOTICE: required by builtin-tool-cloud-sandbox/src/systemRole.ts β€”
+ // lists the topic files synced into the sandbox upload dir. Read lazily
+ // from the chat store so we only pay the cost when the placeholder renders.
+ sandbox_uploaded_files: () =>
+ tools?.includes('lobe-cloud-sandbox')
+ ? formatUploadedFilesPrompt(chatSelectors.currentUserFiles(getChatStoreState()))
+ : '',
// NOTICE(@nekomeowww): required by builtin-tool-memory/src/systemRole.ts
memory_effort: () => (userMemoryConfig ? (memoryContext?.effort ?? '') : ''),
// Current agent + topic identity β€” referenced by the LobeHub builtin