Skip to content

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

♻️ refactor: add the cronjob tools executiors (#13536)

LiJianaec2d3050607
diff --git a/package.json b/package.json
index e1baa81cbd1..52bef0afce3 100644
--- a/package.json
+++ b/package.json
@@ -211,6 +211,7 @@
"@lobechat/builtin-tool-calculator": "workspace:*",
"@lobechat/builtin-tool-cloud-sandbox": "workspace:*",
"@lobechat/builtin-tool-creds": "workspace:*",
+ "@lobechat/builtin-tool-cron": "workspace:*",
"@lobechat/builtin-tool-group-agent-builder": "workspace:*",
"@lobechat/builtin-tool-group-management": "workspace:*",
"@lobechat/builtin-tool-gtd": "workspace:*",
diff --git a/packages/builtin-tool-cron/package.json b/packages/builtin-tool-cron/package.json
new file mode 100644
index 00000000000..8c278cc026f
--- /dev/null
+++ b/packages/builtin-tool-cron/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "@lobechat/builtin-tool-cron",
+ "version": "1.0.0",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts",
+ "./executor": "./src/executor/index.ts"
+ },
+ "main": "./src/index.ts",
+ "dependencies": {},
+ "devDependencies": {
+ "@lobechat/types": "workspace:*"
+ }
+}
diff --git a/packages/builtin-tool-cron/src/ExecutionRuntime/index.ts b/packages/builtin-tool-cron/src/ExecutionRuntime/index.ts
new file mode 100644
index 00000000000..497ea8d482e
--- /dev/null
+++ b/packages/builtin-tool-cron/src/ExecutionRuntime/index.ts
@@ -0,0 +1,451 @@
+import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
+
+import type {
+ CreateCronJobParams,
+ CronJobSummary,
+ CronStats,
+ DeleteCronJobParams,
+ GetCronJobParams,
+ ListCronJobsParams,
+ ResetExecutionsParams,
+ ToggleCronJobParams,
+ UpdateCronJobParams,
+} from '../types';
+
+/**
+ * Service interface for Cron Job operations
+ * Abstracted to allow different implementations
+ */
+export interface ICronService {
+ /**
+ * Create a new cron job
+ */
+ create: (data: {
+ agentId: string;
+ content: string;
+ cronPattern: string;
+ description?: string;
+ enabled?: boolean;
+ maxExecutions?: number | null;
+ name: string;
+ timezone?: string;
+ }) => Promise<{ data: CronJobSummary }>;
+
+ /**
+ * Delete a cron job
+ */
+ delete: (id: string) => Promise<{ success: boolean }>;
+
+ /**
+ * Get a cron job by ID
+ */
+ findById: (id: string) => Promise<{ data: CronJobSummary }>;
+
+ /**
+ * Get execution statistics
+ */
+ getStats: () => Promise<{ data: CronStats }>;
+
+ /**
+ * List cron jobs with filtering
+ */
+ list: (options: {
+ agentId?: string;
+ enabled?: boolean;
+ limit?: number;
+ offset?: number;
+ }) => Promise<{
+ data: CronJobSummary[];
+ pagination?: {
+ hasMore: boolean;
+ limit: number;
+ offset: number;
+ total: number;
+ };
+ }>;
+
+ /**
+ * Reset execution counts
+ */
+ resetExecutions: (id: string, newMaxExecutions?: number) => Promise<{ data: CronJobSummary }>;
+
+ /**
+ * Update a cron job
+ */
+ update: (
+ id: string,
+ data: {
+ content?: string;
+ cronPattern?: string;
+ description?: string;
+ enabled?: boolean;
+ maxExecutions?: number | null;
+ name?: string;
+ timezone?: string;
+ },
+ ) => Promise<{ data: CronJobSummary }>;
+}
+
+/**
+ * Cron Execution Runtime (Server-side)
+ *
+ * This runtime executes cron job tools via the injected ICronService.
+ * The service handles context (userId) internally.
+ */
+export class CronExecutionRuntime {
+ private cronService: ICronService;
+ private context: { agentId?: string; userId?: string };
+
+ constructor(cronService: ICronService, context: { agentId?: string; userId?: string } = {}) {
+ this.cronService = cronService;
+ this.context = context;
+ }
+
+ /**
+ * Create a new scheduled task
+ */
+ async createCronJob(args: CreateCronJobParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const agentId = this.context.agentId;
+ if (!agentId) {
+ return {
+ content: 'Cannot create scheduled task: agentId is not available in the current context.',
+ error: {
+ message: 'agentId is required but not available',
+ type: 'MissingAgentId',
+ },
+ success: false,
+ };
+ }
+
+ const result = await this.cronService.create({
+ agentId,
+ content: args.content,
+ cronPattern: args.cronPattern,
+ description: args.description,
+ enabled: args.enabled ?? true,
+ maxExecutions: args.maxExecutions,
+ name: args.name,
+ timezone: args.timezone || 'UTC',
+ });
+
+ const cronJob = result.data;
+
+ return {
+ content: `Scheduled task "${args.name}" created successfully. It will run according to the pattern "${args.cronPattern}" in timezone ${args.timezone || 'UTC'}.`,
+ state: {
+ cronJob,
+ success: true,
+ },
+ success: true,
+ };
+ } catch (error) {
+ const errorMessage =
+ error instanceof Error ? error.message : 'Failed to create scheduled task';
+
+ return {
+ content: `Failed to create scheduled task: ${errorMessage}`,
+ error: {
+ message: errorMessage,
+ type: 'CreateCronJobFailed',
+ },
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * List all scheduled tasks
+ */
+ async listCronJobs(args: ListCronJobsParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const agentId = this.context.agentId;
+ if (!agentId) {
+ return {
+ content: 'Cannot list scheduled tasks: agentId is not available in the current context.',
+ error: {
+ message: 'agentId is required but not available',
+ type: 'MissingAgentId',
+ },
+ success: false,
+ };
+ }
+
+ const result = await this.cronService.list({
+ agentId,
+ enabled: args.enabled,
+ limit: args.limit || 20,
+ offset: args.offset || 0,
+ });
+
+ const cronJobs = result.data || [];
+ const pagination = result.pagination;
+
+ if (cronJobs.length === 0) {
+ return {
+ content: 'No scheduled tasks found for this agent.',
+ state: {
+ cronJobs: [],
+ pagination,
+ success: true,
+ },
+ success: true,
+ };
+ }
+
+ const taskList = cronJobs
+ .map((job) => {
+ const status = job.enabled ? 'enabled' : 'disabled';
+ const execInfo = job.maxExecutions
+ ? `${job.remainingExecutions ?? 0}/${job.maxExecutions} remaining`
+ : 'unlimited';
+ return `- ${job.name || 'Unnamed'} (${job.id}): ${job.cronPattern} [${status}, ${execInfo}]`;
+ })
+ .join('\n');
+
+ return {
+ content: `Found ${cronJobs.length} scheduled task(s):\n${taskList}`,
+ state: {
+ cronJobs,
+ pagination,
+ success: true,
+ },
+ success: true,
+ };
+ } catch (error) {
+ const errorMessage =
+ error instanceof Error ? error.message : 'Failed to list scheduled tasks';
+
+ return {
+ content: `Failed to list scheduled tasks: ${errorMessage}`,
+ error: {
+ message: errorMessage,
+ type: 'ListCronJobsFailed',
+ },
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Get details of a specific scheduled task
+ */
+ async getCronJob(args: GetCronJobParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.cronService.findById(args.id);
+ const cronJob = result.data;
+
+ const status = cronJob.enabled ? 'enabled' : 'disabled';
+ const execInfo = cronJob.maxExecutions
+ ? `${cronJob.remainingExecutions ?? 0}/${cronJob.maxExecutions} executions remaining`
+ : 'unlimited executions';
+
+ return {
+ content: `Task "${cronJob.name || 'Unnamed'}" (${cronJob.id}):\n- Schedule: ${cronJob.cronPattern} (${cronJob.timezone})\n- Status: ${status}\n- Executions: ${cronJob.totalExecutions} completed, ${execInfo}\n- Last run: ${cronJob.lastExecutedAt || 'never'}`,
+ state: {
+ cronJob,
+ success: true,
+ },
+ success: true,
+ };
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
+ const isNotFound = errorMessage.includes('not found') || errorMessage.includes('NOT_FOUND');
+
+ return {
+ content: isNotFound
+ ? `Scheduled task not found: ${args.id}`
+ : `Failed to get scheduled task: ${errorMessage}`,
+ error: {
+ message: errorMessage,
+ type: isNotFound ? 'CronJobNotFound' : 'GetCronJobFailed',
+ },
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Update an existing scheduled task
+ */
+ async updateCronJob(args: UpdateCronJobParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const { id, ...updateData } = args;
+ const result = await this.cronService.update(id, updateData);
+ const cronJob = result.data;
+
+ const updates: string[] = [];
+ if (args.name) updates.push(`name: "${args.name}"`);
+ if (args.content) updates.push('content updated');
+ if (args.cronPattern) updates.push(`schedule: ${args.cronPattern}`);
+ if (args.timezone) updates.push(`timezone: ${args.timezone}`);
+ if (args.enabled !== undefined) updates.push(args.enabled ? 'enabled' : 'disabled');
+ if (args.maxExecutions !== undefined) {
+ updates.push(
+ args.maxExecutions ? `max executions: ${args.maxExecutions}` : 'unlimited executions',
+ );
+ }
+
+ return {
+ content: `Scheduled task "${cronJob.name || 'Unnamed'}" updated successfully. Changes: ${updates.join(', ') || 'no changes'}.`,
+ state: {
+ cronJob,
+ success: true,
+ },
+ success: true,
+ };
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
+ const isNotFound = errorMessage.includes('not found') || errorMessage.includes('NOT_FOUND');
+
+ return {
+ content: isNotFound
+ ? `Scheduled task not found: ${args.id}`
+ : `Failed to update scheduled task: ${errorMessage}`,
+ error: {
+ message: errorMessage,
+ type: isNotFound ? 'CronJobNotFound' : 'UpdateCronJobFailed',
+ },
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Delete a scheduled task
+ */
+ async deleteCronJob(args: DeleteCronJobParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.cronService.delete(args.id);
+
+ if (!result.success) {
+ return {
+ content: `Scheduled task not found: ${args.id}`,
+ error: {
+ message: `Cron job not found: ${args.id}`,
+ type: 'CronJobNotFound',
+ },
+ success: false,
+ };
+ }
+
+ return {
+ content: `Scheduled task deleted successfully.`,
+ state: {
+ success: true,
+ },
+ success: true,
+ };
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
+ const isNotFound = errorMessage.includes('not found') || errorMessage.includes('NOT_FOUND');
+
+ return {
+ content: isNotFound
+ ? `Scheduled task not found: ${args.id}`
+ : `Failed to delete scheduled task: ${errorMessage}`,
+ error: {
+ message: errorMessage,
+ type: isNotFound ? 'CronJobNotFound' : 'DeleteCronJobFailed',
+ },
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Enable or disable a scheduled task
+ */
+ async toggleCronJob(args: ToggleCronJobParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.cronService.update(args.id, { enabled: args.enabled });
+ const cronJob = result.data;
+
+ return {
+ content: `Scheduled task "${cronJob.name || 'Unnamed'}" has been ${args.enabled ? 'enabled' : 'disabled'}.`,
+ state: {
+ cronJob,
+ success: true,
+ },
+ success: true,
+ };
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
+ const isNotFound = errorMessage.includes('not found') || errorMessage.includes('NOT_FOUND');
+
+ return {
+ content: isNotFound
+ ? `Scheduled task not found: ${args.id}`
+ : `Failed to toggle scheduled task: ${errorMessage}`,
+ error: {
+ message: errorMessage,
+ type: isNotFound ? 'CronJobNotFound' : 'ToggleCronJobFailed',
+ },
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Reset execution count for a scheduled task
+ */
+ async resetExecutions(args: ResetExecutionsParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.cronService.resetExecutions(args.id, args.newMaxExecutions);
+ const cronJob = result.data;
+
+ return {
+ content: `Execution count for "${cronJob.name || 'Unnamed'}" has been reset. ${cronJob.maxExecutions ? `New limit: ${cronJob.maxExecutions} executions` : 'Unlimited executions'}.`,
+ state: {
+ cronJob,
+ success: true,
+ },
+ success: true,
+ };
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
+ const isNotFound = errorMessage.includes('not found') || errorMessage.includes('NOT_FOUND');
+
+ return {
+ content: isNotFound
+ ? `Scheduled task not found: ${args.id}`
+ : `Failed to reset executions: ${errorMessage}`,
+ error: {
+ message: errorMessage,
+ type: isNotFound ? 'CronJobNotFound' : 'ResetExecutionsFailed',
+ },
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Get execution statistics
+ */
+ async getStats(): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.cronService.getStats();
+ const stats = result.data;
+
+ return {
+ content: `Scheduled Tasks Statistics:\n- Total jobs: ${stats.totalJobs}\n- Active (enabled): ${stats.activeJobs}\n- Completed executions: ${stats.completedExecutions}\n- Pending executions: ${stats.pendingExecutions}`,
+ state: {
+ stats,
+ success: true,
+ },
+ success: true,
+ };
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : 'Failed to get statistics';
+
+ return {
+ content: `Failed to get execution statistics: ${errorMessage}`,
+ error: {
+ message: errorMessage,
+ type: 'GetStatsFailed',
+ },
+ success: false,
+ };
+ }
+ }
+}
diff --git a/packages/builtin-tool-cron/src/executor/index.ts b/packages/builtin-tool-cron/src/executor/index.ts
new file mode 100644
index 00000000000..04b886d325a
--- /dev/null
+++ b/packages/builtin-tool-cron/src/executor/index.ts
@@ -0,0 +1,451 @@
+import type { BuiltinToolContext, BuiltinToolResult } from '@lobechat/types';
+import { BaseExecutor } from '@lobechat/types';
+import debug from 'debug';
+
+import { mutate } from '@/libs/swr';
+import { lambdaClient } from '@/libs/trpc/client';
+
+import { CronIdentifier } from '../manifest';
+import {
+ type CreateCronJobParams,
+ CronApiName,
+ type CronJobSummary,
+ type DeleteCronJobParams,
+ type GetCronJobParams,
+ type ListCronJobsParams,
+ type ResetExecutionsParams,
+ type ToggleCronJobParams,
+ type UpdateCronJobParams,
+} from '../types';
+
+const FETCH_CRON_TOPICS_WITH_JOB_INFO_KEY = 'cronTopicsWithJobInfo';
+
+const log = debug('lobe-cron:executor');
+
+class CronExecutor extends BaseExecutor<typeof CronApiName> {
+ readonly identifier = CronIdentifier;
+ protected readonly apiEnum = CronApiName;
+
+ /**
+ * Create a new scheduled task
+ */
+ createCronJob = async (
+ params: CreateCronJobParams,
+ ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ try {
+ const agentId = ctx?.agentId;
+ if (!agentId) {
+ return {
+ content: 'Cannot create scheduled task: agentId is not available in the current context.',
+ error: {
+ message: 'agentId is required but not available',
+ type: 'MissingAgentId',
+ },
+ success: false,
+ };
+ }
+
+ log('[CronExecutor] createCronJob - params:', params, 'agentId:', agentId);
+
+ const result = await lambdaClient.agentCronJob.create.mutate({
+ agentId,
+ content: params.content,
+ cronPattern: params.cronPattern,
+ description: params.description,
+ enabled: params.enabled ?? true,
+ maxExecutions: params.maxExecutions,
+ name: params.name,
+ timezone: params.timezone || 'UTC',
+ });
+
+ const cronJob = result.data as CronJobSummary;
+
+ // Refresh the cron jobs list in sidebar
+ await mutate([FETCH_CRON_TOPICS_WITH_JOB_INFO_KEY, agentId]);
+
+ return {
+ content: `Scheduled task "${params.name}" created successfully. It will run according to the pattern "${params.cronPattern}" in timezone ${params.timezone || 'UTC'}.`,
+ state: {
+ cronJob,
+ success: true,
+ },
+ success: true,
+ };
+ } catch (error) {
+ log('[CronExecutor] createCronJob - error:', error);
+ const errorMessage =
+ error instanceof Error ? error.message : 'Failed to create scheduled task';
+
+ return {
+ content: `Failed to create scheduled task: ${errorMessage}`,
+ error: {
+ message: errorMessage,
+ type: 'CreateCronJobFailed',
+ },
+ success: false,
+ };
+ }
+ };
+
+ /**
+ * List all scheduled tasks for the current agent
+ */
+ listCronJobs = async (
+ params: ListCronJobsParams,
+ ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ try {
+ const agentId = ctx?.agentId;
+ if (!agentId) {
+ return {
+ content: 'Cannot list scheduled tasks: agentId is not available in the current context.',
+ error: {
+ message: 'agentId is required but not available',
+ type: 'MissingAgentId',
+ },
+ success: false,
+ };
+ }
+
+ log('[CronExecutor] listCronJobs - agentId:', agentId, 'params:', params);
+
+ const result = await lambdaClient.agentCronJob.list.query({
+ agentId,
+ enabled: params.enabled,
+ limit: params.limit || 20,
+ offset: params.offset || 0,
+ });
+
+ const cronJobs = (result.data || []) as CronJobSummary[];
+ const pagination = result.pagination;
+
+ if (cronJobs.length === 0) {
+ return {
+ content: 'No scheduled tasks found for this agent.',
+ state: {
+ cronJobs: [],
+ pagination,
+ success: true,
+ },
+ success: true,
+ };
+ }
+
+ // Format the list for display
+ const taskList = cronJobs
+ .map((job) => {
+ const status = job.enabled ? 'enabled' : 'disabled';
+ const execInfo = job.maxExecutions
+ ? `${job.remainingExecutions ?? 0}/${job.maxExecutions} remaining`
+ : 'unlimited';
+ return `- ${job.name || 'Unnamed'} (${job.id}): ${job.cronPattern} [${status}, ${execInfo}]`;
+ })
+ .join('\n');
+
+ return {
+ content: `Found ${cronJobs.length} scheduled task(s):\n${taskList}`,
+ state: {
+ cronJobs,
+ pagination,
+ success: true,
+ },
+ success: true,
+ };
+ } catch (error) {
+ log('[CronExecutor] listCronJobs - error:', error);
+ const errorMessage =
+ error instanceof Error ? error.message : 'Failed to list scheduled tasks';
+
+ return {
+ content: `Failed to list scheduled tasks: ${errorMessage}`,
+ error: {
+ message: errorMessage,
+ type: 'ListCronJobsFailed',
+ },
+ success: false,
+ };
+ }
+ };
+
+ /**
+ * Get details of a specific scheduled task
+ */
+ getCronJob = async (
+ params: GetCronJobParams,
+ _ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ try {
+ log('[CronExecutor] getCronJob - id:', params.id);
+
+ const result = await lambdaClient.agentCronJob.findById.query({ id: params.id });
+ const cronJob = result.data as CronJobSummary;
+
+ const status = cronJob.enabled ? 'enabled' : 'disabled';
+ const execInfo = cronJob.maxExecutions
+ ? `${cronJob.remainingExecutions ?? 0}/${cronJob.maxExecutions} executions remaining`
+ : 'unlimited executions';
+
+ return {
+ content: `Task "${cronJob.name || 'Unnamed'}" (${cronJob.id}):\n- Schedule: ${cronJob.cronPattern} (${cronJob.timezone})\n- Status: ${status}\n- Executions: ${cronJob.totalExecutions} completed, ${execInfo}\n- Last run: ${cronJob.lastExecutedAt || 'never'}`,
+ state: {
+ cronJob,
+ success: true,
+ },
+ success: true,
+ };
+ } catch (error) {
+ log('[CronExecutor] getCronJob - error:', error);
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
+ const isNotFound = errorMessage.includes('not found') || errorMessage.includes('NOT_FOUND');
+
+ return {
+ content: isNotFound
+ ? `Scheduled task not found: ${params.id}`
+ : `Failed to get scheduled task: ${errorMessage}`,
+ error: {
+ message: errorMessage,
+ type: isNotFound ? 'CronJobNotFound' : 'GetCronJobFailed',
+ },
+ success: false,
+ };
+ }
+ };
+
+ /**
+ * Update an existing scheduled task
+ */
+ updateCronJob = async (
+ params: UpdateCronJobParams,
+ _ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ try {
+ log('[CronExecutor] updateCronJob - id:', params.id, 'params:', params);
+
+ const { id, ...updateData } = params;
+ const result = await lambdaClient.agentCronJob.update.mutate({
+ data: updateData,
+ id,
+ });
+
+ const cronJob = result.data as CronJobSummary;
+
+ // Build a summary of what was updated
+ const updates: string[] = [];
+ if (params.name) updates.push(`name: "${params.name}"`);
+ if (params.content) updates.push('content updated');
+ if (params.cronPattern) updates.push(`schedule: ${params.cronPattern}`);
+ if (params.timezone) updates.push(`timezone: ${params.timezone}`);
+ if (params.enabled !== undefined) updates.push(params.enabled ? 'enabled' : 'disabled');
+ if (params.maxExecutions !== undefined) {
+ updates.push(
+ params.maxExecutions ? `max executions: ${params.maxExecutions}` : 'unlimited executions',
+ );
+ }
+
+ // Refresh the cron jobs list in sidebar
+ await mutate([FETCH_CRON_TOPICS_WITH_JOB_INFO_KEY, cronJob.agentId]);
+
+ return {
+ content: `Scheduled task "${cronJob.name || 'Unnamed'}" updated successfully. Changes: ${updates.join(', ') || 'no changes'}.`,
+ state: {
+ cronJob,
+ success: true,
+ },
+ success: true,
+ };
+ } catch (error) {
+ log('[CronExecutor] updateCronJob - error:', error);
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
+ const isNotFound = errorMessage.includes('not found') || errorMessage.includes('NOT_FOUND');
+
+ return {
+ content: isNotFound
+ ? `Scheduled task not found: ${params.id}`
+ : `Failed to update scheduled task: ${errorMessage}`,
+ error: {
+ message: errorMessage,
+ type: isNotFound ? 'CronJobNotFound' : 'UpdateCronJobFailed',
+ },
+ success: false,
+ };
+ }
+ };
+
+ /**
+ * Delete a scheduled task
+ */
+ deleteCronJob = async (
+ params: DeleteCronJobParams,
+ ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ try {
+ log('[CronExecutor] deleteCronJob - id:', params.id);
+
+ await lambdaClient.agentCronJob.delete.mutate({ id: params.id });
+
+ // Refresh the cron jobs list in sidebar
+ if (ctx?.agentId) {
+ await mutate([FETCH_CRON_TOPICS_WITH_JOB_INFO_KEY, ctx.agentId]);
+ }
+
+ return {
+ content: `Scheduled task deleted successfully.`,
+ state: {
+ success: true,
+ },
+ success: true,
+ };
+ } catch (error) {
+ log('[CronExecutor] deleteCronJob - error:', error);
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
+ const isNotFound = errorMessage.includes('not found') || errorMessage.includes('NOT_FOUND');
+
+ return {
+ content: isNotFound
+ ? `Scheduled task not found: ${params.id}`
+ : `Failed to delete scheduled task: ${errorMessage}`,
+ error: {
+ message: errorMessage,
+ type: isNotFound ? 'CronJobNotFound' : 'DeleteCronJobFailed',
+ },
+ success: false,
+ };
+ }
+ };
+
+ /**
+ * Enable or disable a scheduled task
+ */
+ toggleCronJob = async (
+ params: ToggleCronJobParams,
+ _ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ try {
+ log('[CronExecutor] toggleCronJob - id:', params.id, 'enabled:', params.enabled);
+
+ const result = await lambdaClient.agentCronJob.update.mutate({
+ data: { enabled: params.enabled },
+ id: params.id,
+ });
+
+ const cronJob = result.data as CronJobSummary;
+
+ // Refresh the cron jobs list in sidebar
+ await mutate([FETCH_CRON_TOPICS_WITH_JOB_INFO_KEY, cronJob.agentId]);
+
+ return {
+ content: `Scheduled task "${cronJob.name || 'Unnamed'}" has been ${params.enabled ? 'enabled' : 'disabled'}.`,
+ state: {
+ cronJob,
+ success: true,
+ },
+ success: true,
+ };
+ } catch (error) {
+ log('[CronExecutor] toggleCronJob - error:', error);
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
+ const isNotFound = errorMessage.includes('not found') || errorMessage.includes('NOT_FOUND');
+
+ return {
+ content: isNotFound
+ ? `Scheduled task not found: ${params.id}`
+ : `Failed to toggle scheduled task: ${errorMessage}`,
+ error: {
+ message: errorMessage,
+ type: isNotFound ? 'CronJobNotFound' : 'ToggleCronJobFailed',
+ },
+ success: false,
+ };
+ }
+ };
+
+ /**
+ * Reset execution count for a scheduled task
+ */
+ resetExecutions = async (
+ params: ResetExecutionsParams,
+ _ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ try {
+ log(
+ '[CronExecutor] resetExecutions - id:',
+ params.id,
+ 'newMaxExecutions:',
+ params.newMaxExecutions,
+ );
+
+ const result = await lambdaClient.agentCronJob.resetExecutions.mutate({
+ id: params.id,
+ newMaxExecutions: params.newMaxExecutions,
+ });
+
+ const cronJob = result.data as CronJobSummary;
+
+ // Refresh the cron jobs list in sidebar
+ await mutate([FETCH_CRON_TOPICS_WITH_JOB_INFO_KEY, cronJob.agentId]);
+
+ return {
+ content: `Execution count for "${cronJob.name || 'Unnamed'}" has been reset. ${cronJob.maxExecutions ? `New limit: ${cronJob.maxExecutions} executions` : 'Unlimited executions'}.`,
+ state: {
+ cronJob,
+ success: true,
+ },
+ success: true,
+ };
+ } catch (error) {
+ log('[CronExecutor] resetExecutions - error:', error);
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
+ const isNotFound = errorMessage.includes('not found') || errorMessage.includes('NOT_FOUND');
+
+ return {
+ content: isNotFound
+ ? `Scheduled task not found: ${params.id}`
+ : `Failed to reset executions: ${errorMessage}`,
+ error: {
+ message: errorMessage,
+ type: isNotFound ? 'CronJobNotFound' : 'ResetExecutionsFailed',
+ },
+ success: false,
+ };
+ }
+ };
+
+ /**
+ * Get execution statistics
+ */
+ getStats = async (
+ _params: Record<string, never>,
+ _ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ try {
+ log('[CronExecutor] getStats');
+
+ const result = await lambdaClient.agentCronJob.getStats.query();
+ const stats = result.data;
+
+ return {
+ content: `Scheduled Tasks Statistics:\n- Total jobs: ${stats.totalJobs}\n- Active (enabled): ${stats.activeJobs}\n- Completed executions: ${stats.completedExecutions}\n- Pending executions: ${stats.pendingExecutions}`,
+ state: {
+ stats,
+ success: true,
+ },
+ success: true,
+ };
+ } catch (error) {
+ log('[CronExecutor] getStats - error:', error);
+ const errorMessage = error instanceof Error ? error.message : 'Failed to get statistics';
+
+ return {
+ content: `Failed to get execution statistics: ${errorMessage}`,
+ error: {
+ message: errorMessage,
+ type: 'GetStatsFailed',
+ },
+ success: false,
+ };
+ }
+ };
+}
+
+export const cronExecutor = new CronExecutor();
diff --git a/packages/builtin-tool-cron/src/index.ts b/packages/builtin-tool-cron/src/index.ts
new file mode 100644
index 00000000000..c6ad95cb5af
--- /dev/null
+++ b/packages/builtin-tool-cron/src/index.ts
@@ -0,0 +1,26 @@
+export { CronExecutionRuntime, type ICronService } from './ExecutionRuntime';
+export { CronIdentifier, CronManifest } from './manifest';
+export { systemPrompt } from './systemRole';
+export {
+ type CreateCronJobParams,
+ type CreateCronJobState,
+ CronApiName,
+ type CronApiNameType,
+ type CronJobSummary,
+ type CronJobSummaryForContext,
+ type CronStats,
+ type DeleteCronJobParams,
+ type DeleteCronJobState,
+ type GetCronJobParams,
+ type GetCronJobState,
+ type GetStatsParams,
+ type GetStatsState,
+ type ListCronJobsParams,
+ type ListCronJobsState,
+ type ResetExecutionsParams,
+ type ResetExecutionsState,
+ type ToggleCronJobParams,
+ type ToggleCronJobState,
+ type UpdateCronJobParams,
+ type UpdateCronJobState,
+} from './types';
diff --git a/packages/builtin-tool-cron/src/manifest.ts b/packages/builtin-tool-cron/src/manifest.ts
new file mode 100644
index 00000000000..d57a6b4a142
--- /dev/null
+++ b/packages/builtin-tool-cron/src/manifest.ts
@@ -0,0 +1,223 @@
+import type { BuiltinToolManifest } from '@lobechat/types';
+import type { JSONSchema7 } from 'json-schema';
+
+import { systemPrompt } from './systemRole';
+import { CronApiName } from './types';
+
+export const CronIdentifier = 'lobe-cron';
+
+export const CronManifest: BuiltinToolManifest = {
+ api: [
+ {
+ description:
+ 'Create a new scheduled task for the current agent. The task will run automatically at the specified schedule. Minimum interval is 30 minutes.',
+ name: CronApiName.createCronJob,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ content: {
+ description:
+ 'The prompt/instructions that will be sent to the agent when the task runs. This is the main content of the scheduled task.',
+ type: 'string',
+ },
+ cronPattern: {
+ description:
+ 'Standard cron pattern defining when the task runs. Format: "minute hour day month weekday". Examples: "0 9 * * *" (9 AM daily), "30 */2 * * *" (every 2 hours at :30), "0 14 * * 1-5" (2 PM weekdays). Minimum interval is 30 minutes.',
+ type: 'string',
+ },
+ description: {
+ description: 'Optional description explaining what this scheduled task does',
+ type: 'string',
+ },
+ enabled: {
+ default: true,
+ description: 'Whether the task should be enabled immediately (default: true)',
+ type: 'boolean',
+ },
+ maxExecutions: {
+ description:
+ 'Maximum number of times this task will run. Leave empty or null for unlimited executions.',
+ type: ['integer', 'null'],
+ },
+ name: {
+ description:
+ 'Human-readable name for the scheduled task (e.g., "Daily Report", "Weekly Summary")',
+ type: 'string',
+ },
+ timezone: {
+ default: 'UTC',
+ description:
+ 'Timezone for the schedule (e.g., "America/New_York", "Asia/Shanghai", "Europe/London"). Default is UTC.',
+ type: 'string',
+ },
+ },
+ required: ['name', 'content', 'cronPattern'],
+ type: 'object',
+ } satisfies JSONSchema7,
+ },
+ {
+ description:
+ 'List all scheduled tasks for the current agent. Returns task names, schedules, status, and execution counts.',
+ name: CronApiName.listCronJobs,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ enabled: {
+ description: 'Filter by enabled/disabled status. Leave empty to show all tasks.',
+ type: 'boolean',
+ },
+ limit: {
+ default: 20,
+ description: 'Maximum number of results to return (default: 20, max: 100)',
+ maximum: 100,
+ minimum: 1,
+ type: 'integer',
+ },
+ offset: {
+ default: 0,
+ description: 'Number of results to skip for pagination',
+ minimum: 0,
+ type: 'integer',
+ },
+ },
+ type: 'object',
+ } satisfies JSONSchema7,
+ },
+ {
+ description: 'Get detailed information about a specific scheduled task by its ID.',
+ name: CronApiName.getCronJob,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ id: {
+ description: 'The unique ID of the scheduled task to retrieve',
+ type: 'string',
+ },
+ },
+ required: ['id'],
+ type: 'object',
+ } satisfies JSONSchema7,
+ },
+ {
+ description:
+ 'Update an existing scheduled task. You can modify the name, content, schedule, timezone, or execution limits.',
+ name: CronApiName.updateCronJob,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ content: {
+ description: 'New prompt/instructions for the task',
+ type: 'string',
+ },
+ cronPattern: {
+ description: 'New cron pattern for the schedule',
+ type: 'string',
+ },
+ description: {
+ description: 'New description for the task',
+ type: 'string',
+ },
+ enabled: {
+ description: 'Enable or disable the task',
+ type: 'boolean',
+ },
+ id: {
+ description: 'The ID of the scheduled task to update',
+ type: 'string',
+ },
+ maxExecutions: {
+ description: 'New maximum number of executions (null for unlimited)',
+ type: ['integer', 'null'],
+ },
+ name: {
+ description: 'New name for the task',
+ type: 'string',
+ },
+ timezone: {
+ description: 'New timezone for the schedule',
+ type: 'string',
+ },
+ },
+ required: ['id'],
+ type: 'object',
+ } satisfies JSONSchema7,
+ },
+ {
+ description:
+ 'Delete a scheduled task permanently. This action cannot be undone. The task will stop running and all execution history will be removed.',
+ name: CronApiName.deleteCronJob,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ id: {
+ description: 'The ID of the scheduled task to delete',
+ type: 'string',
+ },
+ },
+ required: ['id'],
+ type: 'object',
+ } satisfies JSONSchema7,
+ },
+ {
+ description:
+ 'Enable or disable a scheduled task. Disabled tasks will not run but their configuration is preserved.',
+ name: CronApiName.toggleCronJob,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ enabled: {
+ description: 'Set to true to enable the task, false to disable it',
+ type: 'boolean',
+ },
+ id: {
+ description: 'The ID of the scheduled task to toggle',
+ type: 'string',
+ },
+ },
+ required: ['id', 'enabled'],
+ type: 'object',
+ } satisfies JSONSchema7,
+ },
+ {
+ description:
+ 'Reset the execution count for a scheduled task and re-enable it. Useful when a task has reached its maximum executions or you want to restart the count.',
+ name: CronApiName.resetExecutions,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ id: {
+ description: 'The ID of the scheduled task to reset',
+ type: 'string',
+ },
+ newMaxExecutions: {
+ description:
+ 'Optional new maximum executions value. If not specified, keeps the current max value.',
+ minimum: 1,
+ type: 'integer',
+ },
+ },
+ required: ['id'],
+ type: 'object',
+ } satisfies JSONSchema7,
+ },
+ {
+ description:
+ 'Get execution statistics for all scheduled tasks owned by the user. Shows active jobs, completed executions, and pending executions.',
+ name: CronApiName.getStats,
+ parameters: {
+ additionalProperties: false,
+ properties: {},
+ type: 'object',
+ } satisfies JSONSchema7,
+ },
+ ],
+ identifier: CronIdentifier,
+ meta: {
+ avatar: '⏰',
+ description:
+ 'Manage scheduled tasks that run automatically at specified times. Create, update, enable/disable, and monitor recurring tasks for your agents.',
+ title: 'Scheduled Tasks',
+ },
+ systemRole: systemPrompt,
+ type: 'builtin',
+};
diff --git a/packages/builtin-tool-cron/src/systemRole.ts b/packages/builtin-tool-cron/src/systemRole.ts
new file mode 100644
index 00000000000..28ab37d901d
--- /dev/null
+++ b/packages/builtin-tool-cron/src/systemRole.ts
@@ -0,0 +1,87 @@
+export const systemPrompt = `You have access to a LobeHub Scheduled Tasks Tool. This tool helps you create and manage recurring automated tasks that run at specified times.
+
+<session_context>
+Current user: {{username}}
+Session date: {{date}}
+Current agent: {{agent_id}}
+</session_context>
+
+<existing_scheduled_tasks>
+{{CRON_JOBS_LIST}}
+</existing_scheduled_tasks>
+
+<core_capabilities>
+1. **Create Tasks**: Set up recurring tasks with custom schedules (daily, hourly, weekly patterns)
+2. **Manage Tasks**: Update, enable/disable, or delete existing scheduled tasks
+3. **Monitor Execution**: Track execution counts, view statistics, and manage execution limits
+4. **Reset Tasks**: Reset execution counts to restart completed tasks
+</core_capabilities>
+
+<tooling>
+- **createCronJob**: Create a new scheduled task with a name, content/prompt, and cron schedule
+- **listCronJobs**: List all scheduled tasks for the current agent
+- **getCronJob**: Get detailed information about a specific task
+- **updateCronJob**: Modify an existing task's schedule, content, or settings
+- **deleteCronJob**: Permanently remove a scheduled task
+- **toggleCronJob**: Enable or disable a task without deleting it
+- **resetExecutions**: Reset execution count and re-enable a task that reached its limit
+- **getStats**: Get overall statistics for all scheduled tasks
+</tooling>
+
+<cron_pattern_guide>
+Cron patterns use the format: "minute hour day month weekday"
+
+**Common Patterns:**
+- \`0 9 * * *\` - Every day at 9:00 AM
+- \`30 9 * * *\` - Every day at 9:30 AM
+- \`0 */2 * * *\` - Every 2 hours at :00
+- \`30 */2 * * *\` - Every 2 hours at :30
+- \`0 9 * * 1-5\` - Weekdays at 9:00 AM
+- \`0 9 * * 1,3,5\` - Monday, Wednesday, Friday at 9:00 AM
+- \`0 9 * * 0\` - Every Sunday at 9:00 AM
+
+**Field Values:**
+- Minute: 0-59 (only 0 or 30 for minimum 30-minute interval)
+- Hour: 0-23 or */N for every N hours
+- Day: 1-31 or * for every day
+- Month: 1-12 or * for every month
+- Weekday: 0-6 (0=Sunday, 1=Monday, etc.) or * for every day
+
+**Important:** Minimum execution interval is 30 minutes. Patterns like \`*/5 * * * *\` (every 5 minutes) are not allowed.
+</cron_pattern_guide>
+
+<timezone_guide>
+Always specify a timezone when creating tasks to ensure they run at the expected local time.
+
+**Common Timezones:**
+- Americas: America/New_York, America/Los_Angeles, America/Chicago, America/Toronto
+- Europe: Europe/London, Europe/Paris, Europe/Berlin, Europe/Moscow
+- Asia: Asia/Shanghai, Asia/Tokyo, Asia/Seoul, Asia/Singapore, Asia/Hong_Kong
+- Oceania: Australia/Sydney, Pacific/Auckland
+
+Default timezone is UTC. Ask the user for their preferred timezone if not specified.
+</timezone_guide>
+
+<execution_limits>
+- **maxExecutions**: Set a limit on how many times a task will run (e.g., 10 executions)
+- **null/undefined**: Task runs indefinitely until disabled or deleted
+- **resetExecutions**: When a task reaches its limit, use this to restart the count
+
+When a task reaches its execution limit, it is automatically disabled. Use \`resetExecutions\` to re-enable it with a fresh count.
+</execution_limits>
+
+<best_practices>
+1. **Clear Names**: Use descriptive names like "Daily Morning Briefing" or "Weekly Report Summary"
+2. **Meaningful Content**: Write clear prompts that the agent can execute autonomously
+3. **Appropriate Schedules**: Consider user timezones and avoid scheduling too frequently
+4. **Execution Limits**: Set limits for tasks that shouldn't run forever (e.g., temporary reminders)
+5. **Review Tasks**: Periodically review and clean up unused scheduled tasks
+</best_practices>
+
+<response_expectations>
+- When creating tasks, confirm the schedule in the user's timezone
+- When listing tasks, summarize key information (name, schedule, status, remaining executions)
+- When updating tasks, explain what was changed
+- Always verify the user's intent before deleting tasks
+- Proactively suggest disabling instead of deleting if the user might want the task later
+</response_expectations>`;
diff --git a/packages/builtin-tool-cron/src/types.ts b/packages/builtin-tool-cron/src/types.ts
new file mode 100644
index 00000000000..5c84cc61a88
--- /dev/null
+++ b/packages/builtin-tool-cron/src/types.ts
@@ -0,0 +1,385 @@
+import type { ExecutionConditions } from '@lobechat/types';
+
+export const CronApiName = {
+ /**
+ * Create a new scheduled task for an agent
+ */
+ createCronJob: 'createCronJob',
+
+ /**
+ * Delete a scheduled task
+ */
+ deleteCronJob: 'deleteCronJob',
+
+ /**
+ * Get details of a specific cron job
+ */
+ getCronJob: 'getCronJob',
+
+ /**
+ * Get execution statistics for the user's cron jobs
+ */
+ getStats: 'getStats',
+
+ /**
+ * List all cron jobs for an agent
+ */
+ listCronJobs: 'listCronJobs',
+
+ /**
+ * Reset execution count and re-enable a job
+ */
+ resetExecutions: 'resetExecutions',
+
+ /**
+ * Enable or disable a cron job
+ */
+ toggleCronJob: 'toggleCronJob',
+
+ /**
+ * Update an existing cron job
+ */
+ updateCronJob: 'updateCronJob',
+} as const;
+
+export type CronApiNameType = (typeof CronApiName)[keyof typeof CronApiName];
+
+// ==================== Tool Parameter Types ====================
+
+export interface CreateCronJobParams {
+ /**
+ * The prompt/instructions for the scheduled task
+ */
+ content: string;
+ /**
+ * Standard cron pattern (e.g., "0 9 * * *" for 9 AM daily)
+ * Minimum interval is 30 minutes
+ */
+ cronPattern: string;
+ /**
+ * Optional description of the task
+ */
+ description?: string;
+ /**
+ * Whether the job should be enabled immediately (default: true)
+ */
+ enabled?: boolean;
+ /**
+ * Maximum number of executions (null = unlimited)
+ */
+ maxExecutions?: number | null;
+ /**
+ * Name of the scheduled task
+ */
+ name: string;
+ /**
+ * Timezone for the schedule (default: 'UTC')
+ * Example: 'America/New_York', 'Asia/Shanghai'
+ */
+ timezone?: string;
+}
+
+export interface CreateCronJobState {
+ /**
+ * The created cron job data
+ */
+ cronJob?: CronJobSummary;
+ /**
+ * Error message if creation failed
+ */
+ message?: string;
+ /**
+ * Whether creation was successful
+ */
+ success: boolean;
+}
+
+export interface ListCronJobsParams {
+ /**
+ * Filter by enabled/disabled status
+ */
+ enabled?: boolean;
+ /**
+ * Maximum number of results to return (default: 20, max: 100)
+ */
+ limit?: number;
+ /**
+ * Number of results to skip (for pagination)
+ */
+ offset?: number;
+}
+
+export interface ListCronJobsState {
+ /**
+ * List of cron jobs
+ */
+ cronJobs: CronJobSummary[];
+ /**
+ * Pagination info
+ */
+ pagination?: {
+ hasMore: boolean;
+ limit: number;
+ offset: number;
+ total: number;
+ };
+ /**
+ * Whether the query was successful
+ */
+ success: boolean;
+}
+
+export interface GetCronJobParams {
+ /**
+ * The ID of the cron job to retrieve
+ */
+ id: string;
+}
+
+export interface GetCronJobState {
+ /**
+ * The cron job details
+ */
+ cronJob?: CronJobSummary;
+ /**
+ * Error message if not found
+ */
+ message?: string;
+ /**
+ * Whether the query was successful
+ */
+ success: boolean;
+}
+
+export interface UpdateCronJobParams {
+ /**
+ * New content/prompt for the task
+ */
+ content?: string;
+ /**
+ * New cron pattern
+ */
+ cronPattern?: string;
+ /**
+ * New description
+ */
+ description?: string;
+ /**
+ * Enable or disable the job
+ */
+ enabled?: boolean;
+ /**
+ * The ID of the cron job to update
+ */
+ id: string;
+ /**
+ * New max executions (null = unlimited)
+ */
+ maxExecutions?: number | null;
+ /**
+ * New name for the task
+ */
+ name?: string;
+ /**
+ * New timezone
+ */
+ timezone?: string;
+}
+
+export interface UpdateCronJobState {
+ /**
+ * The updated cron job data
+ */
+ cronJob?: CronJobSummary;
+ /**
+ * Error message if update failed
+ */
+ message?: string;
+ /**
+ * Whether update was successful
+ */
+ success: boolean;
+}
+
+export interface DeleteCronJobParams {
+ /**
+ * The ID of the cron job to delete
+ */
+ id: string;
+}
+
+export interface DeleteCronJobState {
+ /**
+ * Error message if deletion failed
+ */
+ message?: string;
+ /**
+ * Whether deletion was successful
+ */
+ success: boolean;
+}
+
+export interface ToggleCronJobParams {
+ /**
+ * Whether to enable (true) or disable (false) the job
+ */
+ enabled: boolean;
+ /**
+ * The ID of the cron job to toggle
+ */
+ id: string;
+}
+
+export interface ToggleCronJobState {
+ /**
+ * The updated cron job data
+ */
+ cronJob?: CronJobSummary;
+ /**
+ * Error message if toggle failed
+ */
+ message?: string;
+ /**
+ * Whether toggle was successful
+ */
+ success: boolean;
+}
+
+export interface ResetExecutionsParams {
+ /**
+ * The ID of the cron job to reset
+ */
+ id: string;
+ /**
+ * New max executions value (optional, keeps current if not specified)
+ */
+ newMaxExecutions?: number;
+}
+
+export interface ResetExecutionsState {
+ /**
+ * The updated cron job data
+ */
+ cronJob?: CronJobSummary;
+ /**
+ * Error message if reset failed
+ */
+ message?: string;
+ /**
+ * Whether reset was successful
+ */
+ success: boolean;
+}
+
+export interface GetStatsParams {
+ // No parameters required - stats are for the current user
+}
+
+export interface GetStatsState {
+ /**
+ * Error message if query failed
+ */
+ message?: string;
+ /**
+ * Execution statistics
+ */
+ stats?: CronStats;
+ /**
+ * Whether query was successful
+ */
+ success: boolean;
+}
+
+// ==================== Data Types ====================
+
+export interface CronJobSummary {
+ /**
+ * The agent ID this job belongs to
+ */
+ agentId: string;
+ /**
+ * The prompt/instructions for the task
+ */
+ content: string;
+ /**
+ * When the job was created
+ */
+ createdAt: Date;
+ /**
+ * The cron pattern
+ */
+ cronPattern: string;
+ /**
+ * Optional description
+ */
+ description?: string | null;
+ /**
+ * Whether the job is enabled
+ */
+ enabled: boolean | null;
+ /**
+ * Advanced execution conditions
+ */
+ executionConditions?: ExecutionConditions | null;
+ /**
+ * Unique job ID
+ */
+ id: string;
+ /**
+ * When the job last executed
+ */
+ lastExecutedAt?: Date | null;
+ /**
+ * Maximum number of executions (null = unlimited)
+ */
+ maxExecutions?: number | null;
+ /**
+ * Task name
+ */
+ name?: string | null;
+ /**
+ * Remaining executions (null = unlimited)
+ */
+ remainingExecutions?: number | null;
+ /**
+ * Timezone for the schedule
+ */
+ timezone: string;
+ /**
+ * Total number of executions so far
+ */
+ totalExecutions: number;
+}
+
+export interface CronStats {
+ /**
+ * Number of active (enabled) jobs
+ */
+ activeJobs: number;
+ /**
+ * Total executions completed
+ */
+ completedExecutions: number;
+ /**
+ * Remaining executions across all jobs
+ */
+ pendingExecutions: number;
+ /**
+ * Total number of cron jobs
+ */
+ totalJobs: number;
+}
+
+// ==================== Context Types ====================
+
+export interface CronJobSummaryForContext {
+ cronPattern: string;
+ description?: string | null;
+ enabled: boolean;
+ id: string;
+ lastExecutedAt?: string | null;
+ name?: string | null;
+ remainingExecutions?: number | null;
+ timezone: string;
+ totalExecutions: number;
+}
diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.json
index ad08a071f24..9162d19da7f 100644
--- a/packages/builtin-tools/package.json
+++ b/packages/builtin-tools/package.json
@@ -22,6 +22,7 @@
"@lobechat/builtin-tool-brief": "workspace:*",
"@lobechat/builtin-tool-cloud-sandbox": "workspace:*",
"@lobechat/builtin-tool-creds": "workspace:*",
+ "@lobechat/builtin-tool-cron": "workspace:*",
"@lobechat/builtin-tool-group-agent-builder": "workspace:*",
"@lobechat/builtin-tool-group-management": "workspace:*",
"@lobechat/builtin-tool-gtd": "workspace:*",
diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.ts
index fac916724df..e8694b0a598 100644
--- a/packages/builtin-tools/src/index.ts
+++ b/packages/builtin-tools/src/index.ts
@@ -6,6 +6,7 @@ import { BriefManifest } from '@lobechat/builtin-tool-brief';
import { CalculatorManifest } from '@lobechat/builtin-tool-calculator';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { CredsManifest } from '@lobechat/builtin-tool-creds';
+import { CronManifest } from '@lobechat/builtin-tool-cron';
import { GroupAgentBuilderManifest } from '@lobechat/builtin-tool-group-agent-builder';
import { GroupManagementManifest } from '@lobechat/builtin-tool-group-management';
import { GTDManifest } from '@lobechat/builtin-tool-gtd';
@@ -115,6 +116,11 @@ export const builtinTools: LobeBuiltinTool[] = [
manifest: CredsManifest,
type: 'builtin',
},
+ {
+ identifier: CronManifest.identifier,
+ manifest: CronManifest,
+ type: 'builtin',
+ },
{
hidden: true,
identifier: KnowledgeBaseManifest.identifier,
diff --git a/src/server/services/toolExecution/serverRuntimes/cron.ts b/src/server/services/toolExecution/serverRuntimes/cron.ts
new file mode 100644
index 00000000000..c34c09e8260
--- /dev/null
+++ b/src/server/services/toolExecution/serverRuntimes/cron.ts
@@ -0,0 +1,190 @@
+import {
+ CronExecutionRuntime,
+ CronIdentifier,
+ type CronJobSummary,
+ type CronStats,
+ type ICronService,
+} from '@lobechat/builtin-tool-cron';
+import debug from 'debug';
+
+import { AgentCronJobModel } from '@/database/models/agentCronJob';
+
+import { type ServerRuntimeRegistration } from './types';
+
+const log = debug('lobe-server:cron-runtime');
+
+/**
+ * Server-side Cron Service implementation
+ * Wraps AgentCronJobModel to provide ICronService interface
+ */
+class ServerCronService implements ICronService {
+ private cronJobModel: AgentCronJobModel;
+
+ constructor(cronJobModel: AgentCronJobModel) {
+ this.cronJobModel = cronJobModel;
+ }
+
+ async create(data: {
+ agentId: string;
+ content: string;
+ cronPattern: string;
+ description?: string;
+ enabled?: boolean;
+ maxExecutions?: number | null;
+ name: string;
+ timezone?: string;
+ }): Promise<{ data: CronJobSummary }> {
+ log('create: agentId=%s, name=%s', data.agentId, data.name);
+
+ const cronJob = await this.cronJobModel.create({
+ agentId: data.agentId,
+ content: data.content,
+ cronPattern: data.cronPattern,
+ description: data.description,
+ enabled: data.enabled ?? true,
+ maxExecutions: data.maxExecutions,
+ name: data.name,
+ timezone: data.timezone || 'UTC',
+ });
+
+ log('create success: id=%s', cronJob.id);
+
+ return { data: cronJob as CronJobSummary };
+ }
+
+ async delete(id: string): Promise<{ success: boolean }> {
+ log('delete: id=%s', id);
+
+ const deleted = await this.cronJobModel.delete(id);
+
+ log('delete result: %s', deleted ? 'success' : 'not found');
+
+ return { success: !!deleted };
+ }
+
+ async findById(id: string): Promise<{ data: CronJobSummary }> {
+ log('findById: id=%s', id);
+
+ const cronJob = await this.cronJobModel.findById(id);
+
+ if (!cronJob) {
+ throw new Error(`Cron job not found: ${id}`);
+ }
+
+ log('findById success: id=%s', cronJob.id);
+
+ return { data: cronJob as CronJobSummary };
+ }
+
+ async getStats(): Promise<{ data: CronStats }> {
+ log('getStats');
+
+ const stats = await this.cronJobModel.getExecutionStats();
+
+ log('getStats success: totalJobs=%d', stats.totalJobs);
+
+ return { data: stats as CronStats };
+ }
+
+ async list(options: {
+ agentId?: string;
+ enabled?: boolean;
+ limit?: number;
+ offset?: number;
+ }): Promise<{
+ data: CronJobSummary[];
+ pagination?: {
+ hasMore: boolean;
+ limit: number;
+ offset: number;
+ total: number;
+ };
+ }> {
+ log('list: agentId=%s, enabled=%s', options.agentId, options.enabled);
+
+ const result = await this.cronJobModel.findWithPagination({
+ agentId: options.agentId,
+ enabled: options.enabled,
+ limit: options.limit || 20,
+ offset: options.offset || 0,
+ });
+
+ log('list success: %d jobs', result.jobs.length);
+
+ return {
+ data: result.jobs as CronJobSummary[],
+ pagination: {
+ hasMore: (options.offset || 0) + (options.limit || 20) < result.total,
+ limit: options.limit || 20,
+ offset: options.offset || 0,
+ total: result.total,
+ },
+ };
+ }
+
+ async resetExecutions(id: string, newMaxExecutions?: number): Promise<{ data: CronJobSummary }> {
+ log('resetExecutions: id=%s, newMaxExecutions=%s', id, newMaxExecutions);
+
+ const cronJob = await this.cronJobModel.resetExecutions(id, newMaxExecutions);
+
+ if (!cronJob) {
+ throw new Error(`Cron job not found: ${id}`);
+ }
+
+ log('resetExecutions success: id=%s', cronJob.id);
+
+ return { data: cronJob as CronJobSummary };
+ }
+
+ async update(
+ id: string,
+ data: {
+ content?: string;
+ cronPattern?: string;
+ description?: string;
+ enabled?: boolean;
+ maxExecutions?: number | null;
+ name?: string;
+ timezone?: string;
+ },
+ ): Promise<{ data: CronJobSummary }> {
+ log('update: id=%s', id);
+
+ const cronJob = await this.cronJobModel.update(id, data);
+
+ if (!cronJob) {
+ throw new Error(`Cron job not found: ${id}`);
+ }
+
+ log('update success: id=%s', cronJob.id);
+
+ return { data: cronJob as CronJobSummary };
+ }
+}
+
+/**
+ * Cron Server Runtime
+ * Per-request runtime (needs userId, agentId, db)
+ */
+export const cronRuntime: ServerRuntimeRegistration = {
+ factory: (context) => {
+ if (!context.userId) {
+ throw new Error('userId is required for Cron execution');
+ }
+
+ if (!context.serverDB) {
+ throw new Error('serverDB is required for Cron execution');
+ }
+
+ log('Creating CronExecutionRuntime for userId=%s, agentId=%s', context.userId, context.agentId);
+
+ const cronJobModel = new AgentCronJobModel(context.serverDB, context.userId);
+ const cronService = new ServerCronService(cronJobModel);
+
+ return new CronExecutionRuntime(cronService, {
+ agentId: context.agentId,
+ userId: context.userId,
+ });
+ },
+ identifier: CronIdentifier,
+};
diff --git a/src/server/services/toolExecution/serverRuntimes/index.ts b/src/server/services/toolExecution/serverRuntimes/index.ts
index 1c6aba33f39..76915bcb30d 100644
--- a/src/server/services/toolExecution/serverRuntimes/index.ts
+++ b/src/server/services/toolExecution/serverRuntimes/index.ts
@@ -13,6 +13,7 @@ import { briefRuntime } from './brief';
import { calculatorRuntime } from './calculator';
import { cloudSandboxRuntime } from './cloudSandbox';
import { credsRuntime } from './creds';
+import { cronRuntime } from './cron';
import { localSystemRuntime } from './localSystem';
import { memoryRuntime } from './memory';
import { messageRuntime } from './message';
@@ -60,6 +61,7 @@ registerRuntimes([
topicReferenceRuntime,
userInteractionRuntime,
credsRuntime,
+ cronRuntime,
webOnboardingRuntime,
]);
diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.ts
index f1614129976..f6ea6cadd18 100644
--- a/src/store/tool/slices/builtin/executors/index.ts
+++ b/src/store/tool/slices/builtin/executors/index.ts
@@ -9,6 +9,7 @@ import { agentManagementExecutor } from '@lobechat/builtin-tool-agent-management
import { calculatorExecutor } from '@lobechat/builtin-tool-calculator/executor';
import { cloudSandboxExecutor } from '@lobechat/builtin-tool-cloud-sandbox/executor';
import { credsExecutor } from '@lobechat/builtin-tool-creds/executor';
+import { cronExecutor } from '@lobechat/builtin-tool-cron/executor';
import { groupAgentBuilderExecutor } from '@lobechat/builtin-tool-group-agent-builder/executor';
import { groupManagementExecutor } from '@lobechat/builtin-tool-group-management/executor';
import { gtdExecutor } from '@lobechat/builtin-tool-gtd/executor';
@@ -137,6 +138,7 @@ registerExecutors([
calculatorExecutor,
cloudSandboxExecutor,
credsExecutor,
+ cronExecutor,
groupAgentBuilderExecutor,
groupManagementExecutor,
gtdExecutor,