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

🧬 fix: Carry Whole File Refs Through Sandbox Authoring (#15593)

Danny Avila65109083297f
diff --git a/packages/api/src/agents/handlers.spec.ts b/packages/api/src/agents/handlers.spec.ts
index 1c17b12d59..0bdb3cfd8d 100644
--- a/packages/api/src/agents/handlers.spec.ts
+++ b/packages/api/src/agents/handlers.spec.ts
@@ -3852,6 +3852,9 @@ describe('createToolExecuteHandler', () => {
config: {},
} as never;
+ /** The subset of the sandbox IO params these assertions read. */
+ type SandboxIoParams = { session_id?: string; files?: unknown };
+
function makeSandboxAuthoringHandler(
params: Partial<ToolExecuteOptions>,
configurable?: Record<string, unknown>,
@@ -3919,6 +3922,148 @@ describe('createToolExecuteHandler', () => {
});
});
+ it('carries whole file refs into the next authoring call on the same path', async () => {
+ /**
+ * Regression: the batch-local sandbox context rebuilt each ref from
+ * `{ id, name, session_id, storage_session_id }` and replaced the
+ * mounted list wholesale. A second authoring call on the same path
+ * therefore sent the Code API a skill ref stripped of the `version`
+ * it requires, and unmounted every primed file this write did not
+ * itself return.
+ */
+ const skillRef = {
+ id: 'skill-file-1',
+ resource_id: 'skill-1',
+ name: 'SKILL.md',
+ kind: 'skill' as const,
+ version: 7,
+ storage_session_id: 'store-skill',
+ };
+ let reads = 0;
+ const readSandboxFile = jest.fn(async (_params: SandboxIoParams) => {
+ reads += 1;
+ if (reads === 1) {
+ throw new Error('cat: /mnt/data/note.md: No such file or directory');
+ }
+ return { content: 'hello world' };
+ });
+ const writeSandboxFile = jest.fn(async (_params: SandboxIoParams) => ({
+ stdout: 'WROTE 11 bytes to /mnt/data/note.md\n',
+ session_id: 'sess-write',
+ files: [{ id: 'file-note', name: 'note.md', kind: 'user' as const }],
+ }));
+ const handler = makeSandboxAuthoringHandler({ readSandboxFile, writeSandboxFile });
+
+ const codeSessionContext = {
+ session_id: 'sess-prev',
+ files: [skillRef],
+ };
+ const results = await invokeHandler(handler, [
+ {
+ id: 'call_create_note',
+ name: 'create_file',
+ args: { path: '/mnt/data/note.md', content: 'hello world' },
+ codeSessionContext,
+ } as unknown as ToolCallRequest,
+ {
+ id: 'call_edit_note',
+ name: 'edit_file',
+ args: { path: '/mnt/data/note.md', old_text: 'hello', new_text: 'goodbye' },
+ codeSessionContext,
+ } as unknown as ToolCallRequest,
+ ]);
+
+ expect(results.every((result) => result.status === 'success')).toBe(true);
+ /* The follow-up read/write mount the primed skill ref whole — version
+ * included — alongside the file the create just produced. */
+ const followUpFiles = readSandboxFile.mock.calls[1][0].files;
+ expect(followUpFiles).toEqual([
+ skillRef,
+ { id: 'file-note', name: 'note.md', kind: 'user', storage_session_id: 'sess-write' },
+ ]);
+ expect(writeSandboxFile.mock.calls[1][0].files).toEqual(followUpFiles);
+ expect(writeSandboxFile.mock.calls[1][0].session_id).toBe('sess-write');
+ });
+
+ it('keeps a legacy per-file session over the execution session', async () => {
+ /**
+ * `getPreparedCodeOutputBuffer` resolves storage as
+ * `storage_session_id ?? session_id ?? session_id`, so defaulting an
+ * absent `storage_session_id` straight to the execution session masks
+ * the legacy value and remounts the file against the bucket that
+ * merely produced it.
+ */
+ const readSandboxFile = jest.fn(async (_params: SandboxIoParams) => {
+ throw new Error('cat: /mnt/data/legacy.md: No such file or directory');
+ });
+ const writeSandboxFile = jest.fn(async (_params: SandboxIoParams) => ({
+ stdout: 'WROTE 2 bytes to /mnt/data/legacy.md\n',
+ session_id: 'sess-exec',
+ files: [
+ { id: 'file-legacy', name: 'legacy.md', session_id: 'store-legacy' },
+ { id: 'file-fresh', name: 'fresh.md' },
+ ],
+ }));
+ const handler = makeSandboxAuthoringHandler({ readSandboxFile, writeSandboxFile });
+
+ await invokeHandler(handler, [
+ {
+ id: 'call_legacy_1',
+ name: 'create_file',
+ args: { path: '/mnt/data/legacy.md', content: 'hi' },
+ } as unknown as ToolCallRequest,
+ {
+ id: 'call_legacy_2',
+ name: 'create_file',
+ args: { path: '/mnt/data/legacy.md', content: 'hi again', overwrite: true },
+ } as unknown as ToolCallRequest,
+ ]);
+
+ expect(writeSandboxFile.mock.calls[1][0].files).toEqual([
+ {
+ id: 'file-legacy',
+ name: 'legacy.md',
+ session_id: 'store-legacy',
+ storage_session_id: 'store-legacy',
+ },
+ { id: 'file-fresh', name: 'fresh.md', storage_session_id: 'sess-exec' },
+ ]);
+ });
+
+ it('mounts a file named twice by one artifact only once', async () => {
+ /* codeapi rejects an `/exec` whose files collide on a destination and
+ * takes the whole call down, so a repeated ref must fold, not stack. */
+ const readSandboxFile = jest.fn(async (_params: SandboxIoParams) => {
+ throw new Error('cat: /mnt/data/dup.md: No such file or directory');
+ });
+ const writeSandboxFile = jest.fn(async (_params: SandboxIoParams) => ({
+ stdout: 'WROTE 2 bytes to /mnt/data/dup.md\n',
+ session_id: 'sess-exec',
+ files: [
+ { id: 'file-dup', name: 'dup.md', storage_session_id: 'store-1' },
+ { id: 'file-dup', name: 'dup.md', storage_session_id: 'store-1', kind: 'user' as const },
+ ],
+ }));
+ const handler = makeSandboxAuthoringHandler({ readSandboxFile, writeSandboxFile });
+
+ await invokeHandler(handler, [
+ {
+ id: 'call_dup_1',
+ name: 'create_file',
+ args: { path: '/mnt/data/dup.md', content: 'hi' },
+ } as unknown as ToolCallRequest,
+ {
+ id: 'call_dup_2',
+ name: 'create_file',
+ args: { path: '/mnt/data/dup.md', content: 'hi again', overwrite: true },
+ } as unknown as ToolCallRequest,
+ ]);
+
+ expect(writeSandboxFile.mock.calls[1][0].files).toEqual([
+ { id: 'file-dup', name: 'dup.md', storage_session_id: 'store-1', kind: 'user' },
+ ]);
+ });
+
it('contains a file-artifact policy rejection to its call without rejecting the batch', async () => {
const detectorLabel = 'generated-file bearer token';
const detectorRule = 'generated-file-bearer';
diff --git a/packages/api/src/agents/handlers.ts b/packages/api/src/agents/handlers.ts
index fc0c5a68a8..5b6b39ca8c 100644
--- a/packages/api/src/agents/handlers.ts
+++ b/packages/api/src/agents/handlers.ts
@@ -5,6 +5,7 @@ import { logger, normalizeSkillFrontmatterKeys } from '@librechat/data-schemas';
import { hasActivePiiFields, hasActivePiiPatterns } from 'librechat-data-provider';
import type {
LCTool,
+ FileRefs,
EventHandler,
LCToolRegistry,
InjectedMessage,
@@ -453,7 +454,7 @@ export interface ToolExecuteOptions {
readSandboxFile?: (params: {
file_path: string;
session_id?: string;
- files?: Array<{ id: string; name: string; session_id?: string; storage_session_id?: string }>;
+ files?: SandboxFileRef[];
/** Per-conversation stateful runtime-session hint (thread_id); forwarded so a
* host file op that is the first sandbox call joins the same runtime session
* as bash_tool instead of the Code API's default session. */
@@ -477,7 +478,7 @@ export interface ToolExecuteOptions {
readSandboxImage?: (params: {
file_path: string;
session_id?: string;
- files?: Array<{ id: string; name: string; session_id?: string; storage_session_id?: string }>;
+ files?: SandboxFileRef[];
/** @see readSandboxFile.runtime_session_hint */
runtime_session_hint?: string;
codeApiBaseUrl?: string;
@@ -505,7 +506,7 @@ export interface ToolExecuteOptions {
file_path: string;
content: string;
session_id?: string;
- files?: Array<{ id: string; name: string; session_id?: string; storage_session_id?: string }>;
+ files?: SandboxFileRef[];
/** @see readSandboxFile.runtime_session_hint */
runtime_session_hint?: string;
codeApiBaseUrl?: string;
@@ -515,7 +516,7 @@ export interface ToolExecuteOptions {
stdout?: string;
stderr?: string;
session_id?: string;
- files?: Array<{ id: string; name: string; storage_session_id?: string; session_id?: string }>;
+ files?: SandboxFileRef[];
} | null>;
}
@@ -793,9 +794,21 @@ type ExistingSkillFile =
type LoadedSandboxText = LoadedSkillText;
+/**
+ * A code-session file ref as it crosses the host boundary: the SDK's wire
+ * shape (`kind` / `resource_id` / `version` / `inherited`) plus the legacy
+ * per-file `session_id` older Code API responses carry, which
+ * `getPreparedCodeOutputBuffer` still reads as a storage-session fallback.
+ * Every field is load-bearing on the wire — `version` is required for
+ * `kind: 'skill'` refs and `resource_id` names the resource that owns the
+ * file's storage session — so refs must be carried whole, never rebuilt
+ * from a subset.
+ */
+type SandboxFileRef = FileRefs[number] & { session_id?: string };
+
type SandboxSessionContext = {
session_id?: string;
- files?: Array<{ id: string; name: string; session_id?: string; storage_session_id?: string }>;
+ files?: SandboxFileRef[];
};
const MIME_MAP: Readonly<Record<string, string>> = Object.freeze({
@@ -2146,6 +2159,24 @@ function cloneSandboxSessionContext(
};
}
+/** Storage identity of a mounted ref, matching the code session's own key. */
+function sandboxFileIdentity(file: SandboxFileRef): string {
+ return `${file.storage_session_id ?? ''}\0${file.id}`;
+}
+
+/**
+ * Folds a host file-authoring result's `session_id` / `files` into the
+ * batch-local sandbox context that the next authoring call on the same path
+ * reuses, matching how the graph's own code session folds the same artifact:
+ * incoming refs win field by field, an existing ref superseded by storage
+ * identity or by name is dropped, and every other mounted ref survives.
+ *
+ * Both halves are load-bearing. Rebuilding refs from a field subset dropped
+ * `kind`, `resource_id`, `version` and `inherited`, and a primed skill file
+ * stripped of its `version` is an invalid input ref — the Code API requires
+ * it whenever `kind === 'skill'`. Replacing the list wholesale unmounted
+ * every file the run had primed but this particular write did not return.
+ */
function mergeSandboxSessionArtifact(
context: SandboxSessionContext,
artifact: ToolExecuteResult['artifact'],
@@ -2164,32 +2195,57 @@ function mergeSandboxSessionArtifact(
return;
}
- const files: SandboxSessionContext['files'] = [];
+ const execSessionId = context.session_id;
+ const incoming: SandboxFileRef[] = [];
+ const incomingByIdentity = new Map<string, number>();
+ const incomingNames = new Set<string>();
for (const file of value.files) {
if (!file || typeof file !== 'object') {
continue;
}
- const ref = file as {
- id?: unknown;
- name?: unknown;
- session_id?: unknown;
- storage_session_id?: unknown;
- };
+ const ref = file as SandboxFileRef;
if (typeof ref.id !== 'string' || typeof ref.name !== 'string') {
continue;
}
- files.push({
- id: ref.id,
- name: ref.name,
- ...(typeof ref.session_id === 'string' ? { session_id: ref.session_id } : {}),
- ...(typeof ref.storage_session_id === 'string'
- ? { storage_session_id: ref.storage_session_id }
- : {}),
- });
+ /* Carry the ref whole: the Code API reads fields this host never
+ * inspects, so a copy is a downgrade. Only the storage session is
+ * defaulted, and it resolves exactly as `getPreparedCodeOutputBuffer`
+ * resolves it — the legacy per-file `session_id` outranks the execution
+ * session, or an older Code API response would be remounted against the
+ * bucket that merely produced it. */
+ const merged: SandboxFileRef = { ...ref };
+ merged.storage_session_id ??= ref.session_id ?? execSessionId;
+
+ /* One artifact can name the same stored file twice. Fold the repeat into
+ * the entry already collected rather than mounting it again: codeapi
+ * rejects an `/exec` whose files collide on a destination, taking the
+ * whole call down with it. */
+ const identity = sandboxFileIdentity(merged);
+ const seen = incomingByIdentity.get(identity);
+ if (seen !== undefined) {
+ incoming[seen] = { ...incoming[seen], ...merged };
+ continue;
+ }
+ incomingByIdentity.set(identity, incoming.length);
+ incomingNames.add(merged.name);
+ incoming.push(merged);
+ }
+ if (incoming.length === 0) {
+ return;
}
- if (files.length > 0) {
- context.files = files;
+
+ const retained: SandboxFileRef[] = [];
+ for (const existing of context.files ?? []) {
+ const index = incomingByIdentity.get(sandboxFileIdentity(existing));
+ if (index !== undefined) {
+ incoming[index] = { ...existing, ...incoming[index] };
+ continue;
+ }
+ if (!incomingNames.has(existing.name)) {
+ retained.push(existing);
+ }
}
+ context.files = [...retained, ...incoming];
}
/**