π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix: remove the old cron job from lobehub (#14630)
LiJian2098ac83743b
diff --git a/apps/cli/src/commands/brief.ts b/apps/cli/src/commands/brief.tsindex e93216eae65..8889d2ebef6 100644--- a/apps/cli/src/commands/brief.ts+++ b/apps/cli/src/commands/brief.ts@@ -55,7 +55,7 @@ export function registerBriefCommand(program: Command) {typeBadge(b.type, b.priority),truncate(b.title, 40),truncate(b.summary, 50),- b.taskId ? pc.dim(b.taskId) : b.cronJobId ? pc.dim(b.cronJobId) : '-',+ b.taskId ? pc.dim(b.taskId) : '-',b.resolvedAt ? pc.green('resolved') : b.readAt ? pc.dim('read') : 'new',timeAgo(b.createdAt),]);@@ -102,7 +102,6 @@ export function registerBriefCommand(program: Command) {console.log(`${pc.dim('Type:')} ${b.type} ${pc.dim('Created:')} ${timeAgo(b.createdAt)}`);if (b.agentId) console.log(`${pc.dim('Agent:')} ${b.agentId}`);if (b.taskId) console.log(`${pc.dim('Task:')} ${b.taskId}`);- if (b.cronJobId) console.log(`${pc.dim('CronJob:')} ${b.cronJobId}`);if (b.topicId) console.log(`${pc.dim('Topic:')} ${b.topicId}`);console.log(`\n${b.summary}`);diff --git a/apps/cli/src/commands/cron.test.ts b/apps/cli/src/commands/cron.test.tsdeleted file mode 100644index 7b80b25292f..00000000000--- a/apps/cli/src/commands/cron.test.ts+++ /dev/null@@ -1,172 +0,0 @@-import { Command } from 'commander';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { registerCronCommand } from './cron';--const { mockTrpcClient } = vi.hoisted(() => ({- mockTrpcClient: {- agentCronJob: {- batchUpdateStatus: { mutate: vi.fn() },- create: { mutate: vi.fn() },- delete: { mutate: vi.fn() },- findById: { query: vi.fn() },- getStats: { query: vi.fn() },- list: { query: vi.fn() },- resetExecutions: { mutate: vi.fn() },- update: { mutate: vi.fn() },- },- },-}));--const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({- getTrpcClient: vi.fn(),-}));--vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));-vi.mock('../utils/logger', () => ({- log: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() },- setVerbose: vi.fn(),-}));--describe('cron command', () => {- let exitSpy: ReturnType<typeof vi.spyOn>;- let consoleSpy: ReturnType<typeof vi.spyOn>;-- beforeEach(() => {- exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);- consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});- mockGetTrpcClient.mockResolvedValue(mockTrpcClient);- for (const method of Object.values(mockTrpcClient.agentCronJob)) {- for (const fn of Object.values(method)) {- (fn as ReturnType<typeof vi.fn>).mockReset();- }- }- });-- afterEach(() => {- exitSpy.mockRestore();- consoleSpy.mockRestore();- });-- function createProgram() {- const program = new Command();- program.exitOverride();- registerCronCommand(program);- return program;- }-- describe('list', () => {- it('should list cron jobs', async () => {- mockTrpcClient.agentCronJob.list.query.mockResolvedValue({- data: [{ enabled: true, id: 'c1', name: 'Test Job', schedule: '* * * * *' }],- });-- const program = createProgram();- await program.parseAsync(['node', 'test', 'cron', 'list']);-- expect(mockTrpcClient.agentCronJob.list.query).toHaveBeenCalled();- });-- it('should filter by agent-id', async () => {- mockTrpcClient.agentCronJob.list.query.mockResolvedValue({ data: [] });-- const program = createProgram();- await program.parseAsync(['node', 'test', 'cron', 'list', '--agent-id', 'a1']);-- expect(mockTrpcClient.agentCronJob.list.query).toHaveBeenCalledWith(- expect.objectContaining({ agentId: 'a1' }),- );- });- });-- describe('view', () => {- it('should view cron job details', async () => {- mockTrpcClient.agentCronJob.findById.query.mockResolvedValue({- data: { enabled: true, id: 'c1', name: 'Test', schedule: '* * * * *' },- });-- const program = createProgram();- await program.parseAsync(['node', 'test', 'cron', 'view', 'c1']);-- expect(mockTrpcClient.agentCronJob.findById.query).toHaveBeenCalledWith({ id: 'c1' });- });- });-- describe('create', () => {- it('should create a cron job', async () => {- mockTrpcClient.agentCronJob.create.mutate.mockResolvedValue({ data: { id: 'c1' } });-- const program = createProgram();- await program.parseAsync([- 'node',- 'test',- 'cron',- 'create',- '--agent-id',- 'a1',- '-s',- '* * * * *',- '-n',- 'My Job',- ]);-- expect(mockTrpcClient.agentCronJob.create.mutate).toHaveBeenCalledWith(- expect.objectContaining({ agentId: 'a1', cronPattern: '* * * * *', name: 'My Job' }),- );- });- });-- describe('delete', () => {- it('should delete a cron job', async () => {- mockTrpcClient.agentCronJob.delete.mutate.mockResolvedValue({});-- const program = createProgram();- await program.parseAsync(['node', 'test', 'cron', 'delete', 'c1', '--yes']);-- expect(mockTrpcClient.agentCronJob.delete.mutate).toHaveBeenCalledWith({ id: 'c1' });- });- });-- describe('toggle', () => {- it('should batch enable cron jobs', async () => {- mockTrpcClient.agentCronJob.batchUpdateStatus.mutate.mockResolvedValue({- data: { updatedCount: 2 },- });-- const program = createProgram();- await program.parseAsync(['node', 'test', 'cron', 'toggle', 'c1', 'c2', '--enable']);-- expect(mockTrpcClient.agentCronJob.batchUpdateStatus.mutate).toHaveBeenCalledWith({- enabled: true,- ids: ['c1', 'c2'],- });- });- });-- describe('reset', () => {- it('should reset execution count', async () => {- mockTrpcClient.agentCronJob.resetExecutions.mutate.mockResolvedValue({});-- const program = createProgram();- await program.parseAsync(['node', 'test', 'cron', 'reset', 'c1', '--max', '100']);-- expect(mockTrpcClient.agentCronJob.resetExecutions.mutate).toHaveBeenCalledWith({- id: 'c1',- newMaxExecutions: 100,- });- });- });-- describe('stats', () => {- it('should get stats', async () => {- mockTrpcClient.agentCronJob.getStats.query.mockResolvedValue({- data: { totalJobs: 5, totalExecutions: 100 },- });-- const program = createProgram();- await program.parseAsync(['node', 'test', 'cron', 'stats']);-- expect(mockTrpcClient.agentCronJob.getStats.query).toHaveBeenCalled();- });- });-});diff --git a/apps/cli/src/commands/cron.ts b/apps/cli/src/commands/cron.tsdeleted file mode 100644index c9675de638c..00000000000--- a/apps/cli/src/commands/cron.ts+++ /dev/null@@ -1,271 +0,0 @@-import type { Command } from 'commander';-import pc from 'picocolors';--import { getTrpcClient } from '../api/client';-import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/format';-import { log } from '../utils/logger';--export function registerCronCommand(program: Command) {- const cron = program.command('cron').description('Manage agent cron jobs');-- // ββ list ββββββββββββββββββββββββββββββββββββββββββββββ-- cron- .command('list')- .description('List cron jobs')- .option('--agent-id <id>', 'Filter by agent ID')- .option('--enabled', 'Only show enabled jobs')- .option('--disabled', 'Only show disabled jobs')- .option('-L, --limit <n>', 'Page size', '20')- .option('--offset <n>', 'Offset', '0')- .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')- .action(- async (options: {- agentId?: string;- disabled?: boolean;- enabled?: boolean;- json?: string | boolean;- limit?: string;- offset?: string;- }) => {- const client = await getTrpcClient();-- const input: Record<string, any> = {};- if (options.agentId) input.agentId = options.agentId;- if (options.enabled) input.enabled = true;- if (options.disabled) input.enabled = false;- if (options.limit) input.limit = Number.parseInt(options.limit, 10);- if (options.offset) input.offset = Number.parseInt(options.offset, 10);-- const result = await client.agentCronJob.list.query(input as any);- const items = (result as any).data ?? [];-- if (options.json !== undefined) {- const fields = typeof options.json === 'string' ? options.json : undefined;- outputJson(items, fields);- return;- }-- if (items.length === 0) {- console.log('No cron jobs found.');- return;- }-- const rows = items.map((j: any) => [- j.id || '',- truncate(j.name || '', 30),- j.schedule || '',- j.enabled ? pc.green('enabled') : pc.dim('disabled'),- `${j.executionCount ?? 0}/${j.maxExecutions ?? 'β'}`,- j.updatedAt ? timeAgo(j.updatedAt) : '',- ]);-- printTable(rows, ['ID', 'NAME', 'SCHEDULE', 'STATUS', 'EXECUTIONS', 'UPDATED']);- },- );-- // ββ view ββββββββββββββββββββββββββββββββββββββββββββββ-- cron- .command('view <id>')- .description('View cron job details')- .option('--json [fields]', 'Output JSON')- .action(async (id: string, options: { json?: string | boolean }) => {- const client = await getTrpcClient();- const result = await client.agentCronJob.findById.query({ id });- const job = (result as any).data;-- if (options.json !== undefined) {- const fields = typeof options.json === 'string' ? options.json : undefined;- outputJson(job, fields);- return;- }-- if (!job) {- log.error('Cron job not found.');- process.exit(1);- }-- console.log(`${pc.bold('ID:')} ${job.id}`);- console.log(`${pc.bold('Name:')} ${job.name || ''}`);- console.log(`${pc.bold('Agent ID:')} ${job.agentId || ''}`);- console.log(`${pc.bold('Schedule:')} ${job.schedule || ''}`);- console.log(- `${pc.bold('Status:')} ${job.enabled ? pc.green('enabled') : pc.dim('disabled')}`,- );- console.log(- `${pc.bold('Executions:')} ${job.executionCount ?? 0}/${job.maxExecutions ?? 'β'}`,- );- if (job.prompt) console.log(`${pc.bold('Prompt:')} ${truncate(job.prompt, 80)}`);- if (job.createdAt) console.log(`${pc.bold('Created:')} ${timeAgo(job.createdAt)}`);- if (job.updatedAt) console.log(`${pc.bold('Updated:')} ${timeAgo(job.updatedAt)}`);- });-- // ββ create ββββββββββββββββββββββββββββββββββββββββββββ-- cron- .command('create')- .description('Create a cron job')- .requiredOption('--agent-id <id>', 'Agent ID')- .requiredOption('-s, --schedule <cron>', 'Cron schedule expression')- .option('-n, --name <name>', 'Job name')- .option('-p, --prompt <prompt>', 'Prompt text')- .option('--max-executions <n>', 'Maximum number of executions')- .option('--json', 'Output JSON')- .action(- async (options: {- agentId: string;- json?: boolean;- maxExecutions?: string;- name?: string;- prompt?: string;- schedule: string;- }) => {- const client = await getTrpcClient();-- const input: Record<string, any> = {- agentId: options.agentId,- cronPattern: options.schedule,- };- if (options.name) input.name = options.name;- if (options.prompt) input.content = options.prompt;- if (options.maxExecutions) input.maxExecutions = Number.parseInt(options.maxExecutions, 10);-- const result = await client.agentCronJob.create.mutate(input as any);-- if (options.json) {- console.log(JSON.stringify(result, null, 2));- return;- }-- const data = (result as any).data;- console.log(`${pc.green('β')} Created cron job ${pc.bold(data?.id || '')}`);- },- );-- // ββ edit βββββββββββββββββββββββββββββββββββββββββββββββ-- cron- .command('edit <id>')- .description('Update a cron job')- .option('-n, --name <name>', 'Job name')- .option('-s, --schedule <cron>', 'Cron schedule expression')- .option('-p, --prompt <prompt>', 'Prompt text')- .option('--max-executions <n>', 'Maximum number of executions')- .option('--enable', 'Enable the job')- .option('--disable', 'Disable the job')- .action(- async (- id: string,- options: {- disable?: boolean;- enable?: boolean;- maxExecutions?: string;- name?: string;- prompt?: string;- schedule?: string;- },- ) => {- const data: Record<string, any> = {};- if (options.name) data.name = options.name;- if (options.schedule) data.cronPattern = options.schedule;- if (options.prompt) data.content = options.prompt;- if (options.maxExecutions) data.maxExecutions = Number.parseInt(options.maxExecutions, 10);- if (options.enable) data.enabled = true;- if (options.disable) data.enabled = false;-- if (Object.keys(data).length === 0) {- log.error(- 'No changes specified. Use --name, --schedule, --prompt, --enable, or --disable.',- );- process.exit(1);- }-- const client = await getTrpcClient();- await client.agentCronJob.update.mutate({ data, id } as any);- console.log(`${pc.green('β')} Updated cron job ${pc.bold(id)}`);- },- );-- // ββ delete ββββββββββββββββββββββββββββββββββββββββββββ-- cron- .command('delete <id>')- .description('Delete a cron job')- .option('--yes', 'Skip confirmation prompt')- .action(async (id: string, options: { yes?: boolean }) => {- if (!options.yes) {- const confirmed = await confirm('Are you sure you want to delete this cron job?');- if (!confirmed) {- console.log('Cancelled.');- return;- }- }-- const client = await getTrpcClient();- await client.agentCronJob.delete.mutate({ id });- console.log(`${pc.green('β')} Deleted cron job ${pc.bold(id)}`);- });-- // ββ toggle ββββββββββββββββββββββββββββββββββββββββββββ-- cron- .command('toggle <ids...>')- .description('Batch enable or disable cron jobs')- .option('--enable', 'Enable the jobs')- .option('--disable', 'Disable the jobs')- .action(async (ids: string[], options: { disable?: boolean; enable?: boolean }) => {- if (!options.enable && !options.disable) {- log.error('Specify --enable or --disable.');- process.exit(1);- }-- const enabled = !!options.enable;- const client = await getTrpcClient();- const result = await client.agentCronJob.batchUpdateStatus.mutate({ enabled, ids });- const count = (result as any).data?.updatedCount ?? ids.length;- console.log(`${pc.green('β')} ${enabled ? 'Enabled' : 'Disabled'} ${count} cron job(s)`);- });-- // ββ reset βββββββββββββββββββββββββββββββββββββββββββββ-- cron- .command('reset <id>')- .description('Reset execution count for a cron job')- .option('--max <n>', 'Set new max executions')- .action(async (id: string, options: { max?: string }) => {- const client = await getTrpcClient();-- const input: Record<string, any> = { id };- if (options.max) input.newMaxExecutions = Number.parseInt(options.max, 10);-- await client.agentCronJob.resetExecutions.mutate(input as any);- console.log(`${pc.green('β')} Reset execution count for ${pc.bold(id)}`);- });-- // ββ stats βββββββββββββββββββββββββββββββββββββββββββββ-- cron- .command('stats')- .description('Get cron job execution statistics')- .option('--json', 'Output JSON')- .action(async (options: { json?: boolean }) => {- const client = await getTrpcClient();- const result = await client.agentCronJob.getStats.query();- const stats = (result as any).data;-- if (options.json) {- console.log(JSON.stringify(stats, null, 2));- return;- }-- if (!stats) {- console.log('No statistics available.');- return;- }-- for (const [key, value] of Object.entries(stats as Record<string, any>)) {- console.log(`${pc.bold(key + ':')} ${value}`);- }- });-}diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.tsindex e26680477f3..76f7618632d 100644--- a/apps/cli/src/program.ts+++ b/apps/cli/src/program.ts@@ -8,7 +8,6 @@ import { registerBotCommand } from './commands/bot';import { registerCompletionCommand } from './commands/completion';import { registerConfigCommand } from './commands/config';import { registerConnectCommand } from './commands/connect';-import { registerCronCommand } from './commands/cron';import { registerDeviceCommand } from './commands/device';import { registerDocCommand } from './commands/doc';import { registerEvalCommand } from './commands/eval';@@ -60,7 +59,6 @@ export function createProgram() {registerAgentCommand(program);registerAgentGroupCommand(program);registerBotCommand(program);- registerCronCommand(program);registerGenerateCommand(program);registerFileCommand(program);registerHeteroCommand(program);diff --git a/package.json b/package.jsonindex 63d33e74dac..db4279987b2 100644--- a/package.json+++ b/package.json@@ -218,7 +218,6 @@"@lobechat/builtin-tool-claude-code": "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.jsondeleted file mode 100644index 8c278cc026f..00000000000--- a/packages/builtin-tool-cron/package.json+++ /dev/null@@ -1,15 +0,0 @@-{- "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.tsdeleted file mode 100644index 497ea8d482e..00000000000--- a/packages/builtin-tool-cron/src/ExecutionRuntime/index.ts+++ /dev/null@@ -1,451 +0,0 @@-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.tsdeleted file mode 100644index 04b886d325a..00000000000--- a/packages/builtin-tool-cron/src/executor/index.ts+++ /dev/null@@ -1,451 +0,0 @@-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/helpers.ts b/packages/builtin-tool-cron/src/helpers.tsdeleted file mode 100644index 543ddbc98de..00000000000--- a/packages/builtin-tool-cron/src/helpers.ts+++ /dev/null@@ -1,25 +0,0 @@-import type { CronJobSummaryForContext } from './types';--const formatCronJob = (job: CronJobSummaryForContext): string => {- const status = job.enabled ? 'enabled' : 'disabled';- const execInfo =- job.remainingExecutions != null ? `${job.remainingExecutions} remaining` : 'unlimited';- const lastRun = job.lastExecutedAt ?? 'never';- const desc = job.description ? ` - ${job.description}` : '';-- return ` - ${job.name || 'Unnamed'} (id: ${job.id}): ${job.cronPattern} [${job.timezone}] [${status}, ${execInfo}, ${job.totalExecutions} completed, last run: ${lastRun}]${desc}`;-};--export const generateCronJobsList = (jobs: CronJobSummaryForContext[], total?: number): string => {- if (jobs.length === 0) {- return 'No scheduled tasks configured for this agent.';- }-- const lines = jobs.map(formatCronJob);-- if (total && total > jobs.length) {- lines.push(` (showing ${jobs.length} of ${total} tasks β use listCronJobs to see all)`);- }-- return lines.join('\n');-};diff --git a/packages/builtin-tool-cron/src/index.ts b/packages/builtin-tool-cron/src/index.tsdeleted file mode 100644index fb62eb03d56..00000000000--- a/packages/builtin-tool-cron/src/index.ts+++ /dev/null@@ -1,27 +0,0 @@-export { CronExecutionRuntime, type ICronService } from './ExecutionRuntime';-export { generateCronJobsList } from './helpers';-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.tsdeleted file mode 100644index e32b0084757..00000000000--- a/packages/builtin-tool-cron/src/manifest.ts+++ /dev/null@@ -1,223 +0,0 @@-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 automated recurring task. Use this when the user wants something done regularly/repeatedly β e.g., "set as daily task", "do this every morning", "make it a routine", "daily briefing", "weekly summary". The task will run automatically at the specified schedule without user intervention. 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:- 'Automate recurring tasks that repeat on a schedule β daily routines, periodic reports, regular reminders, and any task the user wants done automatically every day/week/hour. Use this whenever the user says "daily task", "routine", "recurring", "every day", "every morning", "regular", "periodic", "set as daily", or implies something should happen repeatedly without manual trigger.',- title: 'Scheduled Tasks',- },- systemRole: systemPrompt,- type: 'builtin',-};diff --git a/packages/builtin-tool-cron/src/systemRole.ts b/packages/builtin-tool-cron/src/systemRole.tsdeleted file mode 100644index 575e295db04..00000000000--- a/packages/builtin-tool-cron/src/systemRole.ts+++ /dev/null@@ -1,101 +0,0 @@-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}}-User timezone: {{timezone}}-</session_context>--<existing_scheduled_tasks>-{{CRON_JOBS_LIST}}-</existing_scheduled_tasks>--<when_to_use>-**Use this tool (lobe-cron) when the user wants tasks to run automatically and repeatedly.** Common trigger phrases include:-- "daily task", "set as daily task", "make it a daily routine"-- "every day", "every morning", "every week", "every hour"-- "recurring", "routine", "regular", "periodic", "scheduled"-- "automatically do X at Y time"-- "remind me every day to..."--**Do NOT confuse with lobe-gtd.** GTD is for one-time planning and manual todo tracking. If the user says "daily task" or "routine task", they almost always mean automated repetition (lobe-cron), NOT a one-time todo item (lobe-gtd).--**Do NOT confuse with lobe-user-memory.** Memory is for saving user preferences and long-term knowledge. "Set as daily task" means schedule it to run repeatedly, NOT save it as a memory.-</when_to_use>--<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.tsdeleted file mode 100644index 5c84cc61a88..00000000000--- a/packages/builtin-tool-cron/src/types.ts+++ /dev/null@@ -1,385 +0,0 @@-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.jsonindex 2fd184500b6..8180a601e08 100644--- a/packages/builtin-tools/package.json+++ b/packages/builtin-tools/package.json@@ -25,7 +25,6 @@"@lobechat/builtin-tool-claude-code": "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.tsindex b8dda9d68b2..f316a6d81eb 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -6,7 +6,6 @@ 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';@@ -164,11 +163,6 @@ export const builtinTools: LobeBuiltinTool[] = [manifest: CredsManifest,type: 'builtin',},- {- identifier: CronManifest.identifier,- manifest: CronManifest,- type: 'builtin',- },{hidden: true,identifier: KnowledgeBaseManifest.identifier,diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex f2d4cbb5274..ee8611563b7 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -736,6 +736,37 @@ export class TopicModel {.returning();};+ getCronTopicsGroupedByCronJob = async (+ agentId: string,+ ): Promise<{ cronJobId: string; topics: TopicItem[] }[]> => {+ const rows = await this.db+ .select()+ .from(topics)+ .where(+ and(+ eq(topics.userId, this.userId),+ eq(topics.agentId, agentId),+ eq(topics.trigger, 'cron'),+ sql`(${topics.metadata}->>'cronJobId') IS NOT NULL`,+ ),+ )+ .orderBy(desc(topics.createdAt));++ const grouped = new Map<string, TopicItem[]>();+ for (const topic of rows) {+ const cronJobId = (topic.metadata as { cronJobId?: string } | null)?.cronJobId;+ if (!cronJobId) continue;+ const group = grouped.get(cronJobId) ?? [];+ group.push(topic);+ grouped.set(cronJobId, group);+ }++ return [...grouped.entries()].map(([cronJobId, topicList]) => ({+ cronJobId,+ topics: topicList,+ }));+ };+// **************** Helper *************** //private genId = () => idGenerator('topics');@@ -821,52 +852,4 @@ export class TopicModel {return result[0]?.total ?? 0;};-- /**- * Get cron topics grouped by cronJob for a specific agent- * Returns topics where trigger='cron' and metadata contains cronJobId- */- getCronTopicsGroupedByCronJob = async (agentId: string) => {- const cronTopics = await this.db- .select({- createdAt: topics.createdAt,- favorite: topics.favorite,- historySummary: topics.historySummary,- id: topics.id,- metadata: topics.metadata,- title: topics.title,- trigger: topics.trigger,- updatedAt: topics.updatedAt,- })- .from(topics)- .where(- and(- eq(topics.userId, this.userId),- eq(topics.agentId, agentId),- eq(topics.trigger, 'cron'),- // Check if metadata contains cronJobId (use ? operator to avoid Neon rt_fetch bug with ->>)- sql`${topics.metadata} ? 'cronJobId'`,- ),- )- .orderBy(desc(topics.updatedAt));-- // Group topics by cronJobId- const groupedTopics = new Map<string, typeof cronTopics>();-- cronTopics.forEach((topic) => {- const cronJobId = topic.metadata?.cronJobId;- if (cronJobId) {- if (!groupedTopics.has(cronJobId)) {- groupedTopics.set(cronJobId, []);- }- groupedTopics.get(cronJobId)!.push(topic);- }- });-- // Convert Map to array of grouped objects- return Array.from(groupedTopics.entries()).map(([cronJobId, topicList]) => ({- cronJobId,- topics: topicList,- }));- };}diff --git a/packages/database/src/schemas/agentCronJob.ts b/packages/database/src/schemas/agentCronJob.tsindex 708705685e6..f312b7deaa0 100644--- a/packages/database/src/schemas/agentCronJob.ts+++ b/packages/database/src/schemas/agentCronJob.ts@@ -1,4 +1,3 @@-import type { ExecutionConditions } from '@lobechat/types';import { boolean, index, integer, jsonb, pgTable, text, timestamp } from 'drizzle-orm/pg-core';import { idGenerator } from '../utils/idGenerator';@@ -7,6 +6,12 @@ import { agents } from './agent';import { chatGroups } from './chatGroup';import { users } from './user';+interface ExecutionConditions {+ activeDays?: number[];+ activeHours?: { end: number; start: number };+ maxExecutionsPerDay?: number;+}+// Agent cron jobs table - supports multiple cron jobs per agentexport const agentCronJobs = pgTable('agent_cron_jobs',@@ -65,8 +70,8 @@ export const agentCronJobs = pgTable(// Type exportsexport type NewAgentCronJob = typeof agentCronJobs.$inferInsert;export type AgentCronJob = typeof agentCronJobs.$inferSelect;+export type CreateAgentCronJobData = Partial<NewAgentCronJob> &+ Pick<NewAgentCronJob, 'agentId' | 'cronPattern' | 'content'>;+export type UpdateAgentCronJobData = Partial<AgentCronJob>;-// Re-export types from types package for consumers-export type { ExecutionConditions } from '@lobechat/types';-export type { InsertAgentCronJob as CreateAgentCronJobData } from '@lobechat/types';-export type { UpdateAgentCronJob as UpdateAgentCronJobData } from '@lobechat/types';+export type { ExecutionConditions };diff --git a/packages/types/src/agentCronJob/index.ts b/packages/types/src/agentCronJob/index.tsdeleted file mode 100644index 81af0e502a2..00000000000--- a/packages/types/src/agentCronJob/index.ts+++ /dev/null@@ -1,111 +0,0 @@-import { z } from 'zod';--// Execution conditions type-export interface ExecutionConditions {- maxExecutionsPerDay?: number;- timeRange?: {- end: string; // "18:00"- start: string; // "09:00"- };- weekdays?: number[]; // [1,2,3,4,5] (Monday=1, Sunday=0)-}--// Cron pattern validation schema-export const cronPatternSchema = z- .string()- .regex(- /^(@(annually|yearly|monthly|weekly|daily|hourly|reboot))|(@every (\d+(ns|us|Β΅s|ms|[hms]))+)|((((\d+,)+\d+|(\d+([/-])\d+)|\d+|\*) ?){5,7})$/,- 'Invalid cron pattern',- );--// Minimum 30 minutes validation (using standard cron format)-export const minimumIntervalSchema = z.string().refine((pattern) => {- // Standard cron format: minute hour day month weekday- // Parse pattern to validate minimum 30-minute interval- const parts = pattern.split(' ');- if (parts.length !== 5) {- return false;- }-- const [minute, hour] = parts;-- // Validate minute is 0 or 30 (we only allow 30-minute intervals)- const isValidMinute = minute === '0' || minute === '30' || minute === '*/30';-- if (!isValidMinute) {- return false;- }-- // Allow minute intervals >= 30 (e.g., */30, */45, */60)- if (minute.startsWith('*/')) {- const interval = parseInt(minute.slice(2));- if (!isNaN(interval) && interval >= 30) {- return true;- }- return false;- }-- // Allow hourly patterns: {0|30} */N * * * where N >= 1- if ((minute === '0' || minute === '30') && hour.startsWith('*/')) {- const interval = parseInt(hour.slice(2));- if (!isNaN(interval) && interval >= 1) {- return true;- }- return false;- }-- // Allow hourly patterns: {0|30} * * * * (every hour at :00 or :30)- if ((minute === '0' || minute === '30') && hour === '*') {- return true;- }-- // Allow specific hour patterns: {0|30} N * * * (runs once per day)- // or {0|30} N * * {weekdays} (runs on specific weekdays)- if ((minute === '0' || minute === '30') && /^\d+$/.test(hour)) {- const h = parseInt(hour);- if (!isNaN(h) && h >= 0 && h <= 23) {- return true;- }- }-- return false;-}, 'Minimum execution interval is 30 minutes');--// Execution conditions schema-export const ExecutionConditionsSchema = z- .object({- maxExecutionsPerDay: z.number().min(1).max(100).optional(),- timeRange: z- .object({- end: z.string().regex(/^([01]?\d|2[0-3]):[0-5]\d$/, 'Invalid time format'),- start: z.string().regex(/^([01]?\d|2[0-3]):[0-5]\d$/, 'Invalid time format'),- })- .optional(),- weekdays: z.array(z.number().min(0).max(6)).optional(),- })- .optional();--// Insert schema for creating agent cron jobs-export const InsertAgentCronJobSchema = z.object({- agentId: z.string(),- content: z.string(), // Allow empty content (when using editData for rich content)- cronPattern: minimumIntervalSchema,- description: z.string().optional().nullable(),- editData: z.record(z.string(), z.any()).optional().nullable(),- enabled: z.boolean().optional().nullable(),- executionConditions: ExecutionConditionsSchema.nullable(),- groupId: z.string().optional().nullable(),- id: z.string().optional(),- maxExecutions: z.number().min(1).max(10_000).optional().nullable(),- name: z.string().optional().nullable(),- remainingExecutions: z.number().optional().nullable(),- timezone: z.string().optional().nullable(),- userId: z.string().optional(),-});--// Update schema (all fields optional)-export const UpdateAgentCronJobSchema = InsertAgentCronJobSchema.partial();--// Type exports-export type InsertAgentCronJob = z.infer<typeof InsertAgentCronJobSchema>;-export type UpdateAgentCronJob = z.infer<typeof UpdateAgentCronJobSchema>;diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 9ed57ff3d72..f50051a4100 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -1,5 +1,4 @@export * from './agent';-export * from './agentCronJob';export * from './agentExecution';export * from './agentGroup';export * from './aiChat';diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex d6b2ac55032..e426297e496 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -77,9 +77,6 @@ export interface OnboardingSessionSnapshot {export interface ChatTopicMetadata {bot?: ChatTopicBotContext;boundDeviceId?: string;- /**- * Cron job ID that triggered this topic creation (if created by scheduled task)- */cronJobId?: string;/*** Scoped pointer to the currently active assistant message for a runningdiff --git a/src/hooks/useFetchCronTopics.ts b/src/hooks/useFetchCronTopics.tsdeleted file mode 100644index 02e5c4b76e8..00000000000--- a/src/hooks/useFetchCronTopics.ts+++ /dev/null@@ -1,29 +0,0 @@-import useSWR from 'swr';--import { lambdaClient } from '@/libs/trpc/client/lambda';-import { useAgentStore } from '@/store/agent';--/**- * Fetch cron topics grouped by cronJob for the current agent- */-export const useFetchCronTopics = () => {- const agentId = useAgentStore((s) => s.activeAgentId);-- const { data, isLoading, error, mutate } = useSWR(- agentId ? ['cronTopics', agentId] : null,- async () => {- if (!agentId) return [];- return await lambdaClient.topic.getCronTopicsGroupedByCronJob.query({ agentId });- },- {- revalidateOnFocus: false,- },- );-- return {- cronTopicsGroups: data || [],- error,- isLoading,- mutate,- };-};diff --git a/src/routes/(main)/agent/_layout/Sidebar/Body.tsx b/src/routes/(main)/agent/_layout/Sidebar/Body.tsxindex 5ef6499f78e..d627c6ea2ed 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Body.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Body.tsx@@ -1,12 +1,10 @@import { Accordion, Flexbox } from '@lobehub/ui';import React, { memo } from 'react';-import CronTopicList from './Cron';import TaskList from './Task';import Topic from './Topic';export enum ChatSidebarKey {- CronTopics = 'cronTopics',Tasks = 'tasks',Topic = 'topic',}@@ -16,7 +14,6 @@ const Body = memo(() => {<Flexbox paddingInline={4}><Accordion defaultExpandedKeys={[ChatSidebarKey.Topic]} gap={8}><TaskList itemKey={ChatSidebarKey.Tasks} />- <CronTopicList itemKey={ChatSidebarKey.CronTopics} /><Topic itemKey={ChatSidebarKey.Topic} /></Accordion></Flexbox>diff --git a/src/routes/(main)/agent/_layout/Sidebar/Cron/Actions.tsx b/src/routes/(main)/agent/_layout/Sidebar/Cron/Actions.tsxdeleted file mode 100644index 38b4ceb6189..00000000000--- a/src/routes/(main)/agent/_layout/Sidebar/Cron/Actions.tsx+++ /dev/null@@ -1,22 +0,0 @@-import { ActionIcon, DropdownMenu } from '@lobehub/ui';-import { MoreHorizontal } from 'lucide-react';-import { memo } from 'react';--import { useCronJobDropdownMenu } from './useDropdownMenu';--interface ActionsProps {- cronJobId: string;- topics: Array<{ id: string }>;-}--const Actions = memo<ActionsProps>(({ cronJobId, topics }) => {- const menuItems = useCronJobDropdownMenu(cronJobId, topics);-- return (- <DropdownMenu items={menuItems}>- <ActionIcon icon={MoreHorizontal} size={'small'} />- </DropdownMenu>- );-});--export default Actions;diff --git a/src/routes/(main)/agent/_layout/Sidebar/Cron/CronTopicGroup.tsx b/src/routes/(main)/agent/_layout/Sidebar/Cron/CronTopicGroup.tsxdeleted file mode 100644index f33277c1845..00000000000--- a/src/routes/(main)/agent/_layout/Sidebar/Cron/CronTopicGroup.tsx+++ /dev/null@@ -1,88 +0,0 @@-'use client';--import { AccordionItem, ActionIcon, Flexbox, Icon, Text } from '@lobehub/ui';-import { Settings2Icon, TimerIcon, TimerOffIcon } from 'lucide-react';-import { memo, useCallback } from 'react';-import { useTranslation } from 'react-i18next';-import { useParams } from 'react-router-dom';--import { type AgentCronJob } from '@/database/schemas/agentCronJob';-import { useRouter } from '@/libs/router/navigation';--import Actions from './Actions';-import CronTopicItem from './CronTopicItem';--interface CronTopicGroupProps {- cronJob: AgentCronJob | null;- cronJobId: string;- topics: Array<{- createdAt: Date | string;- favorite?: boolean | null;- historySummary?: string | null;- id: string;- metadata?: any;- title?: string | null;- trigger?: string | null;- updatedAt: Date | string;- }>;-}--const CronTopicGroup = memo<CronTopicGroupProps>(({ cronJob, cronJobId, topics }) => {- const { t } = useTranslation('setting');- const { aid, cronId } = useParams<{ aid?: string; cronId?: string }>();- const router = useRouter();-- const handleOpenCronJob = useCallback(() => {- if (!aid) return;- router.push(`/agent/${aid}/cron/${cronJobId}`);- }, [aid, cronJobId, router]);-- const cronJobName = cronJob?.name || t('agentCronJobs.unnamedTask');- const isEnabled = cronJob?.enabled ?? false;- const isActive = cronId === cronJobId;-- return (- <AccordionItem- itemKey={cronJobId}- paddingBlock={4}- paddingInline={'8px 4px'}- variant={isActive ? 'filled' : 'borderless'}- action={- <Flexbox horizontal align="center" gap={4}>- <ActionIcon- icon={Settings2Icon}- size="small"- title={t('agentCronJobs.editJob')}- onClick={handleOpenCronJob}- />- <Actions cronJobId={cronJobId} topics={topics} />- </Flexbox>- }- title={- <Flexbox horizontal align="center" gap={6} height={24} style={{ overflow: 'hidden' }}>- <Icon icon={isEnabled ? TimerIcon : TimerOffIcon} style={{ opacity: 0.5 }} />- <Text ellipsis style={{ flex: 1 }} type={isActive ? undefined : 'secondary'}>- {cronJobName}- </Text>- {topics.length > 0 && (- <Text fontSize={11} type="secondary">- {topics.length}- </Text>- )}- </Flexbox>- }- >- <Flexbox gap={1} paddingBlock={1}>- {topics.length > 0 ? (- topics.map((topic) => <CronTopicItem key={topic.id} topic={topic} />)- ) : (- <Text fontSize={12} style={{ padding: '8px 12px' }} type="secondary">- {t('agentCronJobs.noExecutionResults')}- </Text>- )}- </Flexbox>- </AccordionItem>- );-});--export default CronTopicGroup;diff --git a/src/routes/(main)/agent/_layout/Sidebar/Cron/CronTopicItem.tsx b/src/routes/(main)/agent/_layout/Sidebar/Cron/CronTopicItem.tsxdeleted file mode 100644index 2638d49b50a..00000000000--- a/src/routes/(main)/agent/_layout/Sidebar/Cron/CronTopicItem.tsx+++ /dev/null@@ -1,40 +0,0 @@-'use client';--import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { useChatStore } from '@/store/chat';--import TopicItem from '../Topic/List/Item';--interface CronTopicItemProps {- topic: {- createdAt: Date | string;- favorite?: boolean | null;- historySummary?: string | null;- id: string;- metadata?: any;- title?: string | null;- trigger?: string | null;- updatedAt: Date | string;- };-}--const CronTopicItem = memo<CronTopicItemProps>(({ topic }) => {- const { t } = useTranslation('topic');- const [activeTopicId, activeThreadId] = useChatStore((s) => [s.activeTopicId, s.activeThreadId]);-- const displayTitle = topic.title || topic.historySummary || t('defaultTitle');-- return (- <TopicItem- active={activeTopicId === topic.id}- fav={!!topic.favorite}- id={topic.id}- threadId={activeThreadId}- title={displayTitle}- />- );-});--export default CronTopicItem;diff --git a/src/routes/(main)/agent/_layout/Sidebar/Cron/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Cron/index.tsxdeleted file mode 100644index 16a013f13a2..00000000000--- a/src/routes/(main)/agent/_layout/Sidebar/Cron/index.tsx+++ /dev/null@@ -1,130 +0,0 @@-'use client';--import { Accordion, AccordionItem, ActionIcon, Flexbox, Text } from '@lobehub/ui';-import { Plus } from 'lucide-react';-import { memo, useCallback } from 'react';-import { useTranslation } from 'react-i18next';-import urlJoin from 'url-join';--import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';-import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';-import SkeletonList from '@/features/NavPanel/components/SkeletonList';-import { useQueryRoute } from '@/hooks/useQueryRoute';-import { useAgentStore } from '@/store/agent';-import { agentSelectors } from '@/store/agent/selectors';-import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';--import CronTopicGroup from './CronTopicGroup';--interface CronTopicListProps {- itemKey: string;-}--const CronTopicList = memo<CronTopicListProps>(({ itemKey }) => {- const { t } = useTranslation('setting');- const router = useQueryRoute();- const [agentId, useFetchCronTopicsWithJobInfo] = useAgentStore((s) => [- s.activeAgentId,- s.useFetchCronTopicsWithJobInfo,- ]);- const isHeterogeneous = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);- const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);- const { data: cronTopicsGroupsWithJobInfo = [], isLoading } = useFetchCronTopicsWithJobInfo(- agentId,- enableBusinessFeatures && !isHeterogeneous,- );-- const handleCreateCronJob = useCallback(() => {- if (!agentId) return;- router.push(urlJoin('/agent', agentId, 'cron', 'new'));- }, [agentId, router]);-- if (!enableBusinessFeatures || isHeterogeneous) return null;-- const addAction = (- <ActionIcon- disabled={!agentId}- icon={Plus}- size={'small'}- title={t('agentCronJobs.addJob')}- onClick={handleCreateCronJob}- />- );-- if (isLoading) {- return (- <AccordionItem- action={addAction}- itemKey={itemKey}- paddingBlock={4}- paddingInline={'8px 4px'}- title={- <Flexbox horizontal align="center" gap={4}>- <Text ellipsis fontSize={12} type={'secondary'} weight={500}>- {t('agentCronJobs.title')}- </Text>- <NeuralNetworkLoading size={14} />- </Flexbox>- }- >- <SkeletonList />- </AccordionItem>- );- }-- if (cronTopicsGroupsWithJobInfo.length === 0) {- return (- <AccordionItem- action={addAction}- itemKey={itemKey}- paddingBlock={4}- paddingInline={'8px 4px'}- title={- <Flexbox horizontal align="center" gap={4}>- <Text ellipsis fontSize={12} type={'secondary'} weight={500}>- {t('agentCronJobs.title')}- </Text>- </Flexbox>- }- >- <EmptyNavItem title={t('agentCronJobs.addJob')} onClick={handleCreateCronJob} />- </AccordionItem>- );- }-- const totalCronJobs = cronTopicsGroupsWithJobInfo.length;-- return (- <AccordionItem- action={addAction}- itemKey={itemKey}- paddingBlock={4}- paddingInline={'8px 4px'}- title={- <Flexbox horizontal align="center" gap={4}>- <Text ellipsis fontSize={12} type={'secondary'} weight={500}>- {t('agentCronJobs.title')}- </Text>- {totalCronJobs > 0 && (- <Text fontSize={11} type="secondary">- {totalCronJobs}- </Text>- )}- </Flexbox>- }- >- <Accordion defaultExpandedKeys={cronTopicsGroupsWithJobInfo.map((g) => g.cronJobId)} gap={2}>- {cronTopicsGroupsWithJobInfo.map((group) => (- <CronTopicGroup- cronJob={group.cronJob}- cronJobId={group.cronJobId}- key={group.cronJobId}- topics={group.topics}- />- ))}- </Accordion>- </AccordionItem>- );-});--export default CronTopicList;diff --git a/src/routes/(main)/agent/_layout/Sidebar/Cron/useDropdownMenu.tsx b/src/routes/(main)/agent/_layout/Sidebar/Cron/useDropdownMenu.tsxdeleted file mode 100644index 707194ca949..00000000000--- a/src/routes/(main)/agent/_layout/Sidebar/Cron/useDropdownMenu.tsx+++ /dev/null@@ -1,106 +0,0 @@-import { type MenuProps } from '@lobehub/ui';-import { Icon } from '@lobehub/ui';-import { App } from 'antd';-import { Trash } from 'lucide-react';-import { useCallback, useMemo } from 'react';-import { useTranslation } from 'react-i18next';--import { agentCronJobService } from '@/services/agentCronJob';-import { topicService } from '@/services/topic';-import { useAgentStore } from '@/store/agent';--export const useCronJobDropdownMenu = (- cronJobId: string,- topics: Array<{ id: string }>,-): MenuProps['items'] => {- const { t } = useTranslation(['setting', 'common']);- const { modal } = App.useApp();-- const refreshCronTopics = useAgentStore((s) => s.internal_refreshCronTopics);-- const handleDeleteCronJob = useCallback(async () => {- try {- // Delete all topics associated with this cron job- if (topics.length > 0) {- const topicIds = topics.map((t) => t.id);- await topicService.batchRemoveTopics(topicIds);- }-- // Delete the cron job- await agentCronJobService.delete(cronJobId);-- // Refresh the cron topics list- await refreshCronTopics();- } catch (error) {- console.error('Failed to delete cron job:', error);- modal.error({- content: t('agentCronJobs.deleteFailed' as any),- title: t('error' as any, { ns: 'common' }),- });- }- }, [cronJobId, topics, refreshCronTopics, modal, t]);-- const handleClearTopics = useCallback(async () => {- if (topics.length === 0) return;-- try {- const topicIds = topics.map((t) => t.id);- await topicService.batchRemoveTopics(topicIds);-- // Refresh the cron topics list- await refreshCronTopics();- } catch (error) {- console.error('Failed to clear topics:', error);- modal.error({- content: t('agentCronJobs.clearTopicsFailed' as any),- title: t('error' as any, { ns: 'common' }),- });- }- }, [topics, refreshCronTopics, modal, t]);-- return useMemo(- () =>- [- {- icon: <Icon icon={Trash} />,- key: 'clearTopics',- label: t('agentCronJobs.clearTopics' as any),- onClick: () => {- modal.confirm({- cancelText: t('cancel', { ns: 'common' }),- centered: true,- content: t(- 'agentCronJobs.confirmClearTopics' as any,- { count: topics.length } as any,- ),- okButtonProps: { danger: true },- okText: t('ok', { ns: 'common' }),- onOk: handleClearTopics,- title: t('agentCronJobs.clearTopics' as any),- });- },- },- {- type: 'divider' as const,- },- {- danger: true,- icon: <Icon icon={Trash} />,- key: 'deleteCronJob',- label: t('agentCronJobs.deleteCronJob' as any),- onClick: () => {- modal.confirm({- cancelText: t('cancel', { ns: 'common' }),- centered: true,- content: t('agentCronJobs.confirmDeleteCronJob' as any),- okButtonProps: { danger: true },- okText: t('ok', { ns: 'common' }),- onOk: handleDeleteCronJob,- title: t('agentCronJobs.deleteCronJob' as any),- });- },- },- ].filter(Boolean) as MenuProps['items'],- [topics.length, handleClearTopics, handleDeleteCronJob, t, modal],- );-};diff --git a/src/routes/(main)/agent/cron/[cronId]/CronConfig.ts b/src/routes/(main)/agent/cron/[cronId]/CronConfig.tsdeleted file mode 100644index 04690c15285..00000000000--- a/src/routes/(main)/agent/cron/[cronId]/CronConfig.ts+++ /dev/null@@ -1,78 +0,0 @@-// Schedule type options-export const SCHEDULE_TYPE_OPTIONS = [- { label: 'agentCronJobs.scheduleType.daily', value: 'daily' },- { label: 'agentCronJobs.scheduleType.hourly', value: 'hourly' },- { label: 'agentCronJobs.scheduleType.weekly', value: 'weekly' },-] as const;--// Timezone options - covering major cities worldwide-export const TIMEZONE_OPTIONS = [- { label: 'UTC', value: 'UTC' },-- // Americas- { label: 'America/New_York (EST/EDT, UTC-5/-4)', value: 'America/New_York' },- { label: 'America/Chicago (CST/CDT, UTC-6/-5)', value: 'America/Chicago' },- { label: 'America/Denver (MST/MDT, UTC-7/-6)', value: 'America/Denver' },- { label: 'America/Los_Angeles (PST/PDT, UTC-8/-7)', value: 'America/Los_Angeles' },- { label: 'America/Toronto (EST/EDT, UTC-5/-4)', value: 'America/Toronto' },- { label: 'America/Vancouver (PST/PDT, UTC-8/-7)', value: 'America/Vancouver' },- { label: 'America/Mexico_City (CST, UTC-6)', value: 'America/Mexico_City' },- { label: 'America/Sao_Paulo (BRT, UTC-3)', value: 'America/Sao_Paulo' },- { label: 'America/Buenos_Aires (ART, UTC-3)', value: 'America/Buenos_Aires' },-- // Europe- { label: 'Europe/London (GMT/BST, UTC+0/+1)', value: 'Europe/London' },- { label: 'Europe/Paris (CET/CEST, UTC+1/+2)', value: 'Europe/Paris' },- { label: 'Europe/Berlin (CET/CEST, UTC+1/+2)', value: 'Europe/Berlin' },- { label: 'Europe/Madrid (CET/CEST, UTC+1/+2)', value: 'Europe/Madrid' },- { label: 'Europe/Rome (CET/CEST, UTC+1/+2)', value: 'Europe/Rome' },- { label: 'Europe/Amsterdam (CET/CEST, UTC+1/+2)', value: 'Europe/Amsterdam' },- { label: 'Europe/Brussels (CET/CEST, UTC+1/+2)', value: 'Europe/Brussels' },- { label: 'Europe/Moscow (MSK, UTC+3)', value: 'Europe/Moscow' },- { label: 'Europe/Istanbul (TRT, UTC+3)', value: 'Europe/Istanbul' },-- // Asia- { label: 'Asia/Dubai (GST, UTC+4)', value: 'Asia/Dubai' },- { label: 'Asia/Kolkata (IST, UTC+5:30)', value: 'Asia/Kolkata' },- { label: 'Asia/Shanghai (CST, UTC+8)', value: 'Asia/Shanghai' },- { label: 'Asia/Hong_Kong (HKT, UTC+8)', value: 'Asia/Hong_Kong' },- { label: 'Asia/Taipei (CST, UTC+8)', value: 'Asia/Taipei' },- { label: 'Asia/Singapore (SGT, UTC+8)', value: 'Asia/Singapore' },- { label: 'Asia/Tokyo (JST, UTC+9)', value: 'Asia/Tokyo' },- { label: 'Asia/Seoul (KST, UTC+9)', value: 'Asia/Seoul' },- { label: 'Asia/Bangkok (ICT, UTC+7)', value: 'Asia/Bangkok' },- { label: 'Asia/Jakarta (WIB, UTC+7)', value: 'Asia/Jakarta' },-- // Oceania- { label: 'Australia/Sydney (AEDT/AEST, UTC+11/+10)', value: 'Australia/Sydney' },- { label: 'Australia/Melbourne (AEDT/AEST, UTC+11/+10)', value: 'Australia/Melbourne' },- { label: 'Australia/Brisbane (AEST, UTC+10)', value: 'Australia/Brisbane' },- { label: 'Australia/Perth (AWST, UTC+8)', value: 'Australia/Perth' },- { label: 'Pacific/Auckland (NZDT/NZST, UTC+13/+12)', value: 'Pacific/Auckland' },-- // Africa & Middle East- { label: 'Africa/Cairo (EET, UTC+2)', value: 'Africa/Cairo' },- { label: 'Africa/Johannesburg (SAST, UTC+2)', value: 'Africa/Johannesburg' },-];--// Weekday options for checkbox group-export const WEEKDAY_OPTIONS = [- { label: 'agentCronJobs.weekday.short.monday', value: 1 },- { label: 'agentCronJobs.weekday.short.tuesday', value: 2 },- { label: 'agentCronJobs.weekday.short.wednesday', value: 3 },- { label: 'agentCronJobs.weekday.short.thursday', value: 4 },- { label: 'agentCronJobs.weekday.short.friday', value: 5 },- { label: 'agentCronJobs.weekday.short.saturday', value: 6 },- { label: 'agentCronJobs.weekday.short.sunday', value: 0 },-] as const;--// Weekday labels for display (i18n keys)-export const WEEKDAY_LABELS: Record<number, string> = {- 0: 'agentCronJobs.weekday.sunday',- 1: 'agentCronJobs.weekday.monday',- 2: 'agentCronJobs.weekday.tuesday',- 3: 'agentCronJobs.weekday.wednesday',- 4: 'agentCronJobs.weekday.thursday',- 5: 'agentCronJobs.weekday.friday',- 6: 'agentCronJobs.weekday.saturday',-};diff --git a/src/routes/(main)/agent/cron/[cronId]/features/CronJobContentEditor.tsx b/src/routes/(main)/agent/cron/[cronId]/features/CronJobContentEditor.tsxdeleted file mode 100644index f301d90149f..00000000000--- a/src/routes/(main)/agent/cron/[cronId]/features/CronJobContentEditor.tsx+++ /dev/null@@ -1,106 +0,0 @@-'use client';--import {- ReactCodemirrorPlugin,- ReactCodePlugin,- ReactHRPlugin,- ReactLinkPlugin,- ReactListPlugin,- ReactMathPlugin,- ReactTablePlugin,-} from '@lobehub/editor';-import { Editor, useEditor } from '@lobehub/editor/react';-import { FormGroup } from '@lobehub/ui';-import { createStaticStyles } from 'antd-style';-import { memo, useCallback, useEffect, useRef } from 'react';-import { useTranslation } from 'react-i18next';--const styles = createStaticStyles(({ css }) => ({- editorWrapper: css`- min-height: 200px;- padding-block: 8px;- padding-inline: 0;- `,-}));--interface CronJobContentEditorProps {- enableRichRender: boolean;- initialValue: string;- onChange: (value: string) => void;-}--const CronJobContentEditor = memo<CronJobContentEditorProps>(- ({ enableRichRender, initialValue, onChange }) => {- const { t } = useTranslation('setting');- const editor = useEditor();- const currentValueRef = useRef(initialValue);-- useEffect(() => {- currentValueRef.current = initialValue;- }, [initialValue]);-- useEffect(() => {- if (!editor) return;- try {- setTimeout(() => {- if (initialValue) {- editor.setDocument(enableRichRender ? 'markdown' : 'text', initialValue);- }- }, 100);- } catch (error) {- console.error('[CronJobContentEditor] Failed to initialize editor content:', error);- setTimeout(() => {- editor.setDocument(enableRichRender ? 'markdown' : 'text', initialValue);- }, 100);- }- }, [editor, enableRichRender, initialValue]);-- const handleContentChange = useCallback(- (e: any) => {- const nextContent = enableRichRender- ? (e.getDocument('markdown') as unknown as string)- : (e.getDocument('text') as unknown as string);-- const finalContent = nextContent || '';-- if (finalContent !== currentValueRef.current) {- currentValueRef.current = finalContent;- onChange(finalContent);- }- },- [enableRichRender, onChange],- );-- return (- <FormGroup title={t('agentCronJobs.content')} variant="filled">- <div className={styles.editorWrapper}>- <Editor- content={''}- editor={editor}- lineEmptyPlaceholder={t('agentCronJobs.form.content.placeholder')}- placeholder={t('agentCronJobs.form.content.placeholder')}- style={{ paddingBottom: 48 }}- type={'text'}- variant={'chat'}- plugins={- enableRichRender- ? [- ReactListPlugin,- ReactCodePlugin,- ReactCodemirrorPlugin,- ReactHRPlugin,- ReactLinkPlugin,- ReactTablePlugin,- ReactMathPlugin,- ]- : undefined- }- onTextChange={handleContentChange}- />- </div>- </FormGroup>- );- },-);--export default CronJobContentEditor;diff --git a/src/routes/(main)/agent/cron/[cronId]/features/CronJobHeader.tsx b/src/routes/(main)/agent/cron/[cronId]/features/CronJobHeader.tsxdeleted file mode 100644index 4f29914a7e8..00000000000--- a/src/routes/(main)/agent/cron/[cronId]/features/CronJobHeader.tsx+++ /dev/null@@ -1,58 +0,0 @@-'use client';--import { Flexbox, Input } from '@lobehub/ui';-import { Switch } from '@lobehub/ui/base-ui';-import { createStaticStyles } from 'antd-style';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--const styles = createStaticStyles(({ css }) => ({- titleInput: css`- flex: 1;- font-size: 28px;- font-weight: 500;- line-height: 1.4;- `,-}));--interface CronJobHeaderProps {- enabled?: boolean;- isNewJob?: boolean;- isTogglingEnabled?: boolean;- name: string;- onNameChange: (name: string) => void;- onToggleEnabled?: (enabled: boolean) => void;-}--const CronJobHeader = memo<CronJobHeaderProps>(- ({ enabled, isNewJob, isTogglingEnabled, name, onNameChange, onToggleEnabled }) => {- const { t } = useTranslation(['setting', 'common']);-- return (- <Flexbox- horizontal- align="center"- gap={16}- justify="space-between"- style={{ marginBottom: 8 }}- >- <Input- className={styles.titleInput}- placeholder={t('agentCronJobs.form.name.placeholder')}- value={name}- variant="borderless"- onChange={(e) => onNameChange(e.target.value)}- />- {!isNewJob && (- <Switch- checked={enabled ?? false}- loading={isTogglingEnabled}- onChange={onToggleEnabled}- />- )}- </Flexbox>- );- },-);--export default CronJobHeader;diff --git a/src/routes/(main)/agent/cron/[cronId]/features/CronJobSaveButton.tsx b/src/routes/(main)/agent/cron/[cronId]/features/CronJobSaveButton.tsxdeleted file mode 100644index a0499ff5596..00000000000--- a/src/routes/(main)/agent/cron/[cronId]/features/CronJobSaveButton.tsx+++ /dev/null@@ -1,33 +0,0 @@-'use client';--import { Button, Flexbox } from '@lobehub/ui';-import { Save } from 'lucide-react';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--interface CronJobSaveButtonProps {- disabled?: boolean;- loading?: boolean;- onSave: () => void;-}--const CronJobSaveButton = memo<CronJobSaveButtonProps>(({ disabled, loading, onSave }) => {- const { t } = useTranslation('setting');-- return (- <Flexbox paddingBlock={8}>- <Button- disabled={disabled}- icon={Save}- loading={loading}- style={{ maxWidth: 200, width: '100%' }}- type="primary"- onClick={onSave}- >- {t('agentCronJobs.saveAsNew')}- </Button>- </Flexbox>- );-});--export default CronJobSaveButton;diff --git a/src/routes/(main)/agent/cron/[cronId]/features/CronJobScheduleConfig.tsx b/src/routes/(main)/agent/cron/[cronId]/features/CronJobScheduleConfig.tsxdeleted file mode 100644index dd24de07da8..00000000000--- a/src/routes/(main)/agent/cron/[cronId]/features/CronJobScheduleConfig.tsx+++ /dev/null@@ -1,255 +0,0 @@-'use client';--import { type ScheduleType } from '@lobechat/utils/cron';-import { Checkbox, Flexbox, FormGroup, Text } from '@lobehub/ui';-import { Select } from '@lobehub/ui/base-ui';-import { Divider, InputNumber, TimePicker } from 'antd';-import { createStaticStyles, cx } from 'antd-style';-import { type Dayjs } from 'dayjs';-import dayjs from 'dayjs';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { SCHEDULE_TYPE_OPTIONS, TIMEZONE_OPTIONS } from '../CronConfig';--const styles = createStaticStyles(({ css, cssVar }) => ({- label: css`- flex-shrink: 0;- width: 120px;- `,- row: css`- min-height: 48px;- padding-block: 12px;- padding-inline: 0;- `,- weekdayButton: css`- cursor: pointer;-- display: flex;- align-items: center;- justify-content: center;-- width: 40px;- height: 32px;- border: 1px solid ${cssVar.colorBorder};- border-radius: 6px;-- font-size: 12px;- font-weight: 500;- color: ${cssVar.colorTextSecondary};-- background: transparent;-- transition: all 0.15s ease;-- &:hover {- border-color: ${cssVar.colorPrimary};- color: ${cssVar.colorPrimary};- }- `,- weekdayButtonActive: css`- border-color: ${cssVar.colorPrimary};- color: ${cssVar.colorTextLightSolid};- background: ${cssVar.colorPrimary};-- &:hover {- border-color: ${cssVar.colorPrimaryHover};- color: ${cssVar.colorTextLightSolid};- background: ${cssVar.colorPrimaryHover};- }- `,-}));--interface CronJobScheduleConfigProps {- hourlyInterval?: number;- maxExecutions?: number | null;- onScheduleChange: (updates: {- hourlyInterval?: number;- maxExecutions?: number | null;- scheduleType?: ScheduleType;- timezone?: string;- triggerTime?: Dayjs;- weekdays?: number[];- }) => void;- scheduleType: ScheduleType;- timezone: string;- triggerTime: Dayjs;- weekdays: number[];-}--const WEEKDAYS = [- { key: 1, label: 'agentCronJobs.weekdays.mon' },- { key: 2, label: 'agentCronJobs.weekdays.tue' },- { key: 3, label: 'agentCronJobs.weekdays.wed' },- { key: 4, label: 'agentCronJobs.weekdays.thu' },- { key: 5, label: 'agentCronJobs.weekdays.fri' },- { key: 6, label: 'agentCronJobs.weekdays.sat' },- { key: 0, label: 'agentCronJobs.weekdays.sun' },-];--const CronJobScheduleConfig = memo<CronJobScheduleConfigProps>(- ({- hourlyInterval,- maxExecutions,- onScheduleChange,- scheduleType,- timezone,- triggerTime,- weekdays,- }) => {- const { t } = useTranslation('setting');-- const toggleWeekday = (day: number) => {- const newWeekdays = weekdays.includes(day)- ? weekdays.filter((d) => d !== day)- : [...weekdays, day];- onScheduleChange({ weekdays: newWeekdays });- };-- const isUnlimited = maxExecutions === null || maxExecutions === undefined;-- return (- <FormGroup title={t('agentCronJobs.schedule')} variant="filled">- {/* Frequency Row */}- <Flexbox horizontal align="center" className={styles.row} gap={24}>- <Text className={styles.label}>{t('agentCronJobs.form.frequency')}</Text>- <Select- style={{ width: 140 }}- value={scheduleType}- variant="outlined"- options={SCHEDULE_TYPE_OPTIONS.map((opt) => ({- label: t(opt.label as any),- value: opt.value,- }))}- onChange={(value: ScheduleType) =>- onScheduleChange({- scheduleType: value,- weekdays: value === 'weekly' ? [1, 2, 3, 4, 5] : [],- })- }- />- </Flexbox>-- <Divider style={{ margin: 0 }} />-- {/* Time Row (for daily/weekly) */}- {scheduleType !== 'hourly' && (- <>- <Flexbox horizontal align="center" className={styles.row} gap={24}>- <Text className={styles.label}>{t('agentCronJobs.form.time')}</Text>- <TimePicker- format="HH:mm"- minuteStep={15}- style={{ width: 120 }}- value={triggerTime ?? dayjs().hour(9).minute(0)}- onChange={(value) => {- if (value) onScheduleChange({ triggerTime: value });- }}- />- </Flexbox>- <Divider style={{ margin: 0 }} />- </>- )}-- {/* Hourly Interval Row */}- {scheduleType === 'hourly' && (- <>- <Flexbox horizontal align="center" className={styles.row} gap={24}>- <Text className={styles.label}>{t('agentCronJobs.form.every')}</Text>- <Flexbox horizontal align="center" gap={8}>- <InputNumber- max={24}- min={1}- style={{ width: 70 }}- value={hourlyInterval ?? 1}- onChange={(value) => onScheduleChange({ hourlyInterval: value ?? 1 })}- />- <Text type="secondary">{t('agentCronJobs.form.hours')}</Text>- <Text type="secondary">{t('agentCronJobs.form.at')}</Text>- <Select- style={{ width: '80px' }}- value={triggerTime?.minute() ?? 0}- variant="outlined"- options={[- { label: ':00', value: 0 },- { label: ':15', value: 15 },- { label: ':30', value: 30 },- { label: ':45', value: 45 },- ]}- onChange={(value: number) =>- onScheduleChange({ triggerTime: dayjs().hour(0).minute(value) })- }- />- </Flexbox>- </Flexbox>- <Divider style={{ margin: 0 }} />- </>- )}-- {/* Weekday Selector (only for weekly) */}- {scheduleType === 'weekly' && (- <>- <Flexbox horizontal align="center" className={styles.row} gap={24}>- <Text className={styles.label}>{t('agentCronJobs.weekdays')}</Text>- <Flexbox horizontal gap={6}>- {WEEKDAYS.map(({ key, label }) => (- <div- key={key}- className={cx(- styles.weekdayButton,- weekdays.includes(key) && styles.weekdayButtonActive,- )}- onClick={() => toggleWeekday(key)}- >- {t(label as any)}- </div>- ))}- </Flexbox>- </Flexbox>- <Divider style={{ margin: 0 }} />- </>- )}-- {/* Timezone Row */}- <Flexbox horizontal align="center" className={styles.row} gap={24}>- <Text className={styles.label}>{t('agentCronJobs.form.timezone')}</Text>- <Select- showSearch- options={TIMEZONE_OPTIONS}- popupMatchSelectWidth={false}- style={{ minWidth: '200px', width: 'fit-content' }}- value={timezone}- variant="outlined"- onChange={(value: string) => onScheduleChange({ timezone: value })}- />- </Flexbox>-- <Divider style={{ margin: 0 }} />-- {/* Execution Limit Row */}- <Flexbox horizontal align="center" className={styles.row} gap={24}>- <Text className={styles.label}>{t('agentCronJobs.maxExecutions')}</Text>- <Flexbox horizontal align="center" gap={12}>- <InputNumber- disabled={isUnlimited}- min={1}- placeholder="100"- style={{ width: 100 }}- value={maxExecutions ?? undefined}- onChange={(value) => onScheduleChange({ maxExecutions: value })}- />- <Text type="secondary">{t('agentCronJobs.form.times')}</Text>- <Checkbox- checked={isUnlimited}- onChange={(checked) => onScheduleChange({ maxExecutions: checked ? null : 100 })}- >- {t('agentCronJobs.form.unlimited')}- </Checkbox>- </Flexbox>- </Flexbox>- </FormGroup>- );- },-);--export default CronJobScheduleConfig;diff --git a/src/routes/(main)/agent/cron/[cronId]/index.tsx b/src/routes/(main)/agent/cron/[cronId]/index.tsxdeleted file mode 100644index 82738fce31e..00000000000--- a/src/routes/(main)/agent/cron/[cronId]/index.tsx+++ /dev/null@@ -1,526 +0,0 @@-'use client';--import { EDITOR_DEBOUNCE_TIME } from '@lobechat/const';-import { buildCronPattern, parseCronPattern, type ScheduleType } from '@lobechat/utils/cron';-import { ActionIcon, Flexbox } from '@lobehub/ui';-import { useDebounceFn } from 'ahooks';-import { App, Empty, message } from 'antd';-import { type Dayjs } from 'dayjs';-import dayjs from 'dayjs';-import { Trash2 } from 'lucide-react';-import { memo, useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';-import { useTranslation } from 'react-i18next';-import { useParams } from 'react-router-dom';-import useSWR from 'swr';--import AutoSaveHint from '@/components/Editor/AutoSaveHint';-import Loading from '@/components/Loading/BrandTextLoading';-import { type UpdateAgentCronJobData } from '@/database/schemas/agentCronJob';-import NavHeader from '@/features/NavHeader';-import WideScreenContainer from '@/features/WideScreenContainer';-import { useQueryRoute } from '@/hooks/useQueryRoute';-import { mutate } from '@/libs/swr';-import { lambdaClient } from '@/libs/trpc/client/lambda';-import { agentCronJobService } from '@/services/agentCronJob';-import { topicService } from '@/services/topic';-import { useAgentStore } from '@/store/agent';-import { useChatStore } from '@/store/chat';-import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';-import { useUserStore } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';--import CronJobContentEditor from './features/CronJobContentEditor';-import CronJobHeader from './features/CronJobHeader';-import CronJobSaveButton from './features/CronJobSaveButton';-import CronJobScheduleConfig from './features/CronJobScheduleConfig';--interface CronJobDraft {- content: string;- cronPattern: string;- description: string;- hourlyInterval?: number; // For hourly: interval in hours (1, 2, 6, 12)- maxExecutions?: number | null;- name: string;- scheduleType: ScheduleType;- timezone: string;- triggerTime: Dayjs; // Trigger time (HH:mm)- weekdays: number[]; // For weekly: selected days-}--type AutoSaveStatus = 'idle' | 'saving' | 'saved';-interface AutoSaveState {- lastUpdatedTime: Date | null | any;- status: AutoSaveStatus;-}--const autoSaveStore = {- listeners: new Set<() => void>(),- state: { lastUpdatedTime: null, status: 'idle' as AutoSaveStatus },-};--const getAutoSaveState = () => autoSaveStore.state;-const subscribeAutoSave = (listener: () => void) => {- autoSaveStore.listeners.add(listener);- return () => autoSaveStore.listeners.delete(listener);-};-const setAutoSaveState = (patch: Partial<AutoSaveState>) => {- autoSaveStore.state = { ...autoSaveStore.state, ...patch };- autoSaveStore.listeners.forEach((listener) => listener());-};-const useAutoSaveState = () =>- useSyncExternalStore(subscribeAutoSave, getAutoSaveState, getAutoSaveState);--const AutoSaveHintSlot = memo(() => {- const { lastUpdatedTime, status } = useAutoSaveState();- return <AutoSaveHint lastUpdatedTime={lastUpdatedTime} saveStatus={status} />;-});--const resolveDate = (value?: Date | string | null) => {- if (!value) return null;- return typeof value === 'string' ? new Date(value) : value;-};--const CronJobDetailPage = memo(() => {- const { t } = useTranslation(['setting', 'common']);- const { aid, cronId } = useParams<{ aid?: string; cronId?: string }>();- const router = useQueryRoute();- const { modal } = App.useApp();- const enableRichRender = useUserStore(labPreferSelectors.enableInputMarkdown);- const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);-- const isNewJob = cronId === 'new';-- const [draft, setDraft] = useState<CronJobDraft | null>(null);- const [isTogglingEnabled, setIsTogglingEnabled] = useState(false);- const draftRef = useRef<CronJobDraft | null>(null);- const contentRef = useRef('');- const pendingSaveRef = useRef(false);- const initializedIdRef = useRef<string | null>(null);- const readyRef = useRef(false);- const lastSavedNameRef = useRef<string | null>(null);- const lastSavedPayloadRef = useRef<UpdateAgentCronJobData | null>(null);- const lastSavedAtRef = useRef<Date | null>(null);- const previousCronIdRef = useRef<string | null>(null);- const hydratedAtRef = useRef<string | null>(null);- const isDirtyRef = useRef(false);-- const [activeTopicId, refreshTopic, switchTopic] = useChatStore((s) => [- s.activeTopicId,- s.refreshTopic,- s.switchTopic,- ]);-- const [activeAgentId, internal_refreshCronTopics] = useAgentStore((s) => [- s.activeAgentId,- s.internal_refreshCronTopics,- ]);- const cronListAgentId = activeAgentId || aid;-- const { data: cronJob, isLoading } = useSWR(- enableBusinessFeatures && cronId && !isNewJob ? ['cronJob', cronId] : null,- async () => {- if (!cronId || isNewJob) return null;- const result = await agentCronJobService.getById(cronId);- return result.success ? result.data : null;- },- {- dedupingInterval: 0,- revalidateIfStale: true,- revalidateOnFocus: false,- revalidateOnMount: true,- },- );-- const buildUpdateData = useCallback(- (snapshot: CronJobDraft | null, content: string): UpdateAgentCronJobData | null => {- if (!snapshot) return null;- if (!snapshot.content) return null;- if (!snapshot.name) return null;-- // Build cron pattern from schedule configuration- const cronPattern = buildCronPattern(- snapshot.scheduleType,- snapshot.triggerTime,- snapshot.hourlyInterval,- snapshot.weekdays,- );-- return {- content,- cronPattern,- description: snapshot.description?.trim() || null,- executionConditions: null, // No longer using executionConditions for time/weekdays- maxExecutions: snapshot.maxExecutions ?? null,- name: snapshot.name?.trim() || null,- timezone: snapshot.timezone,- };- },- [],- );-- const refreshCronList = useCallback(() => {- if (!cronListAgentId) return;- void mutate(['cronTopicsWithJobInfo', cronListAgentId]);- }, [cronListAgentId]);-- useEffect(() => {- const prevCronId = previousCronIdRef.current;- if (prevCronId && prevCronId !== cronId && lastSavedPayloadRef.current) {- const payload = lastSavedPayloadRef.current;- const updatedAt = lastSavedAtRef.current;- mutate(- ['cronJob', prevCronId],- (current) =>- current- ? {- ...current,- ...payload,- executionConditions: payload.executionConditions ?? null,- ...(updatedAt ? { updatedAt } : null),- }- : current,- false,- );- }-- previousCronIdRef.current = cronId ?? null;- lastSavedPayloadRef.current = null;- lastSavedAtRef.current = null;- hydratedAtRef.current = null;- isDirtyRef.current = false;- }, [cronId]);-- const { run: debouncedSave, cancel: cancelDebouncedSave } = useDebounceFn(- async () => {- if (isNewJob) return; // Don't auto-save new jobs- if (!cronId || initializedIdRef.current !== cronId) return;- const payload = buildUpdateData(draftRef.current, contentRef.current);- if (!payload) return;- if (!payload.content || !payload.name) return;-- try {- await agentCronJobService.update(cronId, payload);- const savedAt = new Date();- lastSavedPayloadRef.current = payload;- lastSavedAtRef.current = savedAt;- isDirtyRef.current = false;- setAutoSaveState({ lastUpdatedTime: savedAt, status: 'saved' });- const nextName = payload.name ?? null;- if (nextName !== lastSavedNameRef.current) {- lastSavedNameRef.current = nextName;- refreshCronList();- }- } catch (error) {- console.error('Failed to update cron job:', error);- setAutoSaveState({ status: 'idle' });- message.error('Failed to update scheduled task');- }- },- { wait: EDITOR_DEBOUNCE_TIME },- );-- useEffect(() => {- cancelDebouncedSave();- pendingSaveRef.current = false;- }, [cancelDebouncedSave, cronId]);-- const scheduleSave = useCallback(() => {- if (isNewJob) return; // Don't auto-save new jobs- if (!readyRef.current || !draftRef.current) {- pendingSaveRef.current = true;- return;- }- isDirtyRef.current = true;- setAutoSaveState({ status: 'saving' });- debouncedSave();- }, [debouncedSave, isNewJob]);-- const flushPendingSave = useCallback(() => {- if (isNewJob) return; // Don't auto-save new jobs- if (!pendingSaveRef.current || !draftRef.current) return;- pendingSaveRef.current = false;- isDirtyRef.current = true;- setAutoSaveState({ status: 'saving' });- debouncedSave();- }, [debouncedSave, isNewJob]);-- const updateDraft = useCallback(- (patch: Partial<CronJobDraft>) => {- setDraft((prev) => {- if (!prev) return prev;- const next = { ...prev, ...patch };- draftRef.current = next;- return next;- });- scheduleSave();- },- [scheduleSave],- );-- const handleContentChange = useCallback(- (content: string) => {- contentRef.current = content;- updateDraft({ content });- },- [updateDraft],- );-- const handleToggleEnabled = useCallback(- async (enabled: boolean) => {- if (!cronId) return;- setIsTogglingEnabled(true);- setAutoSaveState({ status: 'saving' });- try {- await agentCronJobService.update(cronId, { enabled });- await mutate(- ['cronJob', cronId],- (current) => (current ? { ...current, enabled } : current),- false,- );- await internal_refreshCronTopics();- setAutoSaveState({ lastUpdatedTime: new Date(), status: 'saved' });- } catch (error) {- console.error('Failed to update cron job status:', error);- setAutoSaveState({ status: 'idle' });- message.error('Failed to update scheduled task');- } finally {- setIsTogglingEnabled(false);- }- },- [cronId, internal_refreshCronTopics],- );-- const handleDeleteCronJob = useCallback(async () => {- if (!cronId) return;-- modal.confirm({- cancelText: t('cancel', { ns: 'common' }),- centered: true,- content: t('agentCronJobs.confirmDeleteCronJob' as any),- okButtonProps: { danger: true },- okText: t('ok', { ns: 'common' }),- onOk: async () => {- try {- let topicIds: string[] = [];- if (aid) {- const groups = await lambdaClient.topic.getCronTopicsGroupedByCronJob.query({- agentId: aid,- });- const group = groups.find((item) => item.cronJobId === cronId);- topicIds = group?.topics.map((topic) => topic.id) || [];- }-- await agentCronJobService.delete(cronId);-- if (topicIds.length > 0) {- await topicService.batchRemoveTopics(topicIds);- await refreshTopic();- if (activeTopicId && topicIds.includes(activeTopicId)) {- switchTopic();- }- }-- if (cronListAgentId) {- await mutate(['cronTopicsWithJobInfo', cronListAgentId]);- router.push(`/agent/${cronListAgentId}`);- } else {- router.push('/');- }- } catch (error) {- console.error('Failed to delete cron job:', error);- message.error('Failed to delete scheduled task');- }- },- title: t('agentCronJobs.deleteCronJob' as any),- });- }, [activeTopicId, cronId, cronListAgentId, modal, refreshTopic, router, switchTopic, t]);-- const handleSaveNewJob = useCallback(async () => {- if (!aid) {- message.error('Agent ID is required');- return;- }-- const payload = buildUpdateData(draftRef.current, contentRef.current);- if (!payload) {- message.error('Please fill in all required fields');- return;- }-- if (!payload.content || !payload.name || !payload.cronPattern) {- message.error('Name and content are required');- return;- }-- setAutoSaveState({ status: 'saving' });- try {- const result = await agentCronJobService.create({- agentId: aid,- content: payload.content,- cronPattern: payload.cronPattern,- description: payload.description,- enabled: true,- executionConditions: payload.executionConditions,- maxExecutions: payload.maxExecutions,- name: payload.name,- timezone: payload.timezone,- });-- if (result.success && result.data) {- setAutoSaveState({ lastUpdatedTime: new Date(), status: 'saved' });- message.success('Scheduled task created successfully');- refreshCronList();- // Navigate to the newly created job- router.push(`/agent/${aid}/cron/${result.data.id}`);- } else {- throw new Error('Failed to create job');- }- } catch (error) {- console.error('Failed to create cron job:', error);- setAutoSaveState({ status: 'idle' });- message.error('Failed to create scheduled task');- }- }, [aid, buildUpdateData, refreshCronList, router]);-- // Initialize draft for new jobs- useEffect(() => {- if (!isNewJob || draft) return;-- // Get browser timezone- const browserTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;-- const defaultDraft: CronJobDraft = {- content: '',- cronPattern: '0 0 * * *', // Default: daily at midnight- description: '',- maxExecutions: null,- name: '',- scheduleType: 'daily',- timezone: browserTimezone,- triggerTime: dayjs().hour(0).minute(0),- weekdays: [0, 1, 2, 3, 4, 5, 6],- };-- setDraft(defaultDraft);- draftRef.current = defaultDraft;- contentRef.current = '';- readyRef.current = true;- }, [isNewJob, draft]);-- useEffect(() => {- if (!cronJob) return;- const cronUpdatedAt = cronJob.updatedAt ? new Date(cronJob.updatedAt).toISOString() : null;- const shouldHydrate =- initializedIdRef.current !== cronJob.id ||- (cronUpdatedAt !== hydratedAtRef.current && !isDirtyRef.current);-- if (!shouldHydrate) return;- initializedIdRef.current = cronJob.id;- hydratedAtRef.current = cronUpdatedAt;- isDirtyRef.current = false;- readyRef.current = false;- lastSavedNameRef.current = cronJob.name ?? null;-- // Parse cron pattern to extract schedule configuration- const parsed = parseCronPattern(cronJob.cronPattern);-- const nextDraft: CronJobDraft = {- content: cronJob.content || '',- cronPattern: cronJob.cronPattern,- description: cronJob.description || '',- hourlyInterval: parsed.hourlyInterval,- maxExecutions: cronJob.maxExecutions ?? null,- name: cronJob.name || '',- scheduleType: parsed.scheduleType,- timezone: cronJob.timezone || 'UTC',- triggerTime: dayjs().hour(parsed.triggerHour).minute(parsed.triggerMinute),- weekdays:- parsed.scheduleType === 'weekly' && parsed.weekdays- ? parsed.weekdays- : [0, 1, 2, 3, 4, 5, 6], // Default: all days for weekly- };-- setDraft(nextDraft);- draftRef.current = nextDraft;-- contentRef.current = nextDraft.content;-- setAutoSaveState({- lastUpdatedTime: resolveDate(cronJob.updatedAt),- status: 'saved',- });-- readyRef.current = true;- flushPendingSave();- }, [cronJob, flushPendingSave]);-- if (!enableBusinessFeatures) {- return null;- }-- return (- <Flexbox flex={1} height={'100%'}>- <NavHeader- left={!isNewJob ? <AutoSaveHintSlot /> : undefined}- right={- !isNewJob ? (- <ActionIcon- icon={Trash2}- title={t('delete', { ns: 'common' })}- onClick={handleDeleteCronJob}- />- ) : undefined- }- />- <Flexbox flex={1} style={{ overflowY: 'auto' }}>- <WideScreenContainer paddingBlock={16}>- {isLoading && <Loading debugId="CronJobDetailPage" />}- {!isLoading && !cronJob && !isNewJob && (- <Empty- description={t('agentCronJobs.empty.description')}- image={Empty.PRESENTED_IMAGE_SIMPLE}- />- )}- {!isLoading && (cronJob || isNewJob) && draft && (- <Flexbox gap={24}>- <CronJobHeader- enabled={cronJob?.enabled ?? false}- isNewJob={isNewJob}- isTogglingEnabled={isTogglingEnabled}- name={draft.name}- onNameChange={(name) => updateDraft({ name })}- onToggleEnabled={handleToggleEnabled}- />-- <CronJobScheduleConfig- hourlyInterval={draft.hourlyInterval}- maxExecutions={draft.maxExecutions}- scheduleType={draft.scheduleType}- timezone={draft.timezone}- triggerTime={draft.triggerTime}- weekdays={draft.weekdays}- onScheduleChange={(updates) => updateDraft(updates)}- />-- <CronJobContentEditor- enableRichRender={enableRichRender}- initialValue={cronJob?.content || ''}- onChange={handleContentChange}- />-- {isNewJob && (- <CronJobSaveButton- disabled={!draft.name || !draft.content}- loading={false}- onSave={handleSaveNewJob}- />- )}- </Flexbox>- )}- </WideScreenContainer>- </Flexbox>- </Flexbox>- );-});--export default CronJobDetailPage;diff --git a/src/routes/(main)/agent/profile/features/AgentCronJobs/CronJobCards.tsx b/src/routes/(main)/agent/profile/features/AgentCronJobs/CronJobCards.tsxdeleted file mode 100644index caf3d69dd3e..00000000000--- a/src/routes/(main)/agent/profile/features/AgentCronJobs/CronJobCards.tsx+++ /dev/null@@ -1,161 +0,0 @@-'use client';--import { ActionIcon, Flexbox, Icon } from '@lobehub/ui';-import { Badge, Card, Col, Popconfirm, Row, Switch, Typography } from 'antd';-import dayjs from 'dayjs';-import { Calendar, Clock, Edit, Trash2 } from 'lucide-react';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { type AgentCronJob } from '@/database/schemas/agentCronJob';--import { useAgentCronJobs } from './hooks/useAgentCronJobs';--const { Text } = Typography;--interface CronJobCardsProps {- cronJobs: AgentCronJob[];- loading?: boolean;- onDelete: (jobId: string) => void;- onEdit: (jobId: string) => void;-}--const getIntervalText = (cronPattern: string) => {- const intervalMap: Record<string, string> = {- '*/30 * * * *': 'agentCronJobs.interval.30min',- '0 * * * *': 'agentCronJobs.interval.1hour',- '0 */12 * * *': 'agentCronJobs.interval.12hours',- '0 */2 * * *': 'agentCronJobs.interval.2hours',- '0 */6 * * *': 'agentCronJobs.interval.6hours',- '0 0 * * *': 'agentCronJobs.interval.daily',- '0 0 * * 0': 'agentCronJobs.interval.weekly',- };-- return intervalMap[cronPattern] || cronPattern;-};--const getStatusInfo = (job: AgentCronJob) => {- if (!job.enabled) {- return { status: 'default' as const, text: 'agentCronJobs.status.disabled' };- }-- if (job.remainingExecutions === 0) {- return { status: 'error' as const, text: 'agentCronJobs.status.depleted' };- }-- return { status: 'success' as const, text: 'agentCronJobs.status.enabled' };-};--const CronJobCards = memo<CronJobCardsProps>(({ cronJobs, loading, onDelete, onEdit }) => {- const { t } = useTranslation('setting');- const { updateCronJob } = useAgentCronJobs();-- const handleToggleEnabled = async (job: AgentCronJob) => {- await updateCronJob(job.id, { enabled: !job.enabled });- };-- return (- <Row gutter={[12, 12]}>- {cronJobs.map((job) => {- const statusInfo = getStatusInfo(job);- const intervalText = getIntervalText(job.cronPattern);-- return (- <Col key={job.id} lg={8} md={12} xs={24}>- <Card- loading={loading}- size="small"- style={{ height: '100%' }}- extra={- <Flexbox horizontal align="center" gap={4}>- <ActionIcon- icon={Edit}- size="small"- title={t('agentCronJobs.editJob')}- onClick={() => onEdit(job.id)}- />- <Popconfirm- title={t('agentCronJobs.confirmDelete')}- onConfirm={() => onDelete(job.id)}- >- <ActionIcon icon={Trash2} size="small" title={t('agentCronJobs.deleteJob')} />- </Popconfirm>- </Flexbox>- }- styles={{- actions: { marginTop: 0 },- body: { paddingBottom: 12, paddingTop: 8 },- header: { borderBottom: 'none', marginTop: '8px', minHeight: 0, paddingBottom: 0 },- }}- title={- <Flexbox horizontal align="center" justify="space-between">- <Flexbox horizontal align="center" gap={8} style={{ flex: 1 }}>- <span- style={{- fontSize: '13px',- fontWeight: 500,- overflow: 'hidden',- textOverflow: 'ellipsis',- whiteSpace: 'nowrap',- }}- >- {job.name || t('agentCronJobs.unnamedTask')}- </span>- <Badge status={statusInfo.status} />- </Flexbox>- <Switch- checked={job.enabled || false}- size="small"- onChange={() => handleToggleEnabled(job)}- />- </Flexbox>- }- >- <Flexbox gap={8}>- <Text- ellipsis={{ tooltip: job.content }}- style={{- WebkitBoxOrient: 'vertical',- WebkitLineClamp: 2,- color: '#666',- display: '-webkit-box',- fontSize: '12px',- overflow: 'hidden',- }}- >- {job.content}- </Text>-- <Flexbox gap={8}>- <Flexbox horizontal align="center" gap={6}>- <Icon icon={Clock} size={12} />- <Text style={{ fontSize: '11px' }}>{t(intervalText as any)}</Text>- </Flexbox>-- {job.remainingExecutions !== null && (- <Flexbox horizontal align="center" gap={6}>- <Text style={{ fontSize: '11px' }}>- {t('agentCronJobs.remainingExecutions', { count: job.remainingExecutions })}- </Text>- </Flexbox>- )}-- {job.lastExecutedAt && (- <Flexbox horizontal align="center" gap={6}>- <Icon icon={Calendar} size={12} />- <Text style={{ fontSize: '11px' }}>- {dayjs(job.lastExecutedAt).format('MM/DD HH:mm')}- </Text>- </Flexbox>- )}- </Flexbox>- </Flexbox>- </Card>- </Col>- );- })}- </Row>- );-});--export default CronJobCards;diff --git a/src/routes/(main)/agent/profile/features/AgentCronJobs/CronJobForm.tsx b/src/routes/(main)/agent/profile/features/AgentCronJobs/CronJobForm.tsxdeleted file mode 100644index ee210a0df89..00000000000--- a/src/routes/(main)/agent/profile/features/AgentCronJobs/CronJobForm.tsx+++ /dev/null@@ -1,204 +0,0 @@-'use client';--import { Checkbox, Form, Input, InputNumber, Select, TimePicker } from 'antd';-import dayjs from 'dayjs';-import { memo, useEffect } from 'react';-import { useTranslation } from 'react-i18next';--import { type AgentCronJob } from '@/database/schemas/agentCronJob';--// Form data interface - excludes server-managed fields-interface CronJobFormData {- content: string;- cronPattern: string;- enabled?: boolean;- executionConditions?: any;- maxExecutions?: number | null;- name?: string | null;-}--const { TextArea } = Input;--interface CronJobFormProps {- editingJob?: AgentCronJob;- formRef?: any;- onCancel?: () => void;- onSubmit: (data: CronJobFormData) => void;-}--// Standard cron format: minute hour day month weekday-const CRON_PATTERNS = [- { label: 'agentCronJobs.interval.30min', value: '*/30 * * * *' }, // Every 30 minutes- { label: 'agentCronJobs.interval.1hour', value: '0 * * * *' }, // Every hour- { label: 'agentCronJobs.interval.2hours', value: '0 */2 * * *' }, // Every 2 hours- { label: 'agentCronJobs.interval.6hours', value: '0 */6 * * *' }, // Every 6 hours- { label: 'agentCronJobs.interval.12hours', value: '0 */12 * * *' }, // Every 12 hours- { label: 'agentCronJobs.interval.daily', value: '0 0 * * *' }, // Daily at midnight- { label: 'agentCronJobs.interval.weekly', value: '0 0 * * 0' }, // Weekly on Sunday-];--const WEEKDAY_OPTIONS = [- { label: 'Monday', value: 1 },- { label: 'Tuesday', value: 2 },- { label: 'Wednesday', value: 3 },- { label: 'Thursday', value: 4 },- { label: 'Friday', value: 5 },- { label: 'Saturday', value: 6 },- { label: 'Sunday', value: 0 },-];--const CronJobForm = memo<CronJobFormProps>(({ editingJob, formRef, onSubmit }) => {- const { t } = useTranslation('setting');- const [form] = Form.useForm();-- // Expose form instance via ref- if (formRef) {- formRef.current = form;- }-- useEffect(() => {- if (editingJob) {- const conditions = editingJob.executionConditions;- form.setFieldsValue({- content: editingJob.content,- cronPattern: editingJob.cronPattern,- maxExecutions: editingJob.maxExecutions,- maxExecutionsPerDay: conditions?.maxExecutionsPerDay,- name: editingJob.name,- timeRange: conditions?.timeRange- ? [dayjs(conditions.timeRange.start, 'HH:mm'), dayjs(conditions.timeRange.end, 'HH:mm')]- : undefined,- weekdays: conditions?.weekdays || [],- });- } else {- form.resetFields();- }- }, [editingJob, form]);-- const handleSubmit = async (values: any) => {- const executionConditions: any = {};-- if (values.timeRange && values.timeRange.length === 2) {- executionConditions.timeRange = {- end: values.timeRange[1].format('HH:mm'),- start: values.timeRange[0].format('HH:mm'),- };- }-- if (values.weekdays && values.weekdays.length > 0) {- executionConditions.weekdays = values.weekdays;- }-- if (values.maxExecutionsPerDay) {- executionConditions.maxExecutionsPerDay = values.maxExecutionsPerDay;- }-- const data: CronJobFormData = {- content: values.content,- cronPattern: values.cronPattern,- enabled: false,- executionConditions: Object.keys(executionConditions).length > 0 ? executionConditions : null,- maxExecutions: values.maxExecutions || null,- name: values.name,- };-- onSubmit(data);- };-- const validateTimeRange = (_: any, value: any) => {- if (!value || value.length !== 2) {- return Promise.resolve();- }-- const [start, end] = value;- if (start.isAfter(end)) {- return Promise.reject(new Error(t('agentCronJobs.form.validation.invalidTimeRange')));- }-- return Promise.resolve();- };-- return (- <Form- form={form}- layout="vertical"- initialValues={{- cronPattern: '*/30 * * * *', // Default to every 30 minutes- weekdays: [],- }}- onFinish={handleSubmit}- >- <Form.Item- label={t('agentCronJobs.name')}- name="name"- rules={[{ message: t('agentCronJobs.form.validation.nameRequired'), required: true }]}- >- <Input placeholder={t('agentCronJobs.form.name.placeholder')} />- </Form.Item>-- <Form.Item- label={t('agentCronJobs.content')}- name="content"- rules={[{ message: t('agentCronJobs.form.validation.contentRequired'), required: true }]}- >- <TextArea- showCount- maxLength={1000}- placeholder={t('agentCronJobs.form.content.placeholder')}- rows={3}- />- </Form.Item>-- <Form.Item- label={t('agentCronJobs.schedule')}- name="cronPattern"- rules={[{ required: true }]}- >- <Select>- {CRON_PATTERNS.map((pattern) => (- <Select.Option key={pattern.value} value={pattern.value}>- {t(pattern.label as any)}- </Select.Option>- ))}- </Select>- </Form.Item>-- <Form.Item label={t('agentCronJobs.maxExecutions')} name="maxExecutions">- <InputNumber- min={1}- placeholder={t('agentCronJobs.form.maxExecutions.placeholder')}- style={{ width: '100%' }}- />- </Form.Item>-- <Form.Item- label={t('agentCronJobs.timeRange')}- name="timeRange"- rules={[{ validator: validateTimeRange }]}- >- <TimePicker.RangePicker- format="HH:mm"- style={{ width: '100%' }}- placeholder={[- t('agentCronJobs.form.timeRange.start'),- t('agentCronJobs.form.timeRange.end'),- ]}- />- </Form.Item>-- <Form.Item label={t('agentCronJobs.weekdays')} name="weekdays">- <Checkbox.Group options={WEEKDAY_OPTIONS} />- </Form.Item>-- <Form.Item label="Max Executions Per Day" name="maxExecutionsPerDay">- <InputNumber- min={1}- placeholder="Leave empty for no daily limit"- style={{ width: '100%' }}- />- </Form.Item>- </Form>- );-});--export default CronJobForm;diff --git a/src/routes/(main)/agent/profile/features/AgentCronJobs/CronJobList.tsx b/src/routes/(main)/agent/profile/features/AgentCronJobs/CronJobList.tsxdeleted file mode 100644index ffc6948098f..00000000000--- a/src/routes/(main)/agent/profile/features/AgentCronJobs/CronJobList.tsx+++ /dev/null@@ -1,138 +0,0 @@-'use client';--import { ActionIcon, Flexbox, Icon } from '@lobehub/ui';-import { Badge, List, Popconfirm, Switch, Typography } from 'antd';-import dayjs from 'dayjs';-import { Calendar, Clock, Edit, Trash2 } from 'lucide-react';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { type AgentCronJob } from '@/database/schemas/agentCronJob';--import { useAgentCronJobs } from './hooks/useAgentCronJobs';--const { Text, Paragraph } = Typography;--interface CronJobListProps {- cronJobs: AgentCronJob[];- loading?: boolean;- onDelete: (jobId: string) => void;- onEdit: (jobId: string) => void;-}--const getIntervalText = (cronPattern: string) => {- const intervalMap: Record<string, string> = {- '*/30 * * * *': 'agentCronJobs.interval.30min',- '0 * * * *': 'agentCronJobs.interval.1hour',- '0 */12 * * *': 'agentCronJobs.interval.12hours',- '0 */2 * * *': 'agentCronJobs.interval.2hours',- '0 */6 * * *': 'agentCronJobs.interval.6hours',- '0 0 * * *': 'agentCronJobs.interval.daily',- '0 0 * * 0': 'agentCronJobs.interval.weekly',- };-- return intervalMap[cronPattern] || cronPattern;-};--const getStatusInfo = (job: AgentCronJob) => {- if (!job.enabled) {- return { status: 'default' as const, text: 'agentCronJobs.status.disabled' };- }-- if (job.remainingExecutions === 0) {- return { status: 'error' as const, text: 'agentCronJobs.status.depleted' };- }-- return { status: 'success' as const, text: 'agentCronJobs.status.enabled' };-};--const CronJobList = memo<CronJobListProps>(({ cronJobs, loading, onEdit, onDelete }) => {- const { t } = useTranslation('setting');- const { updateCronJob } = useAgentCronJobs();-- const handleToggleEnabled = async (job: AgentCronJob) => {- await updateCronJob(job.id, { enabled: !job.enabled });- };-- return (- <List- dataSource={cronJobs}- loading={loading}- renderItem={(job) => {- const statusInfo = getStatusInfo(job);- const intervalText = getIntervalText(job.cronPattern);-- return (- <List.Item- actions={[- <ActionIcon- icon={Edit}- key="edit"- size="small"- title={t('agentCronJobs.editJob')}- onClick={() => onEdit(job.id)}- />,- <Popconfirm- key="delete"- title={t('agentCronJobs.confirmDelete')}- onConfirm={() => onDelete(job.id)}- >- <ActionIcon icon={Trash2} size="small" title={t('agentCronJobs.deleteJob')} />- </Popconfirm>,- ]}- >- <List.Item.Meta- avatar={- <Switch- checked={job.enabled || false}- size="small"- onChange={() => handleToggleEnabled(job)}- />- }- description={- <Flexbox gap={4}>- <Paragraph- ellipsis={{ rows: 2, tooltip: job.content }}- style={{ color: '#666', fontSize: '12px', margin: 0 }}- >- {job.content}- </Paragraph>-- <Flexbox horizontal gap={8} style={{ marginTop: 4 }}>- <Flexbox horizontal align="center" gap={4}>- <Icon icon={Clock} size={12} />- <Text style={{ fontSize: '11px' }}>{t(intervalText as any)}</Text>- </Flexbox>-- {job.remainingExecutions !== null && (- <Text style={{ fontSize: '11px' }}>- {t('agentCronJobs.remainingExecutions', { count: job.remainingExecutions })}- </Text>- )}-- {job.lastExecutedAt && (- <Flexbox horizontal align="center" gap={4}>- <Icon icon={Calendar} size={12} />- <Text style={{ fontSize: '11px' }}>- {dayjs(job.lastExecutedAt).format('MM/DD HH:mm')}- </Text>- </Flexbox>- )}- </Flexbox>- </Flexbox>- }- title={- <Flexbox horizontal align="center" gap={8}>- <span>{job.name}</span>- <Badge status={statusInfo.status} text={t(statusInfo.text as any)} />- </Flexbox>- }- />- </List.Item>- );- }}- />- );-});--export default CronJobList;diff --git a/src/routes/(main)/agent/profile/features/AgentCronJobs/hooks/useAgentCronJobs.ts b/src/routes/(main)/agent/profile/features/AgentCronJobs/hooks/useAgentCronJobs.tsdeleted file mode 100644index 9cc655efe75..00000000000--- a/src/routes/(main)/agent/profile/features/AgentCronJobs/hooks/useAgentCronJobs.ts+++ /dev/null@@ -1,137 +0,0 @@-import { message } from 'antd';-import { useCallback } from 'react';-import { useTranslation } from 'react-i18next';-import useSWR from 'swr';--import {- type CreateAgentCronJobData,- type UpdateAgentCronJobData,-} from '@/database/schemas/agentCronJob';-import { agentCronJobService } from '@/services/agentCronJob';--export const useAgentCronJobs = (agentId?: string, enabled: boolean = true) => {- const { t } = useTranslation('setting');-- // Fetch cron jobs for the agent- const {- data: cronJobs,- error,- isLoading: loading,- mutate,- } = useSWR(- enabled && agentId ? `/api/agent-cron-jobs/${agentId}` : null,- enabled && agentId ? () => agentCronJobService.getByAgentId(agentId) : null,- {- onError: (error) => {- console.error('Failed to fetch cron jobs:', error);- message.error('Failed to load scheduled tasks');- },- },- );-- // Create a new cron job- const createCronJob = useCallback(- async (data: Omit<CreateAgentCronJobData, 'userId'>) => {- if (!agentId) return;-- try {- const result = await agentCronJobService.create({- ...data,- agentId,- });-- if (result.success) {- message.success(t('agentCronJobs.createSuccess'));- await mutate();- return result.data;- }- } catch (error) {- console.error('Failed to create cron job:', error);- message.error('Failed to create scheduled task');- throw error;- }- },- [agentId, mutate, t],- );-- // Update a cron job- const updateCronJob = useCallback(- async (id: string, data: UpdateAgentCronJobData) => {- try {- const result = await agentCronJobService.update(id, data);-- if (result.success) {- message.success(t('agentCronJobs.updateSuccess'));- await mutate();- return result.data;- }- } catch (error) {- console.error('Failed to update cron job:', error);- message.error('Failed to update scheduled task');- throw error;- }- },- [mutate, t],- );-- // Delete a cron job- const deleteCronJob = useCallback(- async (id: string) => {- try {- const result = await agentCronJobService.delete(id);-- if (result.success) {- message.success(t('agentCronJobs.deleteSuccess'));- await mutate();- }- } catch (error) {- console.error('Failed to delete cron job:', error);- message.error('Failed to delete scheduled task');- throw error;- }- },- [mutate, t],- );-- // Get execution statistics- const getStats = useCallback(async () => {- try {- return await agentCronJobService.getStats();- } catch (error) {- console.error('Failed to get cron job stats:', error);- throw error;- }- }, []);-- // Reset execution counts- const resetExecutions = useCallback(- async (id: string, newMaxExecutions?: number) => {- try {- const result = await agentCronJobService.resetExecutions(id, newMaxExecutions);-- if (result.success) {- message.success('Execution counts reset successfully');- await mutate();- return result.data;- }- } catch (error) {- console.error('Failed to reset executions:', error);- message.error('Failed to reset execution counts');- throw error;- }- },- [mutate],- );-- return {- createCronJob,- cronJobs: cronJobs?.data || [],- deleteCronJob,- error,- getStats,- loading,- refetch: mutate,- resetExecutions,- updateCronJob,- };-};diff --git a/src/routes/(main)/agent/profile/features/AgentCronJobs/index.tsx b/src/routes/(main)/agent/profile/features/AgentCronJobs/index.tsxdeleted file mode 100644index f439a6bab15..00000000000--- a/src/routes/(main)/agent/profile/features/AgentCronJobs/index.tsx+++ /dev/null@@ -1,76 +0,0 @@-'use client';--import { Flexbox } from '@lobehub/ui';-import { Typography } from 'antd';-import { Clock } from 'lucide-react';-import { memo, useCallback } from 'react';-import { useTranslation } from 'react-i18next';-import urlJoin from 'url-join';--import { useQueryRoute } from '@/hooks/useQueryRoute';-import { useAgentStore } from '@/store/agent';-import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';--import CronJobCards from './CronJobCards';-import { useAgentCronJobs } from './hooks/useAgentCronJobs';--const { Title } = Typography;--const AgentCronJobs = memo(() => {- const { t } = useTranslation('setting');- const agentId = useAgentStore((s) => s.activeAgentId);- const router = useQueryRoute();- const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);-- const { cronJobs, loading, deleteCronJob } = useAgentCronJobs(agentId, enableBusinessFeatures);-- // Edit: Navigate to cron job detail page- const handleEdit = useCallback(- (jobId: string) => {- if (!agentId) return;- router.push(urlJoin('/agent', agentId, 'cron', jobId));- },- [agentId, router],- );-- // Delete: Keep the existing delete logic- const handleDelete = useCallback(- async (jobId: string) => {- await deleteCronJob(jobId);- },- [deleteCronJob],- );-- if (!enableBusinessFeatures) return null;-- if (!agentId) {- return null;- }-- const hasCronJobs = cronJobs && cronJobs.length > 0;-- // Only show if there are jobs- if (!hasCronJobs) {- return null;- }-- return (- <Flexbox gap={12} style={{ marginBottom: 16, marginTop: 16 }}>- <Title level={5} style={{ margin: 0 }}>- <Flexbox horizontal align="center" gap={8}>- <Clock size={16} />- {t('agentCronJobs.title')}- </Flexbox>- </Title>-- <CronJobCards- cronJobs={cronJobs}- loading={loading}- onDelete={handleDelete}- onEdit={handleEdit}- />- </Flexbox>- );-});--export default AgentCronJobs;diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsxindex 2ff23779a67..f272f0a713f 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx@@ -10,9 +10,7 @@ import { useTranslation } from 'react-i18next';import ModelSelect from '@/features/ModelSelect';import { useAgentStore } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';-import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';-import AgentCronJobs from '../AgentCronJobs';import AgentSettings from '../AgentSettings';import EditorCanvas from '../EditorCanvas';import AgentHeader from './AgentHeader';@@ -25,7 +23,6 @@ const ProfileEditor = memo(() => {const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);const updateConfig = useAgentStore((s) => s.updateAgentConfig);const isHeterogeneous = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);- const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);const heterogeneousProvider = config.agencyConfig?.heterogeneousProvider;const updateHeterogeneousCommand = async (command: string) => {@@ -112,8 +109,6 @@ const ProfileEditor = memo(() => {<Divider />{/* Main Content: Prompt Editor */}<EditorCanvas />- {/* Agent Cron Jobs Display (only show if jobs exist) */}- {enableBusinessFeatures && <AgentCronJobs />}{/* Advanced Settings Modal */}<AgentSettings /></>diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex bc19dad19de..52fb87cfbfe 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -11,11 +11,6 @@ import {} from '@lobechat/agent-runtime';import { LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';import { CredsIdentifier, type CredSummary, generateCredsList } from '@lobechat/builtin-tool-creds';-import {- CronIdentifier,- type CronJobSummaryForContext,- generateCronJobsList,-} from '@lobechat/builtin-tool-cron';import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';import {AGENT_DOCUMENT_INJECTION_POSITIONS,@@ -38,7 +33,6 @@ import { type ChatToolPayload, type MessageToolCall, type UIChatMessage } from 'import { sanitizeToolCallArguments, serializePartsForStorage } from '@lobechat/utils';import debug from 'debug';-import { AgentCronJobModel } from '@/database/models/agentCronJob';import { type MessageModel, MessageModel as MessageModelClass } from '@/database/models/message';import { TopicModel } from '@/database/models/topic';import { UserModel } from '@/database/models/user';@@ -527,7 +521,7 @@ export const createRuntimeExecutors = (// and lambdaClient. In execAgent (server/bot) mode we must fetch from DB// directly. Each block is gated on the relevant tool being enabled.- // {{username}} / {{language}} β used by memory, cron, and creds system roles.+ // {{username}} / {{language}} β used by memory and creds system roles.// Single indexed DB lookup; cheap enough to run on each call_llm step.let serverUsername = '';let serverLanguage = '';@@ -575,35 +569,6 @@ export const createRuntimeExecutors = (}}- // {{CRON_JOBS_LIST}} β used by lobe-cron system role.- // Mirrors client-side: lambdaClient.agentCronJob.list.query({ agentId, limit: 4 })- const isCronEnabled = resolved.enabledToolIds.includes(CronIdentifier);- let cronJobsListStr = '';- if (isCronEnabled && lobehubSkillAgentId && ctx.serverDB && ctx.userId) {- try {- const cronJobModel = new AgentCronJobModel(ctx.serverDB, ctx.userId);- const { jobs, total } = await cronJobModel.findWithPagination({- agentId: lobehubSkillAgentId,- limit: 4,- });- const summaries: CronJobSummaryForContext[] = jobs.map((job) => ({- cronPattern: job.cronPattern,- description: job.description ?? undefined,- enabled: job.enabled ?? false,- id: job.id,- lastExecutedAt: job.lastExecutedAt?.toISOString() ?? null,- name: job.name ?? null,- remainingExecutions: job.remainingExecutions ?? null,- timezone: job.timezone ?? 'UTC',- totalExecutions: job.totalExecutions ?? 0,- }));- cronJobsListStr = generateCronJobsList(summaries, total);- log('Fetched %d cron jobs for {{CRON_JOBS_LIST}} substitution', jobs.length);- } catch (error) {- log('Failed to fetch cron jobs for {{CRON_JOBS_LIST}} substitution: %O', error);- }- }-const contextEngineInput = {agentDocuments,additionalVariables: {@@ -617,8 +582,6 @@ export const createRuntimeExecutors = (...(isCredsEnabled && { CREDS_LIST: credsListStr }),// Memory tool variablesmemory_effort: memoryEffort,- // Cron tool variables- ...(isCronEnabled && { CRON_JOBS_LIST: cronJobsListStr }),},userTimezone: ctx.userTimezone,capabilities: {diff --git a/src/server/routers/lambda/agentCronJob.ts b/src/server/routers/lambda/agentCronJob.tsdeleted file mode 100644index 8c26cd51f9e..00000000000--- a/src/server/routers/lambda/agentCronJob.ts+++ /dev/null@@ -1,370 +0,0 @@-import { type InsertAgentCronJob, type UpdateAgentCronJob } from '@lobechat/types';-import { InsertAgentCronJobSchema, UpdateAgentCronJobSchema } from '@lobechat/types';-import { TRPCError } from '@trpc/server';-import { z } from 'zod';--import { AgentCronJobModel } from '@/database/models/agentCronJob';-import { authedProcedure, router } from '@/libs/trpc/lambda';-import { serverDatabase } from '@/libs/trpc/lambda/middleware';--const agentCronJobProcedure = authedProcedure.use(serverDatabase);--const listQuerySchema = z.object({- agentId: z.string().optional(),- enabled: z.boolean().optional(),- limit: z.number().min(1).max(100).default(20),- offset: z.number().min(0).default(0),-});--const resetExecutionsSchema = z.object({- id: z.string(),- newMaxExecutions: z.number().min(1).max(10_000).optional(),-});--const batchUpdateStatusSchema = z.object({- enabled: z.boolean(),- ids: z.array(z.string()),-});--// Create input schema for tRPC that omits server-managed fields-const createAgentCronJobInputSchema = InsertAgentCronJobSchema.omit({- userId: true, // Provided by authentication context-}).extend({- // Optional β when set, the cron job is being created from a recommended task template;- // the server records it so the same template is excluded from future recommendations.- templateId: z.string().max(64).optional(),-});--/**- * Agent Cron Job tRPC Router- *- * Provides type-safe API for managing agent scheduled tasks- */-export const agentCronJobRouter = router({- /**- * Batch update status (enable/disable) for multiple jobs- */- batchUpdateStatus: agentCronJobProcedure- .input(batchUpdateStatusSchema)- .mutation(async ({ input, ctx }) => {- const { userId, serverDB: db } = ctx;- const { ids, enabled } = input;-- try {- const cronJobModel = new AgentCronJobModel(db, userId);- const updatedCount = await cronJobModel.batchUpdateStatus(ids, enabled);-- return {- data: { updatedCount },- message: `${updatedCount} cron jobs ${enabled ? 'enabled' : 'disabled'} successfully`,- success: true,- };- } catch (error) {- console.error('[agentCronJob:batchUpdateStatus]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to update cron job statuses',- });- }- }),-- /**- * Create a new cron job- */- create: agentCronJobProcedure- .input(createAgentCronJobInputSchema)- .mutation(async ({ input, ctx }) => {- const { userId, serverDB: db } = ctx;-- try {- const cronJobModel = new AgentCronJobModel(db, userId);- // `templateId` is accepted for analytics/cloud bookkeeping but not persisted- // on the cron job itself.- const { templateId: _templateId, ...cronJobInput } = input;- // Add userId to the input data since it's provided by authentication context- const cronJobData = { ...cronJobInput, userId };- const cronJob = await cronJobModel.create(cronJobData as InsertAgentCronJob);-- return {- data: cronJob,- message: 'Cron job created successfully',- success: true,- };- } catch (error) {- console.error('[agentCronJob:create]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to create cron job',- });- }- }),-- /**- * Delete a cron job- */- delete: agentCronJobProcedure- .input(z.object({ id: z.string() }))- .mutation(async ({ input, ctx }) => {- const { userId, serverDB: db } = ctx;- const { id } = input;-- try {- const cronJobModel = new AgentCronJobModel(db, userId);- const deleted = await cronJobModel.delete(id);-- if (!deleted) {- throw new TRPCError({- code: 'NOT_FOUND',- message: 'Cron job not found or access denied',- });- }-- return {- message: 'Cron job deleted successfully',- success: true,- };- } catch (error) {- if (error instanceof TRPCError) throw error;-- console.error('[agentCronJob:delete]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to delete cron job',- });- }- }),-- /**- * List cron jobs by agent ID- */- findByAgent: agentCronJobProcedure- .input(z.object({ agentId: z.string() }))- .query(async ({ input, ctx }) => {- const { userId, serverDB: db } = ctx;- const { agentId } = input;-- try {- const cronJobModel = new AgentCronJobModel(db, userId);- const cronJobs = await cronJobModel.findByAgentId(agentId);-- return {- data: cronJobs,- success: true,- };- } catch (error) {- console.error('[agentCronJob:findByAgent]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to fetch agent cron jobs',- });- }- }),-- /**- * Get a single cron job by ID- */- findById: agentCronJobProcedure- .input(z.object({ id: z.string() }))- .query(async ({ input, ctx }) => {- const { userId, serverDB: db } = ctx;- const { id } = input;-- try {- const cronJobModel = new AgentCronJobModel(db, userId);- const cronJob = await cronJobModel.findById(id);-- if (!cronJob) {- throw new TRPCError({- code: 'NOT_FOUND',- message: 'Cron job not found',- });- }-- return {- data: cronJob,- success: true,- };- } catch (error) {- if (error instanceof TRPCError) throw error;-- console.error('[agentCronJob:findById]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to fetch cron job',- });- }- }),-- /**- * Get jobs that are near depletion (for warnings)- */- getNearDepletion: agentCronJobProcedure- .input(z.object({ threshold: z.number().min(1).max(20).default(5) }))- .query(async ({ input, ctx }) => {- const { userId, serverDB: db } = ctx;- const { threshold } = input;-- try {- const cronJobModel = new AgentCronJobModel(db, userId);- const jobs = await cronJobModel.getTasksNearDepletion(threshold);-- return {- data: jobs,- success: true,- };- } catch (error) {- console.error('[agentCronJob:getNearDepletion]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to fetch near depletion jobs',- });- }- }),-- /**- * Get execution statistics for user's cron jobs- */- getStats: agentCronJobProcedure.query(async ({ ctx }) => {- const { userId, serverDB: db } = ctx;-- try {- const cronJobModel = new AgentCronJobModel(db, userId);- const stats = await cronJobModel.getExecutionStats();-- return {- data: stats,- success: true,- };- } catch (error) {- console.error('[agentCronJob:getStats]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to fetch execution statistics',- });- }- }),-- /**- * List cron jobs with filtering and pagination- */- list: agentCronJobProcedure.input(listQuerySchema).query(async ({ input, ctx }) => {- const { userId, serverDB: db } = ctx;- const { agentId, enabled, limit, offset } = input;-- try {- const cronJobModel = new AgentCronJobModel(db, userId);- const result = await cronJobModel.findWithPagination({- agentId,- enabled,- limit,- offset,- });-- return {- data: result.jobs,- pagination: {- hasMore: offset + limit < result.total,- limit,- offset,- total: result.total,- },- success: true,- };- } catch (error) {- console.error('[agentCronJob:list]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to fetch cron jobs',- });- }- }),-- /**- * Reset execution counts for a cron job- */- resetExecutions: agentCronJobProcedure- .input(resetExecutionsSchema)- .mutation(async ({ input, ctx }) => {- const { userId, serverDB: db } = ctx;- const { id, newMaxExecutions } = input;-- try {- const cronJobModel = new AgentCronJobModel(db, userId);- const cronJob = await cronJobModel.resetExecutions(id, newMaxExecutions);-- if (!cronJob) {- throw new TRPCError({- code: 'NOT_FOUND',- message: 'Cron job not found or access denied',- });- }-- return {- data: cronJob,- message: 'Execution counts reset successfully',- success: true,- };- } catch (error) {- if (error instanceof TRPCError) throw error;-- console.error('[agentCronJob:resetExecutions]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to reset execution counts',- });- }- }),-- /**- * Update a cron job- */- update: agentCronJobProcedure- .input(- z.object({- data: UpdateAgentCronJobSchema,- id: z.string(),- }),- )- .mutation(async ({ input, ctx }) => {- const { userId, serverDB: db } = ctx;- const { id, data } = input;-- try {- const cronJobModel = new AgentCronJobModel(db, userId);- const cronJob = await cronJobModel.update(id, data as UpdateAgentCronJob);-- if (!cronJob) {- throw new TRPCError({- code: 'NOT_FOUND',- message: 'Cron job not found or access denied',- });- }-- return {- data: cronJob,- message: 'Cron job updated successfully',- success: true,- };- } catch (error) {- if (error instanceof TRPCError) throw error;-- console.error('[agentCronJob:update]', error);- throw new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: 'Failed to update cron job',- });- }- }),-- // Note: testExecution moved to cloud layer since it uses AgentCronWorkflow-});diff --git a/src/server/routers/lambda/index.ts b/src/server/routers/lambda/index.tsindex 4b8e1b363a1..d0c818e6a03 100644--- a/src/server/routers/lambda/index.ts+++ b/src/server/routers/lambda/index.ts@@ -11,7 +11,6 @@ import { publicProcedure, router } from '@/libs/trpc/lambda';import { agentRouter } from './agent';import { agentBotProviderRouter } from './agentBotProvider';-import { agentCronJobRouter } from './agentCronJob';import { agentDocumentRouter } from './agentDocument';import { agentEvalRouter } from './agentEval';import { agentEvalExternalRouter } from './agentEvalExternal';@@ -72,7 +71,6 @@ export const lambdaRouter = router({agentBotProvider: agentBotProviderRouter,agentNotify: agentNotifyRouter,botMessage: botMessageRouter,- agentCronJob: agentCronJobRouter,agentDocument: agentDocumentRouter,agentEval: agentEvalRouter,agentEvalExternal: agentEvalExternalRouter,diff --git a/src/server/routers/lambda/topic.ts b/src/server/routers/lambda/topic.tsindex 37586c995ef..e730617b389 100644--- a/src/server/routers/lambda/topic.ts+++ b/src/server/routers/lambda/topic.ts@@ -218,12 +218,6 @@ export const topicRouter = router({return ctx.topicModel.queryAll();}),- getCronTopicsGroupedByCronJob: topicProcedure- .input(z.object({ agentId: z.string() }))- .query(async ({ input, ctx }) => {- return ctx.topicModel.getCronTopicsGroupedByCronJob(input.agentId);- }),-getShareInfo: topicProcedure.input(z.object({ topicId: z.string() })).query(async ({ input, ctx }) => {diff --git a/src/server/services/toolExecution/serverRuntimes/cron.ts b/src/server/services/toolExecution/serverRuntimes/cron.tsdeleted file mode 100644index c34c09e8260..00000000000--- a/src/server/services/toolExecution/serverRuntimes/cron.ts+++ /dev/null@@ -1,190 +0,0 @@-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.tsindex ebc9dcbc065..603e4c43b2a 100644--- a/src/server/services/toolExecution/serverRuntimes/index.ts+++ b/src/server/services/toolExecution/serverRuntimes/index.ts@@ -15,7 +15,6 @@ import { briefRuntime } from './brief';import { calculatorRuntime } from './calculator';import { cloudSandboxRuntime } from './cloudSandbox';import { credsRuntime } from './creds';-import { cronRuntime } from './cron';import { gtdRuntime } from './gtd';import { lobeAgentRuntime } from './lobeAgent';import { localSystemRuntime } from './localSystem';@@ -69,7 +68,6 @@ registerRuntimes([topicReferenceRuntime,userInteractionRuntime,credsRuntime,- cronRuntime,gtdRuntime,webOnboardingRuntime,agentMarketplaceRuntime,diff --git a/src/services/agentCronJob.ts b/src/services/agentCronJob.tsdeleted file mode 100644index a93ce4e485d..00000000000--- a/src/services/agentCronJob.ts+++ /dev/null@@ -1,98 +0,0 @@-import {- type CreateAgentCronJobData,- type UpdateAgentCronJobData,-} from '@/database/schemas/agentCronJob';-import { lambdaClient } from '@/libs/trpc/client/lambda';--/**- * Client-side service for Agent Cron Job operations- *- * This service provides a clean interface for frontend components- * to interact with agent cron job data using tRPC client.- */-class AgentCronJobService {- /**- * Create a new cron job- *- * `templateId` is optional β when set, server records the task template- * interaction so the same template is excluded from future recommendations.- */- async create(data: Omit<CreateAgentCronJobData, 'userId'> & { templateId?: string }) {- return await lambdaClient.agentCronJob.create.mutate(data);- }-- /**- * Get cron jobs for a specific agent- */- async getByAgentId(agentId: string) {- return await lambdaClient.agentCronJob.findByAgent.query({ agentId });- }-- /**- * Get a single cron job by ID- */- async getById(id: string) {- return await lambdaClient.agentCronJob.findById.query({ id });- }-- /**- * List cron jobs with pagination and filtering- */- async list(- options: {- agentId?: string;- enabled?: boolean;- limit?: number;- offset?: number;- } = {},- ) {- return await lambdaClient.agentCronJob.list.query(options);- }-- /**- * Update a cron job- */- async update(id: string, data: UpdateAgentCronJobData) {- return await lambdaClient.agentCronJob.update.mutate({ data, id });- }-- /**- * Delete a cron job- */- async delete(id: string) {- return await lambdaClient.agentCronJob.delete.mutate({ id });- }-- /**- * Reset execution counts- */- async resetExecutions(id: string, newMaxExecutions?: number) {- return await lambdaClient.agentCronJob.resetExecutions.mutate({- id,- newMaxExecutions,- });- }-- /**- * Get execution statistics- */- async getStats() {- return await lambdaClient.agentCronJob.getStats.query();- }-- /**- * Get jobs near depletion- */- async getNearDepletion(threshold: number = 5) {- return await lambdaClient.agentCronJob.getNearDepletion.query({ threshold });- }-- /**- * Batch update status (enable/disable) for multiple jobs- */- async batchUpdateStatus(ids: string[], enabled: boolean) {- return await lambdaClient.agentCronJob.batchUpdateStatus.mutate({ enabled, ids });- }-}--export const agentCronJobService = new AgentCronJobService();diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.tsindex 5e60628242e..469260c3815 100644--- a/src/services/chat/mecha/contextEngineering.ts+++ b/src/services/chat/mecha/contextEngineering.ts@@ -8,11 +8,6 @@ import {generateKlavisServicesList,type KlavisServiceSummary,} from '@lobechat/builtin-tool-creds';-import {- CronIdentifier,- type CronJobSummaryForContext,- generateCronJobsList,-} from '@lobechat/builtin-tool-cron';import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-builder';import { GTDIdentifier } from '@lobechat/builtin-tool-gtd';import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';@@ -423,42 +418,6 @@ export const contextEngineering = async ({}}- // Resolve cron jobs context for cron tool- // Only inject a small preview (up to 4) to save context window;- // the model can call listCronJobs API for the full list.- const isCronEnabled = tools?.includes(CronIdentifier) ?? false;- let cronJobsList: CronJobSummaryForContext[] | undefined;- let cronJobsTotal = 0;-- if (isCronEnabled && agentId) {- try {- const cronResult = await lambdaClient.agentCronJob.list.query({ agentId, limit: 4 });- const jobs = (cronResult as any)?.data ?? [];- cronJobsTotal = (cronResult as any)?.pagination?.total ?? jobs.length;- cronJobsList = jobs.map(- (job: any): CronJobSummaryForContext => ({- cronPattern: job.cronPattern,- description: job.description,- enabled: job.enabled,- id: job.id,- lastExecutedAt: job.lastExecutedAt,- name: job.name,- remainingExecutions: job.remainingExecutions,- timezone: job.timezone ?? 'UTC',- totalExecutions: job.totalExecutions ?? 0,- }),- );- log(- 'Cron jobs context resolved: count=%d, total=%d',- cronJobsList?.length ?? 0,- cronJobsTotal,- );- } catch (error) {- // Silently fail - cron context is optional- log('Failed to resolve cron jobs context:', error);- }- }-const userMemoryConfig =enableUserMemories && userMemoryData? {@@ -756,8 +715,6 @@ export const contextEngineering = async ({CREDS_LIST: () => (credsList ? generateCredsList(credsList) : ''),// NOTICE: required by builtin-tool-creds/src/systemRole.ts (Klavis integrations)KLAVIS_SERVICES_LIST: () => klavisServicesList,- // NOTICE: required by builtin-tool-cron/src/systemRole.ts- CRON_JOBS_LIST: () => (cronJobsList ? generateCronJobsList(cronJobsList, cronJobsTotal) : ''),// NOTICE(@nekomeowww): required by builtin-tool-memory/src/systemRole.tsmemory_effort: () => (userMemoryConfig ? (memoryContext?.effort ?? '') : ''),// Current agent + topic identity β referenced by the LobeHub builtindiff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsxindex e58af7d1855..a338ba14346 100644--- a/src/spa/router/desktopRouter.config.desktop.tsx+++ b/src/spa/router/desktopRouter.config.desktop.tsx@@ -21,7 +21,6 @@ import DesktopAgentChatLayout from '@/routes/(main)/agent/(chat)/_layout';import AgentTopicNotebookRedirectPage from '@/routes/(main)/agent/[topicId]/page';import AgentTopicNotebookDocPage from '@/routes/(main)/agent/[topicId]/page/[docId]';import AgentChannelPage from '@/routes/(main)/agent/channel';-import AgentCronDetailPage from '@/routes/(main)/agent/cron/[cronId]';import AgentPageRedirectPage from '@/routes/(main)/agent/page';import AgentProfilePage from '@/routes/(main)/agent/profile';import CommunityLayout from '@/routes/(main)/community/_layout';@@ -137,10 +136,6 @@ export const desktopRoutes: RouteObject[] = [element: <AgentProfilePage />,path: 'profile',},- {- element: <AgentCronDetailPage />,- path: 'cron/:cronId',- },{element: <AgentChannelPage />,path: 'channel',diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsxindex a2c2e916218..aa06f19a8cb 100644--- a/src/spa/router/desktopRouter.config.tsx+++ b/src/spa/router/desktopRouter.config.tsx@@ -77,13 +77,6 @@ export const desktopRoutes: RouteObject[] = [),path: 'profile',},- {- element: dynamicElement(- () => import('@/routes/(main)/agent/cron/[cronId]'),- 'Desktop > Chat > Cron Detail',- ),- path: 'cron/:cronId',- },{element: dynamicElement(() => import('@/routes/(main)/agent/channel'),diff --git a/src/store/agent/slices/cron/action.ts b/src/store/agent/slices/cron/action.tsdeleted file mode 100644index f31b2d40ec0..00000000000--- a/src/store/agent/slices/cron/action.ts+++ /dev/null@@ -1,115 +0,0 @@-import { type SWRResponse } from 'swr';--import { type AgentCronJob } from '@/database/schemas/agentCronJob';-import { mutate, useClientDataSWR } from '@/libs/swr';-import { lambdaClient } from '@/libs/trpc/client/lambda';-import { agentCronJobService } from '@/services/agentCronJob';-import { type StoreSetter } from '@/store/types';--import { type AgentStore } from '../../store';--const FETCH_CRON_TOPICS_WITH_JOB_INFO_KEY = 'cronTopicsWithJobInfo';--export interface CronTopicGroupWithJobInfo {- cronJob: AgentCronJob | null;- cronJobId: string;- topics: Array<{- createdAt: Date | string;- favorite?: boolean | null;- historySummary?: string | null;- id: string;- metadata?: any;- title?: string | null;- trigger?: string | null;- updatedAt: Date | string;- }>;-}--/**- * Cron Slice Actions- * Handles agent cron job operations- */--type Setter = StoreSetter<AgentStore>;-export const createCronSlice = (set: Setter, get: () => AgentStore, _api?: unknown) =>- new CronSliceActionImpl(set, get, _api);--export class CronSliceActionImpl {- readonly #get: () => AgentStore;-- constructor(set: Setter, get: () => AgentStore, _api?: unknown) {- void _api;- void set;- this.#get = get;- }-- createAgentCronJob = async (): Promise<string | null> => {- const { activeAgentId, internal_refreshCronTopics } = this.#get();- if (!activeAgentId) return null;-- try {- const result = await agentCronJobService.create({- agentId: activeAgentId,- content: '',- cronPattern: '*/30 * * * *',- enabled: false,- });-- if (result.success) {- await internal_refreshCronTopics();- return result.data.id;- }- return null;- } catch (error) {- console.error('Failed to create cron job:', error);- return null;- }- };-- internal_refreshCronTopics = async (): Promise<void> => {- await mutate([FETCH_CRON_TOPICS_WITH_JOB_INFO_KEY, this.#get().activeAgentId]);- };-- useFetchCronTopicsWithJobInfo = (- agentId?: string,- enabled: boolean = true,- ): SWRResponse<CronTopicGroupWithJobInfo[]> => {- return useClientDataSWR<CronTopicGroupWithJobInfo[]>(- enabled && agentId ? [FETCH_CRON_TOPICS_WITH_JOB_INFO_KEY, agentId] : null,- async ([, id]: [string, string]) => {- const [cronJobsResult, cronTopicsGroups] = await Promise.all([- lambdaClient.agentCronJob.findByAgent.query({ agentId: id }),- lambdaClient.topic.getCronTopicsGroupedByCronJob.query({ agentId: id }),- ]);-- const cronJobs = cronJobsResult.success ? cronJobsResult.data : [];- const topicsByCronId = new Map(- cronTopicsGroups.map((group) => [group.cronJobId, group.topics]),- );- const cronJobIds = new Set(cronJobs.map((job) => job.id));-- const groupsWithJobs = cronJobs.map((job) => ({- cronJob: job,- cronJobId: job.id,- topics: topicsByCronId.get(job.id) || [],- }));-- const orphanGroups = cronTopicsGroups- .filter((group) => !cronJobIds.has(group.cronJobId))- .map((group) => ({- cronJob: null,- cronJobId: group.cronJobId,- topics: group.topics,- }));-- return [...groupsWithJobs, ...orphanGroups];- },- {- fallbackData: [],- revalidateOnFocus: false,- },- );- };-}--export type CronSliceAction = Pick<CronSliceActionImpl, keyof CronSliceActionImpl>;diff --git a/src/store/agent/slices/cron/index.ts b/src/store/agent/slices/cron/index.tsdeleted file mode 100644index fd3aeed6f0b..00000000000--- a/src/store/agent/slices/cron/index.ts+++ /dev/null@@ -1 +0,0 @@-export { createCronSlice, type CronSliceAction } from './action';diff --git a/src/store/agent/store.ts b/src/store/agent/store.tsindex 21493e3f60f..aacf5d2259b 100644--- a/src/store/agent/store.ts+++ b/src/store/agent/store.ts@@ -14,8 +14,6 @@ import { type BotSliceAction } from './slices/bot';import { createBotSlice } from './slices/bot';import { type BuiltinAgentSliceAction } from './slices/builtin';import { createBuiltinAgentSlice } from './slices/builtin';-import { type CronSliceAction } from './slices/cron';-import { createCronSlice } from './slices/cron';import { type KnowledgeSliceAction } from './slices/knowledge';import { createKnowledgeSlice } from './slices/knowledge';import { type PluginSliceAction } from './slices/plugin';@@ -28,7 +26,6 @@ export interface AgentStoreAgentSliceAction,BotSliceAction,BuiltinAgentSliceAction,- CronSliceAction,KnowledgeSliceAction,PluginSliceAction,ResetableStore,@@ -37,7 +34,6 @@ export interface AgentStoretype AgentStoreAction = AgentSliceAction &BotSliceAction &BuiltinAgentSliceAction &- CronSliceAction &KnowledgeSliceAction &PluginSliceAction &ResetableStore;@@ -54,7 +50,6 @@ const createStore: StateCreator<AgentStore, [['zustand/devtools', never]]> = (createAgentSlice(...parameters),createBotSlice(...parameters),createBuiltinAgentSlice(...parameters),- createCronSlice(...parameters),createKnowledgeSlice(...parameters),createPluginSlice(...parameters),new AgentStoreResetAction(...parameters),diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.tsindex 533244ee213..7b4407a5ce4 100644--- a/src/store/tool/slices/builtin/executors/index.ts+++ b/src/store/tool/slices/builtin/executors/index.ts@@ -9,7 +9,6 @@ import { agentManagementExecutor } from '@lobechat/builtin-tool-agent-managementimport { 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';@@ -142,7 +141,6 @@ registerExecutors([calculatorExecutor,cloudSandboxExecutor,credsExecutor,- cronExecutor,groupAgentBuilderExecutor,groupManagementExecutor,gtdExecutor,