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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🗂️ feat: Add Agent File Authoring Tools (#13435)
Danny Avila1da789bac03a
diff --git a/api/server/controllers/agents/__tests__/callbacks.spec.js b/api/server/controllers/agents/__tests__/callbacks.spec.jsindex 0ba20d409c..20fcf54a6c 100644--- a/api/server/controllers/agents/__tests__/callbacks.spec.js+++ b/api/server/controllers/agents/__tests__/callbacks.spec.js@@ -7,6 +7,10 @@ jest.mock('nanoid', () => ({jest.mock('@librechat/api', () => ({sendEvent: jest.fn(),+ HOST_FILE_AUTHORING_ARTIFACT_KEY: '__librechat_file_authoring',+ isCodeSessionToolName: jest.fn((name) =>+ ['execute_code', 'bash_tool', 'read_file'].includes(name),+ ),}));jest.mock('@librechat/data-schemas', () => ({@@ -364,12 +368,21 @@ describe('createToolEndCallback', () => {const { processCodeOutput } = require('~/server/services/Files/Code/process');- function makeCodeExecutionEvent({ runId, threadId, toolCallId, fileId, name }) {+ function makeCodeExecutionEvent({+ runId,+ threadId,+ toolCallId,+ fileId,+ name,+ toolName = 'execute_code',+ hostFileAuthoring = false,+ }) {return {output: {- name: 'execute_code',+ name: toolName,tool_call_id: toolCallId,artifact: {+ ...(hostFileAuthoring ? { __librechat_file_authoring: true } : {}),session_id: 'sess-1',files: [{ id: fileId, name, session_id: 'sess-1' }],},@@ -573,6 +586,65 @@ describe('createToolEndCallback', () => {expect(res.write).toHaveBeenCalledTimes(1);});++ it('processes create_file sandbox artifacts like code execution outputs', async () => {+ res.headersSent = true;+ processCodeOutput.mockResolvedValue({+ file: {+ file_id: 'fid-created',+ filename: 'created.txt',+ filepath: '/uploads/created.txt',+ type: 'text/plain',+ conversationId: 'thread789',+ messageId: 'run-create',+ toolCallId: 'tool-create',+ status: 'ready',+ },+ });++ const toolEndCallback = createToolEndCallback({ req, res, artifactPromises });+ const event = makeCodeExecutionEvent({+ runId: 'run-create',+ threadId: 'thread789',+ toolCallId: 'tool-create',+ fileId: 'fid-created',+ name: 'created.txt',+ toolName: 'create_file',+ hostFileAuthoring: true,+ });+ await toolEndCallback({ output: event.output }, event.metadata);+ await Promise.all(artifactPromises);++ expect(processCodeOutput).toHaveBeenCalledWith(+ expect.objectContaining({+ id: 'fid-created',+ name: 'created.txt',+ messageId: 'run-create',+ toolCallId: 'tool-create',+ conversationId: 'thread789',+ }),+ );+ expect(res.write).toHaveBeenCalledTimes(1);+ });++ it('does not process arbitrary user tool artifacts named create_file as code outputs', async () => {+ res.headersSent = true;+ const toolEndCallback = createToolEndCallback({ req, res, artifactPromises });+ const event = makeCodeExecutionEvent({+ runId: 'run-user-create',+ threadId: 'thread789',+ toolCallId: 'tool-user-create',+ fileId: 'fid-user-created',+ name: 'created.txt',+ toolName: 'create_file',+ });++ await toolEndCallback({ output: event.output }, event.metadata);+ await Promise.all(artifactPromises);++ expect(processCodeOutput).not.toHaveBeenCalled();+ expect(res.write).not.toHaveBeenCalled();+ });});});diff --git a/api/server/controllers/agents/__tests__/openai.spec.js b/api/server/controllers/agents/__tests__/openai.spec.jsindex 7638fc2e35..ae81afb1f2 100644--- a/api/server/controllers/agents/__tests__/openai.spec.js+++ b/api/server/controllers/agents/__tests__/openai.spec.js@@ -11,6 +11,50 @@ const mockRecordCollectedUsage = jest.mockResolvedValue({ input_tokens: 100, output_tokens: 50 });const mockGetBalanceConfig = jest.fn().mockReturnValue({ enabled: true });const mockGetTransactionsConfig = jest.fn().mockReturnValue({ enabled: true });+const mockBuildSkillPrimedIdsByName = jest.fn((manualSkillPrimes, alwaysApplySkillPrimes) => {+ const primed = {};+ for (const skill of alwaysApplySkillPrimes ?? []) {+ primed[skill.name] = skill._id.toString();+ }+ for (const skill of manualSkillPrimes ?? []) {+ primed[skill.name] = skill._id.toString();+ }+ return Object.keys(primed).length > 0 ? primed : undefined;+});+const mockEnrichWithSkillConfigurable = jest.fn((result) => result);+const mockBuildAgentToolContext = jest.fn(({ agent, config }) => ({+ agent,+ toolRegistry: config.toolRegistry,+ userMCPAuthMap: config.userMCPAuthMap,+ tool_resources: config.tool_resources,+ actionsEnabled: config.actionsEnabled,+ accessibleSkillIds: config.accessibleSkillIds,+ activeSkillNames: config.activeSkillNames,+ codeEnvAvailable: config.codeEnvAvailable,+ skillAuthoringAvailable: config.skillAuthoringAvailable,+ fileAuthoringToolNames: config.fileAuthoringToolNames,+ skillPrimedIdsByName:+ mockBuildSkillPrimedIdsByName(config.manualSkillPrimes, config.alwaysApplySkillPrimes) ?? {},+}));+const mockEnrichLoadedToolsWithAgentContext = jest.fn(({ result, req, ctx }) =>+ mockEnrichWithSkillConfigurable({+ result,+ context: {+ req,+ accessibleSkillIds: ctx.accessibleSkillIds,+ codeEnvAvailable: ctx.codeEnvAvailable === true,+ skillPrimedIdsByName: ctx.skillPrimedIdsByName,+ activeSkillNames: ctx.activeSkillNames,+ skillAuthoringAvailable: ctx.skillAuthoringAvailable === true,+ fileAuthoringToolNames: ctx.fileAuthoringToolNames,+ },+ }),+);+const mockCanAuthorSkillFiles = jest.fn(+ ({ scopedEditableSkillIds = [], skillCreateAllowed }) =>+ scopedEditableSkillIds.length > 0 || skillCreateAllowed === true,+);+const mockGetSkillToolDeps = jest.fn(() => ({}));jest.mock('nanoid', () => ({nanoid: jest.fn(() => 'mock-nanoid-123'),@@ -104,6 +148,15 @@ jest.mock('~/server/services/Files/permissions', () => ({filterFilesByAgentAccess: jest.fn(),}));+jest.mock('~/server/services/Endpoints/agents/skillDeps', () => ({+ getSkillToolDeps: mockGetSkillToolDeps,+ canAuthorSkillFiles: mockCanAuthorSkillFiles,+ enrichWithSkillConfigurable: mockEnrichWithSkillConfigurable,+ buildSkillPrimedIdsByName: mockBuildSkillPrimedIdsByName,+ buildAgentToolContext: mockBuildAgentToolContext,+ enrichLoadedToolsWithAgentContext: mockEnrichLoadedToolsWithAgentContext,+}));+jest.mock('~/cache', () => ({logViolation: jest.fn(),}));@@ -368,4 +421,87 @@ describe('OpenAIChatCompletionController', () => {expect(resolveRecursionLimit).toHaveBeenCalledWith(req.config.endpoints.agents, mockAgent);});});++ describe('sub-agent skill priming', () => {+ it('passes the sub-agent primed skill IDs into tool execution', async () => {+ const {+ initializeAgent,+ discoverConnectedAgents,+ createToolExecuteHandler,+ } = require('@librechat/api');+ const { loadToolsForExecution } = require('~/server/services/ToolService');+ const subAgent = { id: 'agent-sub', name: 'Sub Agent' };+ const subConfig = {+ id: 'agent-sub',+ model: 'gpt-4',+ model_parameters: {},+ toolRegistry: new Map(),+ userMCPAuthMap: { sub: { token: 'sub-token' } },+ tool_resources: { code_interpreter: { file_ids: ['sub-file'] } },+ actionsEnabled: true,+ accessibleSkillIds: ['sub-skill-id'],+ activeSkillNames: ['sub-hidden-skill'],+ codeEnvAvailable: true,+ skillAuthoringAvailable: true,+ fileAuthoringToolNames: ['create_file', 'edit_file'],+ manualSkillPrimes: [{ name: 'sub-hidden-skill', _id: { toString: () => 'sub-manual-id' } }],+ alwaysApplySkillPrimes: [+ { name: 'sub-always-skill', _id: { toString: () => 'sub-always-id' } },+ ],+ };++ initializeAgent.mockResolvedValueOnce({+ id: 'agent-123',+ model: 'gpt-4',+ model_parameters: {},+ toolRegistry: new Map(),+ edges: [{ source: 'agent-123', target: 'agent-sub' }],+ accessibleSkillIds: ['primary-skill-id'],+ activeSkillNames: ['primary-skill'],+ codeEnvAvailable: false,+ skillAuthoringAvailable: false,+ fileAuthoringToolNames: [],+ manualSkillPrimes: [{ name: 'primary-skill', _id: { toString: () => 'primary-skill-id' } }],+ });+ discoverConnectedAgents.mockImplementationOnce(async (_params, deps) => {+ deps.onAgentInitialized('agent-sub', subAgent, subConfig);+ return {+ agentConfigs: new Map([['agent-sub', subConfig]]),+ edges: [],+ skippedAgentIds: new Set(),+ userMCPAuthMap: undefined,+ };+ });++ await OpenAIChatCompletionController(req, res);++ const toolExecuteOptions = createToolExecuteHandler.mock.calls.at(-1)[0];+ await toolExecuteOptions.loadTools(['read_file'], 'agent-sub');++ expect(loadToolsForExecution).toHaveBeenLastCalledWith(+ expect.objectContaining({+ agent: subAgent,+ toolRegistry: subConfig.toolRegistry,+ userMCPAuthMap: subConfig.userMCPAuthMap,+ tool_resources: subConfig.tool_resources,+ actionsEnabled: true,+ }),+ );+ expect(mockEnrichWithSkillConfigurable).toHaveBeenLastCalledWith({+ result: expect.anything(),+ context: {+ req,+ accessibleSkillIds: ['sub-skill-id'],+ codeEnvAvailable: true,+ skillPrimedIdsByName: {+ 'sub-always-skill': 'sub-always-id',+ 'sub-hidden-skill': 'sub-manual-id',+ },+ activeSkillNames: ['sub-hidden-skill'],+ skillAuthoringAvailable: true,+ fileAuthoringToolNames: ['create_file', 'edit_file'],+ },+ });+ });+ });});diff --git a/api/server/controllers/agents/__tests__/responses.unit.spec.js b/api/server/controllers/agents/__tests__/responses.unit.spec.jsindex e5569fbbf5..8c3a3dbaba 100644--- a/api/server/controllers/agents/__tests__/responses.unit.spec.js+++ b/api/server/controllers/agents/__tests__/responses.unit.spec.js@@ -10,6 +10,50 @@ const mockRecordCollectedUsage = jest.mockResolvedValue({ input_tokens: 100, output_tokens: 50 });const mockGetBalanceConfig = jest.fn().mockReturnValue({ enabled: true });const mockGetTransactionsConfig = jest.fn().mockReturnValue({ enabled: true });+const mockBuildSkillPrimedIdsByName = jest.fn((manualSkillPrimes, alwaysApplySkillPrimes) => {+ const primed = {};+ for (const skill of alwaysApplySkillPrimes ?? []) {+ primed[skill.name] = skill._id.toString();+ }+ for (const skill of manualSkillPrimes ?? []) {+ primed[skill.name] = skill._id.toString();+ }+ return Object.keys(primed).length > 0 ? primed : undefined;+});+const mockEnrichWithSkillConfigurable = jest.fn((result) => result);+const mockBuildAgentToolContext = jest.fn(({ agent, config }) => ({+ agent,+ toolRegistry: config.toolRegistry,+ userMCPAuthMap: config.userMCPAuthMap,+ tool_resources: config.tool_resources,+ actionsEnabled: config.actionsEnabled,+ accessibleSkillIds: config.accessibleSkillIds,+ activeSkillNames: config.activeSkillNames,+ codeEnvAvailable: config.codeEnvAvailable,+ skillAuthoringAvailable: config.skillAuthoringAvailable,+ fileAuthoringToolNames: config.fileAuthoringToolNames,+ skillPrimedIdsByName:+ mockBuildSkillPrimedIdsByName(config.manualSkillPrimes, config.alwaysApplySkillPrimes) ?? {},+}));+const mockEnrichLoadedToolsWithAgentContext = jest.fn(({ result, req, ctx }) =>+ mockEnrichWithSkillConfigurable({+ result,+ context: {+ req,+ accessibleSkillIds: ctx.accessibleSkillIds,+ codeEnvAvailable: ctx.codeEnvAvailable === true,+ skillPrimedIdsByName: ctx.skillPrimedIdsByName,+ activeSkillNames: ctx.activeSkillNames,+ skillAuthoringAvailable: ctx.skillAuthoringAvailable === true,+ fileAuthoringToolNames: ctx.fileAuthoringToolNames,+ },+ }),+);+const mockCanAuthorSkillFiles = jest.fn(+ ({ scopedEditableSkillIds = [], skillCreateAllowed }) =>+ scopedEditableSkillIds.length > 0 || skillCreateAllowed === true,+);+const mockGetSkillToolDeps = jest.fn(() => ({}));jest.mock('nanoid', () => ({nanoid: jest.fn(() => 'mock-nanoid-123'),@@ -154,6 +198,15 @@ jest.mock('~/server/services/Files/permissions', () => ({filterFilesByAgentAccess: jest.fn(),}));+jest.mock('~/server/services/Endpoints/agents/skillDeps', () => ({+ getSkillToolDeps: mockGetSkillToolDeps,+ canAuthorSkillFiles: mockCanAuthorSkillFiles,+ enrichWithSkillConfigurable: mockEnrichWithSkillConfigurable,+ buildSkillPrimedIdsByName: mockBuildSkillPrimedIdsByName,+ buildAgentToolContext: mockBuildAgentToolContext,+ enrichLoadedToolsWithAgentContext: mockEnrichLoadedToolsWithAgentContext,+}));+jest.mock('~/cache', () => ({logViolation: jest.fn(),}));@@ -458,4 +511,87 @@ describe('createResponse controller', () => {);});});++ describe('sub-agent skill priming', () => {+ it('passes the sub-agent primed skill IDs into non-streaming tool execution', async () => {+ const {+ initializeAgent,+ discoverConnectedAgents,+ createToolExecuteHandler,+ } = require('@librechat/api');+ const { loadToolsForExecution } = require('~/server/services/ToolService');+ const subAgent = { id: 'agent-sub', name: 'Sub Agent' };+ const subConfig = {+ id: 'agent-sub',+ model: 'claude-3',+ model_parameters: {},+ toolRegistry: new Map(),+ userMCPAuthMap: { sub: { token: 'sub-token' } },+ tool_resources: { code_interpreter: { file_ids: ['sub-file'] } },+ actionsEnabled: true,+ accessibleSkillIds: ['sub-skill-id'],+ activeSkillNames: ['sub-hidden-skill'],+ codeEnvAvailable: true,+ skillAuthoringAvailable: true,+ fileAuthoringToolNames: ['create_file', 'edit_file'],+ manualSkillPrimes: [{ name: 'sub-hidden-skill', _id: { toString: () => 'sub-manual-id' } }],+ alwaysApplySkillPrimes: [+ { name: 'sub-always-skill', _id: { toString: () => 'sub-always-id' } },+ ],+ };++ initializeAgent.mockResolvedValueOnce({+ id: 'agent-123',+ model: 'claude-3',+ model_parameters: {},+ toolRegistry: new Map(),+ edges: [{ source: 'agent-123', target: 'agent-sub' }],+ accessibleSkillIds: ['primary-skill-id'],+ activeSkillNames: ['primary-skill'],+ codeEnvAvailable: false,+ skillAuthoringAvailable: false,+ fileAuthoringToolNames: [],+ manualSkillPrimes: [{ name: 'primary-skill', _id: { toString: () => 'primary-skill-id' } }],+ });+ discoverConnectedAgents.mockImplementationOnce(async (_params, deps) => {+ deps.onAgentInitialized('agent-sub', subAgent, subConfig);+ return {+ agentConfigs: new Map([['agent-sub', subConfig]]),+ edges: [],+ skippedAgentIds: new Set(),+ userMCPAuthMap: undefined,+ };+ });++ await createResponse(req, res);++ const toolExecuteOptions = createToolExecuteHandler.mock.calls.at(-1)[0];+ await toolExecuteOptions.loadTools(['read_file'], 'agent-sub');++ expect(loadToolsForExecution).toHaveBeenLastCalledWith(+ expect.objectContaining({+ agent: subAgent,+ toolRegistry: subConfig.toolRegistry,+ userMCPAuthMap: subConfig.userMCPAuthMap,+ tool_resources: subConfig.tool_resources,+ actionsEnabled: true,+ }),+ );+ expect(mockEnrichWithSkillConfigurable).toHaveBeenLastCalledWith({+ result: expect.anything(),+ context: {+ req,+ accessibleSkillIds: ['sub-skill-id'],+ codeEnvAvailable: true,+ skillPrimedIdsByName: {+ 'sub-always-skill': 'sub-always-id',+ 'sub-hidden-skill': 'sub-manual-id',+ },+ activeSkillNames: ['sub-hidden-skill'],+ skillAuthoringAvailable: true,+ fileAuthoringToolNames: ['create_file', 'edit_file'],+ },+ });+ });+ });});diff --git a/api/server/controllers/agents/callbacks.js b/api/server/controllers/agents/callbacks.jsindex 314ee481a6..0a8f8854f7 100644--- a/api/server/controllers/agents/callbacks.js+++ b/api/server/controllers/agents/callbacks.js@@ -5,7 +5,6 @@ const {GraphEvents,GraphNodeKeys,ToolEndHandler,- CODE_EXECUTION_TOOLS,createContentAggregator,} = require('@librechat/agents');const {@@ -13,11 +12,21 @@ const {GenerationJobManager,writeAttachmentEvent,createToolExecuteHandler,+ HOST_FILE_AUTHORING_ARTIFACT_KEY,+ isCodeSessionToolName,} = require('@librechat/api');const { processFileCitations } = require('~/server/services/Files/Citations');const { processCodeOutput, runPreviewFinalize } = require('~/server/services/Files/Code/process');const { saveBase64Image } = require('~/server/services/Files/process');+function isHostFileAuthoringArtifact(artifact) {+ return artifact?.[HOST_FILE_AUTHORING_ARTIFACT_KEY] === true;+}++function isCodeArtifactToolOutput(output) {+ return isCodeSessionToolName(output.name) || isHostFileAuthoringArtifact(output.artifact);+}+class ModelEndHandler {/*** @param {Array<UsageMetadata>} collectedUsage@@ -623,7 +632,7 @@ function createToolEndCallback({ req, res, artifactPromises, streamId = null })return;}- if (!CODE_EXECUTION_TOOLS.has(output.name)) {+ if (!isCodeArtifactToolOutput(output)) {return;}@@ -890,7 +899,7 @@ function createResponsesToolEndCallback({ req, res, tracker, artifactPromises })return;}- if (!CODE_EXECUTION_TOOLS.has(output.name)) {+ if (!isCodeArtifactToolOutput(output)) {return;}diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.jsindex 7d2395b09f..be66412f3e 100644--- a/api/server/controllers/agents/openai.js+++ b/api/server/controllers/agents/openai.js@@ -47,8 +47,9 @@ const {} = require('~/server/services/PermissionService');const {getSkillToolDeps,- enrichWithSkillConfigurable,- buildSkillPrimedIdsByName,+ canAuthorSkillFiles,+ buildAgentToolContext,+ enrichLoadedToolsWithAgentContext,} = require('~/server/services/Endpoints/agents/skillDeps');const { getModelsConfig } = require('~/server/controllers/ModelController');const { logViolation } = require('~/cache');@@ -261,6 +262,17 @@ const OpenAIChatCompletionController = async (req, res) => {requiredPermissions: PermissionBits.VIEW,}): [];+ const editableSkillIds = skillsCapabilityEnabled+ ? await findAccessibleResources({+ userId: req.user.id,+ role: req.user.role,+ resourceType: ResourceType.SKILL,+ requiredPermissions: PermissionBits.EDIT,+ })+ : [];+ const skillCreateAllowed = skillsCapabilityEnabled+ ? await getSkillToolDeps().canCreateSkill({ req })+ : false;const { skillStates, defaultActiveOnShare } = await loadSkillStates({userId: req.user.id,@@ -271,6 +283,19 @@ const OpenAIChatCompletionController = async (req, res) => {const manualSkills = extractManualSkills(req.body);+ const primaryScopedSkillIds = resolveAgentScopedSkillIds({+ agent,+ accessibleSkillIds,+ skillsCapabilityEnabled,+ ephemeralSkillsToggle,+ });+ const primaryScopedEditableSkillIds = resolveAgentScopedSkillIds({+ agent,+ accessibleSkillIds: editableSkillIds,+ skillsCapabilityEnabled,+ ephemeralSkillsToggle,+ });+const primaryConfig = await initializeAgent({req,@@ -283,9 +308,11 @@ const OpenAIChatCompletionController = async (req, res) => {endpointOption,allowedProviders,isInitialAgent: true,- accessibleSkillIds: resolveAgentScopedSkillIds({+ accessibleSkillIds: primaryScopedSkillIds,+ skillAuthoringAvailable: canAuthorSkillFiles({agent,- accessibleSkillIds,+ scopedEditableSkillIds: primaryScopedEditableSkillIds,+ skillCreateAllowed,skillsCapabilityEnabled,ephemeralSkillsToggle,}),@@ -310,14 +337,10 @@ const OpenAIChatCompletionController = async (req, res) => {* }>}*/const agentToolContexts = new Map();- agentToolContexts.set(primaryConfig.id, {- agent,- toolRegistry: primaryConfig.toolRegistry,- userMCPAuthMap: primaryConfig.userMCPAuthMap,- tool_resources: primaryConfig.tool_resources,- actionsEnabled: primaryConfig.actionsEnabled,- codeEnvAvailable: primaryConfig.codeEnvAvailable,- });+ agentToolContexts.set(+ primaryConfig.id,+ buildAgentToolContext({ agent, config: primaryConfig }),+ );// Only run BFS discovery (and pay `getModelsConfig` upfront) when the// primary has edges to follow — the common API case is single-agent.@@ -346,6 +369,28 @@ const OpenAIChatCompletionController = async (req, res) => {// sub-agent must clear the same sharing boundary, not the looser// in-app AGENT one.resourceType: ResourceType.REMOTE_AGENT,+ computeAccessibleSkillIds: (handoffAgent) =>+ resolveAgentScopedSkillIds({+ agent: handoffAgent,+ accessibleSkillIds,+ skillsCapabilityEnabled,+ ephemeralSkillsToggle,+ }),+ computeSkillAuthoringAvailable: (handoffAgent) =>+ canAuthorSkillFiles({+ agent: handoffAgent,+ scopedEditableSkillIds: resolveAgentScopedSkillIds({+ agent: handoffAgent,+ accessibleSkillIds: editableSkillIds,+ skillsCapabilityEnabled,+ ephemeralSkillsToggle,+ }),+ skillCreateAllowed,+ skillsCapabilityEnabled,+ ephemeralSkillsToggle,+ }),+ skillStates,+ defaultActiveOnShare,/** @see DiscoverConnectedAgentsParams.codeEnvAvailable */codeEnvAvailable: enabledCapabilities.has(AgentCapabilities.execute_code),},@@ -368,14 +413,7 @@ const OpenAIChatCompletionController = async (req, res) => {logViolation,db: dbMethods,onAgentInitialized: (agentId, handoffAgent, config) => {- agentToolContexts.set(agentId, {- agent: handoffAgent,- toolRegistry: config.toolRegistry,- userMCPAuthMap: config.userMCPAuthMap,- tool_resources: config.tool_resources,- actionsEnabled: config.actionsEnabled,- codeEnvAvailable: config.codeEnvAvailable,- });+ agentToolContexts.set(agentId, buildAgentToolContext({ agent: handoffAgent, config }));},initializeAgent,},@@ -420,18 +458,13 @@ const OpenAIChatCompletionController = async (req, res) => {const toolEndCallback = createToolEndCallback({ req, res, artifactPromises, streamId: null });- /* Stable for the turn: the prime lists are fixed once- `initializeAgent` resolves. Hoisted out of `loadTools` so tool- execution doesn't recompute them. `codeEnvAvailable` is read+ /* Stable for the turn: the primary prime list is fixed once+ `initializeAgent` resolves and is used as the fallback when a+ specific agent context is unavailable. `codeEnvAvailable` is readper-agent from the stored tool context (admin cap AND thatagent's `tools` list includes `execute_code`) — a skills-onlyagent never gains sandbox access even if the admin enabled thecapability globally. */- const skillPrimedIdsByName = buildSkillPrimedIdsByName(- primaryConfig.manualSkillPrimes,- primaryConfig.alwaysApplySkillPrimes,- );-const toolExecuteOptions = {loadTools: async (toolNames, agentId) => {const ctx = agentToolContexts.get(agentId) ?? agentToolContexts.get(primaryConfig.id) ?? {};@@ -446,13 +479,11 @@ const OpenAIChatCompletionController = async (req, res) => {tool_resources: ctx.tool_resources,actionsEnabled: ctx.actionsEnabled,});- return enrichWithSkillConfigurable(+ return enrichLoadedToolsWithAgentContext({result,req,- primaryConfig.accessibleSkillIds,- ctx.codeEnvAvailable === true,- skillPrimedIdsByName,- );+ ctx,+ });},toolEndCallback,...getSkillToolDeps(),diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.jsindex b2805fc19f..74972964da 100644--- a/api/server/controllers/agents/responses.js+++ b/api/server/controllers/agents/responses.js@@ -56,8 +56,9 @@ const {} = require('~/server/services/PermissionService');const {getSkillToolDeps,- enrichWithSkillConfigurable,- buildSkillPrimedIdsByName,+ canAuthorSkillFiles,+ buildAgentToolContext,+ enrichLoadedToolsWithAgentContext,} = require('~/server/services/Endpoints/agents/skillDeps');const { getModelsConfig } = require('~/server/controllers/ModelController');const { logViolation } = require('~/cache');@@ -391,6 +392,17 @@ const createResponse = async (req, res) => {requiredPermissions: PermissionBits.VIEW,}): [];+ const editableSkillIds = skillsCapabilityEnabled+ ? await findAccessibleResources({+ userId: req.user.id,+ role: req.user.role,+ resourceType: ResourceType.SKILL,+ requiredPermissions: PermissionBits.EDIT,+ })+ : [];+ const skillCreateAllowed = skillsCapabilityEnabled+ ? await getSkillToolDeps().canCreateSkill({ req })+ : false;const { skillStates, defaultActiveOnShare } = await loadSkillStates({userId: req.user.id,@@ -401,6 +413,19 @@ const createResponse = async (req, res) => {const manualSkills = extractManualSkills(req.body);+ const primaryScopedSkillIds = resolveAgentScopedSkillIds({+ agent,+ accessibleSkillIds,+ skillsCapabilityEnabled,+ ephemeralSkillsToggle,+ });+ const primaryScopedEditableSkillIds = resolveAgentScopedSkillIds({+ agent,+ accessibleSkillIds: editableSkillIds,+ skillsCapabilityEnabled,+ ephemeralSkillsToggle,+ });+const primaryConfig = await initializeAgent({req,@@ -413,9 +438,11 @@ const createResponse = async (req, res) => {endpointOption,allowedProviders,isInitialAgent: true,- accessibleSkillIds: resolveAgentScopedSkillIds({+ accessibleSkillIds: primaryScopedSkillIds,+ skillAuthoringAvailable: canAuthorSkillFiles({agent,- accessibleSkillIds,+ scopedEditableSkillIds: primaryScopedEditableSkillIds,+ skillCreateAllowed,skillsCapabilityEnabled,ephemeralSkillsToggle,}),@@ -440,14 +467,10 @@ const createResponse = async (req, res) => {* }>}*/const agentToolContexts = new Map();- agentToolContexts.set(primaryConfig.id, {- agent,- toolRegistry: primaryConfig.toolRegistry,- userMCPAuthMap: primaryConfig.userMCPAuthMap,- tool_resources: primaryConfig.tool_resources,- actionsEnabled: primaryConfig.actionsEnabled,- codeEnvAvailable: primaryConfig.codeEnvAvailable,- });+ agentToolContexts.set(+ primaryConfig.id,+ buildAgentToolContext({ agent, config: primaryConfig }),+ );// Only run BFS discovery (and pay `getModelsConfig` upfront) when the// primary has edges to follow — the common API case is single-agent.@@ -476,6 +499,28 @@ const createResponse = async (req, res) => {// sub-agent must clear the same sharing boundary, not the looser// in-app AGENT one.resourceType: ResourceType.REMOTE_AGENT,+ computeAccessibleSkillIds: (handoffAgent) =>+ resolveAgentScopedSkillIds({+ agent: handoffAgent,+ accessibleSkillIds,+ skillsCapabilityEnabled,+ ephemeralSkillsToggle,+ }),+ computeSkillAuthoringAvailable: (handoffAgent) =>+ canAuthorSkillFiles({+ agent: handoffAgent,+ scopedEditableSkillIds: resolveAgentScopedSkillIds({+ agent: handoffAgent,+ accessibleSkillIds: editableSkillIds,+ skillsCapabilityEnabled,+ ephemeralSkillsToggle,+ }),+ skillCreateAllowed,+ skillsCapabilityEnabled,+ ephemeralSkillsToggle,+ }),+ skillStates,+ defaultActiveOnShare,/** @see DiscoverConnectedAgentsParams.codeEnvAvailable */codeEnvAvailable: enabledCapabilities.has(AgentCapabilities.execute_code),},@@ -498,14 +543,7 @@ const createResponse = async (req, res) => {logViolation,db: dbMethods,onAgentInitialized: (agentId, handoffAgent, config) => {- agentToolContexts.set(agentId, {- agent: handoffAgent,- toolRegistry: config.toolRegistry,- userMCPAuthMap: config.userMCPAuthMap,- tool_resources: config.tool_resources,- actionsEnabled: config.actionsEnabled,- codeEnvAvailable: config.codeEnvAvailable,- });+ agentToolContexts.set(agentId, buildAgentToolContext({ agent: handoffAgent, config }));},initializeAgent,},@@ -573,19 +611,13 @@ const createResponse = async (req, res) => {}}- /* Stable for the turn: the prime lists are fixed once- `initializeAgent` resolves. Hoisted here so both the streaming- and non-streaming `loadTools` closures below reuse it without- recomputing per tool execution. `codeEnvAvailable` is read+ /* Stable for the turn: the primary prime list is fixed once+ `initializeAgent` resolves and is used as the fallback when a+ specific agent context is unavailable. `codeEnvAvailable` is readper-agent from the stored tool context (admin cap AND thatagent's `tools` list includes `execute_code`) — a skills-onlyagent never gains sandbox access even if the admin enabled thecapability globally. */- const skillPrimedIdsByName = buildSkillPrimedIdsByName(- manualSkillPrimes,- alwaysApplySkillPrimes,- );-// Create tracker for streaming or aggregator for non-streamingconst tracker = actuallyStreaming ? createResponseTracker() : null;const aggregator = actuallyStreaming ? null : createResponseAggregator();@@ -639,13 +671,11 @@ const createResponse = async (req, res) => {tool_resources: ctx.tool_resources,actionsEnabled: ctx.actionsEnabled,});- return enrichWithSkillConfigurable(+ return enrichLoadedToolsWithAgentContext({result,req,- primaryConfig.accessibleSkillIds,- ctx.codeEnvAvailable === true,- skillPrimedIdsByName,- );+ ctx,+ });},toolEndCallback,...getSkillToolDeps(),@@ -815,13 +845,11 @@ const createResponse = async (req, res) => {tool_resources: ctx.tool_resources,actionsEnabled: ctx.actionsEnabled,});- return enrichWithSkillConfigurable(+ return enrichLoadedToolsWithAgentContext({result,req,- primaryConfig.accessibleSkillIds,- ctx.codeEnvAvailable === true,- skillPrimedIdsByName,- );+ ctx,+ });},toolEndCallback,...getSkillToolDeps(),diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.jsindex 3108f1d72b..c7e62bd9e3 100644--- a/api/server/services/Endpoints/agents/initialize.js+++ b/api/server/services/Endpoints/agents/initialize.js@@ -31,8 +31,9 @@ const { loadAgentTools, loadToolsForExecution } = require('~/server/services/Tooconst { filterFilesByAgentAccess } = require('~/server/services/Files/permissions');const {getSkillToolDeps,- enrichWithSkillConfigurable,- buildSkillPrimedIdsByName,+ canAuthorSkillFiles,+ buildAgentToolContext,+ enrichLoadedToolsWithAgentContext,} = require('./skillDeps');const { getModelsConfig } = require('~/server/controllers/ModelController');const { checkPermission, findAccessibleResources } = require('~/server/services/PermissionService');@@ -149,6 +150,17 @@ const initializeClient = async ({ req, res, signal, endpointOption }) => {requiredPermissions: PermissionBits.VIEW,}): [];+ const editableSkillIds = skillsCapabilityEnabled+ ? await findAccessibleResources({+ userId: req.user.id,+ role: req.user.role,+ resourceType: ResourceType.SKILL,+ requiredPermissions: PermissionBits.EDIT,+ })+ : [];+ const skillCreateAllowed = skillsCapabilityEnabled+ ? await getSkillToolDeps().canCreateSkill({ req })+ : false;const { skillStates, defaultActiveOnShare } = await loadSkillStates({userId: req.user.id,@@ -195,14 +207,11 @@ const initializeClient = async ({ req, res, signal, endpointOption }) => {* the agent initialized. Falls back to `false` on any stray* ctx miss so a skills-only agent never gains sandbox access* even if capability lookup somehow skips. */- return enrichWithSkillConfigurable(+ return enrichLoadedToolsWithAgentContext({result,req,- ctx.accessibleSkillIds,- ctx.codeEnvAvailable === true,- ctx.skillPrimedIdsByName,- ctx.activeSkillNames,- );+ ctx,+ });},toolEndCallback,...getSkillToolDeps(),@@ -285,6 +294,19 @@ const initializeClient = async ({ req, res, signal, endpointOption }) => {skillsCapabilityEnabled,ephemeralSkillsToggle,});+ const primaryScopedEditableSkillIds = resolveAgentScopedSkillIds({+ agent: primaryAgent,+ accessibleSkillIds: editableSkillIds,+ skillsCapabilityEnabled,+ ephemeralSkillsToggle,+ });+ const primarySkillAuthoringAvailable = canAuthorSkillFiles({+ agent: primaryAgent,+ scopedEditableSkillIds: primaryScopedEditableSkillIds,+ skillCreateAllowed,+ skillsCapabilityEnabled,+ ephemeralSkillsToggle,+ });const primaryConfig = await initializeAgent({@@ -299,6 +321,7 @@ const initializeClient = async ({ req, res, signal, endpointOption }) => {allowedProviders,isInitialAgent: true,accessibleSkillIds: primaryScopedSkillIds,+ skillAuthoringAvailable: primarySkillAuthoringAvailable,codeEnvAvailable,skillStates,defaultActiveOnShare,@@ -324,27 +347,10 @@ const initializeClient = async ({ req, res, signal, endpointOption }) => {logger.debug(`[initializeClient] Storing tool context for ${primaryConfig.id}: ${primaryConfig.toolDefinitions?.length ?? 0} tools, registry size: ${primaryConfig.toolRegistry?.size ?? '0'}`,);- /** Maps each primed skill name (manual `$` or always-apply) to the- * `_id` of the exact doc that was primed. Plumbed to- * `enrichWithSkillConfigurable` so the read_file handler can pin- * same-name collision lookups to the resolver's chosen doc AND relax- * the disable-model-invocation gate for skills whose body is already- * in this turn's context. */- const skillPrimedIdsByName = buildSkillPrimedIdsByName(- primaryConfig.manualSkillPrimes,- primaryConfig.alwaysApplySkillPrimes,+ agentToolContexts.set(+ primaryConfig.id,+ buildAgentToolContext({ agent: primaryAgent, config: primaryConfig }),);- agentToolContexts.set(primaryConfig.id, {- agent: primaryAgent,- toolRegistry: primaryConfig.toolRegistry,- userMCPAuthMap: primaryConfig.userMCPAuthMap,- tool_resources: primaryConfig.tool_resources,- actionsEnabled: primaryConfig.actionsEnabled,- accessibleSkillIds: primaryConfig.accessibleSkillIds,- activeSkillNames: primaryConfig.activeSkillNames,- codeEnvAvailable: primaryConfig.codeEnvAvailable,- skillPrimedIdsByName,- });const {agentConfigs: discoveredConfigs,@@ -371,6 +377,19 @@ const initializeClient = async ({ req, res, signal, endpointOption }) => {skillsCapabilityEnabled,ephemeralSkillsToggle,}),+ computeSkillAuthoringAvailable: (agent) =>+ canAuthorSkillFiles({+ agent,+ scopedEditableSkillIds: resolveAgentScopedSkillIds({+ agent,+ accessibleSkillIds: editableSkillIds,+ skillsCapabilityEnabled,+ ephemeralSkillsToggle,+ }),+ skillCreateAllowed,+ skillsCapabilityEnabled,+ ephemeralSkillsToggle,+ }),skillStates,defaultActiveOnShare,codeEnvAvailable,@@ -400,28 +419,8 @@ const initializeClient = async ({ req, res, signal, endpointOption }) => {// set. The per-agent tool context map is OK to keep populated even// for pruned ids: it's only read by closure in ON_TOOL_EXECUTE,// stale entries are unreachable at runtime.- //- // Handoff agents get the same `skillPrimedIdsByName` plumbing as the- // primary so `read_file` can pin same-name collisions to the exact- // primed doc AND relax the `disable-model-invocation: true` gate for- // skills whose body is already in this turn's context — matters for- // handoff agents that have their own always-apply skills bound or- // that the user `$`-invokes within the handoff flow.onAgentInitialized: (agentId, agent, config) => {- agentToolContexts.set(agentId, {- agent,- toolRegistry: config.toolRegistry,- userMCPAuthMap: config.userMCPAuthMap,- tool_resources: config.tool_resources,- actionsEnabled: config.actionsEnabled,- accessibleSkillIds: config.accessibleSkillIds,- activeSkillNames: config.activeSkillNames,- codeEnvAvailable: config.codeEnvAvailable,- skillPrimedIdsByName: buildSkillPrimedIdsByName(- config.manualSkillPrimes,- config.alwaysApplySkillPrimes,- ),- });+ agentToolContexts.set(agentId, buildAgentToolContext({ agent, config }));},// Pass through the `@librechat/api` exports so that tests which// `jest.mock('@librechat/api')` can override the initializer/validator.@@ -468,16 +467,7 @@ const initializeClient = async ({ req, res, signal, endpointOption }) => {if (agentToolContexts.has(agentId)) {continue;}- agentToolContexts.set(agentId, {- agent: config,- toolRegistry: config.toolRegistry,- userMCPAuthMap: config.userMCPAuthMap,- tool_resources: config.tool_resources,- actionsEnabled: config.actionsEnabled,- accessibleSkillIds: config.accessibleSkillIds,- activeSkillNames: config.activeSkillNames,- codeEnvAvailable: config.codeEnvAvailable,- });+ agentToolContexts.set(agentId, buildAgentToolContext({ agent: config, config }));}// `discoverConnectedAgents` always returns a concrete array, so no@@ -565,6 +555,18 @@ const initializeClient = async ({ req, res, signal, endpointOption }) => {skippedAgentIds.add(agentId);return null;}+ const scopedSkillIds = resolveAgentScopedSkillIds({+ agent,+ accessibleSkillIds,+ skillsCapabilityEnabled,+ ephemeralSkillsToggle,+ });+ const scopedEditableSkillIds = resolveAgentScopedSkillIds({+ agent,+ accessibleSkillIds: editableSkillIds,+ skillsCapabilityEnabled,+ ephemeralSkillsToggle,+ });const config = await initializeAgent({req,@@ -576,9 +578,11 @@ const initializeClient = async ({ req, res, signal, endpointOption }) => {parentMessageId,endpointOption: { ...endpointOption, endpoint: EModelEndpoint.agents },allowedProviders,- accessibleSkillIds: resolveAgentScopedSkillIds({+ accessibleSkillIds: scopedSkillIds,+ skillAuthoringAvailable: canAuthorSkillFiles({agent,- accessibleSkillIds,+ scopedEditableSkillIds,+ skillCreateAllowed,skillsCapabilityEnabled,ephemeralSkillsToggle,}),@@ -611,20 +615,7 @@ const initializeClient = async ({ req, res, signal, endpointOption }) => {},);agentConfigs.set(agentId, config);- agentToolContexts.set(agentId, {- agent,- toolRegistry: config.toolRegistry,- userMCPAuthMap: config.userMCPAuthMap,- tool_resources: config.tool_resources,- actionsEnabled: config.actionsEnabled,- accessibleSkillIds: config.accessibleSkillIds,- activeSkillNames: config.activeSkillNames,- codeEnvAvailable: config.codeEnvAvailable,- skillPrimedIdsByName: buildSkillPrimedIdsByName(- config.manualSkillPrimes,- config.alwaysApplySkillPrimes,- ),- });+ agentToolContexts.set(agentId, buildAgentToolContext({ agent, config }));return config;} catch (err) {logger.error(`[processAgent] Error processing subagent ${agentId}:`, err);diff --git a/api/server/services/Endpoints/agents/initialize.spec.js b/api/server/services/Endpoints/agents/initialize.spec.jsindex fd1eb7c897..846e5adb1f 100644--- a/api/server/services/Endpoints/agents/initialize.spec.js+++ b/api/server/services/Endpoints/agents/initialize.spec.js@@ -68,9 +68,10 @@ jest.mock('~/cache', () => ({}));const { initializeClient } = require('./initialize');+const { getSkillToolDeps } = require('./skillDeps');const { logger } = require('@librechat/data-schemas');const { User, AclEntry } = require('~/db/models');-const { createAgent } = require('~/models');+const { createAgent, createSkill } = require('~/models');jest.spyOn(logger, 'warn').mockImplementation(() => {});@@ -226,6 +227,56 @@ describe('initializeClient — processAgent ACL gate', () => {handoffContextAttachment,]);});++ it('does not enable skill authoring for VIEW-only shared skills', async () => {+ const { skill } = await createSkill({+ name: 'shared-view-only',+ description: 'Use for read-only sharing.',+ body: '# Shared view-only skill\n',+ author: new mongoose.Types.ObjectId(),+ authorName: 'Skill Owner',+ });+ await AclEntry.create({+ principalType: PrincipalType.USER,+ principalId: testUser._id,+ principalModel: PrincipalModel.USER,+ resourceType: ResourceType.SKILL,+ resourceId: skill._id,+ permBits: PermissionBits.VIEW,+ grantedBy: testUser._id,+ });++ const endpointOption = makeEndpointOption();+ endpointOption.agent = Promise.resolve({+ id: PRIMARY_ID,+ name: 'Primary',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ skills_enabled: true,+ });+ mockInitializeAgent.mockResolvedValue(makePrimaryConfig([]));+ const req = makeReq();+ req.config.endpoints.agents = { capabilities: ['skills'] };+ const canCreateSkillSpy = jest+ .spyOn(getSkillToolDeps(), 'canCreateSkill')+ .mockResolvedValue(false);++ try {+ await initializeClient({+ req,+ res: {},+ signal: new AbortController().signal,+ endpointOption,+ });+ } finally {+ canCreateSkillSpy.mockRestore();+ }++ const initializeParams = mockInitializeAgent.mock.calls[0][0];+ expect(initializeParams.accessibleSkillIds.map(String)).toContain(skill._id.toString());+ expect(initializeParams.skillAuthoringAvailable).toBe(false);+ });});describe('initializeClient — subagent loading', () => {diff --git a/api/server/services/Endpoints/agents/skillDeps.js b/api/server/services/Endpoints/agents/skillDeps.jsindex ee2c6841da..1a0a5ff149 100644--- a/api/server/services/Endpoints/agents/skillDeps.js+++ b/api/server/services/Endpoints/agents/skillDeps.js@@ -1,18 +1,173 @@+const crypto = require('crypto');const { getStrategyFunctions } = require('~/server/services/Files/strategies');const { batchUploadCodeEnvFiles } = require('~/server/services/Files/Code/crud');const {getSessionInfo,checkIfActive,readSandboxFile,+ writeSandboxFile,} = require('~/server/services/Files/Code/process');-const { enrichWithSkillConfigurable } = require('@librechat/api');+const {+ checkAccess,+ getStorageMetadata,+ resolveRequestTenantId,+ enrichWithSkillConfigurable,+} = require('@librechat/api');+const {+ Permissions,+ FileContext,+ ResourceType,+ PermissionBits,+ AccessRoleIds,+ PrincipalType,+ PermissionTypes,+ isEphemeralAgentId,+} = require('librechat-data-provider');+const { checkPermission, grantPermission } = require('~/server/services/PermissionService');+const { getFileStrategy } = require('~/server/utils/getFileStrategy');const db = require('~/models');+function resolveSkillStorage(req, { isImage = false } = {}) {+ const source = getFileStrategy(req.config, { context: FileContext.skill_file, isImage });+ const strategy = getStrategyFunctions(source);+ if (!strategy.saveBuffer) {+ throw new Error(`Storage backend "${source}" does not support file writes`);+ }+ return { saveBuffer: strategy.saveBuffer, source };+}++function basename(relativePath) {+ const slash = relativePath.lastIndexOf('/');+ return slash === -1 ? relativePath : relativePath.slice(slash + 1);+}++async function saveSkillFileContent({ req, skillId, relativePath, content, mimeType }) {+ const existingFile = await db.getSkillFileByPath(skillId, relativePath);+ const tenantId = resolveRequestTenantId(req);+ const fileId = crypto.randomUUID();+ const filename = basename(relativePath);+ const storageFileName = `${fileId}__${filename}`;+ const buffer = Buffer.from(content, 'utf8');+ const storage = resolveSkillStorage(req, { isImage: mimeType.startsWith('image/') });+ const filepath = await storage.saveBuffer({+ userId: req.user.id,+ buffer,+ fileName: storageFileName,+ basePath: 'uploads',+ tenantId,+ });+ const storageMetadata = getStorageMetadata({ filepath, source: storage.source });++ let result;+ try {+ result = await db.upsertSkillFile({+ skillId,+ relativePath,+ file_id: fileId,+ filename,+ filepath,+ ...storageMetadata,+ source: storage.source,+ mimeType,+ bytes: buffer.length,+ isExecutable: false,+ author: req.user._id ?? req.user.id,+ tenantId,+ });+ } catch (error) {+ const { deleteFile } = getStrategyFunctions(storage.source);+ if (deleteFile) {+ await deleteFile(req, { filepath, user: req.user.id, tenantId }).catch(() => undefined);+ }+ throw error;+ }++ if (existingFile && existingFile.filepath !== filepath) {+ const { deleteFile } = getStrategyFunctions(existingFile.source);+ if (deleteFile) {+ deleteFile(req, {+ filepath: existingFile.filepath,+ storageKey: existingFile.storageKey,+ storageRegion: existingFile.storageRegion,+ user: existingFile.author ?? req.user.id,+ tenantId: existingFile.tenantId ?? tenantId,+ }).catch(() => undefined);+ }+ }++ return { bytes: result.bytes, relativePath: result.relativePath };+}++function canCreateSkill({ req }) {+ return checkAccess({+ req,+ user: req.user,+ permissionType: PermissionTypes.SKILLS,+ permissions: [Permissions.USE, Permissions.CREATE],+ getRoleByName: db.getRoleByName,+ });+}++function canEditSkill({ req, skillId }) {+ return checkPermission({+ userId: req.user.id,+ role: req.user.role,+ resourceType: ResourceType.SKILL,+ resourceId: skillId,+ requiredPermission: PermissionBits.EDIT,+ });+}++function isAgentSkillsEnabledForRun({ agent, skillsCapabilityEnabled, ephemeralSkillsToggle }) {+ if (!skillsCapabilityEnabled) {+ return false;+ }+ if (isEphemeralAgentId(agent.id)) {+ return ephemeralSkillsToggle === true;+ }+ return agent.skills_enabled === true;+}++function canAuthorSkillFiles({+ agent,+ scopedEditableSkillIds = [],+ skillCreateAllowed,+ skillsCapabilityEnabled,+ ephemeralSkillsToggle,+}) {+ return (+ isAgentSkillsEnabledForRun({ agent, skillsCapabilityEnabled, ephemeralSkillsToggle }) &&+ (scopedEditableSkillIds.length > 0 || skillCreateAllowed === true)+ );+}++function grantSkillOwner({ req, skillId }) {+ return grantPermission({+ principalType: PrincipalType.USER,+ principalId: req.user.id,+ resourceType: ResourceType.SKILL,+ resourceId: skillId,+ accessRoleId: AccessRoleIds.SKILL_OWNER,+ grantedBy: req.user.id,+ });+}++function getAuthorSkillByName({ req, name }) {+ const author = req.user?._id ?? req.user?.id;+ if (!author) {+ return null;+ }+ return db.getAuthorSkillByName({+ name,+ author,+ tenantId: resolveRequestTenantId(req),+ });+}+/**- * Builds the `skillPrimedIdsByName` map passed through to- * `enrichWithSkillConfigurable`. Centralized here so the four CJS call- * sites (`initialize.js`, `responses.js` x2, `openai.js`) share one- * source of truth — if `ResolvedManualSkill` ever renames `_id` or+ * Builds the `skillPrimedIdsByName` map threaded through+ * `buildAgentToolContext`. Centralized here so every runtime route shares+ * one source of truth — if `ResolvedManualSkill` ever renames `_id` or* gains new identifying fields, only this helper changes.** Combines both manual (`$`-popover) primes AND always-apply primes so@@ -59,9 +214,80 @@ function buildSkillPrimedIdsByName(manualSkillPrimes, alwaysApplySkillPrimes) {return out;}+/**+ * Builds the per-agent context consumed by ON_TOOL_EXECUTE. Keeping this+ * shape in one Adapter gives every runtime path the same configurable+ * fields and the same primed-skill pinning behavior.+ *+ * @param {object} params+ * @param {object} params.agent+ * @param {object} params.config+ * @returns {object}+ */+function buildAgentToolContext({ agent, config }) {+ return {+ agent,+ toolRegistry: config.toolRegistry,+ userMCPAuthMap: config.userMCPAuthMap,+ tool_resources: config.tool_resources,+ actionsEnabled: config.actionsEnabled,+ accessibleSkillIds: config.accessibleSkillIds,+ activeSkillNames: config.activeSkillNames,+ codeEnvAvailable: config.codeEnvAvailable,+ skillAuthoringAvailable: config.skillAuthoringAvailable,+ fileAuthoringToolNames: config.fileAuthoringToolNames,+ skillPrimedIdsByName:+ buildSkillPrimedIdsByName(config.manualSkillPrimes, config.alwaysApplySkillPrimes) ?? {},+ };+}++function hasOwn(value, key) {+ return Object.prototype.hasOwnProperty.call(value ?? {}, key);+}++/**+ * Applies per-agent runtime context to a loadToolsForExecution result.+ *+ * @param {object} params+ * @param {{ loadedTools: unknown[], configurable?: Record<string, unknown> }} params.result+ * @param {object} params.req+ * @param {object | undefined} params.ctx+ * @param {object | undefined} [params.fallback]+ * @returns {{ loadedTools: unknown[], configurable: Record<string, unknown> }}+ */+function enrichLoadedToolsWithAgentContext({ result, req, ctx = {}, fallback = {} }) {+ const codeEnvAvailable = hasOwn(ctx, 'codeEnvAvailable')+ ? ctx.codeEnvAvailable === true+ : fallback.codeEnvAvailable === true;+ const skillAuthoringAvailable = hasOwn(ctx, 'skillAuthoringAvailable')+ ? ctx.skillAuthoringAvailable === true+ : fallback.skillAuthoringAvailable === true;++ return enrichWithSkillConfigurable({+ result,+ context: {+ req,+ codeEnvAvailable,+ accessibleSkillIds: ctx.accessibleSkillIds ?? fallback.accessibleSkillIds,+ skillPrimedIdsByName: ctx.skillPrimedIdsByName ?? fallback.skillPrimedIdsByName,+ activeSkillNames: ctx.activeSkillNames ?? fallback.activeSkillNames,+ skillAuthoringAvailable,+ fileAuthoringToolNames: ctx.fileAuthoringToolNames ?? fallback.fileAuthoringToolNames,+ },+ });+}+/** Skill-related properties for ToolExecuteOptions (stable references, allocated once). */const skillToolDeps = {getSkillByName: db.getSkillByName,+ getAuthorSkillByName,+ createSkill: db.createSkill,+ updateSkill: db.updateSkill,+ deleteSkill: db.deleteSkill,+ canCreateSkill,+ canEditSkill,+ grantSkillOwner,+ saveSkillFileContent,listSkillFiles: db.listSkillFiles,getStrategyFunctions,batchUploadCodeEnvFiles,@@ -79,6 +305,7 @@ const skillToolDeps = {* the agents-side `ToolNode` via `tc.codeSessionContext`.*/readSandboxFile,+ writeSandboxFile,};function getSkillToolDeps() {@@ -87,6 +314,10 @@ function getSkillToolDeps() {module.exports = {getSkillToolDeps,+ canAuthorSkillFiles,+ isAgentSkillsEnabledForRun,enrichWithSkillConfigurable,buildSkillPrimedIdsByName,+ buildAgentToolContext,+ enrichLoadedToolsWithAgentContext,};diff --git a/api/server/services/Files/Code/process.js b/api/server/services/Files/Code/process.jsindex d9940da05b..10ba254a19 100644--- a/api/server/services/Files/Code/process.js+++ b/api/server/services/Files/Code/process.js@@ -1042,11 +1042,101 @@ async function readSandboxFile({ file_path, session_id, files, req }) {}}+/**+ * Writes a UTF-8 text file into the code-execution sandbox by running a+ * small Python writer through the sandbox `/exec` endpoint. The payload is+ * base64-encoded JSON so neither the file path nor the content is+ * interpolated into shell syntax.+ *+ * @param {Object} params+ * @param {string} params.file_path - Path inside the sandbox (prefer `/mnt/data/...`).+ * @param {string} params.content - Complete UTF-8 text content to write.+ * @param {string} [params.session_id] - Sandbox session id from the seeded context.+ * @param {Array<{id: string, name: string, session_id?: string}>} [params.files] - File refs to mount.+ * @param {ServerRequest} [params.req] - Current authenticated request, used to mint Code API auth.+ * @returns {Promise<{stdout?: string, stderr?: string, session_id?: string, files?: Array<Object>} | null>}+ */+async function writeSandboxFile({ file_path, content, session_id, files, req }) {+ const baseURL = getCodeBaseURL();+ if (!baseURL) {+ return null;+ }++ const payload = Buffer.from(+ JSON.stringify({+ file_path,+ content_b64: Buffer.from(content, 'utf8').toString('base64'),+ }),+ 'utf8',+ ).toString('base64');+ const code = [+ "python3 - <<'PY'",+ 'import base64, json, os',+ `payload = ${JSON.stringify(payload)}`,+ "data = json.loads(base64.b64decode(payload).decode('utf-8'))",+ "path = data['file_path']",+ "content = base64.b64decode(data['content_b64'])",+ 'parent = os.path.dirname(path)',+ 'if parent:',+ ' os.makedirs(parent, exist_ok=True)',+ "with open(path, 'wb') as f:",+ ' f.write(content)',+ 'print(f"WROTE {len(content)} bytes to {path}")',+ 'PY',+ ].join('\n');++ /** @type {Record<string, unknown>} */+ const postData = { lang: 'bash', code };+ if (session_id) {+ postData.session_id = session_id;+ }+ if (files && files.length > 0) {+ postData.files = files;+ }++ try {+ const authHeaders = await getCodeApiAuthHeaders(req);+ const response = await axios({+ method: 'post',+ url: `${baseURL}/exec`,+ data: postData,+ headers: {+ 'Content-Type': 'application/json',+ 'User-Agent': 'LibreChat/1.0',+ ...authHeaders,+ },+ httpAgent: codeServerHttpAgent,+ httpsAgent: codeServerHttpsAgent,+ timeout: 15000,+ });+ const result = response?.data ?? {};+ if (result.stderr && (result.stdout == null || result.stdout === '')) {+ throw new Error(String(result.stderr).trim());+ }+ if (result.stdout == null && result.session_id == null) {+ return null;+ }+ return {+ stdout: result.stdout == null ? undefined : String(result.stdout),+ stderr: result.stderr == null ? undefined : String(result.stderr),+ session_id: result.session_id,+ files: result.files,+ };+ } catch (error) {+ logAxiosError({+ message: `Error writing sandbox file "${file_path}"`,+ error,+ });+ throw error;+ }+}+module.exports = {primeFiles,checkIfActive,getSessionInfo,processCodeOutput,readSandboxFile,+ writeSandboxFile,runPreviewFinalize,};diff --git a/api/server/services/Files/Code/process.spec.js b/api/server/services/Files/Code/process.spec.jsindex b1a11a44a4..0bff06adf3 100644--- a/api/server/services/Files/Code/process.spec.js+++ b/api/server/services/Files/Code/process.spec.js@@ -161,7 +161,13 @@ const {getStorageMetadata,} = require('@librechat/api');-const { processCodeOutput, getSessionInfo, readSandboxFile, primeFiles } = require('./process');+const {+ processCodeOutput,+ getSessionInfo,+ readSandboxFile,+ writeSandboxFile,+ primeFiles,+} = require('./process');describe('Code Process', () => {const mockReq = {@@ -1626,6 +1632,95 @@ describe('Code Process', () => {});});+ describe('writeSandboxFile', () => {+ function extractWritePayload() {+ const code = mockAxios.mock.calls[0][0].data.code;+ const match = /payload = "([^"]+)"/.exec(code);+ expect(match).not.toBeNull();+ const payload = JSON.parse(Buffer.from(match[1], 'base64').toString('utf8'));+ return {+ file_path: payload.file_path,+ content: Buffer.from(payload.content_b64, 'base64').toString('utf8'),+ code,+ };+ }++ it('POSTs a bash python writer to /exec and forwards session context', async () => {+ mockAxios.mockResolvedValueOnce({+ data: {+ stdout: 'WROTE 11 bytes to /mnt/data/new.txt\n',+ stderr: '',+ session_id: 'sess-new',+ files: [{ id: 'file-new', name: 'new.txt', storage_session_id: 'sess-new' }],+ },+ });+ const files = [{ id: 'f1', name: 'input.csv', session_id: 'sess-prev' }];++ const result = await writeSandboxFile({+ file_path: '/mnt/data/new.txt',+ content: 'hello world',+ session_id: 'sess-prev',+ files,+ req: mockReq,+ });++ const call = mockAxios.mock.calls[0][0];+ expect(call.method).toBe('post');+ expect(call.url).toBe('https://code-api.example.com/exec');+ expect(call.data.lang).toBe('bash');+ expect(call.data.session_id).toBe('sess-prev');+ expect(call.data.files).toEqual(files);+ expect(call.timeout).toBe(15000);+ expect(call.httpAgent).toBe(codeServerHttpAgent);+ expect(call.httpsAgent).toBe(codeServerHttpsAgent);+ expect(result).toMatchObject({+ stdout: 'WROTE 11 bytes to /mnt/data/new.txt\n',+ session_id: 'sess-new',+ files: [{ id: 'file-new', name: 'new.txt' }],+ });+ });++ it('encodes path and content in a base64 JSON payload instead of shell-interpolating them', async () => {+ mockAxios.mockResolvedValueOnce({ data: { stdout: 'ok', stderr: '', session_id: 'sess' } });+ const trickyPath = `/mnt/data/quote'$(whoami).txt`;+ const trickyContent = "hello ' $(rm -rf /)\nsecond line";++ await writeSandboxFile({+ file_path: trickyPath,+ content: trickyContent,+ });++ const { file_path, content, code } = extractWritePayload();+ expect(file_path).toBe(trickyPath);+ expect(content).toBe(trickyContent);+ expect(code).not.toContain(trickyPath);+ expect(code).not.toContain(trickyContent);+ });++ it('returns null when getCodeBaseURL is not configured', async () => {+ const { getCodeBaseURL } = require('@librechat/agents');+ getCodeBaseURL.mockReturnValueOnce('');++ const result = await writeSandboxFile({+ file_path: '/mnt/data/x.txt',+ content: 'x',+ });++ expect(result).toBeNull();+ expect(mockAxios).not.toHaveBeenCalled();+ });++ it('throws when the writer reports stderr without stdout', async () => {+ mockAxios.mockResolvedValueOnce({+ data: { stdout: '', stderr: 'Permission denied\n' },+ });++ await expect(writeSandboxFile({ file_path: '/root/nope.txt', content: 'x' })).rejects.toThrow(+ 'Permission denied',+ );+ });+ });+describe('primeFiles reupload pushes FRESH sandbox ids (Pass-N review P2)', () => {/*** Regression: when a primed code file is missing/expired in thediff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.jsindex 67b68bdad1..4375f6e307 100644--- a/api/server/services/ToolService.js+++ b/api/server/services/ToolService.js@@ -23,6 +23,7 @@ const {getMissingCustomUserVars,buildWebSearchDynamicContext,getCodeApiAuthHeaders,+ isFileAuthoringToolDefinition,} = require('@librechat/api');const {Time,@@ -1380,6 +1381,13 @@ async function loadToolsForExecution({}}+ const fileAuthoringToolNames = new Set(+ toolRegistry+ ? Array.from(toolRegistry.values())+ .filter((definition) => isFileAuthoringToolDefinition(definition))+ .map((definition) => definition.name)+ : [],+ );const specialToolNames = new Set([AgentConstants.TOOL_SEARCH,AgentConstants.PROGRAMMATIC_TOOL_CALLING,@@ -1387,6 +1395,7 @@ async function loadToolsForExecution({AgentConstants.BASH_TOOL,AgentConstants.SKILL_TOOL,AgentConstants.READ_FILE,+ ...fileAuthoringToolNames,]);let ptcOrchestratedToolNames = [];diff --git a/client/src/components/Chat/Input/ToolsDropdown.tsx b/client/src/components/Chat/Input/ToolsDropdown.tsxindex fa6150b61d..25225808bd 100644--- a/client/src/components/Chat/Input/ToolsDropdown.tsx+++ b/client/src/components/Chat/Input/ToolsDropdown.tsx@@ -226,7 +226,7 @@ const ToolsDropdown = ({ disabled }: ToolsDropdownProps) => {onClick: handleSkillsToggle,hideOnClick: false,render: (props) => (- <div {...props}>+ <div {...props} data-testid="tools-menu-skills"><div className="flex items-center gap-2"><ScrollText className="icon-md" aria-hidden="true" /><span>{localize('com_ui_skills')}</span>diff --git a/client/src/components/Chat/Messages/Content/Part.tsx b/client/src/components/Chat/Messages/Content/Part.tsxindex a0502816f6..6df833370a 100644--- a/client/src/components/Chat/Messages/Content/Part.tsx+++ b/client/src/components/Chat/Messages/Content/Part.tsx@@ -18,6 +18,7 @@ import {Text,SkillCall,ReadFileCall,+ FileAuthoringCall,BashCall,SubagentCall,} from './Parts';@@ -230,6 +231,19 @@ const Part = memo(function Part({onExpand={onToolExpand}/>);+ } else if (isToolCall && (toolCall.name === 'create_file' || toolCall.name === 'edit_file')) {+ return (+ <FileAuthoringCall+ toolName={toolCall.name}+ args={toolCall.args}+ output={toolCall.output ?? ''}+ initialProgress={toolCall.progress ?? 0.1}+ isSubmitting={isSubmitting}+ attachments={attachments}+ hideAttachments={hideAttachments}+ onExpand={onToolExpand}+ />+ );} else if (isToolCall && toolCall.name === Tools.bash_tool) {return (<BashCalldiff --git a/client/src/components/Chat/Messages/Content/Parts/FileAuthoringCall.tsx b/client/src/components/Chat/Messages/Content/Parts/FileAuthoringCall.tsxnew file mode 100644index 0000000000..bb98eb361f--- /dev/null+++ b/client/src/components/Chat/Messages/Content/Parts/FileAuthoringCall.tsx@@ -0,0 +1,186 @@+import { useMemo } from 'react';+import { FilePenLine, FilePlus2 } from 'lucide-react';+import type { TAttachment } from 'librechat-data-provider';+import ProgressText from '~/components/Chat/Messages/Content/ProgressText';+import useToolCallState from './useToolCallState';+import useLazyHighlight from './useLazyHighlight';+import CodeWindowHeader from './CodeWindowHeader';+import { AttachmentGroup } from './Attachment';+import parseJsonField from './parseJsonField';+import { langFromPath } from './ReadFileCall';+import { useLocalize } from '~/hooks';+import { cn } from '~/utils';++type FileAuthoringToolName = 'create_file' | 'edit_file';++type ToolCallArgs = string | Record<string, unknown> | undefined;++interface TextEditPreview {+ oldText: string;+ newText: string;+}++function hasDiff(output: string): boolean {+ return /\n@@\s/.test(output) || output.includes('\n--- ') || output.includes('\n+++ ');+}++function parseArgsObject(args: ToolCallArgs): Record<string, unknown> | undefined {+ if (typeof args === 'object' && args !== null) {+ return args;+ }+ if (typeof args !== 'string') {+ return undefined;+ }+ try {+ const parsed = JSON.parse(args);+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {+ return parsed as Record<string, unknown>;+ }+ } catch {+ return undefined;+ }+ return undefined;+}++function textValue(value: unknown): string {+ return typeof value === 'string' ? value : '';+}++function editPreviewLines(prefix: '-' | '+', text: string): string {+ return text+ .split('\n')+ .map((line) => `${prefix}${line}`)+ .join('\n');+}++function formatEditPreview(edits: TextEditPreview[]): string {+ return edits+ .map((edit, index) => {+ const suffix = edits.length > 1 ? ` ${index + 1}` : '';+ return [+ `--- old_text${suffix}`,+ `+++ new_text${suffix}`,+ '@@',+ editPreviewLines('-', edit.oldText),+ editPreviewLines('+', edit.newText),+ ].join('\n');+ })+ .join('\n\n');+}++function buildEditArgsPreview(args: ToolCallArgs): string {+ const parsed = parseArgsObject(args);+ if (Array.isArray(parsed?.edits) && parsed.edits.length > 0) {+ const edits = parsed.edits+ .map((edit): TextEditPreview | undefined => {+ if (typeof edit !== 'object' || edit === null || Array.isArray(edit)) {+ return undefined;+ }+ const entry = edit as Record<string, unknown>;+ const oldText = textValue(entry.old_text);+ const newText = textValue(entry.new_text);+ return oldText || newText ? { oldText, newText } : undefined;+ })+ .filter((edit): edit is TextEditPreview => !!edit);+ return formatEditPreview(edits);+ }++ const oldText = parsed ? textValue(parsed.old_text) : parseJsonField(args, 'old_text');+ const newText = parsed ? textValue(parsed.new_text) : parseJsonField(args, 'new_text');+ if (!oldText && !newText) {+ return '';+ }+ return formatEditPreview([{ oldText, newText }]);+}++export default function FileAuthoringCall({+ toolName,+ isSubmitting,+ initialProgress = 0.1,+ args,+ output = '',+ attachments,+ hideAttachments = false,+ onExpand,+}: {+ toolName: FileAuthoringToolName;+ initialProgress: number;+ isSubmitting: boolean;+ args?: string | Record<string, unknown>;+ output?: string;+ attachments?: TAttachment[];+ hideAttachments?: boolean;+ onExpand?: () => void;+}) {+ const localize = useLocalize();+ const isCreate = toolName === 'create_file';+ const filePath = useMemo(() => parseJsonField(args, 'file_path'), [args]);+ const authoredContent = useMemo(() => parseJsonField(args, 'content'), [args]);+ const editArgsPreview = useMemo(() => buildEditArgsPreview(args), [args]);+ const fileName = filePath.split('/').pop() || filePath;+ const fileLang = useMemo(() => langFromPath(filePath), [filePath]);+ const outputIsDiff = hasDiff(output);+ const preview = isCreate ? output || authoredContent : output || editArgsPreview;+ const previewIsDiff = outputIsDiff || (!isCreate && !!editArgsPreview && !output);+ let previewLang = 'plaintext';+ if (previewIsDiff) {+ previewLang = 'diff';+ } else if (isCreate && authoredContent && !output) {+ previewLang = fileLang;+ }++ const { showCode, toggleCode, expandStyle, expandRef, progress, cancelled, hasError } =+ useToolCallState(initialProgress, isSubmitting, output, !!filePath || !!preview, onExpand);++ const highlighted = useLazyHighlight(preview || undefined, previewLang);+ const Icon = isCreate ? FilePlus2 : FilePenLine;++ return (+ <>+ <div className="relative my-1.5 flex size-5 shrink-0 items-center gap-2.5">+ <ProgressText+ progress={progress}+ onClick={toggleCode}+ inProgressText={localize(isCreate ? 'com_ui_creating_file' : 'com_ui_editing_file', {+ 0: fileName,+ })}+ finishedText={+ cancelled+ ? localize('com_ui_cancelled')+ : localize(isCreate ? 'com_ui_created_file' : 'com_ui_edited_file', { 0: fileName })+ }+ errorSuffix={hasError && !cancelled ? localize('com_ui_tool_failed') : undefined}+ icon={+ <Icon+ className={cn(+ 'size-4 shrink-0 text-text-secondary',+ progress < 1 && !cancelled && !hasError && 'animate-pulse',+ )}+ aria-hidden="true"+ />+ }+ hasInput={!!filePath || !!preview}+ isExpanded={showCode}+ error={cancelled}+ />+ </div>+ <div style={expandStyle}>+ <div className="overflow-hidden" ref={expandRef}>+ {!!preview && (+ <div className="my-2 overflow-hidden rounded-lg border border-border-light bg-surface-secondary">+ <CodeWindowHeader language={previewIsDiff ? 'diff' : fileName} code={preview} />+ <pre className="max-h-[300px] overflow-auto bg-surface-chat p-4 font-mono text-xs dark:bg-surface-primary-alt">+ <code className={`hljs language-${previewLang} !whitespace-pre`}>+ {highlighted ?? preview}+ </code>+ </pre>+ </div>+ )}+ </div>+ </div>+ {!hideAttachments && attachments && attachments.length > 0 && (+ <AttachmentGroup attachments={attachments} />+ )}+ </>+ );+}diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/FileAuthoringCall.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/FileAuthoringCall.test.tsxnew file mode 100644index 0000000000..08e19f73c3--- /dev/null+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/FileAuthoringCall.test.tsx@@ -0,0 +1,153 @@+import React from 'react';+import { render, screen } from '@testing-library/react';+import FileAuthoringCall from '../FileAuthoringCall';++jest.mock('~/hooks', () => ({+ useLocalize:+ () =>+ (key: string, values?: Record<string | number, string>): string => {+ const translations: Record<string, string> = {+ com_ui_created_file: 'Created {{0}}',+ com_ui_creating_file: 'Creating {{0}}',+ com_ui_edited_file: 'Edited {{0}}',+ com_ui_editing_file: 'Editing {{0}}',+ com_ui_cancelled: 'Cancelled',+ com_ui_tool_failed: 'failed',+ };+ return (translations[key] ?? key).replace('{{0}}', values?.[0] ?? '');+ },+}));++jest.mock('~/utils', () => ({+ cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),+}));++jest.mock('~/components/Chat/Messages/Content/ProgressText', () => ({+ __esModule: true,+ default: ({+ progress,+ inProgressText,+ finishedText,+ }: {+ progress: number;+ inProgressText: string;+ finishedText: string;+ }) => <div data-testid="progress-text">{progress < 1 ? inProgressText : finishedText}</div>,+}));++jest.mock('../CodeWindowHeader', () => ({+ __esModule: true,+ default: ({ language }: { language: string }) => (+ <div data-testid="code-window-header" data-language={language} />+ ),+}));++jest.mock('../Attachment', () => ({+ AttachmentGroup: () => <div data-testid="attachment-group" />,+}));++jest.mock('../useLazyHighlight', () => ({+ __esModule: true,+ default: () => null,+}));++jest.mock('../useToolCallState', () => ({+ __esModule: true,+ default: (initialProgress: number) => ({+ showCode: true,+ toggleCode: jest.fn(),+ expandStyle: {},+ expandRef: { current: null },+ progress: initialProgress,+ cancelled: false,+ hasError: false,+ }),+}));++describe('FileAuthoringCall', () => {+ it('shows create_file content args while the call is in progress', () => {+ render(+ <FileAuthoringCall+ toolName="create_file"+ initialProgress={0.5}+ isSubmitting={true}+ args={{+ file_path: 'skills/demo/SKILL.md',+ content: '# Demo\n\nUse this skill for testing.',+ }}+ output=""+ />,+ );++ expect(screen.getByTestId('progress-text')).toHaveTextContent('Creating SKILL.md');+ expect(screen.getByTestId('code-window-header')).toHaveAttribute('data-language', 'SKILL.md');+ expect(screen.getByText(/Use this skill for testing/)).toBeInTheDocument();+ });++ it('shows completed create_file output instead of full content args', () => {+ render(+ <FileAuthoringCall+ toolName="create_file"+ initialProgress={1}+ isSubmitting={false}+ args={{+ file_path: 'skills/demo/SKILL.md',+ content: '# Demo\n\nLarge generated body should not stay mounted after completion.',+ }}+ output="Created skills/demo/SKILL.md (4096 chars)."+ />,+ );++ expect(screen.getByTestId('progress-text')).toHaveTextContent('Created SKILL.md');+ expect(screen.getByText('Created skills/demo/SKILL.md (4096 chars).')).toBeInTheDocument();+ expect(screen.queryByText(/Large generated body/)).not.toBeInTheDocument();+ });++ it('shows edit_file replacement args while the call is in progress', () => {+ render(+ <FileAuthoringCall+ toolName="edit_file"+ initialProgress={0.5}+ isSubmitting={true}+ args={{+ file_path: 'skills/demo/SKILL.md',+ old_text: 'description: Old behavior',+ new_text: 'description: New behavior',+ }}+ output=""+ />,+ );++ expect(screen.getByTestId('progress-text')).toHaveTextContent('Editing SKILL.md');+ expect(screen.getByTestId('code-window-header')).toHaveAttribute('data-language', 'diff');+ const preview = screen.getByText((_, element) => element?.tagName.toLowerCase() === 'code');+ expect(preview).toHaveTextContent('--- old_text');+ expect(preview).toHaveTextContent('+++ new_text');+ expect(preview).toHaveTextContent('-description: Old behavior');+ expect(preview).toHaveTextContent('+description: New behavior');+ });++ it('shows batched edit_file replacements from edits args while the call is in progress', () => {+ render(+ <FileAuthoringCall+ toolName="edit_file"+ initialProgress={0.5}+ isSubmitting={true}+ args={{+ file_path: 'skills/demo/SKILL.md',+ edits: [+ { old_text: 'first old', new_text: 'first new' },+ { old_text: 'second old', new_text: 'second new' },+ ],+ }}+ output=""+ />,+ );++ const preview = screen.getByText((_, element) => element?.tagName.toLowerCase() === 'code');+ expect(preview).toHaveTextContent('--- old_text 1');+ expect(preview).toHaveTextContent('+++ new_text 2');+ expect(preview).toHaveTextContent('-first old');+ expect(preview).toHaveTextContent('+second new');+ });+});diff --git a/client/src/components/Chat/Messages/Content/Parts/index.ts b/client/src/components/Chat/Messages/Content/Parts/index.tsindex da495abb82..6d6bf470b7 100644--- a/client/src/components/Chat/Messages/Content/Parts/index.ts+++ b/client/src/components/Chat/Messages/Content/Parts/index.ts@@ -11,5 +11,6 @@ export { default as AgentUpdate } from './AgentUpdate';export { default as EditTextPart } from './EditTextPart';export { default as SkillCall } from './SkillCall';export { default as ReadFileCall } from './ReadFileCall';+export { default as FileAuthoringCall } from './FileAuthoringCall';export { default as BashCall } from './BashCall';export { default as SubagentCall } from './SubagentCall';diff --git a/client/src/components/Chat/Messages/Content/__tests__/Part.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/Part.test.tsxindex 1da1d389d1..5fd1498287 100644--- a/client/src/components/Chat/Messages/Content/__tests__/Part.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/Part.test.tsx@@ -14,6 +14,9 @@ jest.mock('../Parts', () => ({Text: ({ text }: { text?: string }) => <div data-testid="text">{text}</div>,SkillCall: () => <div data-testid="skill-call" />,ReadFileCall: () => <div data-testid="read-file-call" />,+ FileAuthoringCall: ({ toolName }: { toolName: string }) => (+ <div data-testid="file-authoring-call" data-tool-name={toolName} />+ ),BashCall: ({ commandField }: { commandField?: string }) => (<div data-testid="bash-call" data-command-field={commandField ?? 'command'} />),@@ -101,4 +104,31 @@ describe('Part tool renderer selection', () => {expect(screen.getByTestId('execute-code')).toBeInTheDocument();expect(screen.queryByTestId('bash-call')).not.toBeInTheDocument();});++ it('routes create_file calls through the file-authoring renderer', () => {+ renderPart(+ toolCallPart('create_file', '{"file_path":"skills/demo/SKILL.md","content":"# Demo"}'),+ );++ expect(screen.getByTestId('file-authoring-call')).toHaveAttribute(+ 'data-tool-name',+ 'create_file',+ );+ expect(screen.queryByTestId('tool-call')).not.toBeInTheDocument();+ });++ it('routes edit_file calls through the file-authoring renderer', () => {+ renderPart(+ toolCallPart(+ 'edit_file',+ '{"file_path":"skills/demo/SKILL.md","old_text":"Demo","new_text":"Updated"}',+ ),+ );++ expect(screen.getByTestId('file-authoring-call')).toHaveAttribute(+ 'data-tool-name',+ 'edit_file',+ );+ expect(screen.queryByTestId('tool-call')).not.toBeInTheDocument();+ });});diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 59f0766e6e..80d92f9f86 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -1390,6 +1390,10 @@"com_ui_read_aloud": "Read aloud","com_ui_read_file": "Read {{0}}","com_ui_reading_file": "Reading {{0}}",+ "com_ui_created_file": "Created {{0}}",+ "com_ui_creating_file": "Creating {{0}}",+ "com_ui_edited_file": "Edited {{0}}",+ "com_ui_editing_file": "Editing {{0}}","com_ui_redirect_uri": "Redirect URI","com_ui_redirect_uri_instructions": "Copy this redirect URI and configure it in your OAuth provider settings.","com_ui_redirecting_to_provider": "Redirecting to {{0}}, please wait...",diff --git a/e2e/setup/mock-llm-server.js b/e2e/setup/mock-llm-server.jsindex 1aa9ad78a6..4f34190e9c 100644--- a/e2e/setup/mock-llm-server.js+++ b/e2e/setup/mock-llm-server.js@@ -9,6 +9,19 @@ const DEFAULT_PORT = 8889;const MOCK_REPLY = process.env.MOCK_LLM_REPLY || 'E2E mock reply: pong';const MODEL_FALLBACK = 'mock-model';const STREAM_CHUNK_DELAY_MS = Number(process.env.MOCK_LLM_CHUNK_DELAY_MS) || 60;+const CREATE_SKILL_MARKER = 'E2E_CREATE_SKILL:';+const EDIT_SKILL_MARKER = 'E2E_EDIT_SKILL:';+const CREATE_FILE_AUTHORING_FINAL_TEXT = 'E2E file authoring complete';+const EDIT_FILE_AUTHORING_FINAL_TEXT = 'E2E file edit complete';+const CREATE_FILE_TOOL_NAME = 'create_file';+const EDIT_FILE_TOOL_NAME = 'edit_file';+const BASH_TOOL_NAME = 'bash_tool';+const CREATE_SKILL_TOOL_CALL_ID = 'call_e2e_create_skill';+const EDIT_SKILL_TOOL_CALL_ID = 'call_e2e_edit_skill';+const SKILL_DESCRIPTION =+ 'Use this skill to verify LibreChat skill file authoring in mock end-to-end tests.';+const EDITED_SKILL_DESCRIPTION =+ 'Use this edited skill to verify LibreChat skill file authoring in mock end-to-end tests.';const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));@@ -32,7 +45,106 @@ function toChunks(text) {return text.match(/\S+\s*/g) || [text];}-async function streamCompletion(res, model) {+function getToolName(tool) {+ if (!tool || typeof tool !== 'object') {+ return '';+ }+ if (typeof tool.name === 'string') {+ return tool.name;+ }+ if (tool.function && typeof tool.function.name === 'string') {+ return tool.function.name;+ }+ return '';+}++function hasTool(body, name) {+ const tools = Array.isArray(body.tools) ? body.tools : [];+ const functions = Array.isArray(body.functions) ? body.functions : [];+ return [...tools, ...functions].some((tool) => getToolName(tool) === name);+}++function getContentText(content) {+ if (typeof content === 'string') {+ return content;+ }+ if (!Array.isArray(content)) {+ return '';+ }+ return content+ .map((part) => {+ if (typeof part === 'string') {+ return part;+ }+ if (part && typeof part === 'object' && typeof part.text === 'string') {+ return part.text;+ }+ return '';+ })+ .join('\n');+}++function getLatestUserText(body) {+ const messages = Array.isArray(body.messages) ? body.messages : [];+ for (let index = messages.length - 1; index >= 0; index--) {+ const message = messages[index];+ if (!message || message.role !== 'user') {+ continue;+ }+ return getContentText(message.content);+ }+ return '';+}++function getRequestedSkillName(body, marker) {+ const text = getLatestUserText(body);+ const markerIndex = text.indexOf(marker);+ if (markerIndex === -1) {+ return '';+ }+ const afterMarker = text.slice(markerIndex + marker.length);+ const skillName = afterMarker.match(/[a-z0-9][a-z0-9-]*/)?.[0];+ if (skillName) {+ return skillName;+ }+ return '';+}++function hasFileAuthoringToolResult(body, toolCallId) {+ const messages = Array.isArray(body.messages) ? body.messages : [];+ return messages.some(+ (message) => message && message.role === 'tool' && message.tool_call_id === toolCallId,+ );+}++function buildSkillBody(skillName) {+ return `---+name: ${skillName}+description: ${SKILL_DESCRIPTION}+---++# ${skillName}++Created by the Playwright mock e2e suite to verify host file authoring without code execution.`;+}++function buildCreateSkillArgs(skillName) {+ return {+ file_path: `skills/${skillName}/SKILL.md`,+ content: buildSkillBody(skillName),+ overwrite: false,+ };+}++function buildEditSkillArgs(skillName) {+ return {+ file_path: `skills/${skillName}/SKILL.md`,+ old_text: `description: ${SKILL_DESCRIPTION}`,+ new_text: `description: ${EDITED_SKILL_DESCRIPTION}`,+ };+}++async function streamTextCompletion(res, model, text = MOCK_REPLY) {res.writeHead(200, {'Content-Type': 'text/event-stream','Cache-Control': 'no-cache',@@ -55,7 +167,7 @@ async function streamCompletion(res, model) {};send({ role: 'assistant', content: '' });- for (const chunk of toChunks(MOCK_REPLY)) {+ for (const chunk of toChunks(text)) {await delay(STREAM_CHUNK_DELAY_MS);send({ content: chunk });}@@ -64,7 +176,54 @@ async function streamCompletion(res, model) {res.end();}-function jsonCompletion(res, model) {+async function streamToolCall(res, model, { toolName, toolCallId, args }) {+ res.writeHead(200, {+ 'Content-Type': 'text/event-stream',+ 'Cache-Control': 'no-cache',+ Connection: 'keep-alive',+ });+ if (typeof res.flushHeaders === 'function') {+ res.flushHeaders();+ }++ const id = 'chatcmpl-e2e-mock';+ const created = 1700000000;+ const base = { id, object: 'chat.completion.chunk', created, model };+ const send = (delta, finishReason = null) => {+ const payload = {+ ...base,+ choices: [{ index: 0, delta, finish_reason: finishReason }],+ };+ res.write(`data: ${JSON.stringify(payload)}\n\n`);+ };++ send({ role: 'assistant', content: '' });+ await delay(STREAM_CHUNK_DELAY_MS);+ send({+ tool_calls: [+ {+ index: 0,+ id: toolCallId,+ type: 'function',+ function: { name: toolName, arguments: '' },+ },+ ],+ });+ await delay(STREAM_CHUNK_DELAY_MS);+ send({+ tool_calls: [+ {+ index: 0,+ function: { arguments: JSON.stringify(args) },+ },+ ],+ });+ send({}, 'tool_calls');+ res.write('data: [DONE]\n\n');+ res.end();+}++function jsonCompletion(res, model, content = MOCK_REPLY) {const payload = {id: 'chatcmpl-e2e-mock',object: 'chat.completion',@@ -73,7 +232,7 @@ function jsonCompletion(res, model) {choices: [{index: 0,- message: { role: 'assistant', content: MOCK_REPLY },+ message: { role: 'assistant', content },finish_reason: 'stop',},],@@ -83,6 +242,108 @@ function jsonCompletion(res, model) {res.end(JSON.stringify(payload));}+function jsonToolCall(res, model, { toolName, toolCallId, args }) {+ const payload = {+ id: 'chatcmpl-e2e-mock',+ object: 'chat.completion',+ created: 1700000000,+ model,+ choices: [+ {+ index: 0,+ message: {+ role: 'assistant',+ content: null,+ tool_calls: [+ {+ id: toolCallId,+ type: 'function',+ function: {+ name: toolName,+ arguments: JSON.stringify(args),+ },+ },+ ],+ },+ finish_reason: 'tool_calls',+ },+ ],+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },+ };+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(payload));+}++async function handleFileAuthoringOperation(body, res, model, operation) {+ const finalText = `${operation.finalText}: ${operation.skillName}`;+ if (hasFileAuthoringToolResult(body, operation.toolCallId)) {+ if (body.stream) {+ await streamTextCompletion(res, model, finalText);+ } else {+ jsonCompletion(res, model, finalText);+ }+ return true;+ }++ if (!hasTool(body, operation.toolName)) {+ const unavailable = `E2E file authoring unavailable: ${operation.toolName} was not advertised.`;+ if (body.stream) {+ await streamTextCompletion(res, model, unavailable);+ } else {+ jsonCompletion(res, model, unavailable);+ }+ return true;+ }++ if (hasTool(body, BASH_TOOL_NAME)) {+ const unexpected = `E2E file authoring unavailable: ${BASH_TOOL_NAME} was unexpectedly advertised.`;+ if (body.stream) {+ await streamTextCompletion(res, model, unexpected);+ } else {+ jsonCompletion(res, model, unexpected);+ }+ return true;+ }++ const toolCall = {+ toolName: operation.toolName,+ toolCallId: operation.toolCallId,+ args: operation.args,+ };+ if (body.stream) {+ await streamToolCall(res, model, toolCall);+ } else {+ jsonToolCall(res, model, toolCall);+ }+ return true;+}++async function handleFileAuthoringE2E(body, res, model) {+ const createSkillName = getRequestedSkillName(body, CREATE_SKILL_MARKER);+ if (createSkillName) {+ return await handleFileAuthoringOperation(body, res, model, {+ skillName: createSkillName,+ toolName: CREATE_FILE_TOOL_NAME,+ toolCallId: CREATE_SKILL_TOOL_CALL_ID,+ finalText: CREATE_FILE_AUTHORING_FINAL_TEXT,+ args: buildCreateSkillArgs(createSkillName),+ });+ }++ const editSkillName = getRequestedSkillName(body, EDIT_SKILL_MARKER);+ if (editSkillName) {+ return await handleFileAuthoringOperation(body, res, model, {+ skillName: editSkillName,+ toolName: EDIT_FILE_TOOL_NAME,+ toolCallId: EDIT_SKILL_TOOL_CALL_ID,+ finalText: EDIT_FILE_AUTHORING_FINAL_TEXT,+ args: buildEditSkillArgs(editSkillName),+ });+ }++ return false;+}+async function handleRequest(req, res) {if (req.method === 'GET' && (req.url === '/health' || req.url === '/')) {res.writeHead(200, { 'Content-Type': 'application/json' });@@ -93,8 +354,11 @@ async function handleRequest(req, res) {if (req.method === 'POST' && req.url && req.url.endsWith('/chat/completions')) {const body = await readJsonBody(req);const model = body.model || MODEL_FALLBACK;+ if (await handleFileAuthoringE2E(body, res, model)) {+ return;+ }if (body.stream) {- await streamCompletion(res, model);+ await streamTextCompletion(res, model);} else {jsonCompletion(res, model);}diff --git a/e2e/specs/mock/helpers.ts b/e2e/specs/mock/helpers.tsindex f60837bba3..7ad75687fd 100644--- a/e2e/specs/mock/helpers.ts+++ b/e2e/specs/mock/helpers.ts@@ -29,6 +29,14 @@ export async function selectMockEndpoint(page: Page, endpoint: MockEndpoint) {await expect(modelSelectorTrigger(page)).not.toHaveText('Select a model');}+/** Enable the ephemeral Skills capability from the composer tool menu. */+export async function enableSkills(page: Page) {+ await page.getByRole('button', { name: 'Tools Options' }).click();+ await page.getByTestId('tools-menu-skills').click();+ await page.keyboard.press('Escape');+ await expect(page.getByRole('button', { name: 'Skills' })).toBeVisible();+}+/** The mock reply as rendered in the conversation, scoped to the messages view. */export function mockReply(page: Page) {return page.getByTestId('messages-view').getByText(new RegExp(MOCK_REPLY_TEXT, 'i'));diff --git a/e2e/specs/mock/skill-file-authoring.spec.ts b/e2e/specs/mock/skill-file-authoring.spec.tsnew file mode 100644index 0000000000..5e9bd1f25f--- /dev/null+++ b/e2e/specs/mock/skill-file-authoring.spec.ts@@ -0,0 +1,187 @@+import { expect, test } from '@playwright/test';+import type { Page } from '@playwright/test';+import {+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+ enableSkills,+ selectMockEndpoint,+ sendMessage,+} from './helpers';++const FINAL_TEXT = 'E2E file authoring complete';+const EDIT_FINAL_TEXT = 'E2E file edit complete';+const DESCRIPTION =+ 'Use this skill to verify LibreChat skill file authoring in mock end-to-end tests.';+const EDITED_DESCRIPTION =+ 'Use this edited skill to verify LibreChat skill file authoring in mock end-to-end tests.';++type SkillSummary = {+ _id: string;+ name: string;+ description: string;+};++type SkillDetail = SkillSummary & {+ body: string;+};++type RefreshTokenBody = {+ token?: string;+};++const uniqueSkillName = () => `e2e-file-authoring-${Date.now()}-${Math.floor(Math.random() * 1e4)}`;++async function getAccessToken(page: Page): Promise<string> {+ const result = await page.evaluate(async () => {+ const response = await fetch('/api/auth/refresh', {+ method: 'POST',+ credentials: 'include',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({}),+ });+ const text = await response.text();+ let json: unknown = null;+ try {+ json = text ? JSON.parse(text) : null;+ } catch {+ json = null;+ }+ return { ok: response.ok, status: response.status, text, json };+ });++ if (!result.ok) {+ throw new Error(+ `Expected /api/auth/refresh to return 2xx, got ${result.status}: ${result.text}`,+ );+ }++ const body = result.json as RefreshTokenBody | null;+ if (!body?.token) {+ throw new Error(`Expected /api/auth/refresh to return a token, got: ${result.text}`);+ }++ return body.token;+}++async function fetchJson<T>(page: Page, path: string, token: string): Promise<T> {+ const result = await page.evaluate(+ async ({ accessToken, urlPath }) => {+ const response = await fetch(urlPath, {+ credentials: 'include',+ headers: { Authorization: `Bearer ${accessToken}` },+ });+ const text = await response.text();+ let json: unknown = null;+ try {+ json = text ? JSON.parse(text) : null;+ } catch {+ json = null;+ }+ return { ok: response.ok, status: response.status, text, json };+ },+ { accessToken: token, urlPath: path },+ );++ if (!result.ok) {+ throw new Error(`Expected ${path} to return 2xx, got ${result.status}: ${result.text}`);+ }+ return result.json as T;+}++async function findSkill(+ page: Page,+ skillName: string,+ token: string,+): Promise<SkillSummary | null> {+ const body = await fetchJson<{ skills?: SkillSummary[] }>(+ page,+ `/api/skills?search=${encodeURIComponent(skillName)}&limit=10`,+ token,+ );+ return body.skills?.find((skill) => skill.name === skillName) ?? null;+}++async function waitForPersistedSkill(+ page: Page,+ skillName: string,+ expectedDescription = DESCRIPTION,+): Promise<SkillDetail> {+ const token = await getAccessToken(page);+ let latestSkill: SkillDetail | null = null;+ for (let attempt = 0; attempt < 20; attempt++) {+ const skill = await findSkill(page, skillName, token);+ if (skill) {+ latestSkill = await fetchJson<SkillDetail>(+ page,+ `/api/skills/${encodeURIComponent(skill._id)}`,+ token,+ );+ if (latestSkill.description === expectedDescription) {+ return latestSkill;+ }+ }+ await new Promise((resolve) => setTimeout(resolve, 500));+ }++ expect(latestSkill, `Expected skill "${skillName}" to be persisted`).not.toBeNull();+ expect(latestSkill?.description).toBe(expectedDescription);+ return latestSkill!;+}++test.describe('skill file authoring tools', () => {+ test('creates and edits a skill without enabling code execution', async ({ page }) => {+ test.setTimeout(120000);+ const skillName = uniqueSkillName();+ const prompt = [+ `${FINAL_TEXT} request`,+ `E2E_CREATE_SKILL:${skillName}`,+ 'Create the skill file using host file authoring only.',+ ].join('\n');+ const editPrompt = [+ `${EDIT_FINAL_TEXT} request`,+ `E2E_EDIT_SKILL:${skillName}`,+ 'Edit the skill file using host file authoring only.',+ ].join('\n');++ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ await enableSkills(page);++ const response = await sendMessage(page, prompt);+ expect(response.ok()).toBeTruthy();++ await expect(page).toHaveURL(/\/c\/(?!new)/, { timeout: 15000 });+ const conversationUrl = page.url();+ await expect(+ page.getByTestId('messages-view').getByText(`${FINAL_TEXT}: ${skillName}`),+ ).toBeVisible({ timeout: 30000 });++ const skill = await waitForPersistedSkill(page, skillName);+ expect(skill.description).toBe(DESCRIPTION);+ expect(skill.body).toContain(`name: ${skillName}`);+ expect(skill.body).toContain(DESCRIPTION);++ const editResponse = await sendMessage(page, editPrompt);+ expect(editResponse.ok()).toBeTruthy();++ await expect(+ page.getByTestId('messages-view').getByText(`${EDIT_FINAL_TEXT}: ${skillName}`),+ ).toBeVisible({ timeout: 30000 });++ const editedSkill = await waitForPersistedSkill(page, skillName, EDITED_DESCRIPTION);+ expect(editedSkill.body).toContain(EDITED_DESCRIPTION);++ await page.reload({ timeout: 10000 });+ await expect(page).toHaveURL(conversationUrl);+ await expect(+ page.getByTestId('messages-view').getByText(`${FINAL_TEXT}: ${skillName}`),+ ).toBeVisible({ timeout: 30000 });+ await expect(+ page.getByTestId('messages-view').getByText(`${EDIT_FINAL_TEXT}: ${skillName}`),+ ).toBeVisible({ timeout: 30000 });++ await page.goto(`/skills/${editedSkill._id}`, { timeout: 10000 });+ await expect(page.getByRole('heading', { level: 1, name: skillName })).toBeVisible();+ await expect(page.getByText(EDITED_DESCRIPTION)).toBeVisible();+ });+});diff --git a/packages/api/src/agents/__tests__/initialize.test.ts b/packages/api/src/agents/__tests__/initialize.test.tsindex eba713916f..128ff76a00 100644--- a/packages/api/src/agents/__tests__/initialize.test.ts+++ b/packages/api/src/agents/__tests__/initialize.test.ts@@ -1251,13 +1251,11 @@ describe('initializeAgent — skill `allowed-tools` union (Phase 6)', () => {expect(definedNames).not.toContain('mcp__broken__tool');});- it('falls through to empty toolDefinitions when BOTH the union and base-only loadTools calls return undefined', async () => {+ it('falls back to host-provided skill authoring tools when BOTH loadTools calls return undefined', async () => {/* Worst-case silent-failure path: production loaders catch errorsand return undefined. If the agent's own tools fail to load AND- the retry without extras also fails, we have nothing to give the- LLM. The current behavior is to fall through to the `?? {}`- fallback rather than throw — pinning that contract here so the- turn doesn't crash hard but the agent simply has no tools. */+ the retry without extras also fails, loaded registry tools drop out,+ but host-provided file authoring remains available for skill access. */const { agent, req, res, loadTools, db } = createMocks();agent.tools = ['web_search'];const { Types } = await import('mongoose');@@ -1283,16 +1281,18 @@ describe('initializeAgent — skill `allowed-tools` union (Phase 6)', () => {allowedProviders: new Set([Providers.OPENAI]),isInitialAgent: true,accessibleSkillIds: [skillId],+ skillAuthoringAvailable: true,manualSkills: ['broken-skill'],},{ ...db, listSkillsByAccess: emptyListSkillsByAccess, getSkillByName },);- /* Two attempts (initial + retry), both undefined → empty fallback.- The agent gets no tool definitions for the turn but does NOT- crash; downstream code handles the empty case. */+ /* Two attempts (initial + retry), both undefined. Registry-backed tools+ fall away, but read/create/edit_file are registered by the initializer+ so skill authoring still works. */expect(loadTools).toHaveBeenCalledTimes(2);- expect(result.toolDefinitions).toEqual([]);+ const definedNames = result.toolDefinitions?.map((d) => d.name) ?? [];+ expect(definedNames).toEqual(['read_file', 'create_file', 'edit_file']);});it('propagates the error when loadTools fails AND there are no skill-added extras to drop', async () => {@@ -1374,6 +1374,8 @@ describe('initializeAgent — execute_code capability expansion', () => {const names = (result.toolDefinitions ?? []).map((d) => d.name);expect(names).toContain('bash_tool');expect(names).toContain('read_file');+ expect(names).toContain('create_file');+ expect(names).toContain('edit_file');/* The legacy `execute_code` tool def is no longer registered by thispath — the string stays in `agent.tools` as the capability triggerbut never appears in the tool definitions the LLM sees. */@@ -1382,6 +1384,12 @@ describe('initializeAgent — execute_code capability expansion', () => {expect(readFile?.description).toContain('code-execution sandbox');expect(readFile?.description).not.toContain('{skillName}');expect(readFile?.description).not.toContain('SKILL.md');+ const createFile = result.toolDefinitions?.find((d) => d.name === 'create_file');+ expect(createFile?.description).toContain('code-execution sandbox');+ expect(createFile?.description).toContain('/mnt/data/');+ expect(createFile?.description).not.toContain('skills/');+ expect(result.skillAuthoringAvailable).toBe(false);+ expect(result.fileAuthoringToolNames).toEqual(new Set(['create_file', 'edit_file']));});it('upgrades read_file to the skill-aware description when active skills are in scope', async () => {@@ -1422,8 +1430,92 @@ describe('initializeAgent — execute_code capability expansion', () => {const readFile = result.toolDefinitions?.find((d) => d.name === 'read_file');expect(readFile?.description).toContain('{skillName}/{filePath}');+ expect(readFile?.description).toContain('skills/{skillName}/');+ expect(readFile?.description).toContain('SKILL.md');+ const names = result.toolDefinitions?.map((d) => d.name) ?? [];+ expect(names).toContain('skill');+ expect(names).toContain('create_file');+ expect(names).toContain('edit_file');+ });++ it('keeps skill authoring tools hidden for read-only skill access', async () => {+ const { agent, req, res, loadTools, db } = createMocks();+ agent.tools = [];+ const { Types } = await import('mongoose');+ const skillId = new Types.ObjectId();+ const author = { toString: () => req.user?.id } as unknown as import('mongoose').Types.ObjectId;++ const result = await initializeAgent(+ {+ req,+ res,+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set([Providers.OPENAI]),+ isInitialAgent: true,+ codeEnvAvailable: false,+ accessibleSkillIds: [skillId],+ skillAuthoringAvailable: false,+ },+ {+ ...db,+ listSkillsByAccess: jest.fn().mockResolvedValue({+ skills: [+ {+ _id: skillId,+ name: 'read-only-skill',+ description: 'Read-only skill.',+ author,+ },+ ],+ has_more: false,+ after: null,+ }),+ },+ );++ const names = result.toolDefinitions?.map((d) => d.name) ?? [];+ expect(names).toContain('skill');+ expect(names).toContain('read_file');+ expect(names).not.toContain('create_file');+ expect(names).not.toContain('edit_file');+ expect(names).not.toContain('bash_tool');+ expect(result.skillAuthoringAvailable).toBe(false);+ });++ it('registers skill authoring tools for first-time skill creators', async () => {+ const { agent, req, res, loadTools, db } = createMocks();+ agent.tools = [];++ const result = await initializeAgent(+ {+ req,+ res,+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set([Providers.OPENAI]),+ isInitialAgent: true,+ accessibleSkillIds: [],+ skillAuthoringAvailable: true,+ codeEnvAvailable: false,+ },+ db,+ );++ const names = (result.toolDefinitions ?? []).map((d) => d.name);+ expect(names).toContain('create_file');+ expect(names).toContain('edit_file');+ expect(names).toContain('read_file');+ expect(names).not.toContain('bash_tool');+ const readFile = result.toolDefinitions?.find((d) => d.name === 'read_file');+ expect(readFile?.description).toContain('skills/{skillName}/');expect(readFile?.description).toContain('SKILL.md');- expect(result.toolDefinitions?.map((d) => d.name)).toContain('skill');+ const createFile = result.toolDefinitions?.find((d) => d.name === 'create_file');+ expect(createFile?.description).toContain('skills/');+ expect(result.skillAuthoringAvailable).toBe(true);+ expect(result.fileAuthoringToolNames).toEqual(new Set(['create_file', 'edit_file']));});it('does not register bash_tool + read_file when codeEnvAvailable=false', async () => {@@ -1447,6 +1539,8 @@ describe('initializeAgent — execute_code capability expansion', () => {const names = (result.toolDefinitions ?? []).map((d) => d.name);expect(names).not.toContain('bash_tool');expect(names).not.toContain('read_file');+ expect(names).not.toContain('create_file');+ expect(names).not.toContain('edit_file');});it('does not register bash_tool + read_file when agent does not request execute_code', async () => {@@ -1470,6 +1564,8 @@ describe('initializeAgent — execute_code capability expansion', () => {const names = (result.toolDefinitions ?? []).map((d) => d.name);expect(names).not.toContain('bash_tool');expect(names).not.toContain('read_file');+ expect(names).not.toContain('create_file');+ expect(names).not.toContain('edit_file');});it('narrows codeEnvAvailable on InitializedAgent to the per-agent effective value', async () => {diff --git a/packages/api/src/agents/discovery.ts b/packages/api/src/agents/discovery.tsindex 57321a4cb3..a627fdd5dd 100644--- a/packages/api/src/agents/discovery.ts+++ b/packages/api/src/agents/discovery.ts@@ -69,6 +69,11 @@ export interface DiscoverConnectedAgentsParams {* allowlist (or the full accessible set when scoping is disabled).*/computeAccessibleSkillIds?: (agent: Agent) => InitializeAgentParams['accessibleSkillIds'];+ /** Optional per-sub-agent skill authoring gate, paired with the scoped skill IDs. */+ computeSkillAuthoringAvailable?: (+ agent: Agent,+ accessibleSkillIds: InitializeAgentParams['accessibleSkillIds'],+ ) => InitializeAgentParams['skillAuthoringAvailable'];/** Per-user skill active/inactive state, forwarded to each sub-agent. */skillStates?: InitializeAgentParams['skillStates'];/** Default active-on-share flag, forwarded to each sub-agent. */@@ -148,6 +153,7 @@ export async function discoverConnectedAgents(parentMessageId,resourceType = ResourceType.AGENT,computeAccessibleSkillIds,+ computeSkillAuthoringAvailable,skillStates,defaultActiveOnShare,codeEnvAvailable,@@ -237,6 +243,7 @@ export async function discoverConnectedAgents(endpoint: EModelEndpoint.agents,};+ const scopedSkillIds = computeAccessibleSkillIds?.(agent);const config = await initializeAgent({req,@@ -248,7 +255,8 @@ export async function discoverConnectedAgents(parentMessageId,endpointOption: subAgentEndpointOption,allowedProviders,- accessibleSkillIds: computeAccessibleSkillIds?.(agent),+ accessibleSkillIds: scopedSkillIds,+ skillAuthoringAvailable: computeSkillAuthoringAvailable?.(agent, scopedSkillIds),skillStates,defaultActiveOnShare,codeEnvAvailable,diff --git a/packages/api/src/agents/handlers.spec.ts b/packages/api/src/agents/handlers.spec.tsindex 58a3b7287a..b597e8880a 100644--- a/packages/api/src/agents/handlers.spec.ts+++ b/packages/api/src/agents/handlers.spec.ts@@ -51,6 +51,22 @@ function invokeHandler(});}+function invokeHandlerWithConfig(+ handler: ReturnType<typeof createToolExecuteHandler>,+ toolCalls: ToolCallRequest[],+ configurable: Record<string, unknown>,+): Promise<ToolExecuteResult[]> {+ return new Promise((resolve, reject) => {+ const request: ToolExecuteBatchRequest = {+ toolCalls,+ configurable,+ resolve,+ reject,+ };+ handler.handle('on_tool_execute', request);+ });+}+/*** Sentinel non-empty `accessibleSkillIds` for fixtures that need to opt* into "skills are effectively in scope". The `read_file` handler short-@@ -334,6 +350,7 @@ describe('createToolExecuteHandler', () => {const legacyPtcTool = createMockTool(Constants.PROGRAMMATIC_TOOL_CALLING, capturedConfigs);const toolRegistry = new Map([['custom_tool', { name: 'custom_tool' }],+ ['create_file', { name: 'create_file' }],[Constants.PROGRAMMATIC_TOOL_CALLING, { name: Constants.PROGRAMMATIC_TOOL_CALLING }],[Constants.BASH_PROGRAMMATIC_TOOL_CALLING,@@ -344,7 +361,11 @@ describe('createToolExecuteHandler', () => {const ptcToolMap = new Map([['custom_tool', createMockTool('custom_tool', [])]]);const loadTools: ToolExecuteOptions['loadTools'] = jest.fn(async () => ({loadedTools: [legacyPtcTool] as never[],- configurable: { toolRegistry, ptcToolMap },+ configurable: {+ toolRegistry,+ ptcToolMap,+ fileAuthoringToolNames: new Set(['create_file']),+ },}));const handler = createToolExecuteHandler({ loadTools });@@ -362,6 +383,45 @@ describe('createToolExecuteHandler', () => {});});+ describe('host file authoring collisions', () => {+ it('invokes a loaded user tool named create_file when host file authoring is not active', async () => {+ const capturedArgs: unknown[] = [];+ const capturedConfigs: Record<string, unknown>[] = [];+ const tool = createMockTool('create_file', capturedConfigs, { capturedArgs });+ const loadTools: ToolExecuteOptions['loadTools'] = jest.fn(async () => ({+ loadedTools: [tool] as never[],+ configurable: { fileAuthoringToolNames: new Set<string>() },+ }));+ const handler = createToolExecuteHandler({ loadTools });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_user_create_file',+ name: 'create_file',+ args: { custom: true },+ codeSessionContext: {+ session_id: 'ignored-session',+ files: [+ {+ id: 'ignored-file',+ name: 'ignored.txt',+ storage_session_id: 'ignored-session',+ resource_id: 'user-1',+ kind: 'user',+ },+ ],+ },+ },+ ]);++ expect(result.status).toBe('success');+ expect(result.content).toContain('create_file executed');+ expect(capturedArgs).toEqual([{ custom: true }]);+ expect(capturedConfigs[0].session_id).toBeUndefined();+ expect(capturedConfigs[0]._injected_files).toBeUndefined();+ });+ });+describe('tool error handling', () => {it('truncates oversized tool errors in the result and log context', async () => {const oversizedMessage = `tool failed: ${'x'.repeat(15_000)}`;@@ -975,225 +1035,1479 @@ describe('createToolExecuteHandler', () => {});});- describe('read_file sandbox fallback (code-env paths + non-skill segments)', () => {- function makeReadFileHandler(params: {- codeEnvAvailable?: boolean;- accessibleSkillIds?: unknown[];- activeSkillNames?: Set<string>;- skillPrimedIdsByName?: Record<string, string>;- readSandboxFile?: ToolExecuteOptions['readSandboxFile'];- getSkillByName?: ToolExecuteOptions['getSkillByName'];- }) {+ describe('file authoring tools for skills', () => {+ const { Types } = jest.requireActual('mongoose') as typeof import('mongoose');+ const SKILL_ID = new Types.ObjectId();+ const req = {+ user: {+ id: 'user-1',+ _id: new Types.ObjectId(),+ role: 'USER',+ name: 'Test User',+ },+ config: {},+ } as never;++ function makeAuthoringHandler(+ params: Partial<ToolExecuteOptions>,+ configurable?: Record<string, unknown>,+ ) {+ const toolConfigurable = {+ req,+ accessibleSkillIds: skillsInScope(),+ skillAuthoringAvailable: true,+ fileAuthoringToolNames: new Set(['create_file', 'edit_file']),+ ...(configurable ?? {}),+ };const loadTools: ToolExecuteOptions['loadTools'] = jest.fn(async () => ({loadedTools: [],- configurable: {- codeEnvAvailable: params.codeEnvAvailable === true,- accessibleSkillIds: params.accessibleSkillIds ?? [],- activeSkillNames: params.activeSkillNames,- skillPrimedIdsByName: params.skillPrimedIdsByName,- },+ configurable: toolConfigurable,}));return createToolExecuteHandler({loadTools,- getSkillByName: params.getSkillByName,- readSandboxFile: params.readSandboxFile,+ canCreateSkill: jest.fn(async () => true),+ canEditSkill: jest.fn(async () => true),+ grantSkillOwner: jest.fn(async () => undefined),+ ...params,});}- it('routes /mnt/data/ paths to the sandbox fallback when codeEnv is available', async () => {- const readSandboxFile = jest.fn(async () => ({ content: 'hello-world' }));- const handler = makeReadFileHandler({- codeEnvAvailable: true,- accessibleSkillIds: skillsInScope(),- readSandboxFile,+ it('creates a new SKILL.md through create_file', async () => {+ const createSkill = jest.fn(async () => ({+ skill: {+ _id: SKILL_ID,+ name: 'new-skill',+ body: '# New skill',+ version: 1,+ },+ }));+ const grantSkillOwner = jest.fn(async () => undefined);+ const handler = makeAuthoringHandler({+ getSkillByName: jest.fn(async () => null),+ createSkill: createSkill as unknown as ToolExecuteOptions['createSkill'],+ grantSkillOwner,});const [result] = await invokeHandler(handler, [{- id: 'call_mnt_1',- name: Constants.READ_FILE,- args: { file_path: '/mnt/data/sentinel.txt' },- codeSessionContext: {- session_id: 'sess-X',- files: [{ id: 'f1', name: 'sentinel.txt', session_id: 'sess-X' }],+ id: 'call_create_skill',+ name: 'create_file',+ args: {+ file_path: 'skills/new-skill/SKILL.md',+ content:+ '---\nname: new-skill\ndescription: Use for tests\ndisable-model-invocation: true\nallowed-tools:\n - execute_code\n---\n# New skill\n',},- } as unknown as ToolCallRequest,+ },]);- expect(readSandboxFile).toHaveBeenCalledWith({- file_path: '/mnt/data/sentinel.txt',- session_id: 'sess-X',- files: [{ id: 'f1', name: 'sentinel.txt', session_id: 'sess-X' }],- });expect(result.status).toBe('success');- expect(result.content).toContain('hello-world');+ expect(result.content).toContain('Created skills/new-skill/SKILL.md');+ expect(result.artifact).toMatchObject({+ path: 'skills/new-skill/SKILL.md',+ created: true,+ });+ expect(createSkill).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'new-skill',+ description: 'Use for tests',+ frontmatter: expect.objectContaining({+ name: 'new-skill',+ description: 'Use for tests',+ 'disable-model-invocation': true,+ 'allowed-tools': ['execute_code'],+ }),+ }),+ );+ expect(grantSkillOwner).toHaveBeenCalledWith({ req, skillId: SKILL_ID });});- it('returns a clear error for /mnt/data/ when codeEnv is not available', async () => {- const readSandboxFile = jest.fn();- const handler = makeReadFileHandler({- codeEnvAvailable: false,- accessibleSkillIds: skillsInScope(),- readSandboxFile,+ it('adds required SKILL.md frontmatter when create_file only provides markdown', async () => {+ const createSkill = jest.fn(async () => ({+ skill: {+ _id: SKILL_ID,+ name: 'auto-skill',+ body: '# Auto skill',+ version: 1,+ },+ }));+ const handler = makeAuthoringHandler({+ getSkillByName: jest.fn(async () => null),+ createSkill: createSkill as unknown as ToolExecuteOptions['createSkill'],});const [result] = await invokeHandler(handler, [{- id: 'call_mnt_2',- name: Constants.READ_FILE,- args: { file_path: '/mnt/data/sentinel.txt' },+ id: 'call_create_auto_frontmatter',+ name: 'create_file',+ args: {+ file_path: 'skills/auto-skill/SKILL.md',+ content: '# Auto skill\nUse this skill when testing generated frontmatter.\n',+ },},]);- expect(readSandboxFile).not.toHaveBeenCalled();- expect(result.status).toBe('error');- expect(result.errorMessage).toContain('code-execution sandbox path');+ expect(result.status).toBe('success');+ expect(createSkill).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'auto-skill',+ description: 'Use this skill when testing generated frontmatter.',+ body: expect.stringContaining('name: auto-skill'),+ frontmatter: expect.objectContaining({+ name: 'auto-skill',+ description: 'Use this skill when testing generated frontmatter.',+ }),+ }),+ );});- it('falls back to sandbox when first segment is not a known skill name', async () => {- const readSandboxFile = jest.fn(async () => ({ content: 'sandbox-data' }));- const handler = makeReadFileHandler({- codeEnvAvailable: true,- accessibleSkillIds: skillsInScope(),- activeSkillNames: new Set(['only-real-skill']),- readSandboxFile,+ it('preserves block-scalar SKILL.md descriptions when creating skills', async () => {+ const createSkill = jest.fn(async () => ({+ skill: {+ _id: SKILL_ID,+ name: 'block-description-skill',+ body: '# Block description skill',+ version: 1,+ },+ }));+ const handler = makeAuthoringHandler({+ getSkillByName: jest.fn(async () => null),+ createSkill: createSkill as unknown as ToolExecuteOptions['createSkill'],});const [result] = await invokeHandler(handler, [{- id: 'call_unknown_skill',- name: Constants.READ_FILE,- args: { file_path: 'not-a-skill/foo.md' },- codeSessionContext: { session_id: 'sess-Y' },- } as unknown as ToolCallRequest,+ id: 'call_create_block_description',+ name: 'create_file',+ args: {+ file_path: 'skills/block-description-skill/SKILL.md',+ content:+ '---\nname: block-description-skill\ndescription: |-\n Use this skill for long descriptions.\n Keep both lines searchable.\n---\n# Block description skill\n',+ },+ },]);- expect(readSandboxFile).toHaveBeenCalledWith(- expect.objectContaining({ file_path: 'not-a-skill/foo.md', session_id: 'sess-Y' }),- );expect(result.status).toBe('success');- expect(result.content).toContain('sandbox-data');+ expect(createSkill).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'block-description-skill',+ description: 'Use this skill for long descriptions.\nKeep both lines searchable.',+ frontmatter: expect.objectContaining({+ description: 'Use this skill for long descriptions.\nKeep both lines searchable.',+ }),+ }),+ );});- it('does NOT misroute primed skills outside the catalog cap to the sandbox', async () => {- /**- * Regression for review P2 #2: manual ($-popover) and always-apply- * primes are intentionally resolved off the wider `accessibleSkillIds`- * ACL set BEFORE catalog injection — see `resolveManualSkills`.- * A primed skill name can therefore legitimately be ABSENT from- * `activeSkillNames` (which reflects the catalog after the- * `SKILL_CATALOG_LIMIT` cap and active filter).- *- * Without the primed-bypass, the `activeSkillNames` shortcut would- * misroute `read_file("primed-only-skill/references/foo.md")` to- * the sandbox even though the primed skill is in scope and- * `getSkillByName` would resolve it via the pinned `_id`.- */- const primedHex = '507f1f77bcf86cd799439060';- const getSkillByName = jest.fn(async () => ({- _id: primedHex as unknown as never,- name: 'primed-only-skill',- body: '# Primed skill body',- fileCount: 1,+ it('can add bundled files to a newly created skill in the same tool batch', async () => {+ const createdSkill = {+ _id: SKILL_ID,+ name: 'new-skill',+ body: '# New skill',+ fileCount: 0,version: 1,+ };+ const createSkill = jest.fn(async () => ({+ skill: createdSkill,}));- const readSandboxFile = jest.fn();- const getSkillFileByPath = jest.fn(async () => ({- content: 'references content',- mimeType: 'text/markdown',- bytes: 18,- filepath: 'references/foo.md',- source: 'local',- relativePath: 'references/foo.md',- isBinary: false,+ const getSkillByName = jest.fn(async () => createdSkill);+ const saveSkillFileContent = jest.fn(async () => ({+ bytes: 12,+ relativePath: 'references/a.md',}));- const handler = createToolExecuteHandler({- loadTools: jest.fn(async () => ({- loadedTools: [],- configurable: {- codeEnvAvailable: true,- accessibleSkillIds: skillsInScope(),- /* Catalog visible names DO NOT include the primed skill — it's- outside the cap. */- activeSkillNames: new Set(['some-other-skill']),- /* But the prime resolver authorized it for this turn. */- skillPrimedIdsByName: { 'primed-only-skill': primedHex },- },- })),- getSkillByName,- getSkillFileByPath,- readSandboxFile,- });+ const handler = makeAuthoringHandler(+ {+ getSkillByName,+ createSkill: createSkill as unknown as ToolExecuteOptions['createSkill'],+ getSkillFileByPath: jest.fn(async () => null),+ saveSkillFileContent,+ },+ {+ accessibleSkillIds: [],+ skillPrimedIdsByName: {},+ activeSkillNames: new Set(['stale-skill']),+ },+ );- const [result] = await invokeHandler(handler, [+ const results = await invokeHandler(handler, [{- id: 'call_primed_outside_catalog',- name: Constants.READ_FILE,- args: { file_path: 'primed-only-skill/references/foo.md' },+ id: 'call_create_skill',+ name: 'create_file',+ args: {+ file_path: 'skills/new-skill/SKILL.md',+ content: '---\nname: new-skill\ndescription: Use for tests\n---\n# New skill\n',+ },+ },+ {+ id: 'call_create_reference',+ name: 'create_file',+ args: {+ file_path: 'skills/new-skill/references/a.md',+ content: 'reference text',+ },},]);- // Primed skill resolved through the existing skill path, not the- // sandbox shortcut.- expect(readSandboxFile).not.toHaveBeenCalled();- expect(getSkillByName).toHaveBeenCalledWith('primed-only-skill', expect.any(Array), {});- expect(result.status).toBe('success');- expect(result.content).toContain('references content');+ expect(results.map((r) => r.status)).toEqual(['success', 'success']);+ expect(saveSkillFileContent).toHaveBeenCalledWith(+ expect.objectContaining({+ skillId: SKILL_ID,+ relativePath: 'references/a.md',+ content: 'reference text',+ }),+ );});- it('routes through sandbox when skills are not effectively enabled (empty accessibleSkillIds)', async () => {- /**- * `accessibleSkillIds: []` is what `resolveAgentScopedSkillIds`- * returns when the admin capability is off, the ephemeral badge is- * off, or the persisted agent has `skills_enabled !== true`. Skip- * the skill resolver entirely.- */- const readSandboxFile = jest.fn(async () => ({ content: 'sandbox-content' }));- const getSkillByName = jest.fn();- const handler = makeReadFileHandler({- codeEnvAvailable: true,+ it('preserves newly authored skills across later tool execution rounds', async () => {+ const createdSkill = {+ _id: SKILL_ID,+ name: 'round-skill',+ body: '---\nname: round-skill\ndescription: Use for tests\n---\n# Round skill\n',+ fileCount: 0,+ version: 1,+ };+ const runtimeConfigurable = {+ req,accessibleSkillIds: [],- readSandboxFile,+ skillPrimedIdsByName: {},+ activeSkillNames: new Set<string>(),+ skillAuthoringAvailable: true,+ fileAuthoringToolNames: new Set(['create_file', 'edit_file']),+ };+ const staleLoadedConfigurable = {+ req,+ accessibleSkillIds: [],+ skillPrimedIdsByName: {},+ activeSkillNames: new Set<string>(),+ skillAuthoringAvailable: true,+ fileAuthoringToolNames: new Set(['create_file', 'edit_file']),+ };+ let created = false;+ const createSkill = jest.fn(async () => {+ created = true;+ return { skill: createdSkill };+ });+ const getSkillByName = jest.fn(async () => (created ? createdSkill : null));+ const loadTools: ToolExecuteOptions['loadTools'] = jest.fn(async () => ({+ loadedTools: [],+ configurable: staleLoadedConfigurable,+ }));+ const handler = createToolExecuteHandler({+ loadTools,+ canCreateSkill: jest.fn(async () => true),+ canEditSkill: jest.fn(async () => true),+ grantSkillOwner: jest.fn(async () => undefined),getSkillByName,+ createSkill: createSkill as unknown as ToolExecuteOptions['createSkill'],});- const [result] = await invokeHandler(handler, [- {- id: 'call_skills_off',- name: Constants.READ_FILE,- args: { file_path: 'whatever/path.md' },- },- ]);+ const [createResult] = await invokeHandlerWithConfig(+ handler,+ [+ {+ id: 'call_create_round_skill',+ name: 'create_file',+ args: {+ file_path: 'skills/round-skill/SKILL.md',+ content: createdSkill.body,+ },+ },+ ],+ runtimeConfigurable,+ );+ const [readResult] = await invokeHandlerWithConfig(+ handler,+ [+ {+ id: 'call_read_round_skill',+ name: Constants.READ_FILE,+ args: { file_path: 'skills/round-skill/SKILL.md' },+ },+ ],+ runtimeConfigurable,+ );- expect(getSkillByName).not.toHaveBeenCalled();- expect(readSandboxFile).toHaveBeenCalled();- expect(result.status).toBe('success');- expect(result.content).toContain('sandbox-content');+ expect(createResult.status).toBe('success');+ expect(readResult.status).toBe('success');+ expect(readResult.content).toContain('Round skill');+ const lookupCalls = getSkillByName.mock.calls as unknown as Array<+ [string, import('mongoose').Types.ObjectId[], Record<string, unknown>]+ >;+ const lastLookup = lookupCalls[lookupCalls.length - 1];+ const lookupIds = lastLookup?.[1];+ expect(lastLookup?.[0]).toBe('round-skill');+ expect(lookupIds?.[0].toString()).toBe(SKILL_ID.toString());+ expect(lastLookup?.[2]).toEqual({});});- it('returns a clear error when skills off + codeEnv off (nowhere to route)', async () => {- const handler = makeReadFileHandler({- codeEnvAvailable: false,- accessibleSkillIds: [],+ it('refuses to overwrite an existing SKILL.md without overwrite: true', async () => {+ const updateSkill = jest.fn();+ const handler = makeAuthoringHandler({+ getSkillByName: jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'existing-skill',+ body: '# Existing',+ fileCount: 0,+ version: 1,+ })),+ updateSkill,});const [result] = await invokeHandler(handler, [{- id: 'call_no_route',- name: Constants.READ_FILE,- args: { file_path: 'whatever/path.md' },+ id: 'call_create_existing',+ name: 'create_file',+ args: {+ file_path: 'skills/existing-skill/SKILL.md',+ content: '---\nname: existing-skill\ndescription: Use for tests\n---\n# Updated\n',+ },},]);expect(result.status).toBe('error');- expect(result.errorMessage).toContain('Skill files are not available');+ expect(result.errorMessage).toContain('overwrite: true');+ expect(updateSkill).not.toHaveBeenCalled();});- it('still resolves a real skill when activeSkillNames knows the name', async () => {- const getSkillByName = jest.fn(async () => ({- _id: 'real-skill-id' as unknown as never,- name: 'real-skill',- body: '# Real Body',+ it('rehydrates same-author existing skills before refusing a duplicate create_file', async () => {+ const existingSkill = {+ _id: SKILL_ID,+ name: 'stale-skill',+ body: '---\nname: stale-skill\ndescription: Existing\n---\n# Existing\n',+ fileCount: 0,+ version: 3,+ };+ const updateSkill = jest.fn();+ const getAuthorSkillByName = jest.fn(async () => existingSkill);+ const handler = makeAuthoringHandler(+ {+ getSkillByName: jest.fn(async () => null),+ getAuthorSkillByName,+ updateSkill,+ },+ {+ accessibleSkillIds: [],+ skillPrimedIdsByName: {},+ activeSkillNames: new Set(['stale-skill']),+ },+ );++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_duplicate_stale_skill',+ name: 'create_file',+ args: {+ file_path: 'skills/stale-skill/SKILL.md',+ content: '---\nname: stale-skill\ndescription: Replacement\n---\n# Replacement\n',+ },+ },+ ]);++ expect(getAuthorSkillByName).toHaveBeenCalledWith({ req, name: 'stale-skill' });+ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain('already exists');+ expect(result.errorMessage).toContain('edit_file');+ expect(result.errorMessage).toContain('overwrite: true');+ expect(updateSkill).not.toHaveBeenCalled();+ });++ it('does not rehydrate same-author skills outside the current agent scope', async () => {+ const updateSkill = jest.fn();+ const getAuthorSkillByName = jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'excluded-skill',+ body: '---\nname: excluded-skill\ndescription: Excluded\n---\n# Excluded\n',+ fileCount: 0,+ version: 1,+ }));+ const handler = makeAuthoringHandler(+ {+ getSkillByName: jest.fn(async () => null),+ getAuthorSkillByName,+ updateSkill,+ },+ {+ accessibleSkillIds: [],+ skillPrimedIdsByName: {},+ activeSkillNames: new Set(['hidden-recovered-skill']),+ },+ );++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_edit_excluded_skill',+ name: 'edit_file',+ args: {+ file_path: 'skills/excluded-skill/SKILL.md',+ old_text: '# Excluded',+ new_text: '# Changed',+ },+ },+ ]);++ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain('not found or not accessible');+ expect(getAuthorSkillByName).not.toHaveBeenCalled();+ expect(updateSkill).not.toHaveBeenCalled();+ });++ it('does not treat stale same-author recovery as a hidden-skill prime', async () => {+ const updateSkill = jest.fn();+ const handler = makeAuthoringHandler(+ {+ getSkillByName: jest.fn(async () => null),+ getAuthorSkillByName: jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'hidden-recovered-skill',+ body: '---\nname: hidden-recovered-skill\ndescription: Hidden\n---\n# Hidden\n',+ fileCount: 0,+ version: 1,+ disableModelInvocation: true,+ })),+ updateSkill,+ },+ {+ accessibleSkillIds: [],+ skillPrimedIdsByName: {},+ activeSkillNames: new Set(['hidden-recovered-skill']),+ },+ );++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_recovered_hidden_skill',+ name: 'edit_file',+ args: {+ file_path: 'skills/hidden-recovered-skill/SKILL.md',+ old_text: '# Hidden',+ new_text: '# Changed',+ },+ },+ ]);++ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain('cannot be authored by the model');+ expect(updateSkill).not.toHaveBeenCalled();+ });++ it('edits a bundled skill file and returns strategies plus a diff', async () => {+ const saveSkillFileContent = jest.fn(async () => ({+ bytes: 10,+ relativePath: 'references/a.md',+ }));+ const handler = makeAuthoringHandler({+ getSkillByName: jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'edit-skill',+ body: '# Existing',+ fileCount: 1,+ version: 1,+ })),+ getSkillFileByPath: jest.fn(async () => ({+ content: 'hello old\n',+ isBinary: false,+ mimeType: 'text/markdown',+ bytes: 10,+ filepath: '/tmp/a.md',+ source: 'local',+ relativePath: 'references/a.md',+ })),+ saveSkillFileContent,+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_edit_file',+ name: 'edit_file',+ args: {+ file_path: 'skills/edit-skill/references/a.md',+ old_text: 'hello old',+ new_text: 'hello new',+ },+ },+ ]);++ expect(result.status).toBe('success');+ expect(result.content).toContain('Strategies: exact');+ expect(result.content).toContain('-hello old');+ expect(result.content).toContain('+hello new');+ expect(result.artifact).toMatchObject({+ path: 'skills/edit-skill/references/a.md',+ edits: 1,+ strategies: ['exact'],+ });+ expect(saveSkillFileContent).toHaveBeenCalledWith(+ expect.objectContaining({+ relativePath: 'references/a.md',+ content: 'hello new\n',+ mimeType: 'text/markdown',+ }),+ );+ });++ it('rejects bundled skill file writes when the skill version changed after reading', async () => {+ const getSkillByName = jest+ .fn()+ .mockResolvedValueOnce({+ _id: SKILL_ID,+ name: 'edit-skill',+ body: '# Existing',+ fileCount: 1,+ version: 1,+ })+ .mockResolvedValueOnce({+ _id: SKILL_ID,+ name: 'edit-skill',+ body: '# Existing changed elsewhere',+ fileCount: 1,+ version: 2,+ });+ const saveSkillFileContent = jest.fn();+ const handler = makeAuthoringHandler({+ getSkillByName,+ getSkillFileByPath: jest.fn(async () => ({+ content: 'hello old\n',+ isBinary: false,+ mimeType: 'text/markdown',+ bytes: 10,+ filepath: '/tmp/a.md',+ source: 'local',+ relativePath: 'references/a.md',+ })),+ saveSkillFileContent,+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_edit_stale_bundled_file',+ name: 'edit_file',+ args: {+ file_path: 'skills/edit-skill/references/a.md',+ old_text: 'hello old',+ new_text: 'hello new',+ },+ },+ ]);++ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain('changed while editing');+ expect(result.errorMessage).toContain('skills/edit-skill/references/a.md');+ expect(saveSkillFileContent).not.toHaveBeenCalled();+ });++ it('passes structured frontmatter when editing SKILL.md', async () => {+ const oldBody =+ '---\nname: runtime-skill\ndescription: Use before\naction: ignored\n---\n# Body\n';+ const currentBody =+ '---\nname: runtime-skill\ndescription: Use before\nuser-invocable: true\ndisable-model-invocation: false\nallowed-tools:\n - web_search\nalways-apply: true\n---\n# Body\n';+ const updateSkill = jest.fn(async () => ({+ status: 'updated',+ skill: {+ _id: SKILL_ID,+ name: 'runtime-skill',+ body: currentBody,+ version: 2,+ },+ }));+ const handler = makeAuthoringHandler({+ getSkillByName: jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'runtime-skill',+ body: oldBody,+ fileCount: 0,+ version: 1,+ })),+ updateSkill: updateSkill as unknown as ToolExecuteOptions['updateSkill'],+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_edit_skill_md_frontmatter',+ name: 'edit_file',+ args: {+ file_path: 'skills/runtime-skill/SKILL.md',+ old_text: 'description: Use before\naction: ignored',+ new_text:+ 'description: Use before\nuser-invocable: false\ndisable-model-invocation: true\nallowed-tools:\n - execute_code\nalways-apply: true',+ },+ },+ ]);++ expect(result.status).toBe('success');+ expect(updateSkill).toHaveBeenCalledWith(+ expect.objectContaining({+ update: expect.objectContaining({+ alwaysApply: true,+ frontmatter: expect.objectContaining({+ name: 'runtime-skill',+ description: 'Use before',+ 'user-invocable': false,+ 'disable-model-invocation': true,+ 'allowed-tools': ['execute_code'],+ 'always-apply': true,+ }),+ }),+ }),+ );+ });++ it('preserves block-scalar SKILL.md descriptions when editing skills', async () => {+ const oldBody = '---\nname: runtime-skill\ndescription: Use before\n---\n# Runtime skill\n';+ const updateSkill = jest.fn(async () => ({+ status: 'updated',+ skill: {+ _id: SKILL_ID,+ name: 'runtime-skill',+ body: oldBody,+ version: 2,+ },+ }));+ const handler = makeAuthoringHandler({+ getSkillByName: jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'runtime-skill',+ body: oldBody,+ fileCount: 0,+ version: 1,+ })),+ updateSkill: updateSkill as unknown as ToolExecuteOptions['updateSkill'],+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_edit_skill_md_block_description',+ name: 'edit_file',+ args: {+ file_path: 'skills/runtime-skill/SKILL.md',+ old_text: 'description: Use before',+ new_text:+ 'description: |-\n Use this skill for long descriptions.\n Keep both lines searchable.',+ },+ },+ ]);++ expect(result.status).toBe('success');+ expect(updateSkill).toHaveBeenCalledWith(+ expect.objectContaining({+ update: expect.objectContaining({+ description: 'Use this skill for long descriptions.\nKeep both lines searchable.',+ frontmatter: expect.objectContaining({+ description: 'Use this skill for long descriptions.\nKeep both lines searchable.',+ }),+ }),+ }),+ );+ });++ it('rejects edit_file attempts to rename a skill through SKILL.md frontmatter', async () => {+ const oldBody = '---\nname: runtime-skill\ndescription: Use before\n---\n# Runtime skill\n';+ const updateSkill = jest.fn();+ const handler = makeAuthoringHandler({+ getSkillByName: jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'runtime-skill',+ body: oldBody,+ fileCount: 0,+ version: 1,+ })),+ updateSkill: updateSkill as unknown as ToolExecuteOptions['updateSkill'],+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_edit_skill_md_name',+ name: 'edit_file',+ args: {+ file_path: 'skills/runtime-skill/SKILL.md',+ old_text: 'name: runtime-skill',+ new_text: 'name: dev-toolkit',+ },+ },+ ]);++ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain(+ 'frontmatter name "dev-toolkit" must match path skill name "runtime-skill"',+ );+ expect(result.errorMessage).toContain('edit_file cannot rename skills');+ expect(updateSkill).not.toHaveBeenCalled();+ });++ it('fails loudly when edit_file old_text is ambiguous', async () => {+ const saveSkillFileContent = jest.fn();+ const handler = makeAuthoringHandler({+ getSkillByName: jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'ambiguous-skill',+ body: '# Existing',+ fileCount: 1,+ version: 1,+ })),+ getSkillFileByPath: jest.fn(async () => ({+ content: 'same\nsame\n',+ isBinary: false,+ mimeType: 'text/markdown',+ bytes: 10,+ filepath: '/tmp/a.md',+ source: 'local',+ relativePath: 'references/a.md',+ })),+ saveSkillFileContent,+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_edit_ambiguous',+ name: 'edit_file',+ args: {+ file_path: 'skills/ambiguous-skill/references/a.md',+ old_text: 'same',+ new_text: 'different',+ },+ },+ ]);++ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain('matched 2 locations');+ expect(saveSkillFileContent).not.toHaveBeenCalled();+ });++ it('blocks authoring hidden skills unless they were primed this turn', async () => {+ const updateSkill = jest.fn();+ const handler = makeAuthoringHandler(+ {+ getSkillByName: jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'hidden-skill',+ body: '---\nname: hidden-skill\ndescription: Hidden\n---\n# Hidden\n',+ fileCount: 0,+ version: 1,+ disableModelInvocation: true,+ })),+ updateSkill: updateSkill as unknown as ToolExecuteOptions['updateSkill'],+ },+ {+ skillPrimedIdsByName: {},+ activeSkillNames: new Set(['hidden-skill']),+ },+ );++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_edit_hidden_skill',+ name: 'edit_file',+ args: {+ file_path: 'skills/hidden-skill/SKILL.md',+ old_text: '# Hidden',+ new_text: '# Changed',+ },+ },+ ]);++ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain('cannot be authored by the model');+ expect(updateSkill).not.toHaveBeenCalled();+ });++ it('allows authoring a hidden skill that was primed this turn', async () => {+ const updateSkill = jest.fn(async () => ({+ status: 'updated',+ skill: {+ _id: SKILL_ID,+ name: 'primed-hidden-skill',+ body: '---\nname: primed-hidden-skill\ndescription: Hidden\n---\n# Changed\n',+ version: 2,+ },+ }));+ const handler = makeAuthoringHandler(+ {+ getSkillByName: jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'primed-hidden-skill',+ body: '---\nname: primed-hidden-skill\ndescription: Hidden\n---\n# Hidden\n',+ fileCount: 0,+ version: 1,+ disableModelInvocation: true,+ })),+ updateSkill: updateSkill as unknown as ToolExecuteOptions['updateSkill'],+ },+ {+ skillPrimedIdsByName: { 'primed-hidden-skill': SKILL_ID.toString() },+ activeSkillNames: new Set(['primed-hidden-skill']),+ },+ );++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_edit_primed_hidden_skill',+ name: 'edit_file',+ args: {+ file_path: 'skills/primed-hidden-skill/SKILL.md',+ old_text: '# Hidden',+ new_text: '# Changed',+ },+ },+ ]);++ expect(result.status).toBe('success');+ expect(updateSkill).toHaveBeenCalled();+ });++ it('overwrites large bundled skill files without reading the old content', async () => {+ const saveSkillFileContent = jest.fn(async () => ({+ bytes: 11,+ relativePath: 'references/large.md',+ }));+ const getStrategyFunctions = jest.fn();+ const handler = makeAuthoringHandler({+ getSkillByName: jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'large-skill',+ body: '# Existing',+ fileCount: 1,+ version: 1,+ })),+ getSkillFileByPath: jest.fn(async () => ({+ isBinary: false,+ mimeType: 'text/markdown',+ bytes: 600 * 1024,+ filepath: '/tmp/large.md',+ source: 'local',+ relativePath: 'references/large.md',+ })),+ getStrategyFunctions,+ saveSkillFileContent,+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_overwrite_large',+ name: 'create_file',+ args: {+ file_path: 'skills/large-skill/references/large.md',+ content: 'replacement',+ overwrite: true,+ },+ },+ ]);++ expect(result.status).toBe('success');+ expect(result.content).toContain('Updated skills/large-skill/references/large.md');+ expect(saveSkillFileContent).toHaveBeenCalledWith(+ expect.objectContaining({+ relativePath: 'references/large.md',+ content: 'replacement',+ }),+ );+ expect(getStrategyFunctions).not.toHaveBeenCalled();+ });++ it('serializes same-file authoring calls so later edits see prior writes', async () => {+ let storedContent = 'one\n';+ const saveSkillFileContent = jest.fn(async ({ content }: { content: string }) => {+ storedContent = content;+ return {+ bytes: Buffer.byteLength(content, 'utf8'),+ relativePath: 'references/a.md',+ };+ });+ const handler = makeAuthoringHandler({+ getSkillByName: jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'serial-skill',+ body: '# Existing',+ fileCount: 1,+ version: 1,+ })),+ getSkillFileByPath: jest.fn(async () => ({+ content: storedContent,+ isBinary: false,+ mimeType: 'text/markdown',+ bytes: Buffer.byteLength(storedContent, 'utf8'),+ filepath: '/tmp/a.md',+ source: 'local',+ relativePath: 'references/a.md',+ })),+ saveSkillFileContent,+ });++ const results = await invokeHandler(handler, [+ {+ id: 'call_edit_one',+ name: 'edit_file',+ args: {+ file_path: 'skills/serial-skill/references/a.md',+ old_text: 'one',+ new_text: 'two',+ },+ },+ {+ id: 'call_edit_two',+ name: 'edit_file',+ args: {+ file_path: 'skills/serial-skill/references/a.md',+ old_text: 'two',+ new_text: 'three',+ },+ },+ ]);++ expect(results.map((r) => r.status)).toEqual(['success', 'success']);+ expect(storedContent).toBe('three\n');+ expect(saveSkillFileContent).toHaveBeenCalledTimes(2);+ });+ });++ describe('file authoring tools for code-exec sandbox files', () => {+ const req = {+ user: { id: 'user-1' },+ config: {},+ } as never;++ function makeSandboxAuthoringHandler(params: Partial<ToolExecuteOptions>) {+ const loadTools: ToolExecuteOptions['loadTools'] = jest.fn(async () => ({+ loadedTools: [],+ configurable: {+ req,+ codeEnvAvailable: true,+ accessibleSkillIds: [],+ skillAuthoringAvailable: false,+ fileAuthoringToolNames: new Set(['create_file', 'edit_file']),+ },+ }));+ return createToolExecuteHandler({+ loadTools,+ ...params,+ });+ }++ it('creates a sandbox file when it does not already exist', async () => {+ const readSandboxFile = jest.fn(async () => {+ throw new Error('cat: /mnt/data/new.txt: No such file or directory');+ });+ const writeSandboxFile = jest.fn(async () => ({+ stdout: 'WROTE 11 bytes to /mnt/data/new.txt\n',+ session_id: 'sess-new',+ files: [{ id: 'file-new', name: 'new.txt', storage_session_id: 'sess-new' }],+ }));+ const handler = makeSandboxAuthoringHandler({+ readSandboxFile,+ writeSandboxFile,+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_create_sandbox',+ name: 'create_file',+ args: {+ file_path: '/mnt/data/new.txt',+ content: 'hello world',+ },+ codeSessionContext: {+ session_id: 'sess-prev',+ files: [{ id: 'f1', name: 'input.csv', session_id: 'sess-prev' }],+ },+ } as unknown as ToolCallRequest,+ ]);++ expect(result.status).toBe('success');+ expect(result.content).toContain('Created /mnt/data/new.txt');+ expect(result.artifact).toMatchObject({+ path: '/mnt/data/new.txt',+ created: true,+ session_id: 'sess-new',+ files: [{ id: 'file-new', name: 'new.txt' }],+ });+ expect(writeSandboxFile).toHaveBeenCalledWith({+ file_path: '/mnt/data/new.txt',+ content: 'hello world',+ session_id: 'sess-prev',+ files: [{ id: 'f1', name: 'input.csv', session_id: 'sess-prev' }],+ req,+ });+ });++ it('refuses to overwrite an existing sandbox file without overwrite: true', async () => {+ const writeSandboxFile = jest.fn();+ const handler = makeSandboxAuthoringHandler({+ readSandboxFile: jest.fn(async () => ({ content: 'existing text\n' })),+ writeSandboxFile,+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_create_existing_sandbox',+ name: 'create_file',+ args: {+ file_path: '/mnt/data/existing.txt',+ content: 'new text\n',+ },+ },+ ]);++ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain('overwrite: true');+ expect(writeSandboxFile).not.toHaveBeenCalled();+ });++ it('edits a sandbox file and returns diff, strategies, and session artifact', async () => {+ const writeSandboxFile = jest.fn(async () => ({+ stdout: 'WROTE 10 bytes to /mnt/data/edit.txt\n',+ session_id: 'sess-edit',+ files: [{ id: 'file-edit', name: 'edit.txt', storage_session_id: 'sess-edit' }],+ }));+ const handler = makeSandboxAuthoringHandler({+ readSandboxFile: jest.fn(async () => ({ content: 'alpha old\n' })),+ writeSandboxFile,+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_edit_sandbox',+ name: 'edit_file',+ args: {+ file_path: '/mnt/data/edit.txt',+ old_text: 'alpha old',+ new_text: 'alpha new',+ },+ },+ ]);++ expect(result.status).toBe('success');+ expect(result.content).toContain('Strategies: exact');+ expect(result.content).toContain('-alpha old');+ expect(result.content).toContain('+alpha new');+ expect(result.artifact).toMatchObject({+ path: '/mnt/data/edit.txt',+ edits: 1,+ strategies: ['exact'],+ session_id: 'sess-edit',+ });+ expect(writeSandboxFile).toHaveBeenCalledWith(+ expect.objectContaining({+ file_path: '/mnt/data/edit.txt',+ content: 'alpha new\n',+ }),+ );+ });++ it('propagates newly created sandbox sessions to queued same-path authoring calls', async () => {+ let readCount = 0;+ let writeCount = 0;+ const sandboxFiles = [+ { id: 'file-queued', name: 'queued.txt', storage_session_id: 'sess-new' },+ ];+ const readSandboxFile = jest.fn(+ async ({+ session_id,+ files,+ }: {+ session_id?: string;+ files?: Array<{ id: string; name: string; storage_session_id?: string }>;+ }) => {+ readCount++;+ if (readCount === 1) {+ throw new Error('cat: /mnt/data/queued.txt: No such file or directory');+ }++ expect(session_id).toBe('sess-new');+ expect(files).toEqual(sandboxFiles);+ return { content: 'hello world\n' };+ },+ );+ const writeSandboxFile = jest.fn(+ async ({+ session_id,+ files,+ content,+ }: {+ session_id?: string;+ files?: Array<{ id: string; name: string; storage_session_id?: string }>;+ content: string;+ }) => {+ writeCount++;+ if (writeCount === 1) {+ expect(session_id).toBeUndefined();+ expect(files).toBeUndefined();+ expect(content).toBe('hello world\n');+ } else {+ expect(session_id).toBe('sess-new');+ expect(files).toEqual(sandboxFiles);+ expect(content).toBe('goodbye world\n');+ }+ return {+ stdout: `WROTE ${content.length} bytes to /mnt/data/queued.txt\n`,+ session_id: 'sess-new',+ files: sandboxFiles,+ };+ },+ );+ const handler = makeSandboxAuthoringHandler({+ readSandboxFile,+ writeSandboxFile,+ });++ const results = await invokeHandler(handler, [+ {+ id: 'call_create_queued_sandbox',+ name: 'create_file',+ args: {+ file_path: '/mnt/data/queued.txt',+ content: 'hello world\n',+ },+ },+ {+ id: 'call_edit_queued_sandbox',+ name: 'edit_file',+ args: {+ file_path: '/mnt/data/queued.txt',+ old_text: 'hello world',+ new_text: 'goodbye world',+ },+ },+ ]);++ expect(results.map((result) => result.status)).toEqual(['success', 'success']);+ expect(readSandboxFile).toHaveBeenCalledTimes(2);+ expect(writeSandboxFile).toHaveBeenCalledTimes(2);+ });++ it('rejects non-skill paths when code execution is unavailable', async () => {+ const writeSandboxFile = jest.fn();+ const loadTools: ToolExecuteOptions['loadTools'] = jest.fn(async () => ({+ loadedTools: [],+ configurable: {+ req,+ codeEnvAvailable: false,+ accessibleSkillIds: [],+ skillAuthoringAvailable: false,+ fileAuthoringToolNames: new Set(['create_file', 'edit_file']),+ },+ }));+ const handler = createToolExecuteHandler({+ loadTools,+ writeSandboxFile,+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_no_code_env_authoring',+ name: 'create_file',+ args: {+ file_path: '/mnt/data/nope.txt',+ content: 'nope',+ },+ },+ ]);++ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain('code execution enabled');+ expect(writeSandboxFile).not.toHaveBeenCalled();+ });++ it('rejects skills/ paths for code-exec-only agents', async () => {+ const createSkill = jest.fn();+ const writeSandboxFile = jest.fn();+ const handler = makeSandboxAuthoringHandler({+ getSkillByName: jest.fn(async () => null),+ createSkill: createSkill as unknown as ToolExecuteOptions['createSkill'],+ writeSandboxFile,+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_code_only_skill_path',+ name: 'create_file',+ args: {+ file_path: 'skills/nope/SKILL.md',+ content: '---\nname: nope\ndescription: Nope\n---\n# Nope\n',+ },+ },+ ]);++ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain('Skill file authoring is not available');+ expect(createSkill).not.toHaveBeenCalled();+ expect(writeSandboxFile).not.toHaveBeenCalled();+ });+ });++ describe('read_file sandbox fallback (code-env paths + non-skill segments)', () => {+ function makeReadFileHandler(params: {+ codeEnvAvailable?: boolean;+ accessibleSkillIds?: unknown[];+ activeSkillNames?: Set<string>;+ skillPrimedIdsByName?: Record<string, string>;+ skillAuthoringAvailable?: boolean;+ req?: unknown;+ readSandboxFile?: ToolExecuteOptions['readSandboxFile'];+ getSkillByName?: ToolExecuteOptions['getSkillByName'];+ getAuthorSkillByName?: ToolExecuteOptions['getAuthorSkillByName'];+ }) {+ const loadTools: ToolExecuteOptions['loadTools'] = jest.fn(async () => ({+ loadedTools: [],+ configurable: {+ req: params.req,+ codeEnvAvailable: params.codeEnvAvailable === true,+ accessibleSkillIds: params.accessibleSkillIds ?? [],+ activeSkillNames: params.activeSkillNames,+ skillPrimedIdsByName: params.skillPrimedIdsByName,+ skillAuthoringAvailable: params.skillAuthoringAvailable === true,+ },+ }));+ return createToolExecuteHandler({+ loadTools,+ getSkillByName: params.getSkillByName,+ getAuthorSkillByName: params.getAuthorSkillByName,+ readSandboxFile: params.readSandboxFile,+ });+ }++ it('routes /mnt/data/ paths to the sandbox fallback when codeEnv is available', async () => {+ const readSandboxFile = jest.fn(async () => ({ content: 'hello-world' }));+ const handler = makeReadFileHandler({+ codeEnvAvailable: true,+ accessibleSkillIds: skillsInScope(),+ readSandboxFile,+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_mnt_1',+ name: Constants.READ_FILE,+ args: { file_path: '/mnt/data/sentinel.txt' },+ codeSessionContext: {+ session_id: 'sess-X',+ files: [{ id: 'f1', name: 'sentinel.txt', session_id: 'sess-X' }],+ },+ } as unknown as ToolCallRequest,+ ]);++ expect(readSandboxFile).toHaveBeenCalledWith({+ file_path: '/mnt/data/sentinel.txt',+ session_id: 'sess-X',+ files: [{ id: 'f1', name: 'sentinel.txt', session_id: 'sess-X' }],+ });+ expect(result.status).toBe('success');+ expect(result.content).toContain('hello-world');+ });++ it('returns a clear error for /mnt/data/ when codeEnv is not available', async () => {+ const readSandboxFile = jest.fn();+ const handler = makeReadFileHandler({+ codeEnvAvailable: false,+ accessibleSkillIds: skillsInScope(),+ readSandboxFile,+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_mnt_2',+ name: Constants.READ_FILE,+ args: { file_path: '/mnt/data/sentinel.txt' },+ },+ ]);++ expect(readSandboxFile).not.toHaveBeenCalled();+ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain('code-execution sandbox path');+ });++ it('falls back to sandbox when first segment is not a known skill name', async () => {+ const readSandboxFile = jest.fn(async () => ({ content: 'sandbox-data' }));+ const handler = makeReadFileHandler({+ codeEnvAvailable: true,+ accessibleSkillIds: skillsInScope(),+ activeSkillNames: new Set(['only-real-skill']),+ readSandboxFile,+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_unknown_skill',+ name: Constants.READ_FILE,+ args: { file_path: 'not-a-skill/foo.md' },+ codeSessionContext: { session_id: 'sess-Y' },+ } as unknown as ToolCallRequest,+ ]);++ expect(readSandboxFile).toHaveBeenCalledWith(+ expect.objectContaining({ file_path: 'not-a-skill/foo.md', session_id: 'sess-Y' }),+ );+ expect(result.status).toBe('success');+ expect(result.content).toContain('sandbox-data');+ });++ it('does NOT misroute primed skills outside the catalog cap to the sandbox', async () => {+ /**+ * Regression for review P2 #2: manual ($-popover) and always-apply+ * primes are intentionally resolved off the wider `accessibleSkillIds`+ * ACL set BEFORE catalog injection — see `resolveManualSkills`.+ * A primed skill name can therefore legitimately be ABSENT from+ * `activeSkillNames` (which reflects the catalog after the+ * `SKILL_CATALOG_LIMIT` cap and active filter).+ *+ * Without the primed-bypass, the `activeSkillNames` shortcut would+ * misroute `read_file("primed-only-skill/references/foo.md")` to+ * the sandbox even though the primed skill is in scope and+ * `getSkillByName` would resolve it via the pinned `_id`.+ */+ const primedHex = '507f1f77bcf86cd799439060';+ const getSkillByName = jest.fn(async () => ({+ _id: primedHex as unknown as never,+ name: 'primed-only-skill',+ body: '# Primed skill body',+ fileCount: 1,+ version: 1,+ }));+ const readSandboxFile = jest.fn();+ const getSkillFileByPath = jest.fn(async () => ({+ content: 'references content',+ mimeType: 'text/markdown',+ bytes: 18,+ filepath: 'references/foo.md',+ source: 'local',+ relativePath: 'references/foo.md',+ isBinary: false,+ }));+ const handler = createToolExecuteHandler({+ loadTools: jest.fn(async () => ({+ loadedTools: [],+ configurable: {+ codeEnvAvailable: true,+ accessibleSkillIds: skillsInScope(),+ /* Catalog visible names DO NOT include the primed skill — it's+ outside the cap. */+ activeSkillNames: new Set(['some-other-skill']),+ /* But the prime resolver authorized it for this turn. */+ skillPrimedIdsByName: { 'primed-only-skill': primedHex },+ },+ })),+ getSkillByName,+ getSkillFileByPath,+ readSandboxFile,+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_primed_outside_catalog',+ name: Constants.READ_FILE,+ args: { file_path: 'primed-only-skill/references/foo.md' },+ },+ ]);++ // Primed skill resolved through the existing skill path, not the+ // sandbox shortcut.+ expect(readSandboxFile).not.toHaveBeenCalled();+ expect(getSkillByName).toHaveBeenCalledWith('primed-only-skill', expect.any(Array), {});+ expect(result.status).toBe('success');+ expect(result.content).toContain('references content');+ });++ it('rehydrates same-author skills when activeSkillNames is stale', async () => {+ const { Types } = jest.requireActual('mongoose') as typeof import('mongoose');+ const skillId = new Types.ObjectId();+ const req = {+ user: {+ id: 'user-1',+ _id: new Types.ObjectId(),+ role: 'USER',+ },+ } as never;+ const recoveredSkill = {+ _id: skillId,+ name: 'stale-catalog-skill',+ body: '# Recovered Body',+ fileCount: 0,+ version: 4,+ };+ const getAuthorSkillByName = jest.fn(async () => recoveredSkill);+ const getSkillByName = jest.fn(async (_name: string, ids: unknown[]) =>+ ids.some((id) => id?.toString() === skillId.toString()) ? recoveredSkill : null,+ );+ const readSandboxFile = jest.fn();+ const handler = makeReadFileHandler({+ req,+ codeEnvAvailable: true,+ skillAuthoringAvailable: true,+ accessibleSkillIds: skillsInScope(),+ activeSkillNames: new Set(['stale-catalog-skill']),+ readSandboxFile,+ getAuthorSkillByName,+ getSkillByName,+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_stale_catalog_skill',+ name: Constants.READ_FILE,+ args: { file_path: 'stale-catalog-skill/SKILL.md' },+ },+ ]);++ expect(getAuthorSkillByName).toHaveBeenCalledWith({ req, name: 'stale-catalog-skill' });+ expect(readSandboxFile).not.toHaveBeenCalled();+ expect(getSkillByName).toHaveBeenCalledWith(+ 'stale-catalog-skill',+ expect.arrayContaining([skillId]),+ expect.objectContaining({ preferModelInvocable: true }),+ );+ expect(result.status).toBe('success');+ expect(result.content).toContain('Recovered Body');+ });++ it('routes through sandbox when skills are not effectively enabled (empty accessibleSkillIds)', async () => {+ /**+ * `accessibleSkillIds: []` is what `resolveAgentScopedSkillIds`+ * returns when the admin capability is off, the ephemeral badge is+ * off, or the persisted agent has `skills_enabled !== true`. Skip+ * the skill resolver entirely.+ */+ const readSandboxFile = jest.fn(async () => ({ content: 'sandbox-content' }));+ const getSkillByName = jest.fn();+ const handler = makeReadFileHandler({+ codeEnvAvailable: true,+ accessibleSkillIds: [],+ readSandboxFile,+ getSkillByName,+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_skills_off',+ name: Constants.READ_FILE,+ args: { file_path: 'whatever/path.md' },+ },+ ]);++ expect(getSkillByName).not.toHaveBeenCalled();+ expect(readSandboxFile).toHaveBeenCalled();+ expect(result.status).toBe('success');+ expect(result.content).toContain('sandbox-content');+ });++ it('returns a clear error when skills off + codeEnv off (nowhere to route)', async () => {+ const handler = makeReadFileHandler({+ codeEnvAvailable: false,+ accessibleSkillIds: [],+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_no_route',+ name: Constants.READ_FILE,+ args: { file_path: 'whatever/path.md' },+ },+ ]);++ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain('Skill files are not available');+ });++ it('still resolves a real skill when activeSkillNames knows the name', async () => {+ const getSkillByName = jest.fn(async () => ({+ _id: 'real-skill-id' as unknown as never,+ name: 'real-skill',+ body: '# Real Body',fileCount: 0,version: 1,}));@@ -1220,6 +2534,66 @@ describe('createToolExecuteHandler', () => {expect(result.content).toContain('Real Body');});+ it('resolves authored skills/{skillName}/... paths without falling back to sandbox', async () => {+ const getSkillByName = jest.fn(async () => ({+ _id: 'real-skill-id' as unknown as never,+ name: 'real-skill',+ body: '# Real Body',+ fileCount: 0,+ version: 1,+ }));+ const readSandboxFile = jest.fn();+ const handler = makeReadFileHandler({+ codeEnvAvailable: true,+ accessibleSkillIds: skillsInScope(),+ activeSkillNames: new Set(['real-skill']),+ readSandboxFile,+ getSkillByName,+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_real_skill_namespace',+ name: Constants.READ_FILE,+ args: { file_path: 'skills/real-skill/SKILL.md' },+ },+ ]);++ expect(getSkillByName).toHaveBeenCalledWith(+ 'real-skill',+ expect.any(Array),+ expect.objectContaining({ preferModelInvocable: true }),+ );+ expect(readSandboxFile).not.toHaveBeenCalled();+ expect(result.status).toBe('success');+ expect(result.content).toContain('File: skills/real-skill/SKILL.md');+ expect(result.content).toContain('Real Body');+ });++ it('does not route explicit skills/ paths to the sandbox when skills are unavailable', async () => {+ const readSandboxFile = jest.fn(async () => ({ content: 'sandbox-content' }));+ const getSkillByName = jest.fn();+ const handler = makeReadFileHandler({+ codeEnvAvailable: true,+ accessibleSkillIds: [],+ readSandboxFile,+ getSkillByName,+ });++ const [result] = await invokeHandler(handler, [+ {+ id: 'call_explicit_skill_namespace_off',+ name: Constants.READ_FILE,+ args: { file_path: 'skills/whatever/SKILL.md' },+ },+ ]);++ expect(getSkillByName).not.toHaveBeenCalled();+ expect(readSandboxFile).not.toHaveBeenCalled();+ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain('Skill files are not available');+ });+it('falls back to sandbox for trailing-slash paths (empty relativePath, codeEnv on)', async () => {/*** Regression for review Finding #4: `read_file("output/")` isdiff --git a/packages/api/src/agents/handlers.ts b/packages/api/src/agents/handlers.tsindex 18eb86c4a3..4306ee1601 100644--- a/packages/api/src/agents/handlers.ts+++ b/packages/api/src/agents/handlers.ts@@ -1,5 +1,7 @@+import yaml from 'js-yaml';+import { Types } from 'mongoose';import { logger } from '@librechat/data-schemas';-import { GraphEvents, Constants, CODE_EXECUTION_TOOLS } from '@librechat/agents';+import { GraphEvents, Constants } from '@librechat/agents';import type {LCTool,EventHandler,@@ -9,15 +11,21 @@ import type {ToolExecuteResult,ToolExecuteBatchRequest,} from '@librechat/agents';-import { Types } from 'mongoose';-import type { CodeEnvRef } from 'librechat-data-provider';import type { StructuredToolInterface } from '@librechat/agents/langchain/tools';+import type { CodeEnvRef } from 'librechat-data-provider';import type { SkillFileRecord } from './skillFiles';import type { ServerRequest } from '~/types';import { logAxiosError, runOutsideTracing } from '~/utils';import { buildSkillPrimeMessage } from './skills';import { cleanCodeToolOutput } from './cleanup';import { primeSkillFiles } from './skillFiles';+import {+ CREATE_FILE_TOOL_NAME,+ EDIT_FILE_TOOL_NAME,+ HOST_FILE_AUTHORING_ARTIFACT_KEY,+ isCodeSessionToolName,+} from './tools';+import { parseFrontmatter } from '../skills/import';export interface ToolEndCallbackData {output: {@@ -82,6 +90,81 @@ export interface ToolExecuteOptions {*/disableModelInvocation?: boolean;} | null>;+ /**+ * Loads a skill by name when the current user is the author. This is a+ * narrow recovery path for freshly-authored skills whose runtime catalog+ * snapshot has not caught up yet; normal skill resolution still goes+ * through `accessibleSkillIds`.+ */+ getAuthorSkillByName?: (params: { req: ServerRequest; name: string }) => Promise<{+ body: string;+ name: string;+ _id: Types.ObjectId;+ version: number;+ fileCount: number;+ disableModelInvocation?: boolean;+ } | null>;+ /** Creates a skill from a tool-authored SKILL.md body. */+ createSkill?: (data: {+ name: string;+ description: string;+ body: string;+ frontmatter?: Record<string, unknown>;+ author: Types.ObjectId;+ authorName: string;+ alwaysApply?: boolean;+ tenantId?: string;+ }) => Promise<{+ skill: {+ _id: Types.ObjectId;+ name: string;+ body: string;+ version: number;+ };+ }>;+ /** Updates a skill body and derived metadata from a tool-authored SKILL.md body. */+ updateSkill?: (params: {+ id: string;+ expectedVersion: number;+ update: {+ body?: string;+ description?: string;+ frontmatter?: Record<string, unknown>;+ alwaysApply?: boolean;+ };+ }) => Promise<+ | {+ status: 'updated';+ skill: { _id: Types.ObjectId; name: string; body: string; version: number };+ }+ | { status: 'conflict'; current: { _id: Types.ObjectId; name: string; version: number } }+ | { status: 'not_found' }+ >;+ /** Checks role-level skill creation permission for the current user. */+ canCreateSkill?: (params: { req: ServerRequest }) => Promise<boolean>;+ /** Checks resource-level edit permission for an existing skill. */+ canEditSkill?: (params: {+ req: ServerRequest;+ skillId: Types.ObjectId | string;+ }) => Promise<boolean>;+ /** Grants SKILL_OWNER to the current user after a tool-created skill is inserted. */+ grantSkillOwner?: (params: {+ req: ServerRequest;+ skillId: Types.ObjectId | string;+ }) => Promise<void>;+ /** Deletes a freshly-created skill if owner-permission setup fails. */+ deleteSkill?: (id: string) => Promise<{ deleted: boolean }>;+ /** Saves or replaces a bundled skill file in configured storage and metadata. */+ saveSkillFileContent?: (params: {+ req: ServerRequest;+ skillId: Types.ObjectId | string;+ relativePath: string;+ content: string;+ mimeType: string;+ }) => Promise<{+ bytes: number;+ relativePath: string;+ }>;/** Lists files bundled with a skill (for code env priming) */listSkillFiles?: (skillId: Types.ObjectId | string) => Promise<SkillFileRecord[]>;/** Storage strategy resolver for skill file streaming */@@ -146,16 +229,37 @@ export interface ToolExecuteOptions {readSandboxFile?: (params: {file_path: string;session_id?: string;- files?: Array<{ id: string; name: string; session_id?: string }>;+ files?: Array<{ id: string; name: string; session_id?: string; storage_session_id?: string }>;req?: ServerRequest;}) => Promise<{ content: string } | null>;+ /**+ * Writes a UTF-8 text file into the code-execution sandbox via the+ * sandbox `/exec` endpoint. Mirrors `readSandboxFile` session forwarding+ * so host-side file-authoring tools can operate in the same sandbox+ * session as `bash_tool` / `read_file`.+ */+ writeSandboxFile?: (params: {+ file_path: string;+ content: string;+ session_id?: string;+ files?: Array<{ id: string; name: string; session_id?: string; storage_session_id?: string }>;+ req?: ServerRequest;+ }) => Promise<{+ stdout?: string;+ stderr?: string;+ session_id?: string;+ files?: Array<{ id: string; name: string; storage_session_id?: string; session_id?: string }>;+ } | null>;}const MAX_READABLE_BYTES = 262_144;const MAX_BINARY_BYTES = 5 * 1024 * 1024;const MAX_CACHE_BYTES = 512 * 1024;+const MAX_AUTHORING_BYTES = 10 * 1024 * 1024;const MAX_TOOL_ERROR_MESSAGE_CHARS = 12_000;const MAX_TOOL_ERROR_STACK_CHARS = 4_000;+const SKILL_FILE_PREFIX = 'skills/';+const SKILL_MD = 'SKILL.md';const IMAGE_MIMES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);@@ -350,6 +454,599 @@ function addLineNumbers(content: string): string {return lines.map((l, i) => `${String(i + 1).padStart(w, ' ')} | ${l}`).join('\n');}+type AuthoringSkill = NonNullable<+ Awaited<ReturnType<NonNullable<ToolExecuteOptions['getSkillByName']>>>+>;++type AuthoringResult = Promise<ToolExecuteResult>;++type ParsedSkillAuthoringPath = {+ skillName: string;+ relativePath: string;+ displayPath: string;+};++type TextEdit = {+ old_text: string;+ new_text: string;+};++type MatchStatus =+ | { status: 'matched'; index: number; length: number; strategy: string }+ | { status: 'none' }+ | { status: 'ambiguous'; strategy: string; count: number };++type LoadedSkillText =+ | { status: 'loaded'; content: string; bytes: number }+ | { status: 'missing' }+ | { status: 'error'; message: string };++type ExistingSkillFile =+ | { status: 'present'; oldContent?: string }+ | { status: 'missing' }+ | { status: 'error'; message: string };++type LoadedSandboxText = LoadedSkillText;++type SandboxSessionContext = {+ session_id?: string;+ files?: Array<{ id: string; name: string; session_id?: string; storage_session_id?: string }>;+};++const MIME_MAP: Readonly<Record<string, string>> = Object.freeze({+ '.md': 'text/markdown',+ '.txt': 'text/plain',+ '.json': 'application/json',+ '.js': 'application/javascript',+ '.mjs': 'application/javascript',+ '.cjs': 'application/javascript',+ '.ts': 'application/typescript',+ '.tsx': 'application/typescript',+ '.jsx': 'application/javascript',+ '.py': 'text/x-python',+ '.sh': 'application/x-sh',+ '.yaml': 'application/yaml',+ '.yml': 'application/yaml',+ '.css': 'text/css',+ '.html': 'text/html',+ '.xml': 'application/xml',+ '.csv': 'text/csv',+ '.toml': 'text/toml',+ '.ini': 'text/ini',+ '.svg': 'image/svg+xml',+});++function errorResult(tc: ToolCallRequest, errorMessage: string): ToolExecuteResult {+ return {+ toolCallId: tc.id,+ status: 'error',+ content: '',+ errorMessage,+ };+}++function successResult(+ tc: ToolCallRequest,+ content: string,+ artifact?: unknown,+): ToolExecuteResult {+ const result: ToolExecuteResult = {+ toolCallId: tc.id,+ status: 'success',+ content,+ };+ if (artifact !== undefined) {+ result.artifact = artifact;+ }+ return result;+}++function guessMimeType(filename: string): string {+ return MIME_MAP[lowercaseExtension(filename)] ?? 'application/octet-stream';+}++function isValidSkillName(value: string): boolean {+ return /^[a-z0-9][a-z0-9-]*$/.test(value);+}++function isValidSkillFileRelativePath(value: string): boolean {+ if (!value || value.length > 500) {+ return false;+ }+ if (value.startsWith('/') || value.startsWith('\\')) {+ return false;+ }+ if (!/^[a-zA-Z0-9._\-/]+$/.test(value)) {+ return false;+ }+ const segments = value.split('/');+ if (segments.some((segment) => segment === '' || segment === '.' || segment === '..')) {+ return false;+ }+ return value !== SKILL_MD && segments[0] !== SKILL_MD;+}++function parseSkillAuthoringPath(filePath: string): ParsedSkillAuthoringPath | string {+ if (!filePath.startsWith(SKILL_FILE_PREFIX)) {+ return `Only skill file paths are supported. Use "skills/{skillName}/SKILL.md" or "skills/{skillName}/{path}".`;+ }++ const rest = filePath.slice(SKILL_FILE_PREFIX.length);+ const slashIdx = rest.indexOf('/');+ const skillName = slashIdx === -1 ? rest : rest.slice(0, slashIdx);+ const relativePath = slashIdx === -1 ? SKILL_MD : rest.slice(slashIdx + 1) || SKILL_MD;++ if (!isValidSkillName(skillName)) {+ return `Invalid skill name "${skillName}". Skill names must be kebab-case.`;+ }+ if (relativePath !== SKILL_MD && !isValidSkillFileRelativePath(relativePath)) {+ return (+ `Invalid skill file path "${relativePath}". ` ++ 'Paths must be relative and cannot contain empty, "." or ".." segments.'+ );+ }++ return {+ skillName,+ relativePath,+ displayPath: `${SKILL_FILE_PREFIX}${skillName}/${relativePath}`,+ };+}++function deriveSkillDescription(body: string, skillName: string): string {+ const fallback = `Use this skill for ${skillName.replace(/-/g, ' ')}.`;+ const headingCandidates: string[] = [];+ for (const line of body.split('\n')) {+ const trimmed = line.trim();+ if (!trimmed) {+ continue;+ }+ const withoutMarkdown = trimmed+ .replace(/^#{1,6}\s+/, '')+ .replace(/^[*>-]\s+/, '')+ .trim();+ if (!withoutMarkdown) {+ continue;+ }+ if (/^#{1,6}\s+/.test(trimmed)) {+ headingCandidates.push(withoutMarkdown);+ continue;+ }+ return truncateMiddle(withoutMarkdown.replace(/\s+/g, ' '), 180);+ }+ const heading = headingCandidates[0];+ return heading ? truncateMiddle(heading.replace(/\s+/g, ' '), 180) : fallback;+}++function splitSkillFrontmatter(content: string):+ | {+ block: string;+ body: string;+ }+ | { error: string }+ | null {+ const trimmed = content.trim();+ if (!trimmed.startsWith('---')) {+ return null;+ }+ const afterOpening = trimmed.slice(3);+ const closingIdx = afterOpening.indexOf('\n---');+ if (closingIdx === -1) {+ return { error: `Invalid ${SKILL_MD} frontmatter: missing closing "---".` };+ }+ const afterClosing = afterOpening.slice(closingIdx + '\n---'.length);+ return {+ block: afterOpening.slice(0, closingIdx),+ body: afterClosing.startsWith('\n') ? afterClosing.slice(1) : afterClosing,+ };+}++function buildSkillMdContent(frontmatter: Record<string, unknown>, body: string): string {+ const dumped = yaml.dump(frontmatter, { lineWidth: -1 }).trimEnd();+ const normalizedBody = body.trimStart();+ return `---\n${dumped}\n---\n${normalizedBody}`;+}++function skillNameMismatchError(frontmatterName: string, skillName: string): string {+ return `${SKILL_MD} frontmatter name "${frontmatterName}" must match path skill name "${skillName}". edit_file cannot rename skills; keep the name unchanged or create a new skills/{newName}/SKILL.md.`;+}++function normalizeSkillMdContent(+ content: string,+ skillName: string,+): { status: 'success'; content: string } | { status: 'error'; error: string } {+ const split = splitSkillFrontmatter(content);+ if (split && 'error' in split) {+ return { status: 'error', error: split.error };+ }++ let normalizedContent = content;+ if (!split) {+ normalizedContent = buildSkillMdContent(+ {+ name: skillName,+ description: deriveSkillDescription(content, skillName),+ },+ content,+ );+ } else {+ const structured = parseStructuredSkillFrontmatter(content);+ if (structured.error) {+ return { status: 'error', error: structured.error };+ }+ const frontmatter = { ...(structured.frontmatter ?? {}) };+ const parsed = parseFrontmatter(content);+ const frontmatterName =+ typeof frontmatter.name === 'string' ? frontmatter.name : parsed.name || undefined;+ if (frontmatterName && frontmatterName !== skillName) {+ return {+ status: 'error',+ error: skillNameMismatchError(frontmatterName, skillName),+ };+ }+ frontmatter.name = skillName;+ const frontmatterDescription =+ typeof frontmatter.description === 'string'+ ? frontmatter.description+ : parsed.description || undefined;+ frontmatter.description =+ frontmatterDescription || deriveSkillDescription(split.body, skillName);+ normalizedContent = buildSkillMdContent(frontmatter, split.body);+ }++ const parsed = parseFrontmatter(normalizedContent);+ if (!parsed.name || !parsed.description) {+ return {+ status: 'error',+ error: `${SKILL_MD} must include YAML frontmatter with "name" and "description".`,+ };+ }+ if (parsed.name !== skillName) {+ return {+ status: 'error',+ error: skillNameMismatchError(parsed.name, skillName),+ };+ }+ if (parsed.invalidBooleans.length > 0) {+ return {+ status: 'error',+ error: parsed.invalidBooleans+ .map((key) => `"${key}" in ${SKILL_MD} frontmatter must be a boolean`)+ .join('; '),+ };+ }+ return { status: 'success', content: normalizedContent };+}++function extractSkillFrontmatterBlock(content: string): string | null {+ const split = splitSkillFrontmatter(content);+ if (!split || 'error' in split) {+ return null;+ }+ return split.block;+}++function parseStructuredSkillFrontmatter(+ content: string,+):+ | { frontmatter?: Record<string, unknown>; error?: undefined }+ | { frontmatter?: undefined; error: string } {+ const block = extractSkillFrontmatterBlock(content);+ if (block == null) {+ return {};+ }+ try {+ const parsed = yaml.load(block);+ if (parsed == null) {+ return { frontmatter: {} };+ }+ if (typeof parsed !== 'object' || Array.isArray(parsed)) {+ return { error: `${SKILL_MD} frontmatter must be a YAML mapping.` };+ }+ return { frontmatter: parsed as Record<string, unknown> };+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ return { error: `Invalid ${SKILL_MD} frontmatter: ${message}` };+ }+}++function parseSkillMdUpdate(content: string): {+ description: string;+ frontmatter?: Record<string, unknown>;+ alwaysApply?: boolean;+} {+ const parsed = parseFrontmatter(content);+ const structured = parseStructuredSkillFrontmatter(content);+ const structuredDescription =+ typeof structured.frontmatter?.description === 'string'+ ? structured.frontmatter.description+ : undefined;+ return {+ description: structuredDescription ?? parsed.description,+ ...(structured.frontmatter !== undefined ? { frontmatter: structured.frontmatter } : {}),+ ...(parsed.alwaysApply !== undefined ? { alwaysApply: parsed.alwaysApply } : {}),+ };+}++function getAuthorInfo(req: ServerRequest): {+ author: Types.ObjectId;+ authorName: string;+ tenantId?: string;+} | null {+ const user = req.user as+ | {+ id?: string;+ _id?: Types.ObjectId | string;+ name?: string;+ username?: string;+ tenantId?: string;+ }+ | undefined;+ if (!user?.id) {+ return null;+ }+ return {+ author: (user._id ?? user.id) as Types.ObjectId,+ authorName: user.name ?? user.username ?? 'Unknown',+ ...(user.tenantId ? { tenantId: user.tenantId } : {}),+ };+}++function normalizeEditArgs(args: {+ old_text?: unknown;+ new_text?: unknown;+ edits?: unknown;+}): TextEdit[] | string {+ if (Array.isArray(args.edits) && args.edits.length > 0) {+ const edits: TextEdit[] = [];+ for (const edit of args.edits) {+ if (!edit || typeof edit !== 'object') {+ return 'Each edit must be an object with old_text and new_text.';+ }+ const entry = edit as { old_text?: unknown; new_text?: unknown };+ if (typeof entry.old_text !== 'string' || typeof entry.new_text !== 'string') {+ return 'Each edit requires string old_text and new_text.';+ }+ if (entry.old_text.length === 0) {+ return 'old_text cannot be empty.';+ }+ edits.push({ old_text: entry.old_text, new_text: entry.new_text });+ }+ return edits;+ }++ if (typeof args.old_text !== 'string' || typeof args.new_text !== 'string') {+ return 'Provide old_text and new_text, or a non-empty edits array.';+ }+ if (args.old_text.length === 0) {+ return 'old_text cannot be empty.';+ }+ return [{ old_text: args.old_text, new_text: args.new_text }];+}++function countExactOccurrences(content: string, needle: string): number[] {+ const indexes: number[] = [];+ let start = 0;+ while (start <= content.length) {+ const index = content.indexOf(needle, start);+ if (index === -1) {+ break;+ }+ indexes.push(index);+ start = index + Math.max(1, needle.length);+ }+ return indexes;+}++function findExactMatch(content: string, needle: string): MatchStatus {+ const matches = countExactOccurrences(content, needle);+ if (matches.length === 1) {+ return { status: 'matched', index: matches[0], length: needle.length, strategy: 'exact' };+ }+ if (matches.length > 1) {+ return { status: 'ambiguous', strategy: 'exact', count: matches.length };+ }+ return { status: 'none' };+}++function lineStarts(content: string): number[] {+ const starts = [0];+ for (let i = 0; i < content.length; i++) {+ if (content[i] === '\n') {+ starts.push(i + 1);+ }+ }+ return starts;+}++function commonIndent(lines: string[]): number {+ const indents = lines+ .filter((line) => line.trim().length > 0)+ .map((line) => {+ const match = /^(\s*)/.exec(line);+ return match ? match[1].length : 0;+ });+ return indents.length > 0 ? Math.min(...indents) : 0;+}++function stripCommonIndent(text: string): string {+ const lines = text.split('\n');+ const indent = commonIndent(lines);+ if (indent === 0) {+ return text;+ }+ return lines.map((line) => line.slice(Math.min(indent, line.length))).join('\n');+}++function findLineWindowMatch(+ content: string,+ needle: string,+ strategy: 'line-trimmed' | 'indentation-flexible',+): MatchStatus {+ const contentLines = content.split('\n');+ const needleLines = needle.split('\n');+ if (needleLines.length > contentLines.length) {+ return { status: 'none' };+ }++ const starts = lineStarts(content);+ const normalizedNeedle =+ strategy === 'line-trimmed'+ ? needleLines.map((line) => line.trimEnd()).join('\n')+ : stripCommonIndent(needle);+ const matches: Array<{ index: number; length: number }> = [];++ for (let i = 0; i <= contentLines.length - needleLines.length; i++) {+ const windowLines = contentLines.slice(i, i + needleLines.length);+ const candidate =+ strategy === 'line-trimmed'+ ? windowLines.map((line) => line.trimEnd()).join('\n')+ : stripCommonIndent(windowLines.join('\n'));+ if (candidate !== normalizedNeedle) {+ continue;+ }+ const index = starts[i];+ const endLine = i + needleLines.length;+ const end = endLine < starts.length ? starts[endLine] - 1 : content.length;+ matches.push({ index, length: end - index });+ }++ if (matches.length === 1) {+ return { status: 'matched', ...matches[0], strategy };+ }+ if (matches.length > 1) {+ return { status: 'ambiguous', strategy, count: matches.length };+ }+ return { status: 'none' };+}++function escapeRegExp(value: string): string {+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++function findWhitespaceNormalizedMatch(content: string, needle: string): MatchStatus {+ const tokens = needle.trim().split(/\s+/).filter(Boolean);+ if (tokens.length < 2) {+ return { status: 'none' };+ }+ const pattern = tokens.map(escapeRegExp).join('\\s+');+ const regex = new RegExp(pattern, 'g');+ const matches: Array<{ index: number; length: number }> = [];+ let match: RegExpExecArray | null;+ while ((match = regex.exec(content)) != null) {+ matches.push({ index: match.index, length: match[0].length });+ if (match[0].length === 0) {+ regex.lastIndex += 1;+ }+ }+ if (matches.length === 1) {+ return { status: 'matched', ...matches[0], strategy: 'whitespace-normalized' };+ }+ if (matches.length > 1) {+ return { status: 'ambiguous', strategy: 'whitespace-normalized', count: matches.length };+ }+ return { status: 'none' };+}++function findReplacementMatch(content: string, needle: string): MatchStatus {+ const exact = findExactMatch(content, needle);+ if (exact.status !== 'none') {+ return exact;+ }+ const lineTrimmed = findLineWindowMatch(content, needle, 'line-trimmed');+ if (lineTrimmed.status !== 'none') {+ return lineTrimmed;+ }+ const whitespaceNormalized = findWhitespaceNormalizedMatch(content, needle);+ if (whitespaceNormalized.status !== 'none') {+ return whitespaceNormalized;+ }+ return findLineWindowMatch(content, needle, 'indentation-flexible');+}++function applyTextEdits(+ content: string,+ edits: TextEdit[],+): { content: string; strategies: string[] } {+ let working = content;+ const strategies: string[] = [];++ for (const edit of edits) {+ const match = findReplacementMatch(working, edit.old_text);+ if (match.status === 'none') {+ throw new Error('old_text did not match the file content.');+ }+ if (match.status === 'ambiguous') {+ throw new Error(+ `old_text matched ${match.count} locations with ${match.strategy}; make it unique before retrying.`,+ );+ }+ working =+ working.slice(0, match.index) + edit.new_text + working.slice(match.index + match.length);+ strategies.push(match.strategy);+ }++ return { content: working, strategies };+}++function formatRange(start: number, count: number): string {+ return count === 1 ? String(start) : `${start},${count}`;+}++function createUnifiedDiff(filePath: string, oldContent: string, newContent: string): string {+ if (oldContent === newContent) {+ return '';+ }++ const oldLines = oldContent.split('\n');+ const newLines = newContent.split('\n');+ let prefix = 0;+ while (+ prefix < oldLines.length &&+ prefix < newLines.length &&+ oldLines[prefix] === newLines[prefix]+ ) {+ prefix += 1;+ }++ let oldSuffix = oldLines.length - 1;+ let newSuffix = newLines.length - 1;+ while (+ oldSuffix >= prefix &&+ newSuffix >= prefix &&+ oldLines[oldSuffix] === newLines[newSuffix]+ ) {+ oldSuffix -= 1;+ newSuffix -= 1;+ }++ const contextStart = Math.max(0, prefix - 3);+ const oldContextEnd = Math.min(oldLines.length - 1, oldSuffix + 3);+ const newContextEnd = Math.min(newLines.length - 1, newSuffix + 3);+ const oldCount = oldContextEnd >= contextStart ? oldContextEnd - contextStart + 1 : 0;+ const newCount = newContextEnd >= contextStart ? newContextEnd - contextStart + 1 : 0;+ const lines = [+ `--- a/${filePath}`,+ `+++ b/${filePath}`,+ `@@ -${formatRange(contextStart + 1, oldCount)} +${formatRange(contextStart + 1, newCount)} @@`,+ ];++ for (let i = contextStart; i < prefix; i++) {+ lines.push(` ${oldLines[i]}`);+ }+ for (let i = prefix; i <= oldSuffix; i++) {+ lines.push(`-${oldLines[i]}`);+ }+ for (let i = prefix; i <= newSuffix; i++) {+ lines.push(`+${newLines[i]}`);+ }+ for (let i = oldSuffix + 1; i <= oldContextEnd; i++) {+ lines.push(` ${oldLines[i]}`);+ }++ return lines.join('\n');+}+/*** Extensions whose contents `read_file` must never serialize as text. `cat`* on a PNG inside the sandbox returns the raw bytes as stdout, JSON-encoded@@ -542,9 +1239,7 @@ async function handleSandboxFileFallback(};}- const ctx = tc.codeSessionContext as- | { session_id?: string; files?: Array<{ id: string; name: string; session_id?: string }> }- | undefined;+ const ctx = tc.codeSessionContext as SandboxSessionContext | undefined;try {const result = await readSandboxFile({file_path: filePath,@@ -604,74 +1299,1235 @@ async function handleSandboxFileFallback(}}-async function handleReadFileCall(+function sandboxSessionContext(tc: ToolCallRequest,- mergedConfigurable: Record<string, unknown>,- options: ToolExecuteOptions,- req?: ServerRequest,-): Promise<ToolExecuteResult> {- const { getSkillByName, getSkillFileByPath, getStrategyFunctions, updateSkillFileContent } =- options;- const args = tc.args as { file_path?: string };- if (!args.file_path) {- return {- toolCallId: tc.id,- status: 'error',- content: '',- errorMessage: 'file_path is required',+ override?: SandboxSessionContext,+): SandboxSessionContext | undefined {+ return override ?? (tc.codeSessionContext as SandboxSessionContext | undefined);+}++function cloneSandboxSessionContext(+ context: SandboxSessionContext | undefined,+): SandboxSessionContext {+ return {+ ...(context?.session_id ? { session_id: context.session_id } : {}),+ ...(context?.files ? { files: context.files.map((file) => ({ ...file })) } : {}),+ };+}++function mergeSandboxSessionArtifact(+ context: SandboxSessionContext,+ artifact: ToolExecuteResult['artifact'],+): void {+ if (!artifact || typeof artifact !== 'object') {+ return;+ }+ const value = artifact as {+ session_id?: unknown;+ files?: unknown;+ };+ if (typeof value.session_id === 'string' && value.session_id.length > 0) {+ context.session_id = value.session_id;+ }+ if (!Array.isArray(value.files)) {+ return;+ }++ const files: SandboxSessionContext['files'] = [];+ 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;};+ 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 }+ : {}),+ });}+ if (files.length > 0) {+ context.files = files;+ }+}- const codeEnvAvailable = mergedConfigurable?.codeEnvAvailable === true;- const accessibleIds = (mergedConfigurable?.accessibleSkillIds as Types.ObjectId[]) ?? [];- /**- * `accessibleSkillIds` is the resolver's authoritative output (admin- * capability AND ACL access AND ephemeral badge / persisted- * `skills_enabled`). Empty ⇒ skills are not effectively in scope, so we- * skip skill resolution entirely and route to the sandbox fallback when- * the agent has code-execution available.- */- const skillsEffectivelyEnabled = accessibleIds.length > 0;+function isSandboxMissingFileError(error: unknown): boolean {+ const message = getThrownValueMessage(error).toLowerCase();+ return (+ message.includes('no such file or directory') ||+ message.includes('cannot access') ||+ message.includes('not found')+ );+}- /**- * Short-circuit absolute code-env paths: the path can never be a skill- * reference (skill paths are relative `{skillName}/...`), and consulting- * `getSkillByName` would just burn a DB round-trip on a guaranteed miss.- */- if (args.file_path.startsWith('/mnt/data/')) {- if (codeEnvAvailable) {- return handleSandboxFileFallback(tc, args.file_path, options, req);+function invalidSandboxAuthoringPath(filePath: string): string | null {+ if (filePath.length === 0) {+ return 'file_path is required';+ }+ if (filePath.includes('\0')) {+ return 'file_path cannot contain NUL bytes';+ }+ if (filePath.endsWith('/')) {+ return `File path "${filePath}" points to a directory. Provide a file path.`;+ }+ return null;+}++async function loadSandboxTextForAuthoring({+ filePath,+ tc,+ options,+ req,+ sandboxContext,+}: {+ filePath: string;+ tc: ToolCallRequest;+ options: ToolExecuteOptions;+ req?: ServerRequest;+ sandboxContext?: SandboxSessionContext;+}): Promise<LoadedSandboxText> {+ const ext = lowercaseExtension(filePath);+ if (BINARY_EXTENSIONS_NEVER_READABLE.has(ext)) {+ return { status: 'error', message: buildBinaryFileError(filePath, ext) };+ }+ if (!options.readSandboxFile) {+ return {+ status: 'error',+ message: `Sandbox file reading is not configured. Use \`bash_tool\` to inspect "${filePath}".`,+ };+ }++ const ctx = sandboxSessionContext(tc, sandboxContext);+ try {+ const result = await options.readSandboxFile({+ file_path: filePath,+ session_id: ctx?.session_id,+ files: ctx?.files,+ ...(req ? { req } : {}),+ });+ if (!result || result.content == null) {+ return {+ status: 'error',+ message: `Failed to read "${filePath}" from the code-execution sandbox.`,+ };+ }+ if (looksBinary(result.content)) {+ return {+ status: 'error',+ message: `"${filePath}" appears to be binary and cannot be edited as text.`,+ };+ }+ if (Buffer.byteLength(result.content, 'utf8') > MAX_AUTHORING_BYTES) {+ return {+ status: 'error',+ message: `File "${filePath}" is too large to edit directly (${Buffer.byteLength(+ result.content,+ 'utf8',+ )} bytes, limit: ${MAX_AUTHORING_BYTES}).`,+ };}return {- toolCallId: tc.id,+ status: 'loaded',+ content: result.content,+ bytes: Buffer.byteLength(result.content, 'utf8'),+ };+ } catch (error) {+ if (isSandboxMissingFileError(error)) {+ return { status: 'missing' };+ }+ const message = getThrownValueMessage(error);+ logger.warn(`[file_authoring] Sandbox read failed for "${filePath}": ${message}`);+ return {status: 'error',- content: '',- errorMessage: `Path "${args.file_path}" is a code-execution sandbox path, but this agent does not have code execution enabled.`,+ message: `Error reading "${filePath}" from the code-execution sandbox: ${message}.`,};}+}- const slashIdx = args.file_path.indexOf('/');- if (slashIdx < 1) {- if (codeEnvAvailable) {- return handleSandboxFileFallback(tc, args.file_path, options, req);+async function writeSandboxTextForAuthoring({+ tc,+ options,+ req,+ filePath,+ content,+ oldContent,+ created,+ sandboxContext,+}: {+ tc: ToolCallRequest;+ options: ToolExecuteOptions;+ req?: ServerRequest;+ filePath: string;+ content: string;+ oldContent?: string;+ created: boolean;+ sandboxContext?: SandboxSessionContext;+}): AuthoringResult {+ if (!options.writeSandboxFile) {+ return errorResult(+ tc,+ `Sandbox file writing is not configured. Use \`bash_tool\` to write "${filePath}".`,+ );+ }+ const ctx = sandboxSessionContext(tc, sandboxContext);+ let writeResult: Awaited<ReturnType<NonNullable<ToolExecuteOptions['writeSandboxFile']>>>;+ try {+ writeResult = await options.writeSandboxFile({+ file_path: filePath,+ content,+ session_id: ctx?.session_id,+ files: ctx?.files,+ ...(req ? { req } : {}),+ });+ } catch (error) {+ const message = getThrownValueMessage(error);+ logger.warn(`[file_authoring] Sandbox write failed for "${filePath}": ${message}`);+ return errorResult(+ tc,+ `Error writing "${filePath}" to the code-execution sandbox: ${message}.`,+ );+ }+ if (!writeResult) {+ return errorResult(tc, `Failed to write "${filePath}" to the code-execution sandbox.`);+ }++ const diff =+ oldContent !== undefined ? createUnifiedDiff(filePath, oldContent, content) : undefined;+ const action = created ? 'Created' : 'Updated';+ const summary = `${action} ${filePath} (${content.length} chars).`;+ return successResult(tc, diff ? `${summary}\n\n${diff}` : summary, {+ path: filePath,+ [HOST_FILE_AUTHORING_ARTIFACT_KEY]: true,+ bytes_written: Buffer.byteLength(content, 'utf8'),+ created,+ ...(diff ? { diff } : {}),+ ...(writeResult.session_id ? { session_id: writeResult.session_id } : {}),+ ...(writeResult.files ? { files: writeResult.files } : {}),+ });+}++async function resolveSkillForAuthoring(+ skillName: string,+ mergedConfigurable: Record<string, unknown>,+ options: ToolExecuteOptions,+): Promise<AuthoringSkill | null> {+ const { getSkillByName } = options;+ if (!getSkillByName) {+ return null;+ }++ const skillPrimedIdsByName =+ (mergedConfigurable?.skillPrimedIdsByName as Record<string, string> | undefined) ?? {};+ const primedIdString = skillPrimedIdsByName[skillName];+ if (primedIdString) {+ return await getSkillByName(skillName, [new Types.ObjectId(primedIdString)], {});+ }++ const accessibleIds = (mergedConfigurable?.accessibleSkillIds as Types.ObjectId[]) ?? [];+ if (accessibleIds.length === 0) {+ return null;+ }++ return await getSkillByName(skillName, accessibleIds, { preferModelInvocable: true });+}++async function resolveAuthorSkillForCurrentUser({+ skillName,+ mergedConfigurable,+ sourceConfigurable,+ options,+ req,+}: {+ skillName: string;+ mergedConfigurable: Record<string, unknown>;+ sourceConfigurable?: Record<string, unknown>;+ options: ToolExecuteOptions;+ req?: ServerRequest;+}): Promise<AuthoringSkill | null> {+ if (!req || !options.getAuthorSkillByName) {+ return null;+ }+ if (!isSkillKnownToCurrentRun(skillName, mergedConfigurable)) {+ return null;+ }+ const skill = await options.getAuthorSkillByName({ req, name: skillName });+ if (!skill) {+ return null;+ }+ rememberAuthoredSkill([mergedConfigurable, sourceConfigurable], skill, { prime: false });+ return skill;+}++function isDuplicateSkillNameError(error: unknown): boolean {+ const maybeError = error as { code?: string | number; message?: string } | undefined;+ return (+ maybeError?.code === 11000 ||+ /skill with name .* already exists/i.test(maybeError?.message ?? '')+ );+}++function isSkillAuthoringAvailable(mergedConfigurable: Record<string, unknown>): boolean {+ return mergedConfigurable.skillAuthoringAvailable === true;+}++function getFileAuthoringToolNames(+ mergedConfigurable: Record<string, unknown>,+): Set<string> | undefined {+ const names = mergedConfigurable.fileAuthoringToolNames;+ return names instanceof Set ? (names as Set<string>) : undefined;+}++function isHostFileAuthoringToolCall(+ toolName: string,+ mergedConfigurable: Record<string, unknown>,+): boolean {+ return getFileAuthoringToolNames(mergedConfigurable)?.has(toolName) === true;+}++function isCodeSessionAwareToolCall(+ toolName: string,+ mergedConfigurable: Record<string, unknown>,+): boolean {+ return isCodeSessionToolName(toolName, getFileAuthoringToolNames(mergedConfigurable));+}++function isSkillPrimedForAuthoring(+ skillName: string,+ mergedConfigurable: Record<string, unknown>,+): boolean {+ const skillPrimedIdsByName =+ (mergedConfigurable.skillPrimedIdsByName as Record<string, string> | undefined) ?? {};+ return typeof skillPrimedIdsByName[skillName] === 'string';+}++function isSkillKnownToCurrentRun(+ skillName: string,+ mergedConfigurable: Record<string, unknown>,+): boolean {+ if (isSkillPrimedForAuthoring(skillName, mergedConfigurable)) {+ return true;+ }+ const activeSkillNames = mergedConfigurable.activeSkillNames;+ return activeSkillNames instanceof Set && activeSkillNames.has(skillName);+}++function hiddenSkillAuthoringDenied(+ tc: ToolCallRequest,+ skill: AuthoringSkill | null,+ skillName: string,+ mergedConfigurable: Record<string, unknown>,+): ToolExecuteResult | null {+ if (+ skill?.disableModelInvocation !== true ||+ isSkillPrimedForAuthoring(skillName, mergedConfigurable)+ ) {+ return null;+ }+ return errorResult(tc, `Skill "${skillName}" cannot be authored by the model`);+}++function mergeAccessibleSkillIds(+ base: Record<string, unknown> | undefined,+ loaded: Record<string, unknown> | undefined,+): Types.ObjectId[] | undefined {+ const values = [+ ...(Array.isArray(loaded?.accessibleSkillIds)+ ? (loaded.accessibleSkillIds as Types.ObjectId[])+ : []),+ ...(Array.isArray(base?.accessibleSkillIds)+ ? (base.accessibleSkillIds as Types.ObjectId[])+ : []),+ ];+ if (values.length === 0) {+ return undefined;+ }+ const seen = new Set<string>();+ const merged: Types.ObjectId[] = [];+ for (const value of values) {+ const key = value.toString();+ if (seen.has(key)) {+ continue;+ }+ seen.add(key);+ merged.push(value);+ }+ return merged;+}++function mergeSkillPrimedIdsByName(+ base: Record<string, unknown> | undefined,+ loaded: Record<string, unknown> | undefined,+): Record<string, string> | undefined {+ const loadedPrimed = loaded?.skillPrimedIdsByName as Record<string, string> | undefined;+ const basePrimed = base?.skillPrimedIdsByName as Record<string, string> | undefined;+ const merged = { ...(loadedPrimed ?? {}), ...(basePrimed ?? {}) };+ return Object.keys(merged).length > 0 ? merged : undefined;+}++function mergeActiveSkillNames(+ base: Record<string, unknown> | undefined,+ loaded: Record<string, unknown> | undefined,+): Set<string> | undefined {+ const names = new Set<string>();+ const loadedNames = loaded?.activeSkillNames;+ if (loadedNames instanceof Set) {+ for (const name of loadedNames) {+ names.add(name);+ }+ }+ const baseNames = base?.activeSkillNames;+ if (baseNames instanceof Set) {+ for (const name of baseNames) {+ names.add(name);+ }+ }+ return names.size > 0 ? names : undefined;+}++function mergeToolConfigurables(+ base: Record<string, unknown> | undefined,+ loaded: Record<string, unknown> | undefined,+): Record<string, unknown> {+ const merged = { ...base, ...loaded };+ const accessibleSkillIds = mergeAccessibleSkillIds(base, loaded);+ if (accessibleSkillIds) {+ merged.accessibleSkillIds = accessibleSkillIds;+ }+ const skillPrimedIdsByName = mergeSkillPrimedIdsByName(base, loaded);+ if (skillPrimedIdsByName) {+ merged.skillPrimedIdsByName = skillPrimedIdsByName;+ }+ const activeSkillNames = mergeActiveSkillNames(base, loaded);+ if (activeSkillNames) {+ merged.activeSkillNames = activeSkillNames;+ }+ return merged;+}++function rememberAuthoredSkill(+ configurables: Array<Record<string, unknown> | undefined>,+ skill: { _id: Types.ObjectId; name: string },+ options: { prime?: boolean } = {},+): void {+ const prime = options.prime !== false;+ const idString = skill._id.toString();+ for (const configurable of configurables) {+ if (!configurable) {+ continue;+ }++ const accessibleIds = Array.isArray(configurable.accessibleSkillIds)+ ? (configurable.accessibleSkillIds as Types.ObjectId[])+ : [];+ if (!Array.isArray(configurable.accessibleSkillIds)) {+ configurable.accessibleSkillIds = accessibleIds;+ }+ if (!accessibleIds.some((id) => id.toString() === idString)) {+ accessibleIds.push(skill._id);+ }++ if (prime) {+ const primedIds =+ (configurable.skillPrimedIdsByName as Record<string, string> | undefined) ?? {};+ primedIds[skill.name] = idString;+ configurable.skillPrimedIdsByName = primedIds;+ }++ const activeSkillNames = configurable.activeSkillNames as Set<string> | undefined;+ if (activeSkillNames) {+ activeSkillNames.add(skill.name);+ } else {+ configurable.activeSkillNames = new Set([skill.name]);+ }+ }+}++async function ensureCanEditSkill(+ tc: ToolCallRequest,+ options: ToolExecuteOptions,+ req: ServerRequest | undefined,+ skillId: Types.ObjectId | string,+): Promise<ToolExecuteResult | null> {+ if (!req) {+ return errorResult(tc, 'Skill file editing is not configured for this request.');+ }+ if (!options.canEditSkill) {+ return errorResult(tc, 'Skill file editing is not configured.');+ }+ const allowed = await options.canEditSkill({ req, skillId });+ return allowed ? null : errorResult(tc, 'Insufficient permissions to edit this skill.');+}++async function ensureCanCreateSkill(+ tc: ToolCallRequest,+ options: ToolExecuteOptions,+ req: ServerRequest | undefined,+): Promise<ToolExecuteResult | null> {+ if (!req) {+ return errorResult(tc, 'Skill creation is not configured for this request.');+ }+ if (!options.canCreateSkill) {+ return errorResult(tc, 'Skill creation is not configured.');+ }+ const allowed = await options.canCreateSkill({ req });+ return allowed ? null : errorResult(tc, 'Insufficient permissions to create skills.');+}++async function loadSkillFileTextForAuthoring({+ skill,+ relativePath,+ options,+ req,+}: {+ skill: AuthoringSkill;+ relativePath: string;+ options: ToolExecuteOptions;+ req?: ServerRequest;+}): Promise<LoadedSkillText> {+ if (relativePath === SKILL_MD) {+ return {+ status: 'loaded',+ content: skill.body ?? '',+ bytes: Buffer.byteLength(skill.body ?? '', 'utf8'),+ };+ }++ const { getSkillFileByPath, getStrategyFunctions, updateSkillFileContent } = options;+ if (!getSkillFileByPath) {+ return { status: 'error', message: 'Skill file reading is not configured.' };+ }++ const file = await getSkillFileByPath(skill._id, relativePath);+ if (!file) {+ return { status: 'missing' };+ }+ if (file.isBinary === true) {+ return { status: 'error', message: `File "${relativePath}" is binary and cannot be edited.` };+ }+ if (file.content != null && file.content !== '') {+ return {+ status: 'loaded',+ content: file.content,+ bytes: Buffer.byteLength(file.content, 'utf8'),+ };+ }+ if (file.bytes > MAX_CACHE_BYTES) {+ return {+ status: 'error',+ message: `File "${relativePath}" is too large to edit directly (${file.bytes} bytes, limit: ${MAX_CACHE_BYTES}).`,+ };+ }+ if (!getStrategyFunctions || !req) {+ return { status: 'error', message: 'Storage access is not configured.' };+ }++ const strategy = getStrategyFunctions(file.source);+ if (!strategy.getDownloadStream) {+ return { status: 'error', message: 'Download is not supported for this storage backend.' };+ }++ const stream = await strategy.getDownloadStream(req, file.filepath);+ const chunks: Uint8Array[] = [];+ let streamedBytes = 0;+ for await (const chunk of stream as AsyncIterable<Uint8Array>) {+ streamedBytes += chunk.byteLength;+ if (streamedBytes > MAX_CACHE_BYTES) {+ if (+ 'destroy' in stream &&+ typeof (stream as NodeJS.ReadableStream & { destroy?: () => void }).destroy === 'function'+ ) {+ (stream as NodeJS.ReadableStream & { destroy: () => void }).destroy();+ }+ return {+ status: 'error',+ message: `File "${relativePath}" exceeded edit limit (${MAX_CACHE_BYTES} bytes).`,+ };+ }+ chunks.push(chunk);+ }++ const buffer = Buffer.concat(chunks);+ const checkLen = Math.min(buffer.length, 8192);+ for (let i = 0; i < checkLen; i++) {+ if (buffer[i] === 0) {+ if (updateSkillFileContent) {+ updateSkillFileContent(skill._id, relativePath, { isBinary: true }).catch(+ (err: unknown) => {+ logAxiosError({+ message: '[loadSkillFileTextForAuthoring] cache write failed',+ error: err,+ });+ },+ );+ }+ return { status: 'error', message: `File "${relativePath}" is binary and cannot be edited.` };+ }+ }++ const text = buffer.toString('utf-8');+ if (updateSkillFileContent) {+ updateSkillFileContent(skill._id, relativePath, { content: text, isBinary: false }).catch(+ (err: unknown) => {+ logAxiosError({+ message: '[loadSkillFileTextForAuthoring] cache write failed',+ error: err,+ });+ },+ );+ }+ return { status: 'loaded', content: text, bytes: buffer.length };+}++async function inspectBundledSkillFileForCreate({+ skill,+ relativePath,+ options,+ req,+}: {+ skill: AuthoringSkill;+ relativePath: string;+ options: ToolExecuteOptions;+ req?: ServerRequest;+}): Promise<ExistingSkillFile> {+ const { getSkillFileByPath } = options;+ if (!getSkillFileByPath) {+ return { status: 'error', message: 'Skill file reading is not configured.' };+ }++ const file = await getSkillFileByPath(skill._id, relativePath);+ if (!file) {+ return { status: 'missing' };+ }+ if (file.isBinary === true || file.bytes > MAX_CACHE_BYTES) {+ return { status: 'present' };+ }+ if (file.content != null && file.content !== '') {+ return { status: 'present', oldContent: file.content };+ }+ if (!options.getStrategyFunctions || !req) {+ return { status: 'present' };+ }++ const loaded = await loadSkillFileTextForAuthoring({+ skill,+ relativePath,+ options,+ req,+ });+ if (loaded.status === 'missing') {+ return { status: 'missing' };+ }+ if (loaded.status === 'error') {+ return { status: 'present' };+ }+ return { status: 'present', oldContent: loaded.content };+}++async function ensureBundledSkillVersionCurrent({+ tc,+ options,+ skill,+ displayPath,+}: {+ tc: ToolCallRequest;+ options: ToolExecuteOptions;+ skill: AuthoringSkill;+ displayPath: string;+}): Promise<ToolExecuteResult | null> {+ if (!options.getSkillByName) {+ return null;+ }++ const current = await options.getSkillByName(skill.name, [skill._id], {});+ if (!current) {+ return errorResult(tc, `Skill "${skill.name}" not found or not accessible.`);+ }+ if (current.version !== skill.version) {+ return errorResult(+ tc,+ `Skill "${skill.name}" changed while editing. Re-read ${displayPath} and retry.`,+ );+ }+ return null;+}++async function writeSkillMd({+ tc,+ options,+ req,+ mergedConfigurable,+ sourceConfigurable,+ skill,+ skillName,+ content,+}: {+ tc: ToolCallRequest;+ options: ToolExecuteOptions;+ req?: ServerRequest;+ mergedConfigurable: Record<string, unknown>;+ sourceConfigurable?: Record<string, unknown>;+ skill: AuthoringSkill | null;+ skillName: string;+ content: string;+}): AuthoringResult {+ const normalized = normalizeSkillMdContent(content, skillName);+ if (normalized.status === 'error') {+ return errorResult(tc, normalized.error);+ }+ content = normalized.content;+ const structured = parseStructuredSkillFrontmatter(content);+ if (structured.error) {+ return errorResult(tc, structured.error);+ }++ if (!skill) {+ const createDenied = await ensureCanCreateSkill(tc, options, req);+ if (createDenied) {+ return createDenied;+ }+ if (!req || !options.createSkill || !options.grantSkillOwner) {+ return errorResult(tc, 'Skill creation is not configured.');+ }+ const author = getAuthorInfo(req);+ if (!author) {+ return errorResult(tc, 'Authentication required to create a skill.');+ }+ const parsed = parseSkillMdUpdate(content);+ let result: Awaited<ReturnType<NonNullable<ToolExecuteOptions['createSkill']>>>;+ try {+ result = await options.createSkill({+ name: skillName,+ description: parsed.description,+ body: content,+ ...(parsed.frontmatter !== undefined ? { frontmatter: parsed.frontmatter } : {}),+ author: author.author,+ authorName: author.authorName,+ ...(parsed.alwaysApply !== undefined ? { alwaysApply: parsed.alwaysApply } : {}),+ ...(author.tenantId ? { tenantId: author.tenantId } : {}),+ });+ } catch (error) {+ if (isDuplicateSkillNameError(error)) {+ return errorResult(+ tc,+ `Skill "${skillName}" already exists for this author. It cannot be created again or overwritten blindly. Read or enable the existing skill, then use edit_file for targeted changes, or choose a new skill name.`,+ );+ }+ throw error;+ }+ try {+ await options.grantSkillOwner({ req, skillId: result.skill._id });+ } catch (error) {+ if (options.deleteSkill) {+ await options.deleteSkill(result.skill._id.toString()).catch((rollbackError: unknown) => {+ logger.error('[create_file] Failed to roll back skill after permission error', {+ rollbackError,+ });+ });+ }+ throw error;+ }+ rememberAuthoredSkill([mergedConfigurable, sourceConfigurable], result.skill);+ return successResult(+ tc,+ `Created ${SKILL_FILE_PREFIX}${skillName}/${SKILL_MD} (${content.length} chars).`,+ {+ path: `${SKILL_FILE_PREFIX}${skillName}/${SKILL_MD}`,+ bytes_written: Buffer.byteLength(content, 'utf8'),+ created: true,+ },+ );+ }++ const editDenied = await ensureCanEditSkill(tc, options, req, skill._id);+ if (editDenied) {+ return editDenied;+ }+ if (!options.updateSkill) {+ return errorResult(tc, 'Skill updating is not configured.');+ }+ const parsedUpdate = parseSkillMdUpdate(content);+ const result = await options.updateSkill({+ id: skill._id.toString(),+ expectedVersion: skill.version,+ update: {+ body: content,+ description: parsedUpdate.description,+ ...(parsedUpdate.frontmatter !== undefined ? { frontmatter: parsedUpdate.frontmatter } : {}),+ ...(parsedUpdate.alwaysApply !== undefined ? { alwaysApply: parsedUpdate.alwaysApply } : {}),+ },+ });+ if (result.status === 'conflict') {+ return errorResult(+ tc,+ `Skill "${skillName}" changed while editing. Re-read ${SKILL_FILE_PREFIX}${skillName}/${SKILL_MD} and retry.`,+ );+ }+ if (result.status === 'not_found') {+ return errorResult(tc, `Skill "${skillName}" not found or not accessible.`);+ }++ const diff = createUnifiedDiff(+ `${SKILL_FILE_PREFIX}${skillName}/${SKILL_MD}`,+ skill.body,+ content,+ );+ const summary = `Updated ${SKILL_FILE_PREFIX}${skillName}/${SKILL_MD} (${content.length} chars).`;+ return successResult(tc, diff ? `${summary}\n\n${diff}` : summary, {+ path: `${SKILL_FILE_PREFIX}${skillName}/${SKILL_MD}`,+ bytes_written: Buffer.byteLength(content, 'utf8'),+ created: false,+ ...(diff ? { diff } : {}),+ });+}++async function writeBundledSkillFile({+ tc,+ options,+ req,+ skill,+ relativePath,+ displayPath,+ content,+ oldContent,+ created,+}: {+ tc: ToolCallRequest;+ options: ToolExecuteOptions;+ req?: ServerRequest;+ skill: AuthoringSkill;+ relativePath: string;+ displayPath: string;+ content: string;+ oldContent?: string;+ created: boolean;+}): AuthoringResult {+ const editDenied = await ensureCanEditSkill(tc, options, req, skill._id);+ if (editDenied) {+ return editDenied;+ }+ if (!req || !options.saveSkillFileContent) {+ return errorResult(tc, 'Skill file writing is not configured.');+ }+ const staleDenied = await ensureBundledSkillVersionCurrent({+ tc,+ options,+ skill,+ displayPath,+ });+ if (staleDenied) {+ return staleDenied;+ }++ await options.saveSkillFileContent({+ req,+ skillId: skill._id,+ relativePath,+ content,+ mimeType: guessMimeType(relativePath),+ });+ const diff =+ oldContent !== undefined ? createUnifiedDiff(displayPath, oldContent, content) : undefined;+ const action = created ? 'Created' : 'Updated';+ const summary = `${action} ${displayPath} (${content.length} chars).`;+ return successResult(tc, diff ? `${summary}\n\n${diff}` : summary, {+ path: displayPath,+ bytes_written: Buffer.byteLength(content, 'utf8'),+ created,+ ...(diff ? { diff } : {}),+ });+}++async function handleSandboxCreateFileCall({+ tc,+ options,+ req,+ filePath,+ content,+ overwrite,+ sandboxContext,+}: {+ tc: ToolCallRequest;+ options: ToolExecuteOptions;+ req?: ServerRequest;+ filePath: string;+ content: string;+ overwrite: boolean;+ sandboxContext?: SandboxSessionContext;+}): AuthoringResult {+ const pathError = invalidSandboxAuthoringPath(filePath);+ if (pathError) {+ return errorResult(tc, pathError);+ }++ const current = await loadSandboxTextForAuthoring({+ filePath,+ tc,+ options,+ req,+ sandboxContext,+ });+ if (current.status === 'error') {+ return errorResult(tc, current.message);+ }+ if (current.status === 'loaded' && !overwrite) {+ return errorResult(tc, 'File already exists. Pass overwrite: true to replace.');+ }++ return await writeSandboxTextForAuthoring({+ tc,+ options,+ req,+ filePath,+ content,+ oldContent: current.status === 'loaded' ? current.content : undefined,+ created: current.status === 'missing',+ sandboxContext,+ });+}++async function handleSandboxEditFileCall({+ tc,+ options,+ req,+ filePath,+ edits,+ sandboxContext,+}: {+ tc: ToolCallRequest;+ options: ToolExecuteOptions;+ req?: ServerRequest;+ filePath: string;+ edits: TextEdit[];+ sandboxContext?: SandboxSessionContext;+}): AuthoringResult {+ const pathError = invalidSandboxAuthoringPath(filePath);+ if (pathError) {+ return errorResult(tc, pathError);+ }++ const current = await loadSandboxTextForAuthoring({+ filePath,+ tc,+ options,+ req,+ sandboxContext,+ });+ if (current.status === 'missing') {+ return errorResult(tc, `File not found: "${filePath}"`);+ }+ if (current.status === 'error') {+ return errorResult(tc, current.message);+ }++ let edited: { content: string; strategies: string[] };+ try {+ edited = applyTextEdits(current.content, edits);+ } catch (error) {+ return errorResult(tc, error instanceof Error ? error.message : 'Failed to edit file');+ }+ if (Buffer.byteLength(edited.content, 'utf8') > MAX_AUTHORING_BYTES) {+ return errorResult(tc, `edited content exceeds ${MAX_AUTHORING_BYTES} byte limit`);+ }++ const result = await writeSandboxTextForAuthoring({+ tc,+ options,+ req,+ filePath,+ content: edited.content,+ oldContent: current.content,+ created: false,+ sandboxContext,+ });+ if (result.status === 'success') {+ result.artifact = {+ ...(typeof result.artifact === 'object' && result.artifact ? result.artifact : {}),+ edits: edits.length,+ strategies: edited.strategies,+ };+ result.content = `${String(result.content)}\n\nStrategies: ${edited.strategies.join(', ')}`;+ }+ return result;+}++async function handleCreateFileCall(+ tc: ToolCallRequest,+ mergedConfigurable: Record<string, unknown>,+ options: ToolExecuteOptions,+ req?: ServerRequest,+ sourceConfigurable?: Record<string, unknown>,+ sandboxContext?: SandboxSessionContext,+): AuthoringResult {+ const args = tc.args as { file_path?: unknown; content?: unknown; overwrite?: unknown };+ if (typeof args.file_path !== 'string' || args.file_path.length === 0) {+ return errorResult(tc, 'file_path is required');+ }+ if (typeof args.content !== 'string') {+ return errorResult(tc, 'content is required');+ }+ if (Buffer.byteLength(args.content, 'utf8') > MAX_AUTHORING_BYTES) {+ return errorResult(tc, `content exceeds ${MAX_AUTHORING_BYTES} byte limit`);+ }++ const overwrite = args.overwrite === true;+ if (!args.file_path.startsWith(SKILL_FILE_PREFIX)) {+ if (mergedConfigurable?.codeEnvAvailable !== true) {+ return errorResult(+ tc,+ `Path "${args.file_path}" is not a skill file, and this agent does not have code execution enabled.`,+ );+ }+ return await handleSandboxCreateFileCall({+ tc,+ options,+ req,+ filePath: args.file_path,+ content: args.content,+ overwrite,+ sandboxContext,+ });+ }++ const parsed = parseSkillAuthoringPath(args.file_path);+ if (typeof parsed === 'string') {+ return errorResult(tc, parsed);+ }+ if (!isSkillAuthoringAvailable(mergedConfigurable)) {+ return errorResult(tc, 'Skill file authoring is not available for this agent.');+ }++ let skill = await resolveSkillForAuthoring(parsed.skillName, mergedConfigurable, options);+ if (!skill) {+ skill = await resolveAuthorSkillForCurrentUser({+ skillName: parsed.skillName,+ mergedConfigurable,+ sourceConfigurable,+ options,+ req,+ });+ }+ const hiddenDenied = hiddenSkillAuthoringDenied(tc, skill, parsed.skillName, mergedConfigurable);+ if (hiddenDenied) {+ return hiddenDenied;+ }+ if (parsed.relativePath === SKILL_MD) {+ if (skill && !overwrite) {+ return errorResult(+ tc,+ `Skill "${parsed.skillName}" already exists. Use edit_file for targeted changes, or pass overwrite: true only if replacing the entire ${parsed.displayPath} is intended.`,+ );}+ return await writeSkillMd({+ tc,+ options,+ req,+ mergedConfigurable,+ sourceConfigurable,+ skill,+ skillName: parsed.skillName,+ content: args.content,+ });+ }++ if (!skill) {+ return errorResult(tc, `Skill "${parsed.skillName}" not found or not accessible.`);+ }++ const current = await inspectBundledSkillFileForCreate({+ skill,+ relativePath: parsed.relativePath,+ options,+ req,+ });+ if (current.status === 'error') {+ return errorResult(tc, current.message);+ }+ if (current.status === 'present' && !overwrite) {+ return errorResult(tc, 'File already exists. Pass overwrite: true to replace.');+ }+ return await writeBundledSkillFile({+ tc,+ options,+ req,+ skill,+ relativePath: parsed.relativePath,+ displayPath: parsed.displayPath,+ content: args.content,+ oldContent: current.status === 'present' ? current.oldContent : undefined,+ created: current.status === 'missing',+ });+}++async function handleEditFileCall(+ tc: ToolCallRequest,+ mergedConfigurable: Record<string, unknown>,+ options: ToolExecuteOptions,+ req?: ServerRequest,+ sandboxContext?: SandboxSessionContext,+): AuthoringResult {+ const args = tc.args as {+ file_path?: unknown;+ old_text?: unknown;+ new_text?: unknown;+ edits?: unknown;+ };+ if (typeof args.file_path !== 'string' || args.file_path.length === 0) {+ return errorResult(tc, 'file_path is required');+ }++ const edits = normalizeEditArgs(args);+ if (typeof edits === 'string') {+ return errorResult(tc, edits);+ }++ if (!args.file_path.startsWith(SKILL_FILE_PREFIX)) {+ if (mergedConfigurable?.codeEnvAvailable !== true) {+ return errorResult(+ tc,+ `Path "${args.file_path}" is not a skill file, and this agent does not have code execution enabled.`,+ );+ }+ return await handleSandboxEditFileCall({+ tc,+ options,+ req,+ filePath: args.file_path,+ edits,+ sandboxContext,+ });+ }++ const parsed = parseSkillAuthoringPath(args.file_path);+ if (typeof parsed === 'string') {+ return errorResult(tc, parsed);+ }+ if (!isSkillAuthoringAvailable(mergedConfigurable)) {+ return errorResult(tc, 'Skill file authoring is not available for this agent.');+ }++ let skill = await resolveSkillForAuthoring(parsed.skillName, mergedConfigurable, options);+ if (!skill) {+ skill = await resolveAuthorSkillForCurrentUser({+ skillName: parsed.skillName,+ mergedConfigurable,+ options,+ req,+ });+ }+ if (!skill) {+ return errorResult(tc, `Skill "${parsed.skillName}" not found or not accessible.`);+ }+ const hiddenDenied = hiddenSkillAuthoringDenied(tc, skill, parsed.skillName, mergedConfigurable);+ if (hiddenDenied) {+ return hiddenDenied;+ }++ const current = await loadSkillFileTextForAuthoring({+ skill,+ relativePath: parsed.relativePath,+ options,+ req,+ });+ if (current.status === 'missing') {+ return errorResult(+ tc,+ `File not found: "${parsed.relativePath}" in skill "${parsed.skillName}"`,+ );+ }+ if (current.status === 'error') {+ return errorResult(tc, current.message);+ }++ let edited: { content: string; strategies: string[] };+ try {+ edited = applyTextEdits(current.content, edits);+ } catch (error) {+ return errorResult(tc, error instanceof Error ? error.message : 'Failed to edit file');+ }+ if (Buffer.byteLength(edited.content, 'utf8') > MAX_AUTHORING_BYTES) {+ return errorResult(tc, `edited content exceeds ${MAX_AUTHORING_BYTES} byte limit`);+ }++ if (parsed.relativePath === SKILL_MD) {+ const result = await writeSkillMd({+ tc,+ options,+ req,+ mergedConfigurable,+ skill,+ skillName: parsed.skillName,+ content: edited.content,+ });+ if (result.status === 'success') {+ result.artifact = {+ ...(typeof result.artifact === 'object' && result.artifact ? result.artifact : {}),+ edits: edits.length,+ strategies: edited.strategies,+ };+ result.content = `${String(result.content)}\n\nStrategies: ${edited.strategies.join(', ')}`;+ }+ return result;+ }++ const result = await writeBundledSkillFile({+ tc,+ options,+ req,+ skill,+ relativePath: parsed.relativePath,+ displayPath: parsed.displayPath,+ content: edited.content,+ oldContent: current.content,+ created: false,+ });+ if (result.status === 'success') {+ result.artifact = {+ ...(typeof result.artifact === 'object' && result.artifact ? result.artifact : {}),+ edits: edits.length,+ strategies: edited.strategies,+ };+ result.content = `${String(result.content)}\n\nStrategies: ${edited.strategies.join(', ')}`;+ }+ return result;+}++async function handleReadFileCall(+ tc: ToolCallRequest,+ mergedConfigurable: Record<string, unknown>,+ options: ToolExecuteOptions,+ req?: ServerRequest,+): Promise<ToolExecuteResult> {+ const { getSkillByName, getSkillFileByPath, getStrategyFunctions, updateSkillFileContent } =+ options;+ const args = tc.args as { file_path?: string };+ if (!args.file_path) {return {toolCallId: tc.id,status: 'error',content: '',- errorMessage: `Invalid file path "${args.file_path}". Use format: {skillName}/{path}`,+ errorMessage: 'file_path is required',};}- const skillName = args.file_path.slice(0, slashIdx);- const relativePath = args.file_path.slice(slashIdx + 1);- if (!relativePath) {- /**- * `read_file("output/")`: a malformed-but-unambiguously-not-a-skill- * path. Stay consistent with the other malformed-path branches and- * route to the sandbox when code execution is available, instead of- * dead-ending with a skill-centric error message.- */+ const codeEnvAvailable = mergedConfigurable?.codeEnvAvailable === true;+ let accessibleIds = (mergedConfigurable?.accessibleSkillIds as Types.ObjectId[]) ?? [];++ /**+ * Short-circuit absolute code-env paths: the path can never be a skill+ * reference (skill paths are relative `{skillName}/...`), and consulting+ * `getSkillByName` would just burn a DB round-trip on a guaranteed miss.+ */+ if (args.file_path.startsWith('/mnt/data/')) {if (codeEnvAvailable) {return handleSandboxFileFallback(tc, args.file_path, options, req);}@@ -679,10 +2535,102 @@ async function handleReadFileCall(toolCallId: tc.id,status: 'error',content: '',- errorMessage: 'Missing file path after skill name',+ errorMessage: `Path "${args.file_path}" is a code-execution sandbox path, but this agent does not have code execution enabled.`,};}+ let skillName: string;+ let relativePath: string;+ const explicitSkillNamespace = args.file_path.startsWith(SKILL_FILE_PREFIX);+ if (explicitSkillNamespace) {+ const parsed = parseSkillAuthoringPath(args.file_path);+ if (typeof parsed === 'string') {+ return {+ toolCallId: tc.id,+ status: 'error',+ content: '',+ errorMessage: parsed,+ };+ }+ skillName = parsed.skillName;+ relativePath = parsed.relativePath;+ } else {+ const slashIdx = args.file_path.indexOf('/');+ if (slashIdx < 1) {+ if (codeEnvAvailable) {+ return handleSandboxFileFallback(tc, args.file_path, options, req);+ }+ return {+ toolCallId: tc.id,+ status: 'error',+ content: '',+ errorMessage: `Invalid file path "${args.file_path}". Use format: {skillName}/{path}`,+ };+ }++ skillName = args.file_path.slice(0, slashIdx);+ relativePath = args.file_path.slice(slashIdx + 1);+ if (!relativePath) {+ /**+ * `read_file("output/")`: a malformed-but-unambiguously-not-a-skill+ * path. Stay consistent with the other malformed-path branches and+ * route to the sandbox when code execution is available, instead of+ * dead-ending with a skill-centric error message.+ */+ if (codeEnvAvailable) {+ return handleSandboxFileFallback(tc, args.file_path, options, req);+ }+ return {+ toolCallId: tc.id,+ status: 'error',+ content: '',+ errorMessage: 'Missing file path after skill name',+ };+ }+ }++ let skillPrimedIdsByName =+ (mergedConfigurable?.skillPrimedIdsByName as Record<string, string> | undefined) ?? {};+ let primedIdString = skillPrimedIdsByName[skillName];+ let isPrimedThisTurn = primedIdString != null;+ const refreshSkillReadScope = () => {+ accessibleIds = (mergedConfigurable?.accessibleSkillIds as Types.ObjectId[]) ?? [];+ skillPrimedIdsByName =+ (mergedConfigurable?.skillPrimedIdsByName as Record<string, string> | undefined) ?? {};+ primedIdString = skillPrimedIdsByName[skillName];+ isPrimedThisTurn = primedIdString != null;+ };+ let recoveredAuthorSkill: AuthoringSkill | null | undefined;+ const recoverAuthorSkill = async () => {+ if (recoveredAuthorSkill !== undefined) {+ return recoveredAuthorSkill;+ }+ recoveredAuthorSkill = await resolveAuthorSkillForCurrentUser({+ skillName,+ mergedConfigurable,+ options,+ req,+ });+ refreshSkillReadScope();+ return recoveredAuthorSkill;+ };+ /**+ * `accessibleSkillIds` is the resolver's normal output (admin+ * capability AND ACL access AND ephemeral badge / persisted+ * `skills_enabled`). A skill authored earlier in this run is also+ * resolvable through `skillPrimedIdsByName`, even when the run started+ * with an empty accessible set for a first-time creator.+ */+ let skillsEffectivelyEnabled = accessibleIds.length > 0 || isPrimedThisTurn;+ if (+ !skillsEffectivelyEnabled &&+ explicitSkillNamespace &&+ isSkillAuthoringAvailable(mergedConfigurable)+ ) {+ await recoverAuthorSkill();+ skillsEffectivelyEnabled = accessibleIds.length > 0 || isPrimedThisTurn;+ }+/*** Skills not in scope (admin capability off, ephemeral badge off, or* persisted `skills_enabled !== true` — all already collapsed into@@ -691,7 +2639,7 @@ async function handleReadFileCall(* the lookup truly has nowhere to go.*/if (!skillsEffectivelyEnabled) {- if (codeEnvAvailable) {+ if (codeEnvAvailable && !explicitSkillNamespace) {return handleSandboxFileFallback(tc, args.file_path, options, req);}return {@@ -718,11 +2666,6 @@ async function handleReadFileCall(* shortcut would misroute `read_file("primed-skill/references/foo.md")`* to the sandbox even though the primed skill is in scope.*/- const skillPrimedIdsByName =- (mergedConfigurable?.skillPrimedIdsByName as Record<string, string> | undefined) ?? {};- const primedIdString = skillPrimedIdsByName[skillName];- const isPrimedThisTurn = primedIdString != null;-/*** Skills are in scope, but the first segment isn't a name we know.* Use the catalog-derived `activeSkillNames` Set (no DB read) to detect@@ -733,15 +2676,18 @@ async function handleReadFileCall(*/const activeSkillNames = mergedConfigurable?.activeSkillNames as Set<string> | undefined;if (activeSkillNames && !activeSkillNames.has(skillName) && !isPrimedThisTurn) {- if (codeEnvAvailable) {- return handleSandboxFileFallback(tc, args.file_path, options, req);+ const recovered = await recoverAuthorSkill();+ if (!recovered) {+ if (codeEnvAvailable && !explicitSkillNamespace) {+ return handleSandboxFileFallback(tc, args.file_path, options, req);+ }+ return {+ toolCallId: tc.id,+ status: 'error',+ content: '',+ errorMessage: `Skill "${skillName}" not found or not accessible`,+ };}- return {- toolCallId: tc.id,- status: 'error',- content: '',- errorMessage: `Skill "${skillName}" not found or not accessible`,- };}if (!getSkillByName) {@@ -763,19 +2709,20 @@ async function handleReadFileCall((rather than relying on mongoose's string auto-cast in `$in` queries)keeps the value correct for any future consumer that compares with`.equals()` or `===`. */- const lookupAccessibleIds = isPrimedThisTurn- ? [new Types.ObjectId(primedIdString)]- : accessibleIds;+ const lookupAccessibleIds = primedIdString ? [new Types.ObjectId(primedIdString)] : accessibleIds;const lookupOptions: { preferUserInvocable?: boolean; preferModelInvocable?: boolean } =- isPrimedThisTurn ? {} : { preferModelInvocable: true };- const skill = await getSkillByName(skillName, lookupAccessibleIds, lookupOptions);+ primedIdString ? {} : { preferModelInvocable: true };+ let skill = await getSkillByName(skillName, lookupAccessibleIds, lookupOptions);if (!skill) {- return {- toolCallId: tc.id,- status: 'error',- content: '',- errorMessage: `Skill "${skillName}" not found or not accessible`,- };+ skill = await recoverAuthorSkill();+ if (!skill) {+ return {+ toolCallId: tc.id,+ status: 'error',+ content: '',+ errorMessage: `Skill "${skillName}" not found or not accessible`,+ };+ }}/**@@ -1170,6 +3117,27 @@ async function handleSkillToolCall(};}+function getFileAuthoringQueueKey(+ tc: ToolCallRequest,+ mergedConfigurable: Record<string, unknown>,+): string | undefined {+ if (!isHostFileAuthoringToolCall(tc.name, mergedConfigurable)) {+ return undefined;+ }+ const args = tc.args as { file_path?: unknown };+ if (typeof args.file_path !== 'string' || args.file_path.length === 0) {+ return undefined;+ }+ if (!args.file_path.startsWith(SKILL_FILE_PREFIX)) {+ return `sandbox:${args.file_path}`;+ }+ const parsed = parseSkillAuthoringPath(args.file_path);+ if (typeof parsed === 'string') {+ return `skill:${args.file_path}`;+ }+ return `skill:${parsed.skillName}`;+}+/*** Creates the ON_TOOL_EXECUTE handler for event-driven tool execution.* This handler receives batched tool calls, loads the required tools,@@ -1191,210 +3159,322 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHandagentId,);const toolMap = new Map(loadedTools.map((t) => [t.name, t]));- const mergedConfigurable = { ...configurable, ...toolConfigurable };+ const sourceConfigurable = configurable as Record<string, unknown> | undefined;+ const loadedConfigurable = toolConfigurable as Record<string, unknown> | undefined;+ const mergedConfigurable = mergeToolConfigurables(+ sourceConfigurable,+ loadedConfigurable,+ );+ const authoringQueues = new Map<string, Promise<void>>();+ const sandboxAuthoringContexts = new Map<string, SandboxSessionContext>();const results: ToolExecuteResult[] = await Promise.all(toolCalls.map(async (tc: ToolCallRequest) => {- if (tc.name === Constants.SKILL_TOOL || tc.name === Constants.READ_FILE) {- const req = mergedConfigurable?.req as ServerRequest | undefined;- const handlerResult =- tc.name === Constants.SKILL_TOOL- ? await handleSkillToolCall(tc, mergedConfigurable, options, req)- : await handleReadFileCall(tc, mergedConfigurable, options, req);-- if (toolEndCallback && handlerResult.artifact) {- await toolEndCallback(- {- output: {- name: tc.name,- tool_call_id: tc.id,- content: handlerResult.content,- artifact: handlerResult.artifact,+ const execute = async (+ sandboxContext?: SandboxSessionContext,+ ): Promise<ToolExecuteResult> => {+ const isFileAuthoringCall = isHostFileAuthoringToolCall(+ tc.name,+ mergedConfigurable,+ );+ const isSandboxFileAuthoringCall =+ isFileAuthoringCall &&+ typeof (tc.args as { file_path?: unknown }).file_path === 'string' &&+ !(tc.args as { file_path: string }).file_path.startsWith(SKILL_FILE_PREFIX);+ if (+ tc.name === Constants.SKILL_TOOL ||+ tc.name === Constants.READ_FILE ||+ isFileAuthoringCall+ ) {+ const req = mergedConfigurable?.req as ServerRequest | undefined;+ let handlerResult: ToolExecuteResult;+ try {+ if (tc.name === Constants.SKILL_TOOL) {+ handlerResult = await handleSkillToolCall(+ tc,+ mergedConfigurable,+ options,+ req,+ );+ } else if (tc.name === Constants.READ_FILE) {+ handlerResult = await handleReadFileCall(+ tc,+ mergedConfigurable,+ options,+ req,+ );+ } else if (tc.name === CREATE_FILE_TOOL_NAME && isFileAuthoringCall) {+ handlerResult = await handleCreateFileCall(+ tc,+ mergedConfigurable,+ options,+ req,+ sourceConfigurable,+ sandboxContext,+ );+ } else if (tc.name === EDIT_FILE_TOOL_NAME && isFileAuthoringCall) {+ handlerResult = await handleEditFileCall(+ tc,+ mergedConfigurable,+ options,+ req,+ sandboxContext,+ );+ } else {+ handlerResult = errorResult(tc, `Tool ${tc.name} not found`);+ }+ } catch (toolError) {+ const { message, logContext } = getSafeToolError(toolError);+ logger.error(`[ON_TOOL_EXECUTE] Tool ${tc.name} error`, {+ ...logContext,+ toolCallArgsShape: getValueShape(tc.args),+ });+ return {+ toolCallId: tc.id,+ status: 'error' as const,+ content: '',+ errorMessage: message,+ };+ }++ if (+ isSandboxFileAuthoringCall &&+ handlerResult.status === 'success' &&+ sandboxContext+ ) {+ mergeSandboxSessionArtifact(sandboxContext, handlerResult.artifact);+ }++ if (toolEndCallback && handlerResult.artifact) {+ await toolEndCallback(+ {+ output: {+ name: tc.name,+ tool_call_id: tc.id,+ content: handlerResult.content,+ artifact: handlerResult.artifact,+ },},- },- {- run_id: (metadata as Record<string, unknown>)?.run_id as string | undefined,- thread_id: (metadata as Record<string, unknown>)?.thread_id as- | string- | undefined,- ...metadata,- },- );- }+ {+ run_id: (metadata as Record<string, unknown>)?.run_id as+ | string+ | undefined,+ thread_id: (metadata as Record<string, unknown>)?.thread_id as+ | string+ | undefined,+ ...metadata,+ },+ );+ }- return handlerResult;- }+ return handlerResult;+ }- const tool = toolMap.get(tc.name);+ const tool = toolMap.get(tc.name);- if (!tool) {- logger.warn(- `[ON_TOOL_EXECUTE] Tool "${tc.name}" not found. Available: ${[...toolMap.keys()].map((k) => `"${k}"`).join(', ')}`,- );- return {- toolCallId: tc.id,- status: 'error' as const,- content: '',- errorMessage: `Tool ${tc.name} not found`,- };- }+ if (!tool) {+ logger.warn(+ `[ON_TOOL_EXECUTE] Tool "${tc.name}" not found. Available: ${[...toolMap.keys()].map((k) => `"${k}"`).join(', ')}`,+ );+ return {+ toolCallId: tc.id,+ status: 'error' as const,+ content: '',+ errorMessage: `Tool ${tc.name} not found`,+ };+ }- try {- const toolCallConfig: Record<string, unknown> = {- id: tc.id,- stepId: tc.stepId,- turn: tc.turn,- };-- if (tc.codeSessionContext && CODE_EXECUTION_TOOLS.has(tc.name)) {- toolCallConfig.session_id = tc.codeSessionContext.session_id;- if (tc.codeSessionContext.files && tc.codeSessionContext.files.length > 0) {- toolCallConfig._injected_files = tc.codeSessionContext.files;- /* Last LC-controlled point before the wire. Mirrors- * codeapi's validator context so the two log sides- * correlate on a single grep. */- const refs = tc.codeSessionContext.files as Array<{- id?: unknown;- resource_id?: unknown;- storage_session_id?: unknown;- kind?: unknown;- version?: unknown;- name?: unknown;- }>;- const summary = refs.map((f) => ({- kind: f.kind,- hasResourceId: typeof f.resource_id === 'string' && !!f.resource_id,- hasStorageSessionId:- typeof f.storage_session_id === 'string' && !!f.storage_session_id,- hasVersion: typeof f.version === 'number',- }));- let missingResourceId = 0;- let missingStorageSessionId = 0;- let missingVersion = 0;- const kindCounts: Record<string, number> = {};- for (const s of summary) {- if (!s.hasResourceId) missingResourceId++;- if (!s.hasStorageSessionId) missingStorageSessionId++;- if (!s.hasVersion) missingVersion++;- const k = typeof s.kind === 'string' ? s.kind : 'unknown';- kindCounts[k] = (kindCounts[k] ?? 0) + 1;- }- logger.debug(- `[code-env:inject] tool=${tc.name} files=${refs.length} ` +- `missingResourceId=${missingResourceId} ` +- `missingStorageSessionId=${missingStorageSessionId} ` +- `missingVersion=${missingVersion} ` +- `kinds=${JSON.stringify(kindCounts)}`,- );- if (missingResourceId > 0) {+ try {+ const toolCallConfig: Record<string, unknown> = {+ id: tc.id,+ stepId: tc.stepId,+ turn: tc.turn,+ };++ if (+ tc.codeSessionContext &&+ isCodeSessionAwareToolCall(tc.name, mergedConfigurable)+ ) {+ toolCallConfig.session_id = tc.codeSessionContext.session_id;+ if (tc.codeSessionContext.files && tc.codeSessionContext.files.length > 0) {+ toolCallConfig._injected_files = tc.codeSessionContext.files;+ /* Last LC-controlled point before the wire. Mirrors+ * codeapi's validator context so the two log sides+ * correlate on a single grep. */+ const refs = tc.codeSessionContext.files as Array<{+ id?: unknown;+ resource_id?: unknown;+ storage_session_id?: unknown;+ kind?: unknown;+ version?: unknown;+ name?: unknown;+ }>;+ const summary = refs.map((f) => ({+ kind: f.kind,+ hasResourceId: typeof f.resource_id === 'string' && !!f.resource_id,+ hasStorageSessionId:+ typeof f.storage_session_id === 'string' && !!f.storage_session_id,+ hasVersion: typeof f.version === 'number',+ }));+ let missingResourceId = 0;+ let missingStorageSessionId = 0;+ let missingVersion = 0;+ const kindCounts: Record<string, number> = {};+ for (const s of summary) {+ if (!s.hasResourceId) missingResourceId++;+ if (!s.hasStorageSessionId) missingStorageSessionId++;+ if (!s.hasVersion) missingVersion++;+ const k = typeof s.kind === 'string' ? s.kind : 'unknown';+ kindCounts[k] = (kindCounts[k] ?? 0) + 1;+ }+ logger.debug(+ `[code-env:inject] tool=${tc.name} files=${refs.length} ` ++ `missingResourceId=${missingResourceId} ` ++ `missingStorageSessionId=${missingStorageSessionId} ` ++ `missingVersion=${missingVersion} ` ++ `kinds=${JSON.stringify(kindCounts)}`,+ );+ if (missingResourceId > 0) {+ logger.warn(+ `[code-env:inject] ${missingResourceId}/${refs.length} files missing resource_id ` ++ `for tool=${tc.name} — codeapi will reject with 400`,+ { summary },+ );+ }+ } else {+ /* Empty `_injected_files` on a code-execution tool+ * call. Almost always means the seeding chain+ * (primeCodeFiles → initialSessions →+ * CodeSessionContext) dropped the file upstream.+ * `session_id` is still emitted for continuity, but+ * concrete file refs must arrive through+ * `_injected_files`; agents no longer falls back to+ * `/files/<sid>`. Pair with `[primeCodeFiles]`+ * traces below to locate the layer that lost the ref. */logger.warn(- `[code-env:inject] ${missingResourceId}/${refs.length} files missing resource_id ` +- `for tool=${tc.name} — codeapi will reject with 400`,- { summary },+ `[code-env:inject] tool=${tc.name} _injected_files=0 — sandbox will see no input files`,+ {+ tool: tc.name,+ session_id: tc.codeSessionContext.session_id,+ codeSessionContextHasFiles: tc.codeSessionContext.files !== undefined,+ codeSessionContextFileCount: tc.codeSessionContext.files?.length ?? 0,+ },);}- } else {- /* Empty `_injected_files` on a code-execution tool- * call. Almost always means the seeding chain- * (primeCodeFiles → initialSessions →- * CodeSessionContext) dropped the file upstream.- * `session_id` is still emitted for continuity, but- * concrete file refs must arrive through- * `_injected_files`; agents no longer falls back to- * `/files/<sid>`. Pair with `[primeCodeFiles]`- * traces below to locate the layer that lost the ref. */- logger.warn(- `[code-env:inject] tool=${tc.name} _injected_files=0 — sandbox will see no input files`,- {- tool: tc.name,- session_id: tc.codeSessionContext.session_id,- codeSessionContextHasFiles: tc.codeSessionContext.files !== undefined,- codeSessionContextFileCount: tc.codeSessionContext.files?.length ?? 0,- },- );}- }- if (- tc.name === Constants.BASH_PROGRAMMATIC_TOOL_CALLING ||- tc.name === Constants.PROGRAMMATIC_TOOL_CALLING- ) {- const toolRegistry = mergedConfigurable?.toolRegistry as- | LCToolRegistry- | undefined;- const ptcToolMap = mergedConfigurable?.ptcToolMap as- | Map<string, StructuredToolInterface>- | undefined;- if (toolRegistry) {- const toolDefs: LCTool[] = Array.from(toolRegistry.values()).filter(- (t) =>- t.name !== Constants.PROGRAMMATIC_TOOL_CALLING &&- t.name !== Constants.BASH_PROGRAMMATIC_TOOL_CALLING &&- t.name !== Constants.TOOL_SEARCH,- );- toolCallConfig.toolDefs = toolDefs;- toolCallConfig.toolMap = ptcToolMap ?? toolMap;+ if (+ tc.name === Constants.BASH_PROGRAMMATIC_TOOL_CALLING ||+ tc.name === Constants.PROGRAMMATIC_TOOL_CALLING+ ) {+ const toolRegistry = mergedConfigurable?.toolRegistry as+ | LCToolRegistry+ | undefined;+ const ptcToolMap = mergedConfigurable?.ptcToolMap as+ | Map<string, StructuredToolInterface>+ | undefined;+ if (toolRegistry) {+ const fileAuthoringToolNames =+ getFileAuthoringToolNames(mergedConfigurable) ?? new Set<string>();+ const toolDefs: LCTool[] = Array.from(toolRegistry.values()).filter(+ (t) =>+ t.name !== Constants.PROGRAMMATIC_TOOL_CALLING &&+ t.name !== Constants.BASH_PROGRAMMATIC_TOOL_CALLING &&+ t.name !== Constants.TOOL_SEARCH &&+ !fileAuthoringToolNames.has(t.name),+ );+ toolCallConfig.toolDefs = toolDefs;+ toolCallConfig.toolMap = ptcToolMap ?? toolMap;+ }}- }- const result = await tool.invoke(normalizeToolInvokeArgs(tc.args, tool), {- toolCall: toolCallConfig,- configurable: mergedConfigurable,- metadata,- } as Record<string, unknown>);-- // Code-execution tools emit per-call boilerplate- // ("Note: ..." paragraphs and `| <annotation>` per-file- // suffixes) that wastes tokens when re-injected into- // every subsequent model turn. Strip it here, *after*- // the tool resolved but *before* downstream consumers- // (model context, SSE forwarding, persistence) see it.- // Non-code-execution tools pass through unchanged.- const cleanedContent =- CODE_EXECUTION_TOOLS.has(tc.name) && typeof result.content === 'string'- ? cleanCodeToolOutput(result.content)- : result.content;-- if (toolEndCallback) {- await toolEndCallback(- {- output: {- name: tc.name,- tool_call_id: tc.id,- content: cleanedContent,- artifact: result.artifact,+ const result = await tool.invoke(normalizeToolInvokeArgs(tc.args, tool), {+ toolCall: toolCallConfig,+ configurable: mergedConfigurable,+ metadata,+ } as Record<string, unknown>);++ // Code-execution tools emit per-call boilerplate+ // ("Note: ..." paragraphs and `| <annotation>` per-file+ // suffixes) that wastes tokens when re-injected into+ // every subsequent model turn. Strip it here, *after*+ // the tool resolved but *before* downstream consumers+ // (model context, SSE forwarding, persistence) see it.+ // Non-code-execution tools pass through unchanged.+ const cleanedContent =+ isCodeSessionAwareToolCall(tc.name, mergedConfigurable) &&+ typeof result.content === 'string'+ ? cleanCodeToolOutput(result.content)+ : result.content;++ if (toolEndCallback) {+ await toolEndCallback(+ {+ output: {+ name: tc.name,+ tool_call_id: tc.id,+ content: cleanedContent,+ artifact: result.artifact,+ },},- },- {- run_id: (metadata as Record<string, unknown>)?.run_id as string | undefined,- thread_id: (metadata as Record<string, unknown>)?.thread_id as- | string- | undefined,- ...metadata,- },- );+ {+ run_id: (metadata as Record<string, unknown>)?.run_id as+ | string+ | undefined,+ thread_id: (metadata as Record<string, unknown>)?.thread_id as+ | string+ | undefined,+ ...metadata,+ },+ );+ }++ return {+ toolCallId: tc.id,+ content: cleanedContent,+ artifact: result.artifact,+ status: 'success' as const,+ };+ } catch (toolError) {+ const { message, logContext } = getSafeToolError(toolError);+ logger.error(`[ON_TOOL_EXECUTE] Tool ${tc.name} error`, {+ ...logContext,+ toolCallArgsShape: getValueShape(tc.args),+ toolInputSchemaKind: getToolInputSchemaKind(tool),+ });+ return {+ toolCallId: tc.id,+ status: 'error' as const,+ content: '',+ errorMessage: message,+ };}+ };- return {- toolCallId: tc.id,- content: cleanedContent,- artifact: result.artifact,- status: 'success' as const,- };- } catch (toolError) {- const { message, logContext } = getSafeToolError(toolError);- logger.error(`[ON_TOOL_EXECUTE] Tool ${tc.name} error`, {- ...logContext,- toolCallArgsShape: getValueShape(tc.args),- toolInputSchemaKind: getToolInputSchemaKind(tool),- });- return {- toolCallId: tc.id,- status: 'error' as const,- content: '',- errorMessage: message,- };+ const queueKey = getFileAuthoringQueueKey(tc, mergedConfigurable);+ if (!queueKey) {+ return await execute();+ }+ let sandboxContext: SandboxSessionContext | undefined;+ if (queueKey.startsWith('sandbox:')) {+ sandboxContext =+ sandboxAuthoringContexts.get(queueKey) ??+ cloneSandboxSessionContext(sandboxSessionContext(tc));+ sandboxAuthoringContexts.set(queueKey, sandboxContext);}+ const previous = authoringQueues.get(queueKey) ?? Promise.resolve();+ const resultPromise = previous.then(+ () => execute(sandboxContext),+ () => execute(sandboxContext),+ );+ authoringQueues.set(+ queueKey,+ resultPromise.then(+ () => undefined,+ () => undefined,+ ),+ );+ return await resultPromise;}),);diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.tsindex f9ff1510a2..a7b1edbce0 100644--- a/packages/api/src/agents/initialize.ts+++ b/packages/api/src/agents/initialize.ts@@ -40,7 +40,11 @@ import {unionPrimeAllowedTools,MAX_PRIMED_SKILLS_PER_TURN,} from './skills';-import { registerCodeExecutionTools } from './tools';+import {+ registerCodeExecutionTools,+ registerFileAuthoringTools,+ isFileAuthoringToolDefinition,+} from './tools';import { primeResources } from './resources';import type { ResolvedManualSkill, ResolvedAlwaysApplySkill } from './skills';import type { TFilterFilesByAgentAccess } from './resources';@@ -184,6 +188,10 @@ export type InitializedAgent = Agent & {* (`packages/api/src/agents/added.ts`), so the check is uniform.*/codeEnvAvailable: boolean;+ /** Whether host-side skill file authoring is available for this agent/run. */+ skillAuthoringAvailable: boolean;+ /** Host-side file authoring tool names registered for this run. */+ fileAuthoringToolNames?: Set<string>;/** Accessible skill IDs for ACL checking at execute time */accessibleSkillIds?: import('mongoose').Types.ObjectId[];/**@@ -282,6 +290,8 @@ export interface InitializeAgentParams {isInitialAgent?: boolean;/** Accessible skill IDs for this user (pre-computed by the caller via ACL query) */accessibleSkillIds?: import('mongoose').Types.ObjectId[];+ /** Whether skill file authoring should be exposed even before a user has viewable skills. */+ skillAuthoringAvailable?: boolean;/** Whether the code execution environment is available (execute_code capability enabled) */codeEnvAvailable?: boolean;/** Per-user skill active/inactive overrides for filtering the skill catalog. */@@ -607,7 +617,8 @@ export async function initializeAgent(* go first so their names win on dedup (primes earlier in the list* contribute before the same name gets deduped on a later prime).*/- const hasSkillAccess = params.accessibleSkillIds && params.accessibleSkillIds.length > 0;+ const hasSkillAccess = (params.accessibleSkillIds?.length ?? 0) > 0;+ const skillAuthoringAvailable = params.skillAuthoringAvailable === true;let manualSkillPrimes: ResolvedManualSkill[] | undefined;let alwaysApplySkillPrimes: ResolvedAlwaysApplySkill[] | undefined;let extraAllowedToolNames: string[] = [];@@ -908,6 +919,26 @@ export async function initializeAgent();}+ if (skillAuthoringAvailable) {+ const skillReadResult = registerCodeExecutionTools({+ toolRegistry,+ toolDefinitions,+ includeBash: false,+ includeSkillFileInstructions: true,+ enableToolOutputReferences: effectiveCodeEnvAvailable,+ });+ toolDefinitions = skillReadResult.toolDefinitions;+ }++ if (effectiveCodeEnvAvailable || skillAuthoringAvailable) {+ const fileAuthoringResult = registerFileAuthoringTools({+ toolRegistry,+ toolDefinitions,+ includeSkillFileInstructions: skillAuthoringAvailable,+ });+ toolDefinitions = fileAuthoringResult.toolDefinitions;+ }+/** Check for tool presence from either full instances or definitions (event-driven mode) */const hasAgentTools = (structuredTools?.length ?? 0) > 0 || (toolDefinitions?.length ?? 0) > 0;const providerTools = resolveProviderToolConflicts({@@ -1026,6 +1057,11 @@ export async function initializeAgent(: undefined;const maxToolResultCharsResolved =providerMaxToolResultChars ?? endpointConfigs?.all?.maxToolResultChars;+ const fileAuthoringToolNames = new Set(+ (toolDefinitions ?? [])+ .filter((toolDefinition) => isFileAuthoringToolDefinition(toolDefinition))+ .map((toolDefinition) => toolDefinition.name),+ );const initializedAgent: InitializedAgent = {...agent,@@ -1039,6 +1075,8 @@ export async function initializeAgent(baseContextTokens,codeEnvAvailable: effectiveCodeEnvAvailable,reasoningKey: customEndpointConfig?.customParams?.reasoningKey,+ skillAuthoringAvailable,+ fileAuthoringToolNames: fileAuthoringToolNames.size > 0 ? fileAuthoringToolNames : undefined,skillCount,accessibleSkillIds: executableSkillIds,activeSkillNames,diff --git a/packages/api/src/agents/skillConfigurable.spec.ts b/packages/api/src/agents/skillConfigurable.spec.tsindex 5b22a23cfa..94bc5dbd28 100644--- a/packages/api/src/agents/skillConfigurable.spec.ts+++ b/packages/api/src/agents/skillConfigurable.spec.ts@@ -5,12 +5,10 @@ describe('enrichWithSkillConfigurable', () => {const accessibleSkillIds = ['skill-a', 'skill-b'];it('augments configurable with req, accessibleSkillIds, and codeEnvAvailable', () => {- const result = enrichWithSkillConfigurable(- { loadedTools: [], configurable: { other: 'value' } },- req,- accessibleSkillIds,- true,- );+ const result = enrichWithSkillConfigurable({+ result: { loadedTools: [], configurable: { other: 'value' } },+ context: { req, accessibleSkillIds, codeEnvAvailable: true },+ });expect(result.configurable).toEqual({other: 'value',@@ -18,21 +16,36 @@ describe('enrichWithSkillConfigurable', () => {codeEnvAvailable: true,accessibleSkillIds,skillPrimedIdsByName: undefined,+ skillAuthoringAvailable: undefined,+ fileAuthoringToolNames: undefined,});});it('propagates codeEnvAvailable=false verbatim (not coerced)', () => {- const result = enrichWithSkillConfigurable(- { loadedTools: [], configurable: {} },- req,- accessibleSkillIds,- false,- );+ const result = enrichWithSkillConfigurable({+ result: { loadedTools: [], configurable: {} },+ context: { req, accessibleSkillIds, codeEnvAvailable: false },+ });expect(result.configurable.codeEnvAvailable).toBe(false);});it('threads skillPrimedIdsByName through unchanged', () => {+ const primed = { 'brand-guidelines': 'abc123' };+ const result = enrichWithSkillConfigurable({+ result: { loadedTools: [], configurable: {} },+ context: {+ req,+ accessibleSkillIds,+ codeEnvAvailable: true,+ skillPrimedIdsByName: primed,+ },+ });++ expect(result.configurable.skillPrimedIdsByName).toBe(primed);+ });++ it('supports the legacy positional shape', () => {const primed = { 'brand-guidelines': 'abc123' };const result = enrichWithSkillConfigurable({ loadedTools: [], configurable: {} },@@ -45,14 +58,29 @@ describe('enrichWithSkillConfigurable', () => {expect(result.configurable.skillPrimedIdsByName).toBe(primed);});+ it('threads skill authoring gates through unchanged', () => {+ const fileAuthoringToolNames = new Set(['create_file', 'edit_file']);+ const result = enrichWithSkillConfigurable({+ result: { loadedTools: [], configurable: {} },+ context: {+ req,+ accessibleSkillIds,+ codeEnvAvailable: true,+ skillAuthoringAvailable: true,+ fileAuthoringToolNames,+ },+ });++ expect(result.configurable.skillAuthoringAvailable).toBe(true);+ expect(result.configurable.fileAuthoringToolNames).toBe(fileAuthoringToolNames);+ });+it('preserves loadedTools unchanged', () => {const tools = [{ name: 'x' }];- const result = enrichWithSkillConfigurable(- { loadedTools: tools, configurable: undefined },- req,- accessibleSkillIds,- false,- );+ const result = enrichWithSkillConfigurable({+ result: { loadedTools: tools, configurable: undefined },+ context: { req, accessibleSkillIds, codeEnvAvailable: false },+ });expect(result.loadedTools).toBe(tools);});diff --git a/packages/api/src/agents/skillConfigurable.ts b/packages/api/src/agents/skillConfigurable.tsindex 9157701c43..ada280d6a0 100644--- a/packages/api/src/agents/skillConfigurable.ts+++ b/packages/api/src/agents/skillConfigurable.ts@@ -24,17 +24,16 @@* Empty/missing → no exception, the gate applies as normal and the* lookup uses the full ACL set.*/-export function enrichWithSkillConfigurable(- result: { loadedTools: unknown[]; configurable?: Record<string, unknown> },- req: { user?: { id?: string } },- accessibleSkillIds: unknown[],- codeEnvAvailable: boolean,+export interface SkillConfigurableContext {+ req: { user?: { id?: string } };+ accessibleSkillIds?: unknown[];+ codeEnvAvailable: boolean;/*** `{ [skillName]: skillIdString }` for every skill primed this turn* (manual or always-apply). The id pins same-name collision lookups to* the exact doc the resolver primed and relaxes the disable-model gate.*/- skillPrimedIdsByName?: Record<string, string>,+ skillPrimedIdsByName?: Record<string, string>;/*** Names of skills the runtime can resolve, captured at agent init by* `injectSkillCatalog`. Lets `read_file` decide whether a@@ -45,17 +44,74 @@ export function enrichWithSkillConfigurable(* off, ephemeral badge off, or persisted `skills_enabled !== true`),* which is the same signal as `accessibleSkillIds.length === 0`.*/+ activeSkillNames?: Set<string>;+ /** True when skills/{skillName}/... write paths are enabled for this run. */+ skillAuthoringAvailable?: boolean;+ /** Host file-authoring names registered by initializeAgent for this run. */+ fileAuthoringToolNames?: Set<string>;+}++export interface SkillConfigurableLoadResult {+ loadedTools: unknown[];+ configurable?: Record<string, unknown>;+}++export interface EnrichWithSkillConfigurableParams {+ result: SkillConfigurableLoadResult;+ context: SkillConfigurableContext;+}++export function enrichWithSkillConfigurable(params: EnrichWithSkillConfigurableParams): {+ loadedTools: unknown[];+ configurable: Record<string, unknown>;+};+export function enrichWithSkillConfigurable(+ result: SkillConfigurableLoadResult,+ req: { user?: { id?: string } },+ accessibleSkillIds: unknown[] | undefined,+ codeEnvAvailable: boolean,+ skillPrimedIdsByName?: Record<string, string>,+ activeSkillNames?: Set<string>,+ skillAuthoringAvailable?: boolean,+ fileAuthoringToolNames?: Set<string>,+): { loadedTools: unknown[]; configurable: Record<string, unknown> };+export function enrichWithSkillConfigurable(+ first: EnrichWithSkillConfigurableParams | SkillConfigurableLoadResult,+ req?: { user?: { id?: string } },+ accessibleSkillIds?: unknown[],+ codeEnvAvailable?: boolean,+ skillPrimedIdsByName?: Record<string, string>,activeSkillNames?: Set<string>,+ skillAuthoringAvailable?: boolean,+ fileAuthoringToolNames?: Set<string>,): { loadedTools: unknown[]; configurable: Record<string, unknown> } {+ const { result, context } =+ 'result' in first && 'context' in first+ ? first+ : {+ result: first,+ context: {+ req: req ?? {},+ accessibleSkillIds,+ codeEnvAvailable: codeEnvAvailable === true,+ skillPrimedIdsByName,+ activeSkillNames,+ skillAuthoringAvailable,+ fileAuthoringToolNames,+ },+ };+return {...result,configurable: {...result.configurable,- req,- codeEnvAvailable,- accessibleSkillIds,- skillPrimedIdsByName,- activeSkillNames,+ req: context.req,+ codeEnvAvailable: context.codeEnvAvailable,+ accessibleSkillIds: context.accessibleSkillIds,+ skillPrimedIdsByName: context.skillPrimedIdsByName,+ activeSkillNames: context.activeSkillNames,+ skillAuthoringAvailable: context.skillAuthoringAvailable,+ fileAuthoringToolNames: context.fileAuthoringToolNames,},};}diff --git a/packages/api/src/agents/tools.spec.ts b/packages/api/src/agents/tools.spec.tsindex 0643259847..3a0306d0f5 100644--- a/packages/api/src/agents/tools.spec.ts+++ b/packages/api/src/agents/tools.spec.ts@@ -6,6 +6,7 @@*/jest.mock('@librechat/agents', () => ({...jest.requireActual('@librechat/agents'),+ CODE_EXECUTION_TOOLS: new Set(['execute_code', 'bash_tool']),ReadFileToolDefinition: {name: 'read_file',description: 'read skill files using {skillName}/{filePath} and SKILL.md',@@ -38,8 +39,24 @@ jest.mock('@librechat/agents', () => ({enableToolOutputReferences === true ? 'bash {{tool<idx>turn<turn>}}' : 'bash',}));+import { CODE_EXECUTION_TOOLS } from '@librechat/agents';import type { LCTool, LCToolRegistry } from '@librechat/agents';-import { buildToolSet, BuildToolSetConfig, registerCodeExecutionTools } from './tools';+import {+ buildToolSet,+ BuildToolSetConfig,+ registerCodeExecutionTools,+ registerFileAuthoringTools,+ FILE_AUTHORING_TOOL_NAMES,+ isFileAuthoringToolDefinition,+ isCodeSessionToolName,+} from './tools';++function filePathDescription(tool?: LCTool): string {+ const parameters = tool?.parameters as+ | { properties?: { file_path?: { description?: string } } }+ | undefined;+ return parameters?.properties?.file_path?.description ?? '';+}describe('buildToolSet', () => {describe('event-driven mode (toolDefinitions)', () => {@@ -238,6 +255,7 @@ describe('registerCodeExecutionTools', () => {const readFile = upgraded.toolDefinitions.find((d) => d.name === 'read_file');expect(upgraded.registered).toEqual([]);expect(readFile?.description).toContain('{skillName}/{filePath}');+ expect(readFile?.description).toContain('skills/{skillName}/');expect(readFile?.description).toContain('SKILL.md');expect(toolRegistry.get('read_file')?.description).toBe(readFile?.description);});@@ -421,3 +439,119 @@ describe('registerCodeExecutionTools', () => {});});});++describe('registerFileAuthoringTools', () => {+ const makeRegistry = (): LCToolRegistry => new Map() as unknown as LCToolRegistry;++ it('recognizes host-side file authoring tools as code-session-aware without mutating the shared set', () => {+ expect(isCodeSessionToolName('bash_tool')).toBe(true);+ expect(isCodeSessionToolName('create_file')).toBe(false);+ expect(isCodeSessionToolName('edit_file')).toBe(false);+ expect(isCodeSessionToolName('create_file', FILE_AUTHORING_TOOL_NAMES)).toBe(true);+ expect(isCodeSessionToolName('edit_file', FILE_AUTHORING_TOOL_NAMES)).toBe(true);+ expect(CODE_EXECUTION_TOOLS.has('create_file')).toBe(false);+ expect(CODE_EXECUTION_TOOLS.has('edit_file')).toBe(false);+ });++ it('registers create_file and edit_file with skill-aware descriptions', () => {+ const toolRegistry = makeRegistry();+ const result = registerFileAuthoringTools({+ toolRegistry,+ toolDefinitions: [],+ includeSkillFileInstructions: true,+ });++ const names = result.toolDefinitions.map((d) => d.name).sort();+ expect(names).toEqual(['create_file', 'edit_file']);+ expect(result.registered.sort()).toEqual(['create_file', 'edit_file']);+ expect(toolRegistry.has('create_file')).toBe(true);+ expect(toolRegistry.has('edit_file')).toBe(true);+ expect(result.toolDefinitions[0].responseFormat).toBe('content_and_artifact');+ expect(result.toolDefinitions.map((d) => d.description).join('\n')).toContain('skills/');+ expect(toolRegistry.get('create_file')?.description).toContain('frontmatter name must match');+ expect(toolRegistry.get('edit_file')?.description).toContain('edit_file cannot rename skills');+ expect(filePathDescription(toolRegistry.get('create_file'))).toContain(+ 'frontmatter name must match',+ );+ expect(filePathDescription(toolRegistry.get('edit_file'))).toContain(+ 'edit_file cannot rename skills',+ );+ });++ it('registers code-only descriptions for code-exec-only agents', () => {+ const toolRegistry = makeRegistry();+ const result = registerFileAuthoringTools({+ toolRegistry,+ toolDefinitions: [],+ includeSkillFileInstructions: false,+ });++ const createFile = result.toolDefinitions.find((d) => d.name === 'create_file');+ const editFile = result.toolDefinitions.find((d) => d.name === 'edit_file');+ expect(createFile?.description).toContain('code-execution sandbox');+ expect(createFile?.description).toContain('/mnt/data/');+ expect(createFile?.description).not.toContain('skills/');+ expect(editFile?.description).toContain('code-execution sandbox');+ expect(editFile?.description).toContain('/mnt/data/');+ expect(editFile?.description).not.toContain('skills/');+ expect(filePathDescription(createFile)).toContain('code-execution sandbox');+ expect(filePathDescription(createFile)).not.toContain('skills/');+ expect(filePathDescription(createFile)).not.toContain('SKILL.md');+ expect(filePathDescription(editFile)).toContain('code-execution sandbox');+ expect(filePathDescription(editFile)).not.toContain('skills/');+ expect(filePathDescription(editFile)).not.toContain('rename skills');+ });++ it('is idempotent across repeated registration calls', () => {+ const toolRegistry = makeRegistry();+ const first = registerFileAuthoringTools({+ toolRegistry,+ toolDefinitions: [],+ });+ const second = registerFileAuthoringTools({+ toolRegistry,+ toolDefinitions: first.toolDefinitions,+ });++ expect(second.registered).toEqual([]);+ expect(second.toolDefinitions).toHaveLength(2);+ });++ it('upgrades code-only definitions to skill-aware definitions', () => {+ const toolRegistry = makeRegistry();+ const codeOnly = registerFileAuthoringTools({+ toolRegistry,+ toolDefinitions: [],+ includeSkillFileInstructions: false,+ });+ const upgraded = registerFileAuthoringTools({+ toolRegistry,+ toolDefinitions: codeOnly.toolDefinitions,+ includeSkillFileInstructions: true,+ });++ expect(upgraded.registered).toEqual([]);+ expect(upgraded.toolDefinitions.find((d) => d.name === 'create_file')?.description).toContain(+ 'skills/',+ );+ expect(toolRegistry.get('edit_file')?.description).toContain('skills/');+ });++ it('distinguishes host file authoring definitions from user tools with matching names', () => {+ const result = registerFileAuthoringTools({+ toolRegistry: makeRegistry(),+ toolDefinitions: [],+ includeSkillFileInstructions: true,+ });+ const createFile = result.toolDefinitions.find((d) => d.name === 'create_file');++ expect(isFileAuthoringToolDefinition(createFile)).toBe(true);+ expect(+ isFileAuthoringToolDefinition({+ name: 'create_file',+ description: 'A user-defined create_file action',+ parameters: { type: 'object', properties: {} } as LCTool['parameters'],+ }),+ ).toBe(false);+ });+});diff --git a/packages/api/src/agents/tools.ts b/packages/api/src/agents/tools.tsindex 59c7ade5d8..b86047cba7 100644--- a/packages/api/src/agents/tools.ts+++ b/packages/api/src/agents/tools.ts@@ -1,10 +1,26 @@import {+ CODE_EXECUTION_TOOLS,BashExecutionToolDefinition,ReadFileToolDefinition,buildBashExecutionToolDescription,} from '@librechat/agents';import type { LCTool, LCToolRegistry } from '@librechat/agents';+export const CREATE_FILE_TOOL_NAME = 'create_file';+export const EDIT_FILE_TOOL_NAME = 'edit_file';+export const HOST_FILE_AUTHORING_ARTIFACT_KEY = '__librechat_file_authoring';+export const FILE_AUTHORING_TOOL_NAMES: ReadonlySet<string> = new Set([+ CREATE_FILE_TOOL_NAME,+ EDIT_FILE_TOOL_NAME,+]);++export function isCodeSessionToolName(+ name: string,+ hostFileAuthoringToolNames?: ReadonlySet<string>,+): boolean {+ return CODE_EXECUTION_TOOLS.has(name) || hostFileAuthoringToolNames?.has(name) === true;+}+interface ToolDefLike {name: string;[key: string]: unknown;@@ -86,6 +102,19 @@ export interface RegisterCodeExecutionToolsResult {registered: string[];}+export type RegisterFileAuthoringToolsResult = RegisterCodeExecutionToolsResult;++export interface RegisterFileAuthoringToolsParams {+ toolRegistry: LCToolRegistry | undefined;+ toolDefinitions: LCTool[] | undefined;+ /**+ * When true, descriptions point the model at the skill file namespace+ * (`skills/{skillName}/...`) in addition to sandbox paths. When false,+ * descriptions stay focused on code-execution sandbox files.+ */+ includeSkillFileInstructions?: boolean;+}+/*** Hoisted module-level definition for skill-aware `read_file` so* `registerCodeExecutionTools` doesn't re-allocate on every call. The@@ -93,9 +122,13 @@ export interface RegisterCodeExecutionToolsResult {* per-request state — so a single frozen object is safe to share across* every agent init.*/+const SKILL_READ_FILE_DESCRIPTION = `${ReadFileToolDefinition.description}++Also accepts authored skill file paths using "skills/{skillName}/...", including "skills/{skillName}/SKILL.md".`;+const READ_FILE_DEF: LCTool = Object.freeze({name: ReadFileToolDefinition.name,- description: ReadFileToolDefinition.description,+ description: SKILL_READ_FILE_DESCRIPTION,parameters: ReadFileToolDefinition.parameters as unknown as LCTool['parameters'],responseFormat: ReadFileToolDefinition.responseFormat,}) as LCTool;@@ -123,16 +156,215 @@ const CODE_READ_FILE_DEF: LCTool = Object.freeze({responseFormat: ReadFileToolDefinition.responseFormat,}) as LCTool;+const SKILL_CREATE_FILE_PARAMETERS: LCTool['parameters'] = Object.freeze({+ type: 'object',+ properties: {+ file_path: {+ type: 'string',+ description:+ 'Path to write. Use "skills/{skillName}/..." for skill files when available, or a code-execution sandbox path such as "/mnt/data/result.txt" when code execution is enabled. For SKILL.md, the YAML frontmatter name must match {skillName}.',+ },+ content: {+ type: 'string',+ description: 'Complete file contents.',+ },+ overwrite: {+ type: 'boolean',+ description: 'Must be true to replace an existing file. Refuses otherwise.',+ default: false,+ },+ },+ required: ['file_path', 'content'],+}) as LCTool['parameters'];++const CODE_CREATE_FILE_PARAMETERS: LCTool['parameters'] = Object.freeze({+ type: 'object',+ properties: {+ file_path: {+ type: 'string',+ description:+ 'Path to write in the code-execution sandbox, such as "/mnt/data/result.txt". Prefer /mnt/data/{file} for files that should remain available to later sandbox calls.',+ },+ content: {+ type: 'string',+ description: 'Complete file contents.',+ },+ overwrite: {+ type: 'boolean',+ description: 'Must be true to replace an existing file. Refuses otherwise.',+ default: false,+ },+ },+ required: ['file_path', 'content'],+}) as LCTool['parameters'];++const SKILL_EDIT_FILE_PARAMETERS: LCTool['parameters'] = Object.freeze({+ type: 'object',+ properties: {+ file_path: {+ type: 'string',+ description:+ 'Path to edit. Use "skills/{skillName}/..." for skill files when available, or a code-execution sandbox path such as "/mnt/data/result.txt" when code execution is enabled. edit_file cannot rename skills; keep SKILL.md frontmatter name equal to {skillName}.',+ },+ old_text: {+ type: 'string',+ description: 'Exact text to find. Must match exactly one location in the file.',+ },+ new_text: {+ type: 'string',+ description: 'Replacement text.',+ },+ edits: {+ type: 'array',+ description: 'Optional batch of replacements. Each old_text must match exactly once.',+ items: {+ type: 'object',+ properties: {+ old_text: { type: 'string' },+ new_text: { type: 'string' },+ },+ required: ['old_text', 'new_text'],+ },+ },+ },+ required: ['file_path'],+}) as LCTool['parameters'];++const CODE_EDIT_FILE_PARAMETERS: LCTool['parameters'] = Object.freeze({+ type: 'object',+ properties: {+ file_path: {+ type: 'string',+ description: 'Path to edit in the code-execution sandbox, such as "/mnt/data/result.txt".',+ },+ old_text: {+ type: 'string',+ description: 'Exact text to find. Must match exactly one location in the file.',+ },+ new_text: {+ type: 'string',+ description: 'Replacement text.',+ },+ edits: {+ type: 'array',+ description: 'Optional batch of replacements. Each old_text must match exactly once.',+ items: {+ type: 'object',+ properties: {+ old_text: { type: 'string' },+ new_text: { type: 'string' },+ },+ required: ['old_text', 'new_text'],+ },+ },+ },+ required: ['file_path'],+}) as LCTool['parameters'];++const SKILL_CREATE_FILE_DESCRIPTION = `Create a new file, or overwrite an existing file with explicit intent.++Use for new files and full rewrites where the change is larger than half the file. Requires overwrite: true to replace existing files. Refuses otherwise.++Paths starting with "skills/" target the skill file system:+- skills/{skillName}/SKILL.md - the skill's main instruction file+- skills/{skillName}/references/{file} - supporting reference files+- skills/{skillName}/scripts/{file} - helper scripts+- skills/{skillName}/templates/{file} - output templates++For skills/{skillName}/SKILL.md, YAML frontmatter name must match {skillName}. To use a different skill name, create a new skills/{newName}/SKILL.md instead.++When code execution is enabled, non-skills paths target the code-execution sandbox. Prefer /mnt/data/{file} for files that should remain available to later sandbox calls.`;++const CODE_CREATE_FILE_DESCRIPTION = `Create a new file, or overwrite an existing file with explicit intent.++Use for new files and full rewrites where the change is larger than half the file. Requires overwrite: true to replace existing files. Refuses otherwise.++Targets code-execution sandbox paths. Prefer /mnt/data/{file} for files that should remain available to later sandbox calls.`;++const SKILL_EDIT_FILE_DESCRIPTION = `Apply targeted text replacements to an existing file.++Use for small, precise changes. Each old_text must match exactly one location. Tries exact match first; falls back to whitespace-tolerant matching if needed. Reports which matching strategy was used. Returns a unified diff.++For skills/{skillName}/SKILL.md, edit description, title, or body content, but keep YAML frontmatter name equal to {skillName}. edit_file cannot rename skills; create a new skills/{newName}/SKILL.md for a different skill name.++Paths starting with "skills/" target the skill file system. When code execution is enabled, non-skills paths target the code-execution sandbox.`;++const CODE_EDIT_FILE_DESCRIPTION = `Apply targeted text replacements to an existing file.++Use for small, precise changes. Each old_text must match exactly one location. Tries exact match first; falls back to whitespace-tolerant matching if needed. Reports which matching strategy was used. Returns a unified diff.++Targets code-execution sandbox paths, such as /mnt/data/result.txt.`;++const SKILL_CREATE_FILE_DEF: LCTool = Object.freeze({+ name: CREATE_FILE_TOOL_NAME,+ description: SKILL_CREATE_FILE_DESCRIPTION,+ parameters: SKILL_CREATE_FILE_PARAMETERS,+ responseFormat: 'content_and_artifact' as LCTool['responseFormat'],+}) as LCTool;++const CODE_CREATE_FILE_DEF: LCTool = Object.freeze({+ name: CREATE_FILE_TOOL_NAME,+ description: CODE_CREATE_FILE_DESCRIPTION,+ parameters: CODE_CREATE_FILE_PARAMETERS,+ responseFormat: 'content_and_artifact' as LCTool['responseFormat'],+}) as LCTool;++const SKILL_EDIT_FILE_DEF: LCTool = Object.freeze({+ name: EDIT_FILE_TOOL_NAME,+ description: SKILL_EDIT_FILE_DESCRIPTION,+ parameters: SKILL_EDIT_FILE_PARAMETERS,+ responseFormat: 'content_and_artifact' as LCTool['responseFormat'],+}) as LCTool;++const CODE_EDIT_FILE_DEF: LCTool = Object.freeze({+ name: EDIT_FILE_TOOL_NAME,+ description: CODE_EDIT_FILE_DESCRIPTION,+ parameters: CODE_EDIT_FILE_PARAMETERS,+ responseFormat: 'content_and_artifact' as LCTool['responseFormat'],+}) as LCTool;+function buildReadFileDef(includeSkillFileInstructions: boolean): LCTool {return includeSkillFileInstructions ? READ_FILE_DEF : CODE_READ_FILE_DEF;}+function buildFileAuthoringDefs(includeSkillFileInstructions: boolean): LCTool[] {+ return includeSkillFileInstructions+ ? [SKILL_CREATE_FILE_DEF, SKILL_EDIT_FILE_DEF]+ : [CODE_CREATE_FILE_DEF, CODE_EDIT_FILE_DEF];+}+function isCodeOnlyReadFileDef(def: LCTool | undefined): boolean {return (def?.name === ReadFileToolDefinition.name && def?.description === CODE_READ_FILE_DESCRIPTION);}+function isCodeOnlyFileAuthoringDef(def: LCTool | undefined): boolean {+ if (def?.name === CREATE_FILE_TOOL_NAME) {+ return def.description === CODE_CREATE_FILE_DESCRIPTION;+ }+ if (def?.name === EDIT_FILE_TOOL_NAME) {+ return def.description === CODE_EDIT_FILE_DESCRIPTION;+ }+ return false;+}++export function isFileAuthoringToolDefinition(def: LCTool | undefined): boolean {+ if (def?.name === CREATE_FILE_TOOL_NAME) {+ return (+ def.description === CODE_CREATE_FILE_DESCRIPTION ||+ def.description === SKILL_CREATE_FILE_DESCRIPTION+ );+ }+ if (def?.name === EDIT_FILE_TOOL_NAME) {+ return (+ def.description === CODE_EDIT_FILE_DESCRIPTION ||+ def.description === SKILL_EDIT_FILE_DESCRIPTION+ );+ }+ return false;+}+/*** The `bash_tool` description varies along exactly one axis — whether* the LLM-facing `{{tool<idx>turn<turn>}}` reference syntax guide is@@ -239,3 +471,54 @@ export function registerCodeExecutionTools(registered,};}++export function registerFileAuthoringTools(+ params: RegisterFileAuthoringToolsParams,+): RegisterFileAuthoringToolsResult {+ const { toolRegistry, toolDefinitions, includeSkillFileInstructions = true } = params;++ const candidates = buildFileAuthoringDefs(includeSkillFileInstructions);+ const inputDefinitions = toolDefinitions ?? [];+ let workingDefinitions = inputDefinitions;++ const registered: string[] = [];+ const newDefs: LCTool[] = [];+ for (const def of candidates) {+ const existingIndex = workingDefinitions.findIndex((d) => d.name === def.name);+ const existingDef = existingIndex >= 0 ? workingDefinitions[existingIndex] : undefined;+ const registryDef = toolRegistry?.get(def.name);++ if (+ includeSkillFileInstructions &&+ (isCodeOnlyFileAuthoringDef(existingDef) || isCodeOnlyFileAuthoringDef(registryDef))+ ) {+ if (isCodeOnlyFileAuthoringDef(existingDef)) {+ workingDefinitions =+ workingDefinitions === inputDefinitions ? [...inputDefinitions] : workingDefinitions;+ workingDefinitions[existingIndex] = def;+ }+ if (isCodeOnlyFileAuthoringDef(registryDef)) {+ toolRegistry?.set(def.name, def);+ }+ continue;+ }++ const inRegistry = toolRegistry?.has(def.name) === true;+ const inDefs = existingIndex >= 0;+ if (inRegistry || inDefs) {+ continue;+ }++ toolRegistry?.set(def.name, def);+ newDefs.push(def);+ registered.push(def.name);+ }++ if (newDefs.length === 0) {+ return { toolDefinitions: workingDefinitions, registered };+ }+ return {+ toolDefinitions: [...workingDefinitions, ...newDefs],+ registered,+ };+}diff --git a/packages/data-schemas/src/methods/skill.spec.ts b/packages/data-schemas/src/methods/skill.spec.tsindex 85ecf41bf8..bbd1d16530 100644--- a/packages/data-schemas/src/methods/skill.spec.ts+++ b/packages/data-schemas/src/methods/skill.spec.ts@@ -645,6 +645,55 @@ describe('Skill CRUD methods', () => {expect(fetched?.allowedTools).toEqual(['execute_code']);});+ it('getAuthorSkillByName resolves only the matching author and tenant', async () => {+ const sharedName = 'author-owned-lookup';+ const ownerSkill = await Skill.create({+ name: sharedName,+ description: 'Owner tenant skill.',+ body: 'owner body',+ frontmatter: {},+ author: owner._id,+ authorName: owner.name ?? 'Skill Owner',+ tenantId: 'tenant-a',+ version: 1,+ source: 'inline',+ fileCount: 0,+ });+ await Skill.create({+ name: sharedName,+ description: 'Other author skill.',+ body: 'other body',+ frontmatter: {},+ author: other._id,+ authorName: other.name ?? 'Other',+ tenantId: 'tenant-a',+ version: 1,+ source: 'inline',+ fileCount: 0,+ });+ await Skill.create({+ name: sharedName,+ description: 'Owner different tenant skill.',+ body: 'tenant b body',+ frontmatter: {},+ author: owner._id,+ authorName: owner.name ?? 'Skill Owner',+ tenantId: 'tenant-b',+ version: 1,+ source: 'inline',+ fileCount: 0,+ });++ const fetched = await methods.getAuthorSkillByName({+ name: sharedName,+ author: owner._id,+ tenantId: 'tenant-a',+ });++ expect(fetched?._id.toString()).toBe(ownerSkill._id.toString());+ expect(fetched?.body).toBe('owner body');+ });+it('preferModelInvocable picks the model-invocable doc on same-name collision (does NOT filter on userInvocable)', async () => {/* Same-name collision scenario the model paths must handle: an olderuser-invocable variant and a newer model-only variantdiff --git a/packages/data-schemas/src/methods/skill.ts b/packages/data-schemas/src/methods/skill.tsindex bc1d2260c6..85fc7d30a3 100644--- a/packages/data-schemas/src/methods/skill.ts+++ b/packages/data-schemas/src/methods/skill.ts@@ -489,6 +489,12 @@ export type UpdateSkillInput = {alwaysApply?: boolean;};+export type GetAuthorSkillByNameParams = {+ name: string;+ author: Types.ObjectId | string;+ tenantId?: string | null;+};+/*** Maps the runtime-enforced frontmatter fields onto their first-class* column equivalents. Returns only the keys that were explicitly set on the@@ -1017,6 +1023,22 @@ export function createSkillMethods(mongoose: typeof import('mongoose'), deps: Skreturn preferred ?? docs[0];}+ async function getAuthorSkillByName(+ params: GetAuthorSkillByNameParams,+ ): Promise<(ISkill & { _id: Types.ObjectId }) | null> {+ const Skill = mongoose.models.Skill as Model<ISkillDocument>;+ const doc = await Skill.findOne({+ name: params.name,+ author: params.author,+ tenantId: params.tenantId ?? null,+ })+ .sort({ updatedAt: -1 })+ .lean();+ return backfillDerivedFromFrontmatter(+ (doc as unknown as (ISkill & { _id: Types.ObjectId }) | null) ?? null,+ );+ }+async function listSkillsByAccess(params: ListSkillsByAccessParams,): Promise<ListSkillsByAccessResult> {@@ -1526,6 +1548,7 @@ export function createSkillMethods(mongoose: typeof import('mongoose'), deps: SkcreateSkill,getSkillById,getSkillByName,+ getAuthorSkillByName,listSkillsByAccess,listAlwaysApplySkills,updateSkill,