diff --git a/api/server/controllers/agents/__tests__/openai.spec.js b/api/server/controllers/agents/__tests__/openai.spec.js index 561145f855..746d0675fc 100644 --- a/api/server/controllers/agents/__tests__/openai.spec.js +++ b/api/server/controllers/agents/__tests__/openai.spec.js @@ -232,6 +232,9 @@ jest.mock('@librechat/api', () => ({ buildInitialToolSessions: jest.fn().mockReturnValue(mockInitialSessions), AgentRunEnvelopeError: MockAgentRunEnvelopeError, createAgentRunEnvelope: (...args) => mockCreateAgentRunEnvelope(...args), + createRemoteExecutionContext: jest.fn((...args) => + jest.requireActual('@librechat/api').createRemoteExecutionContext(...args), + ), resolveAdmittedCodeEnvironmentDecision: (...args) => jest.requireActual('@librechat/api').resolveAdmittedCodeEnvironmentDecision(...args), createMCPRuntimeRequestBody: ({ @@ -1737,6 +1740,30 @@ describe('OpenAIChatCompletionController', () => { }); describe('remote-agent file authorization', () => { + it('passes on what the execution context says about attendance, not an answer of its own', async () => { + const { initializeAgent, createRemoteExecutionContext } = require('@librechat/api'); + const { loadAgentTools } = require('~/server/services/ToolService'); + createRemoteExecutionContext.mockReturnValueOnce({ + principal: { userId: 'user-123' }, + agentId: 'agent-123', + source: { type: 'remote_api', protocol: 'chat.completions', background: true }, + unattended: false, + }); + + await OpenAIChatCompletionController(req, res); + + const [initializeParams] = initializeAgent.mock.calls.at(-1); + await initializeParams.loadTools({ + agentId: 'agent-123', + tools: ['file_search'], + provider: 'openAI', + model: 'gpt-4', + }); + expect(loadAgentTools).toHaveBeenLastCalledWith( + expect.objectContaining({ unattended: false }), + ); + }); + it('threads the remote-agent permission boundary through initialization and tool loading', async () => { const { initializeAgent, createToolExecuteHandler } = require('@librechat/api'); const { loadAgentTools, loadToolsForExecution } = require('~/server/services/ToolService'); @@ -1768,8 +1795,9 @@ describe('OpenAIChatCompletionController', () => { model: 'gpt-4', tool_resources: { file_search: { file_ids: ['owner-file'] } }, }); + /** Nobody reads a chat-completions response in a browser, so tool loading must not prompt. */ expect(loadAgentTools).toHaveBeenLastCalledWith( - expect.objectContaining({ agentResourceType: ResourceType.REMOTE_AGENT }), + expect.objectContaining({ agentResourceType: ResourceType.REMOTE_AGENT, unattended: true }), ); const toolExecuteOptions = createToolExecuteHandler.mock.calls.at(-1)[0]; @@ -1790,6 +1818,7 @@ describe('OpenAIChatCompletionController', () => { agentResourceType: ResourceType.REMOTE_AGENT, requestBody: initializeParams.requestBody, signal: effectiveSignal, + unattended: true, }), ); mockExecution.abort(); diff --git a/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js b/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js index 16f47090cb..d50d91ba0c 100644 --- a/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js +++ b/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js @@ -75,6 +75,7 @@ jest.mock('@librechat/api', () => ({ persistedReasoningOverrideFields: jest.requireActual('@librechat/api').persistedReasoningOverrideFields, isScheduleFireRequest: jest.fn(() => false), + createScheduleExecutionContext: jest.fn(() => undefined), exemptFromConcurrencyLimiter: jest.fn(() => false), toPendingSteer: jest.fn((item) => item), isSteerPreemptSupported: jest.fn(() => true), diff --git a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js index 440bdde7ca..11dbb42a0e 100644 --- a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js +++ b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js @@ -297,6 +297,8 @@ jest.mock('@librechat/api', () => ({ jest.requireActual('@librechat/api').persistedReasoningOverrideFields, logAgentMemorySnapshot: jest.fn(), isScheduleFireRequest: (...args) => mockIsScheduleFireRequest(...args), + createScheduleExecutionContext: (...args) => + jest.requireActual('@librechat/api').createScheduleExecutionContext(...args), exemptFromConcurrencyLimiter: (...args) => mockExemptFromConcurrencyLimiter(...args), toPendingSteer: jest.fn((item) => item), promoteDrainedSteers: (...args) => @@ -1255,6 +1257,57 @@ describe('ResumableAgentController resume metadata', () => { expect(mockDecrementPendingRequest).toHaveBeenCalledWith('user-123'); }); + it.each([ + ['a verified schedule trigger', true], + ['an ordinary request that copies the trigger body', false], + ])('passes the schedule context to initialization only for %s', async (_label, trusted) => { + const conversationId = 'scheduled-context-conversation'; + mockGenerationJobManager.claimGeneration.mockResolvedValue( + wonGenerationClaim({ streamId: conversationId, conversationId }), + ); + mockIsScheduleLive.mockResolvedValue(true); + const req = { + _isAgentTrigger: trusted, + _isScheduledFire: trusted, + _isManualScheduledFire: false, + user: { id: 'user-123', tenantId: 'tenant-1' }, + body: { + text: 'Run the scheduled digest.', + messageId: 'scheduled-context-message', + conversationId: 'new', + newConversationId: conversationId, + agent_id: 'agent-1', + scheduleId: 'schedule-1', + scheduledFor: '2026-08-17T12:00:00.000Z', + agentTrigger: { + version: 1, + event: { + type: 'schedule.occurrence', + occurredAt: Date.parse('2026-08-17T12:00:00.000Z'), + source: { type: 'schedule', id: 'schedule-1' }, + }, + }, + endpointOption: { endpoint: 'agents', agent_id: 'agent-1' }, + }, + config: {}, + }; + const initializeClient = jest.fn().mockRejectedValue(new Error('stop before provider')); + + await AgentController(req, createResumableResponse(), jest.fn(), initializeClient, null); + + expect(initializeClient).toHaveBeenCalledTimes(1); + expect(initializeClient.mock.calls[0][0].executionContext).toEqual( + trusted + ? { + principal: { userId: 'user-123', tenantId: 'tenant-1' }, + agentId: 'agent-1', + source: { type: 'schedule', id: 'schedule-1', manual: false, resumed: false }, + unattended: false, + } + : undefined, + ); + }); + it('rejects a superseded automatic occurrence after durable job creation and preserves its outcome', async () => { const conversationId = 'scheduled-conversation-123'; mockGenerationJobManager.claimGeneration.mockResolvedValue( diff --git a/api/server/controllers/agents/__tests__/responses.unit.spec.js b/api/server/controllers/agents/__tests__/responses.unit.spec.js index e7f0bc1570..77bd9c49cb 100644 --- a/api/server/controllers/agents/__tests__/responses.unit.spec.js +++ b/api/server/controllers/agents/__tests__/responses.unit.spec.js @@ -299,6 +299,9 @@ jest.mock('@librechat/api', () => ({ })), AgentRunEnvelopeError: MockAgentRunEnvelopeError, createAgentRunEnvelope: (...args) => mockCreateAgentRunEnvelope(...args), + createRemoteExecutionContext: jest.fn((...args) => + jest.requireActual('@librechat/api').createRemoteExecutionContext(...args), + ), resolveAdmittedCodeEnvironmentDecision: (...args) => jest.requireActual('@librechat/api').resolveAdmittedCodeEnvironmentDecision(...args), resolvePersistableCodeEnvironmentDecision: (...args) => @@ -2690,6 +2693,30 @@ describe('createResponse controller', () => { }, ); + it('passes on what the execution context says about attendance, not an answer of its own', async () => { + const { initializeAgent, createRemoteExecutionContext } = require('@librechat/api'); + const { loadAgentTools } = require('~/server/services/ToolService'); + createRemoteExecutionContext.mockReturnValueOnce({ + principal: { userId: 'user-123' }, + agentId: 'agent-123', + source: { type: 'remote_api', protocol: 'responses', background: true }, + unattended: false, + }); + + await createResponse(req, res); + + const [initializeParams] = initializeAgent.mock.calls.at(-1); + await initializeParams.loadTools({ + agentId: 'agent-123', + tools: ['file_search'], + provider: 'anthropic', + model: 'claude-3', + }); + expect(loadAgentTools).toHaveBeenLastCalledWith( + expect.objectContaining({ unattended: false }), + ); + }); + it.each([false, true])( 'threads the remote-agent permission boundary through initialization and tool loading (stream=%s)', async (stream) => { @@ -2727,8 +2754,12 @@ describe('createResponse controller', () => { model: 'claude-3', tool_resources: { file_search: { file_ids: ['owner-file'] } }, }); + /** A foreground response answers an API client, so tool loading must not prompt. */ expect(loadAgentTools).toHaveBeenLastCalledWith( - expect.objectContaining({ agentResourceType: ResourceType.REMOTE_AGENT }), + expect.objectContaining({ + agentResourceType: ResourceType.REMOTE_AGENT, + unattended: true, + }), ); const toolExecuteOptions = createToolExecuteHandler.mock.calls.at(-1)[0]; @@ -2749,6 +2780,7 @@ describe('createResponse controller', () => { agentResourceType: ResourceType.REMOTE_AGENT, requestBody: initializeParams.requestBody, signal: effectiveSignal, + unattended: true, }), ); mockExecution.abort(); diff --git a/api/server/controllers/agents/__tests__/resume.spec.js b/api/server/controllers/agents/__tests__/resume.spec.js index b995483df7..884585c1e7 100644 --- a/api/server/controllers/agents/__tests__/resume.spec.js +++ b/api/server/controllers/agents/__tests__/resume.spec.js @@ -1150,7 +1150,7 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => { expect(mockInitializeClient.mock.calls[0][0].scheduleJobIdentity.scheduleMCPCompletion).toEqual( lineage, ); - expect(mockInitializeClient.mock.calls[0][0].scheduledTokenContext).toBeUndefined(); + expect(mockInitializeClient.mock.calls[0][0].executionContext).toBeUndefined(); expect(capturedInit.isScheduledFire).not.toBe(true); expect(mockClaimScheduleResume).not.toHaveBeenCalled(); expect(mockRecordScheduleOutcome).not.toHaveBeenCalled(); @@ -1393,12 +1393,11 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => { await settled; expect(capturedInit.isScheduledFire).toBe(true); - expect(mockInitializeClient.mock.calls[0][0].scheduledTokenContext).toEqual({ - scheduleId: 'schedule-1', - ownerId: USER_ID, - tenantId: TENANT_ID, + expect(mockInitializeClient.mock.calls[0][0].executionContext).toEqual({ + principal: { userId: USER_ID, tenantId: TENANT_ID }, agentId: AGENT_ID, - invocationMode: 'delegated', + source: { type: 'schedule', id: 'schedule-1', manual: false, resumed: true }, + unattended: false, }); expect(mockClaimScheduleResume).toHaveBeenCalledWith('schedule-1', scheduledFor, { diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.js index c4cc776f7e..78309f09e0 100644 --- a/api/server/controllers/agents/openai.js +++ b/api/server/controllers/agents/openai.js @@ -14,6 +14,7 @@ const { const { writeSSE, createRun, + createRemoteExecutionContext, createChunk, applyContextToAgent, buildRunToolSet, @@ -129,7 +130,7 @@ const filterFilesByRemoteAgentAccess = (params) => * @param {boolean} [runtime.definitionsOnly=true] - When true, returns only serializable * tool definitions without creating full tool instances (for event-driven mode) */ -function createToolLoader({ req, res, signal, definitionsOnly = true }) { +function createToolLoader({ req, res, signal, unattended, definitionsOnly = true }) { return async function loadTools({ tools, model, @@ -157,7 +158,7 @@ function createToolLoader({ req, res, signal, definitionsOnly = true }) { definitionsOnly, accessibleMcpServerNames, streamId: null, // No resumable stream for OpenAI compat - unattended: true, + unattended, }); } catch (error) { if (isFatalAgentInitializationError(error, { signal }) || isContentFilterError(error)) { @@ -292,6 +293,12 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => { const requestStartTime = envelope.receivedAt; const request = envelope.payload; const { principal } = envelope; + const executionContext = createRemoteExecutionContext({ + principal, + agentId: request.model, + protocol: 'chat.completions', + background: false, + }); // Request-backed tool adapters still observe the validated envelope payload; // shared initialization receives the transport-free runtime below. req.body = request; @@ -531,7 +538,12 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => { agentsEConfig?.backgroundTasks?.completionResultMaxChars; // Create tool loader - const loadTools = createToolLoader({ req, res, signal: execution.signal }); + const loadTools = createToolLoader({ + req, + res, + signal: execution.signal, + unattended: executionContext.unattended, + }); // Initialize the agent first to check for disableStreaming const endpointOption = { @@ -893,7 +905,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => { const result = await loadToolsForExecution({ req, res, - unattended: true, + unattended: executionContext.unattended, agentResourceType: ResourceType.REMOTE_AGENT, conversationId, requestBody: mcpRequestBody, diff --git a/api/server/controllers/agents/request.js b/api/server/controllers/agents/request.js index c4c1291b5e..1929d05240 100644 --- a/api/server/controllers/agents/request.js +++ b/api/server/controllers/agents/request.js @@ -26,6 +26,7 @@ const { checkAndIncrementPendingRequest, exemptFromConcurrencyLimiter, isScheduleFireRequest, + createScheduleExecutionContext, isUnpersistedPreliminaryParent, startAgentProjectContextResolution, assertChatProjectInstructions, @@ -2054,6 +2055,7 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit req, res, endpointOption, + executionContext: createScheduleExecutionContext(req), // Use the job's abort controller signal - allows abort via GenerationJobManager.abortJob() signal: job.abortController.signal, jobCreatedAt, diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.js index 6e6f0af5d3..5048fba597 100644 --- a/api/server/controllers/agents/responses.js +++ b/api/server/controllers/agents/responses.js @@ -11,6 +11,7 @@ const { const { createRun, applyContextToAgent, + createRemoteExecutionContext, buildInitialToolSessions, buildRunToolSet, AgentRunEnvelopeError, @@ -456,6 +457,12 @@ const executeResponse = async (envelope, { req, res }) => { addConvoToolApprovalAllows: db.addConvoToolApprovalAllows, }); const responseId = responseRuntime.responseId; + const executionContext = createRemoteExecutionContext({ + principal, + agentId: request.model, + protocol: 'responses', + background: responseRuntime.background, + }); const terminalRunError = createTerminalRunErrorObserver({ maxProviderErrorChars: appConfig?.endpoints?.agents?.maxProviderErrorChars, logger, @@ -621,6 +628,7 @@ const executeResponse = async (envelope, { req, res }) => { res, signal: execution.signal, ...responseRuntime.toolContext(execution), + unattended: executionContext.unattended, }); const skillDbMethods = getSkillDbMethods(); @@ -1122,6 +1130,7 @@ const executeResponse = async (envelope, { req, res }) => { ...responseRuntime.toolContext(execution), req, res, + unattended: executionContext.unattended, agentResourceType: ResourceType.REMOTE_AGENT, conversationId, requestBody: mcpRequestBody, @@ -1356,6 +1365,7 @@ const executeResponse = async (envelope, { req, res }) => { ...responseRuntime.toolContext(execution), req, res, + unattended: executionContext.unattended, agentResourceType: ResourceType.REMOTE_AGENT, conversationId, requestBody: mcpRequestBody, diff --git a/api/server/controllers/agents/resume.js b/api/server/controllers/agents/resume.js index 1728469337..430e54c057 100644 --- a/api/server/controllers/agents/resume.js +++ b/api/server/controllers/agents/resume.js @@ -52,7 +52,7 @@ const { rejectChangedResumeProjectContext, PROJECT_CONTEXT_CHANGED_REASON, PROJECT_CONTEXT_CHANGED_RESPONSE, - restoreScheduledTokenContext, + restoreExecutionContext, recoverTurnMessageReference, applyForcedRetention, applyForcedTemporaryRequest, @@ -1953,7 +1953,7 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle) parentMessageId: job.metadata.userMessage?.messageId ?? Constants.NO_PARENT, }); const result = await initializeClient({ - scheduledTokenContext: restoreScheduledTokenContext(req, job.metadata), + executionContext: restoreExecutionContext(req, job.metadata), scheduleJobIdentity: job.metadata, req, res, diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.js index 7782b61ac1..87dd0d1c27 100644 --- a/api/server/services/Endpoints/agents/initialize.js +++ b/api/server/services/Endpoints/agents/initialize.js @@ -2150,7 +2150,7 @@ function createInitializeClient(dependencies = {}) { params.req, dependencies.resolveUpstreamTokenProvider, params.signal, - params.scheduledTokenContext, + params.executionContext, ); return initializeWithScheduleMCPExecution( { @@ -2160,7 +2160,7 @@ function createInitializeClient(dependencies = {}) { params.req, params.res, ), - restoredContext: params.scheduledTokenContext, + executionContext: params.executionContext, restoredJob: params.scheduleJobIdentity, }, () => require('~/server/services/Schedules/consent'), @@ -2169,7 +2169,7 @@ function createInitializeClient(dependencies = {}) { { req: params.req, context: getMCPRequestContext(params.req), - restoredContext: params.scheduledTokenContext, + executionContext: params.executionContext, host: dependencies.scheduledBearerHost, signal: params.signal, streamId: params.req._resumableStreamId, diff --git a/api/server/services/Endpoints/agents/initialize.spec.js b/api/server/services/Endpoints/agents/initialize.spec.js index dd479b68f6..e51435ac87 100644 --- a/api/server/services/Endpoints/agents/initialize.spec.js +++ b/api/server/services/Endpoints/agents/initialize.spec.js @@ -45,6 +45,19 @@ jest.mock('@librechat/api', () => ({ createSequentialChainEdges: jest.fn(), })); +/** What the chat controller passes for a fresh occurrence, or the resume host for a restored one. */ +function scheduledContext(req, restored, scheduleId) { + const { restoreExecutionContext, createScheduleExecutionContext } = require('@librechat/api'); + return restored + ? restoreExecutionContext(req, { + userId: req.user.id, + tenantId: req.user.tenantId, + scheduleId, + agent_id: PRIMARY_ID, + }) + : createScheduleExecutionContext(req); +} + /** Captured by the `getDefaultHandlers` mock so tests can drive the * `ON_TOOL_EXECUTE` pipeline with a real subagent id and observe whether * the tool context (agent, tool_resources, skill ACLs) was preserved. */ @@ -223,14 +236,7 @@ describe('initializeClient — processAgent ACL gate', () => { req, res: {}, signal, - scheduledTokenContext: restored - ? { - scheduleId: 'sched-1', - ownerId: req.user.id, - agentId: PRIMARY_ID, - invocationMode: 'delegated', - } - : undefined, + executionContext: scheduledContext(req, restored, 'sched-1'), endpointOption: makeEndpointOption(), }); @@ -298,14 +304,7 @@ describe('initializeClient — processAgent ACL gate', () => { signal: new AbortController().signal, endpointOption: makeEndpointOption(), jobCreatedAt: 42, - scheduledTokenContext: restored - ? { - scheduleId: 'sched-bearer', - ownerId: req.user.id, - agentId: PRIMARY_ID, - invocationMode: 'delegated', - } - : undefined, + executionContext: scheduledContext(req, restored, 'sched-bearer'), }); expect(bind).toHaveBeenCalledWith( { diff --git a/packages/api/src/agents/authority/context.spec.ts b/packages/api/src/agents/authority/context.spec.ts new file mode 100644 index 0000000000..be25beb04e --- /dev/null +++ b/packages/api/src/agents/authority/context.spec.ts @@ -0,0 +1,190 @@ +import { + getScheduleSource, + restoreExecutionContext, + toScheduledTokenContext, + createRemoteExecutionContext, + createScheduleExecutionContext, +} from './context'; + +const user = { id: 'owner', tenantId: 'tenant' }; + +function scheduleFire({ manual = false, agentId = 'root-agent' as unknown } = {}) { + return { + user, + _isAgentTrigger: true, + body: { + agent_id: agentId, + scheduleId: 'spoofed', + agentTrigger: { + version: 1, + event: { + type: 'schedule.occurrence', + occurredAt: 0, + source: { type: 'schedule', id: 'schedule' }, + }, + metadata: { manual }, + }, + }, + }; +} + +const savedJob = { + userId: 'owner', + tenantId: 'tenant', + scheduleId: 'schedule', + scheduleManual: true, + agent_id: 'root-agent', +}; + +describe('createScheduleExecutionContext', () => { + it.each([false, true])('reads the verified trigger, not the body (manual=%s)', (manual) => { + const context = createScheduleExecutionContext(scheduleFire({ manual })); + + expect(context).toEqual({ + principal: { userId: 'owner', tenantId: 'tenant' }, + agentId: 'root-agent', + source: { type: 'schedule', id: 'schedule', manual, resumed: false }, + unattended: false, + }); + expect(Object.isFrozen(context)).toBe(true); + expect(Object.isFrozen(context?.principal)).toBe(true); + expect(Object.isFrozen(context?.source)).toBe(true); + }); + + it('ignores schedule fields copied into an ordinary request', () => { + expect( + createScheduleExecutionContext({ ...scheduleFire(), _isAgentTrigger: false }), + ).toBeUndefined(); + expect( + createScheduleExecutionContext({ user, body: { scheduleId: 'forged' } }), + ).toBeUndefined(); + }); + + it('keeps no agent when the trigger body carries a non-string one', () => { + expect(createScheduleExecutionContext(scheduleFire({ agentId: 42 }))?.agentId).toBeUndefined(); + }); +}); + +describe('restoreExecutionContext', () => { + it('rebuilds a paused scheduled run from its saved job', () => { + const context = restoreExecutionContext({ user }, savedJob); + + expect(context).toEqual({ + principal: { userId: 'owner', tenantId: 'tenant' }, + agentId: 'root-agent', + source: { type: 'schedule', id: 'schedule', manual: true, resumed: true }, + unattended: false, + }); + expect(Object.isFrozen(context)).toBe(true); + }); + + it('returns nothing for an unscheduled job', () => { + expect(restoreExecutionContext({ user }, { userId: 'owner' })).toBeUndefined(); + expect(restoreExecutionContext({ user })).toBeUndefined(); + }); + + it.each([{ userId: 'different' }, { tenantId: 'different' }])( + 'refuses a job owned by someone else %j', + (override) => { + expect(() => restoreExecutionContext({ user }, { ...savedJob, ...override })).toThrow( + 'Scheduled job identity', + ); + }, + ); + + it.each([{ agent_id: undefined }, { tenantId: undefined }])( + 'restores a legacy job %j without an agent, so it cannot mint', + (override) => { + const context = restoreExecutionContext({ user }, { ...savedJob, ...override }); + + expect(getScheduleSource(context)).toMatchObject({ id: 'schedule', resumed: true }); + expect(context?.agentId).toBeUndefined(); + expect(toScheduledTokenContext(context)).toBeUndefined(); + }, + ); +}); + +describe('createRemoteExecutionContext', () => { + it('records the principal, agent and protocol', () => { + const context = createRemoteExecutionContext({ + principal: { userId: 'owner', tenantId: 'tenant', role: 'USER' }, + agentId: 'agent_remote', + protocol: 'responses', + background: true, + }); + + expect(context).toEqual({ + principal: { userId: 'owner', tenantId: 'tenant', role: 'USER' }, + agentId: 'agent_remote', + source: { type: 'remote_api', protocol: 'responses', background: true }, + unattended: false, + }); + expect(Object.isFrozen(context.source)).toBe(true); + }); +}); + +describe('whether anybody can follow a sign-in prompt', () => { + const remote = (background: boolean) => + createRemoteExecutionContext({ + principal: { userId: 'owner' }, + protocol: 'chat.completions', + background, + }); + const job = { userId: 'owner', tenantId: 'tenant', scheduleId: 'sched-1', agent_id: 'agent_x' }; + + it.each([ + ['a foreground remote run', remote(false), true], + ['a background remote run', remote(true), false], + ['a scheduled run', createScheduleExecutionContext(scheduleFire()), false], + [ + 'a resumed scheduled run', + restoreExecutionContext({ user: { id: 'owner', tenantId: 'tenant' } }, job), + false, + ], + ])('is decided where the run enters: %s', (_label, context, expected) => { + expect(context?.unattended).toBe(expected); + }); +}); + +describe('toScheduledTokenContext', () => { + it('projects the identity host credential providers bind to', () => { + const fresh = toScheduledTokenContext(createScheduleExecutionContext(scheduleFire())); + const resumed = toScheduledTokenContext(restoreExecutionContext({ user }, savedJob)); + const expected = { + scheduleId: 'schedule', + ownerId: 'owner', + tenantId: 'tenant', + agentId: 'root-agent', + invocationMode: 'delegated', + }; + + expect(fresh).toEqual(expected); + expect(resumed).toEqual(expected); + expect(Object.isFrozen(fresh)).toBe(true); + }); + + it('omits the tenant for a tenant-less owner', () => { + const context = createScheduleExecutionContext({ ...scheduleFire(), user: { id: 'owner' } }); + + expect(toScheduledTokenContext(context)).not.toHaveProperty('tenantId'); + }); + + it.each([[' '], ['']])('projects nothing for a blank agent %j', (agentId) => { + expect( + toScheduledTokenContext(createScheduleExecutionContext(scheduleFire({ agentId }))), + ).toBeUndefined(); + }); + + it('projects nothing for an unscheduled run', () => { + expect( + toScheduledTokenContext( + createRemoteExecutionContext({ + principal: { userId: 'owner' }, + agentId: 'agent_remote', + protocol: 'responses', + background: false, + }), + ), + ).toBeUndefined(); + }); +}); diff --git a/packages/api/src/agents/authority/context.ts b/packages/api/src/agents/authority/context.ts new file mode 100644 index 0000000000..bbda66919a --- /dev/null +++ b/packages/api/src/agents/authority/context.ts @@ -0,0 +1,172 @@ +import type { ScheduledTokenContext } from '~/schedules/context'; +import type { AgentRunProtocol } from '../envelope'; +import { readScheduleFireContext } from '~/schedules/trigger'; + +/** The user whose authority a run exercises. */ +export interface ExecutionPrincipal { + readonly userId: string; + readonly tenantId?: string; + readonly role?: string; +} + +/** Why the run exists, as established by the server at its entry point. */ +export type ExecutionSource = + | { + readonly type: 'schedule'; + /** The schedule that fired, read from the verified trigger or the saved job. */ + readonly id: string; + /** Started by the owner's Run Now rather than the schedule's cadence. */ + readonly manual: boolean; + /** Restored from a saved job after an approval pause, not a fresh occurrence. */ + readonly resumed: boolean; + } + | { + readonly type: 'remote_api'; + readonly protocol: AgentRunProtocol; + /** A background Responses run, whose events go to a stream the owner can follow. */ + readonly background: boolean; + }; + +/** + * Who a run acts for and why, built once by the server where the run enters and passed + * down from there. No client or model input sets any field. Frozen: a consumer cannot + * change what a later consumer sees. + */ +export interface ExecutionContext { + readonly principal: ExecutionPrincipal; + /** The root agent the run was admitted for. Subagents and handoffs keep it. */ + readonly agentId?: string; + readonly source: ExecutionSource; + /** + * Nobody can follow a sign-in prompt for this run: a remote API run with no generation + * stream answers an API client, not a person. Decided here, so nothing that loads tools + * for the run works it out again. + */ + readonly unattended: boolean; +} + +interface AuthenticatedRequest { + user: { id: string; tenantId?: string }; +} + +function principalOf(user: AuthenticatedRequest['user']): ExecutionPrincipal { + return Object.freeze({ userId: user.id, ...(user.tenantId ? { tenantId: user.tenantId } : {}) }); +} + +/** + * The context of a fresh schedule occurrence, from the trigger the trigger host verified. + * Undefined for any other request, including one whose body copies schedule fields. + */ +export function createScheduleExecutionContext( + req: AuthenticatedRequest & Parameters[0], +): ExecutionContext | undefined { + const fire = readScheduleFireContext(req); + if (!fire) return; + const agentId = req?.body?.agent_id; + return Object.freeze({ + principal: principalOf(req.user), + ...(typeof agentId === 'string' ? { agentId } : {}), + source: Object.freeze({ + type: 'schedule', + id: fire.scheduleId, + manual: fire.manual, + resumed: false, + }), + unattended: false, + }); +} + +/** The schedule fields a saved generation job carries. */ +export interface ScheduleJobIdentity { + userId?: string; + tenantId?: string; + scheduleId?: string; + scheduleManual?: boolean; + agent_id?: string; +} + +/** + * Rebuilds a scheduled run's context from its saved job when it resumes, after the resume + * host has checked job ownership, tenancy, agent and schedule liveness. Throws when the job + * belongs to someone other than the authenticated owner. Undefined for an unscheduled job. + */ +export function restoreExecutionContext( + req: AuthenticatedRequest, + metadata?: ScheduleJobIdentity, +): ExecutionContext | undefined { + if (!metadata?.scheduleId) return; + if ( + metadata.userId !== req.user.id || + (metadata.tenantId != null && metadata.tenantId !== req.user.tenantId) + ) { + throw new Error('Scheduled job identity does not match the authenticated owner.'); + } + /** A legacy job that cannot prove both its root agent and its tenant restores without an agent. */ + const complete = Boolean(metadata.agent_id) && !(req.user.tenantId && metadata.tenantId == null); + return Object.freeze({ + principal: Object.freeze({ + userId: metadata.userId, + ...(metadata.tenantId ? { tenantId: metadata.tenantId } : {}), + }), + ...(complete ? { agentId: metadata.agent_id } : {}), + source: Object.freeze({ + type: 'schedule', + id: metadata.scheduleId, + manual: metadata.scheduleManual === true, + resumed: true, + }), + unattended: false, + }); +} + +/** The context of a run started through the remote agent API. */ +export function createRemoteExecutionContext({ + principal, + agentId, + protocol, + background, +}: { + principal: ExecutionPrincipal; + agentId?: string; + protocol: AgentRunProtocol; + background: boolean; +}): ExecutionContext { + return Object.freeze({ + principal: Object.freeze({ + userId: principal.userId, + ...(principal.tenantId ? { tenantId: principal.tenantId } : {}), + ...(principal.role ? { role: principal.role } : {}), + }), + ...(agentId ? { agentId } : {}), + source: Object.freeze({ type: 'remote_api', protocol, background }), + unattended: !background, + }); +} + +/** The schedule a run belongs to, or undefined for an unscheduled run. */ +export function getScheduleSource( + context?: ExecutionContext, +): Extract | undefined { + return context?.source.type === 'schedule' ? context.source : undefined; +} + +/** + * The schedule identity that host credential providers and scheduled MCP authority bind to. + * Undefined unless the run is scheduled and its root agent is known: a job saved before the + * agent was recorded, or by a tenant-less writer for a tenant member, stays resumable but + * cannot claim a complete minting identity. + */ +export function toScheduledTokenContext( + context?: ExecutionContext, +): ScheduledTokenContext | undefined { + if (context?.source.type !== 'schedule') return; + const agentId = context.agentId; + if (typeof agentId !== 'string' || agentId.trim().length === 0) return; + return Object.freeze({ + scheduleId: context.source.id, + ownerId: context.principal.userId, + ...(context.principal.tenantId ? { tenantId: context.principal.tenantId } : {}), + agentId, + invocationMode: 'delegated', + }); +} diff --git a/packages/api/src/agents/authority/index.ts b/packages/api/src/agents/authority/index.ts new file mode 100644 index 0000000000..c38e8e8215 --- /dev/null +++ b/packages/api/src/agents/authority/index.ts @@ -0,0 +1 @@ +export * from './context'; diff --git a/packages/api/src/agents/index.ts b/packages/api/src/agents/index.ts index 8d88ec839c..d249c9a144 100644 --- a/packages/api/src/agents/index.ts +++ b/packages/api/src/agents/index.ts @@ -19,6 +19,7 @@ export * from './edges'; export * from './errors'; export * from './eventRetention'; export * from './envelope'; +export * from './authority'; export * from './execution'; export * from './files'; export * from './handlers'; diff --git a/packages/api/src/agents/responses/runtime.ts b/packages/api/src/agents/responses/runtime.ts index a0cdc58347..cd9c9c789b 100644 --- a/packages/api/src/agents/responses/runtime.ts +++ b/packages/api/src/agents/responses/runtime.ts @@ -90,6 +90,8 @@ function responseBody(value: unknown): value is TerminalResponse { export interface ResponseExecutionRuntime { completion?: ResponseTerminalCompletion; responseId: string; + /** A background worker run, whose events go to a stream the owner can follow. */ + background: boolean; inputChain: (chain: { messages: T[]; parentMessageId: string }) => { messages: T[]; parentMessageId: string; @@ -130,8 +132,6 @@ export interface ResponseExecutionRuntime { toolContext: (execution: { createdAt: number }) => { streamId: string | null; jobCreatedAt?: number; - /** A foreground run answers an API client and has no stream its owner can follow. */ - unattended?: boolean; }; connection?: AgentExecutionConnection; hooks: Pick< @@ -818,7 +818,8 @@ export function createResponseExecutionRuntime( toolContext: (execution) => admission ? { streamId: admission.record.responseId, jobCreatedAt: execution.createdAt } - : { streamId: null, unattended: true }, + : { streamId: null }, + background: admission != null, responseId: admission?.record.responseId ?? (continuation.generateResponseId ?? generateResponseId)(), connection: admission diff --git a/packages/api/src/agents/responses/worker.runtime.spec.ts b/packages/api/src/agents/responses/worker.runtime.spec.ts index 8f8f37cd7d..d200a75b59 100644 --- a/packages/api/src/agents/responses/worker.runtime.spec.ts +++ b/packages/api/src/agents/responses/worker.runtime.spec.ts @@ -463,6 +463,37 @@ describe('background Responses execution handoff', () => { expect(processStream).toHaveBeenCalledTimes(1); expect(resume).not.toHaveBeenCalled(); }); + it('marks only a worker-admitted run as background, whatever the caller sends', async () => { + let admitted: boolean | undefined; + const { app } = fixture(async (req, res) => { + admitted = createResponseExecutionRuntime(req, res, { + getMessage: async () => null, + jobs: GenerationJobManager, + }).background; + res.json({ ok: true }); + }); + await request(app) + .post('/') + .set('x-lc-response-worker', '1') + .auth(mintBackgroundResponseWorkerToken(record, secret), { type: 'bearer' }) + .send({}) + .expect(200, { ok: true }); + expect(admitted).toBe(true); + + const direct = express(); + direct.use(express.json()); + direct.post('/', (req, res) => { + const runtime = createResponseExecutionRuntime(req, res, { getMessage: async () => null }); + res.json({ + background: runtime.background, + tools: runtime.toolContext({ createdAt: 1 }), + }); + }); + await request(direct) + .post('/') + .send({ background: true }) + .expect(200, { background: false, tools: { streamId: null } }); + }); it('does not enable interactive execution from caller fields without an installed resume validator', async () => { const { app } = fixture(async (req, res) => { const runtime = createResponseExecutionRuntime(req, res, { diff --git a/packages/api/src/schedules/README.md b/packages/api/src/schedules/README.md index e1aa40afd5..08132d2dde 100644 --- a/packages/api/src/schedules/README.md +++ b/packages/api/src/schedules/README.md @@ -62,12 +62,14 @@ Admission allocates a proposed schedule ID before preflight and persists that sa only if creation succeeds. Preflight is validation, not a provisioning/consent hook: hosts must not create durable grants keyed by this proposed ID. Failed admission or a concurrent idempotency-key winner can discard it. Edits -and dispatch use the existing schedule ID. Execution derives the context from the -verified schedule trigger and authenticated owner, then captures it before tool loading. +and dispatch use the existing schedule ID. The chat controller builds one `ExecutionContext` +(`packages/api/src/agents/authority/context.ts`) from the verified schedule trigger and +authenticated owner and passes it to the initializer; the host context above is projected +from it before tool loading. A caller that passes none gets no schedule identity. `agentId` identifies the root scheduled agent throughout child execution and handoffs. -After an approval pause, the resume host restores the context from the saved job after -validating ownership, tenancy, agent identity, and schedule liveness. An explicit initializer -argument carries this restored context; resume body fields cannot replace it. +After an approval pause, the resume host rebuilds the context from the saved job after +validating ownership, tenancy, agent identity, and schedule liveness, and passes it the +same way; resume body fields cannot replace it. The existing resolver closure is passed through tool discovery, execution, and reconnects; it never goes into tool arguments or durable job payloads. diff --git a/packages/api/src/schedules/authorization/receipt.spec.ts b/packages/api/src/schedules/authorization/receipt.spec.ts index b7b20a48a3..4f94e46b95 100644 --- a/packages/api/src/schedules/authorization/receipt.spec.ts +++ b/packages/api/src/schedules/authorization/receipt.spec.ts @@ -15,6 +15,7 @@ import { import { createScheduleMCPRuntimeHost, initializeWithScheduleMCPExecution } from './runtime'; import { createScheduleMCPExecution, getScheduleMCPExecution } from './execution'; import { InMemoryJobStore } from '~/stream/implementations/InMemoryJobStore'; +import { createScheduleExecutionContext } from '~/agents/authority/context'; import { createAgentTriggerExecutionHost } from '~/agents/triggers/host'; import { createAgentTriggerEnvelope } from '~/agents/triggers/envelope'; import { GenerationJobManager } from '~/stream/GenerationJobManager'; @@ -1144,25 +1145,27 @@ it('stores only a safe preparation outage when initial authorization fails after }); const provider = jest.fn(); let failure: unknown; + const fire = { + user: { id: f.scope.userId, tenantId: 'tenant' }, + _isScheduledFire: true, + _isAgentTrigger: true, + body: { + agent_id: 'root', + agentTrigger: { + version: 1, + event: { + type: 'schedule.occurrence', + occurredAt: 0, + source: { id: f.schedule.id, type: 'schedule' }, + }, + }, + }, + }; try { await initializeWithScheduleMCPExecution( { - req: { - user: { id: f.scope.userId, tenantId: 'tenant' }, - _isScheduledFire: true, - _isAgentTrigger: true, - body: { - agent_id: 'root', - agentTrigger: { - version: 1, - event: { - type: 'schedule.occurrence', - occurredAt: 0, - source: { id: f.schedule.id, type: 'schedule' }, - }, - }, - }, - }, + req: fire, + executionContext: createScheduleExecutionContext(fire), context: createMCPRequestContext(), }, () => host, diff --git a/packages/api/src/schedules/authorization/runtime.spec.ts b/packages/api/src/schedules/authorization/runtime.spec.ts index 26f3ec3d65..f65c512503 100644 --- a/packages/api/src/schedules/authorization/runtime.spec.ts +++ b/packages/api/src/schedules/authorization/runtime.spec.ts @@ -1,5 +1,9 @@ import { Permissions, PermissionTypes, AgentCapabilities } from 'librechat-data-provider'; import type { AppConfig, IRole, ISchedule, AgentGraphAccessContext } from '@librechat/data-schemas'; +import { + restoreExecutionContext, + createScheduleExecutionContext, +} from '~/agents/authority/context'; import { createScheduleMCPRuntimeHost, initializeWithScheduleMCPExecution } from './runtime'; import { bindScheduledMCPInvocation, getScheduleMCPExecution } from './execution'; import { executionFixture, readTool } from './execution.helper'; @@ -119,6 +123,10 @@ async function setup() { connect, execution: host.execution, }); + /** As the chat controller does, build the context once from the verified trigger. */ + const prepare = host.prepare; + host.prepare = (input) => + prepare({ executionContext: createScheduleExecutionContext(input.req), ...input }); const context = createMCPRequestContext(); const req = { user: fixture.user, @@ -212,13 +220,12 @@ it('rebuilds the protected root on resume and refuses revoked consent even after await f.host.prepare({ req, context: f.context, - restoredContext: { - scheduleId: 'schedule', - ownerId: 'owner', + executionContext: restoreExecutionContext(req, { + userId: 'owner', tenantId: 'tenant', - agentId: 'root', - invocationMode: 'delegated', - }, + scheduleId: 'schedule', + agent_id: 'root', + }), }); expect(getScheduleMCPExecution(f.context)?.stage).toBe('resume'); await f.host.consent.service.revoke(f.identity, f.snapshot.enrollment!.revision); @@ -406,13 +413,10 @@ it.each([false, true])( ? { req: { user: f.user, _isScheduledFire: true, body: { manual: false } }, context: f.context, - restoredContext: { - scheduleId: 'schedule', - ownerId: 'owner', - tenantId: 'tenant', - agentId: 'root', - invocationMode: 'delegated', - }, + executionContext: restoreExecutionContext( + { user: f.user }, + { userId: 'owner', tenantId: 'tenant', scheduleId: 'schedule', agent_id: 'root' }, + ), restoredJob: { scheduleId: 'schedule', scheduleManual: true }, } : { req: manualReq, context: f.context }, diff --git a/packages/api/src/schedules/authorization/runtime.ts b/packages/api/src/schedules/authorization/runtime.ts index 90d32f5302..482786ec5b 100644 --- a/packages/api/src/schedules/authorization/runtime.ts +++ b/packages/api/src/schedules/authorization/runtime.ts @@ -5,9 +5,9 @@ import { } from 'librechat-data-provider'; import type { ScheduledMCPIdentity, ScheduledMCPReadOnlyPolicy } from 'librechat-data-provider'; import type { RequestScopedMCPConnectionStore } from '~/mcp/types'; +import type { ExecutionContext } from '~/agents/authority/context'; import type { ScheduleMCPCompletionLookup } from './continuation'; import type { ScheduleMCPEnrollmentDeps } from './enrollment'; -import type { ScheduledTokenContext } from '../context'; import { isScheduledMCPCompletionRequest, resolveScheduleMCPCompletion, @@ -18,6 +18,7 @@ import { scheduledMCPIdentity, getScheduleMCPExecution, } from './execution'; +import { getScheduleSource, toScheduledTokenContext } from '~/agents/authority/context'; import { readScheduleFireContext, isScheduleFireRequest } from '../trigger'; import { createScheduleMCPEnrollmentResolver } from './enrollment'; import { getAppConfigOptionsFromUser } from '~/app/service'; @@ -45,7 +46,7 @@ export function createScheduleMCPRuntimeHost( req: RuntimeRequest; signal?: AbortSignal; context?: RequestScopedMCPConnectionStore; - restoredContext?: ScheduledTokenContext; + executionContext?: ExecutionContext; restoredJob?: { scheduleId?: string; scheduleManual?: boolean; @@ -128,7 +129,7 @@ export function createScheduleMCPRuntimeHost( execution, prepare: (input) => prepareSafely(async () => { - const { req, context, restoredContext, restoredJob } = input; + const { req, context, executionContext, restoredJob } = input; const completion = restoredJob?.scheduleMCPCompletion; if (completion !== undefined || isScheduledMCPCompletionRequest(req)) { if (!context) throw new ScheduledMCPPolicyError('binding_mismatch', ''); @@ -174,9 +175,13 @@ export function createScheduleMCPRuntimeHost( return; } if (!isScheduleFireRequest(req)) return; - const fire = readScheduleFireContext(req); - const scheduleId = - restoredContext?.scheduleId ?? fire?.scheduleId ?? restoredJob?.scheduleId; + const schedule = getScheduleSource(executionContext); + /** A resumed run whose saved job restored a complete identity. */ + const restoredContext = schedule?.resumed + ? toScheduledTokenContext(executionContext) + : undefined; + const fresh = schedule?.resumed === false ? schedule : undefined; + const scheduleId = restoredContext?.scheduleId ?? fresh?.id ?? restoredJob?.scheduleId; if (!scheduleId || !context) throw new ScheduledMCPPolicyError('binding_mismatch', ''); const row = await deps.methods.getScheduleById(scheduleId, req.user.id); if (!row || (row.tenantId ?? null) !== (req.user.tenantId ?? null)) @@ -184,7 +189,7 @@ export function createScheduleMCPRuntimeHost( const enrolled = row.mcpConsent !== undefined; const rootId = restoredContext?.agentId ?? - (fire ? req.body?.agent_id : undefined) ?? + (fresh ? executionContext?.agentId : undefined) ?? (!enrolled ? row.agent_id : undefined); if (typeof rootId !== 'string' || rootId !== row.agent_id) throw new ScheduledMCPPolicyError('binding_mismatch', ''); @@ -205,7 +210,7 @@ export function createScheduleMCPRuntimeHost( legacy: !enrolled, manual: restoredContext ? restoredJob?.scheduleId === scheduleId && restoredJob.scheduleManual === true - : fire?.manual === true, + : fresh?.manual === true, }); }, input.signal), }; diff --git a/packages/api/src/schedules/bearer.spec.ts b/packages/api/src/schedules/bearer.spec.ts index 00919f62ea..5c856c0ceb 100644 --- a/packages/api/src/schedules/bearer.spec.ts +++ b/packages/api/src/schedules/bearer.spec.ts @@ -35,8 +35,8 @@ import { getScheduledMCPConfigurationRevision } from './authorization/configurat import { getScheduledMCPToolDefinitionDigest } from './authorization/policy'; import { createScheduleMCPConsentService } from './authorization/service'; import { MCPServersRegistry } from '~/mcp/registry/MCPServersRegistry'; +import { restoreExecutionContext } from '~/agents/authority/context'; import { MCPConnectionFactory } from '~/mcp/MCPConnectionFactory'; -import { restoreScheduledTokenContext } from './context'; import { createScheduleMCPPreflight } from './mcp'; import { FlowStateManager } from '~/flow/manager'; import { MCPConnection } from '~/mcp/connection'; @@ -460,10 +460,10 @@ it('restores the enrolled root after restart, never serializing the resource bea scheduleId: identity.scheduleId, agent_id: identity.agentId, }; - const restored = restoreScheduledTokenContext({ user }, metadata)!; + const restored = restoreExecutionContext({ user }, metadata)!; const req = { user, _isScheduledFire: true, body: {} }; const context = createMCPRequestContext(); - prepareScheduledMCPBearer({ req, restoredContext: restored, context, host: f.host }); + prepareScheduledMCPBearer({ req, executionContext: restored, context, host: f.host }); const invocation = bindScheduledMCPBearerInvocation(context, 'child', 'echo')!; await expect(invocation.resolve({ config, user, serverName: 'Files' })).resolves.toMatchObject({ headers: { Authorization: 'Bearer resource-only' }, @@ -754,7 +754,7 @@ describe('scheduled resource bearer with real MCP SDK and HTTP', () => { req: { user, _isScheduledFire: true, body: {} }, context: resumed, host: f.host, - restoredContext: restoreScheduledTokenContext( + executionContext: restoreExecutionContext( { user }, { userId: user.id, @@ -829,7 +829,7 @@ describe('scheduled resource bearer with real MCP SDK and HTTP', () => { req: { user, _isScheduledFire: true, body: {} }, context: restored, host: f.host, - restoredContext: restoreScheduledTokenContext( + executionContext: restoreExecutionContext( { user }, { userId: user.id, diff --git a/packages/api/src/schedules/bearer.ts b/packages/api/src/schedules/bearer.ts index e814826cdc..e870fea056 100644 --- a/packages/api/src/schedules/bearer.ts +++ b/packages/api/src/schedules/bearer.ts @@ -20,7 +20,7 @@ import type { } from '~/mcp/types'; import type { ScheduleMCPFailureInput, ScheduleMCPSettlementBoundary } from './types'; import type { ScheduleMCPEnrollmentResolver } from './authorization/service'; -import type { ScheduledTokenContext } from './context'; +import type { ExecutionContext } from '~/agents/authority/context'; import { getMCPRequestContext, getMCPRequestSignal, @@ -32,14 +32,15 @@ import { isMCPTransportAuthenticationError, createScheduledMCPTransportError, } from '~/mcp/errors'; +import { getScheduleSource, toScheduledTokenContext } from '~/agents/authority/context'; import { getScheduledMCPConfigurationRevision } from './authorization/configuration'; -import { readScheduleFireContext, isScheduleFireRequest } from './trigger'; import { getScheduleMCPExecution } from './authorization/execution'; import { ScheduleMCPConsentError } from './authorization/service'; import { usesDirectOpenIDBearerRecovery } from '~/mcp/openid'; import { holdMCPRequestFailure } from '~/mcp/signal'; import { awaitOboOperation } from '~/mcp/oauth/obo'; import { isOwnedAbortError } from '~/utils/errors'; +import { isScheduleFireRequest } from './trigger'; import { applyRequestHeaders } from '~/mcp/utils'; export { ScheduledMCPBearerError } from '~/mcp/errors'; @@ -493,7 +494,7 @@ export function rejectScheduledMCPBearer( export function prepareScheduledMCPBearer(input: { req: Parameters[0] & { user: { id: string; tenantId?: string } }; context?: RequestScopedMCPConnectionStore; - restoredContext?: ScheduledTokenContext; + executionContext?: ExecutionContext; host?: ScheduledMCPBearerHost; signal?: AbortSignal; streamId?: string | null; @@ -506,20 +507,10 @@ export function prepareScheduledMCPBearer(input: { const execution = getScheduleMCPExecution(context); if (!isScheduleFireRequest(input.req) && !execution) return; input.signal?.throwIfAborted(); - const fire = readScheduleFireContext(input.req); - const root = input.restoredContext; - const identity = - execution?.identity ?? - root ?? - (fire && typeof input.req.body?.agent_id === 'string' - ? { - scheduleId: fire.scheduleId, - ownerId: input.req.user.id, - tenantId: input.req.user.tenantId, - agentId: input.req.body.agent_id, - invocationMode: 'delegated' as const, - } - : undefined); + const schedule = getScheduleSource(input.executionContext); + const identity = execution?.identity ?? toScheduledTokenContext(input.executionContext); + /** Only a resumed run with a complete restored identity re-enters at the resume stage. */ + const resumed = schedule?.resumed === true && identity != null && !execution; if (context && !identity) { attachScheduledMCPBearer(context, { scheduleId: '', @@ -561,9 +552,14 @@ export function prepareScheduledMCPBearer(input: { context, captured, input.host, - execution?.stage ?? (root ? 'resume' : 'invoke'), + execution?.stage ?? (resumed ? 'resume' : 'invoke'), input.signal, - { manual: execution?.manual === true || (!execution && fire?.manual === true), onFailure }, + { + manual: + execution?.manual === true || + (!execution && schedule?.resumed === false && schedule.manual), + onFailure, + }, ); } diff --git a/packages/api/src/schedules/context.spec.ts b/packages/api/src/schedules/context.spec.ts index 494922feea..b73d2a5a65 100644 --- a/packages/api/src/schedules/context.spec.ts +++ b/packages/api/src/schedules/context.spec.ts @@ -4,8 +4,11 @@ import { bindUpstreamTokenProviderResolver, createScheduleUpstreamTokenProviderResolver, } from './mcp'; +import { + restoreExecutionContext, + createScheduleExecutionContext, +} from '~/agents/authority/context'; import { createLazyOboUpstreamTokenProvider } from '../mcp/oauth/obo'; -import { restoreScheduledTokenContext } from './context'; const user = { id: 'owner', tenantId: 'tenant' } as IUser; const context: ScheduledTokenContext = { @@ -42,7 +45,12 @@ it.each([false, true])('captures verified root identity for manual=%s', async (m const provider = jest.fn().mockResolvedValue({ access_token: 'token' }); const resolve = jest.fn().mockResolvedValue(provider); const signal = new AbortController().signal; - const bound = createScheduleUpstreamTokenProviderResolver(req, resolve, signal)!; + const bound = createScheduleUpstreamTokenProviderResolver( + req, + resolve, + signal, + createScheduleExecutionContext(req), + )!; req.body.agent_id = 'child-agent'; req.body.agentTrigger.event.source.id = 'changed'; await createLazyOboUpstreamTokenProvider(bound, signal, target)(); @@ -52,17 +60,26 @@ it.each([false, true])('captures verified root identity for manual=%s', async (m it('ignores copied schedule metadata on an ordinary interactive request', () => { const resolve = jest.fn(); + const req = { ...request(), _isAgentTrigger: false }; expect( - createScheduleUpstreamTokenProviderResolver({ ...request(), _isAgentTrigger: false }, resolve), + createScheduleUpstreamTokenProviderResolver( + req, + resolve, + undefined, + createScheduleExecutionContext(req), + ), ).toBeUndefined(); expect(resolve).not.toHaveBeenCalled(); }); it('leaves context absent for legacy schedule classification without verified metadata', async () => { const resolve = jest.fn().mockResolvedValue(jest.fn()); + const req = { ...request(), _isAgentTrigger: false, _isScheduledFire: true }; const bound = createScheduleUpstreamTokenProviderResolver( - { ...request(), _isAgentTrigger: false, _isScheduledFire: true }, + req, resolve, + undefined, + createScheduleExecutionContext(req), )!; await bound(); expect(resolve).toHaveBeenCalledWith(user, { signal: undefined }); @@ -110,7 +127,7 @@ it('restores a paused run from job identity without trusting resume body fields' _isScheduledFire: true, body: { scheduleId: 'spoofed', agent_id: 'spoofed' }, }; - const restored = restoreScheduledTokenContext(req, { + const restored = restoreExecutionContext(req, { userId: 'owner', tenantId: 'tenant', scheduleId: 'schedule', @@ -126,7 +143,7 @@ it.each([{ userId: 'different' }, { tenantId: 'different' }])( 'rejects invalid restored identity %j', (override) => { expect(() => - restoreScheduledTokenContext( + restoreExecutionContext( { user }, { userId: 'owner', @@ -144,7 +161,7 @@ it.each([{ agent_id: undefined }, { tenantId: undefined }])( 'leaves legacy job context absent for %j', async (override) => { const req = { user, _isScheduledFire: true }; - const restored = restoreScheduledTokenContext(req, { + const restored = restoreExecutionContext(req, { userId: 'owner', tenantId: 'tenant', scheduleId: 'schedule', diff --git a/packages/api/src/schedules/context.ts b/packages/api/src/schedules/context.ts index 0c2393bbc7..1c245d5561 100644 --- a/packages/api/src/schedules/context.ts +++ b/packages/api/src/schedules/context.ts @@ -6,33 +6,3 @@ export interface ScheduledTokenContext { readonly agentId: string; readonly invocationMode: 'delegated'; } - -interface ScheduleJobIdentity { - userId?: string; - tenantId?: string; - scheduleId?: string; - agent_id?: string; -} - -/** Called by the resume host after job ownership, tenant, agent, and schedule checks. */ -export function restoreScheduledTokenContext( - req: { user: { id: string; tenantId?: string } }, - metadata?: ScheduleJobIdentity, -): ScheduledTokenContext | undefined { - if (!metadata?.scheduleId) return; - if ( - metadata.userId !== req.user.id || - (metadata.tenantId != null && metadata.tenantId !== req.user.tenantId) - ) { - throw new Error('Scheduled job identity does not match the authenticated owner.'); - } - /** Legacy jobs remain resumable, but cannot claim a complete minting context. */ - if (!metadata.agent_id || (req.user.tenantId && metadata.tenantId == null)) return; - return Object.freeze({ - scheduleId: metadata.scheduleId, - ownerId: metadata.userId, - ...(metadata.tenantId ? { tenantId: metadata.tenantId } : {}), - agentId: metadata.agent_id, - invocationMode: 'delegated', - }); -} diff --git a/packages/api/src/schedules/mcp.ts b/packages/api/src/schedules/mcp.ts index efa6700810..355a6c6ed3 100644 --- a/packages/api/src/schedules/mcp.ts +++ b/packages/api/src/schedules/mcp.ts @@ -25,6 +25,7 @@ import type { } from '../mcp/oauth/obo'; import type { ScheduleMCPExecution, createScheduleMCPExecution } from './authorization/execution'; import type { ParsedServerConfig, UserMCPConnectionOptions } from '../mcp/types'; +import type { ExecutionContext } from '~/agents/authority/context'; import type { CheckAccessParams } from '../middleware/access'; import type { MCPToolsSnapshot } from '../mcp/connection'; import type { GetAppConfigOptions } from '../app/service'; @@ -46,7 +47,7 @@ import { ScheduledMCPPolicyError, isScheduledMCPCandidate } from './authorizatio import { MCPConfigInitializationCanceledError } from '../mcp/registry/MCPServersRegistry'; import { createMCPRequestContext, cleanupMCPRequestContext } from '../mcp/request'; import { attachScheduledMCPBearer, ScheduledMCPBearerError } from './bearer'; -import { isScheduleFireRequest, readScheduleFireContext } from './trigger'; +import { toScheduledTokenContext } from '~/agents/authority/context'; import { resolveScheduledMCPRequirements } from './requirements'; import { getAppConfigOptionsFromUser } from '../app/service'; import { createConcurrencyLimiter } from '../utils/promise'; @@ -54,6 +55,7 @@ import { OboTokenResolutionError } from '../mcp/oauth/obo'; import { OpenIDReauthRequiredError } from '../utils/oidc'; import { formatMCPServerTools } from '../mcp/tools'; import { checkAccess } from '../middleware/access'; +import { isScheduleFireRequest } from './trigger'; import { detachOnAbort } from '../utils/promises'; import { getPluginAuthMap } from '../agents/auth'; @@ -117,24 +119,15 @@ export function createScheduleUpstreamTokenProviderResolver( req: Parameters[0] & { user: ScheduledTokenIdentity }, resolve: HostUpstreamTokenProviderResolver | undefined, signal?: AbortSignal, - restoredContext?: ScheduledTokenContext, + executionContext?: ExecutionContext, ): UpstreamTokenProviderResolver | undefined { if (!isScheduleFireRequest(req)) return undefined; - if (restoredContext) - return bindUpstreamTokenProviderResolver(req.user, resolve, signal, restoredContext); - const fire = readScheduleFireContext(req); - const agentId = req.body?.agent_id; - const context: ScheduledTokenContext | undefined = - fire && typeof agentId === 'string' && agentId.trim().length > 0 - ? { - scheduleId: fire.scheduleId, - ownerId: req.user.id, - ...(req.user.tenantId ? { tenantId: req.user.tenantId } : {}), - agentId, - invocationMode: 'delegated', - } - : undefined; - return bindUpstreamTokenProviderResolver(req.user, resolve, signal, context); + return bindUpstreamTokenProviderResolver( + req.user, + resolve, + signal, + toScheduledTokenContext(executionContext), + ); } // The public schedule schema caps mcpPreflightConcurrency at 10. Keep the same