|
| 1 | +import { Effect } from 'effect'; |
| 2 | +import { CronJob } from 'cron'; |
| 3 | +import { randomUUID } from 'crypto'; |
| 4 | +import { createLogger } from '@codingcode/infra'; |
| 5 | +import type { Automation, CreateAutomationInput, UpdateAutomationInput } from './types.js'; |
| 6 | +import { readAutomations, writeAutomations } from './store.js'; |
| 7 | +import { SessionService } from '../session/store.js'; |
| 8 | +import { sendMessage, type AgentEvent } from '../agent/agent.js'; |
| 9 | +import { getLLMClient } from '../llm/factory.js'; |
| 10 | +import { AgentError } from '../core/error.js'; |
| 11 | +import { AppLayer } from '../layer.js'; |
| 12 | + |
| 13 | +const logger = createLogger(); |
| 14 | + |
| 15 | +const TIMEOUT_MS = 5 * 60 * 1000; |
| 16 | + |
| 17 | +export class SchedulerService extends Effect.Service<SchedulerService>()('Scheduler', { |
| 18 | + effect: Effect.gen(function* () { |
| 19 | + const session = yield* SessionService; |
| 20 | + const jobs = new Map<string, CronJob>(); |
| 21 | + |
| 22 | + function scheduleAutomation(auto: Automation): void { |
| 23 | + if (!auto.enabled) return; |
| 24 | + |
| 25 | + const job = new CronJob( |
| 26 | + auto.cron, |
| 27 | + () => { |
| 28 | + runAutomation(auto).catch((e) => logger.error(`Automation ${auto.id} failed:`, e)); |
| 29 | + }, |
| 30 | + null, |
| 31 | + true, |
| 32 | + auto.timezone |
| 33 | + ); |
| 34 | + |
| 35 | + jobs.set(auto.id, job); |
| 36 | + } |
| 37 | + |
| 38 | + async function runAutomation(auto: Automation): Promise<void> { |
| 39 | + logger.info(`Running automation: ${auto.name} (${auto.id})`); |
| 40 | + |
| 41 | + const llmResult = await getLLMClient(); |
| 42 | + if (!llmResult.ok) { |
| 43 | + logger.error(`Failed to get LLM client for automation ${auto.id}:`, llmResult.error); |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + const controller = new AbortController(); |
| 48 | + const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS); |
| 49 | + |
| 50 | + try { |
| 51 | + const { stream, sessionId } = await Effect.runPromise( |
| 52 | + sendMessage(undefined, auto.description, auto.projectCwd, llmResult.value, { |
| 53 | + signal: controller.signal, |
| 54 | + approvalOverride: { permissionMode: 'bypass' }, |
| 55 | + }).pipe(Effect.provide(AppLayer)) |
| 56 | + ); |
| 57 | + |
| 58 | + let lastContent = ''; |
| 59 | + for await (const event of stream) { |
| 60 | + if (event._tag === 'Done') { |
| 61 | + lastContent = event.content; |
| 62 | + } else if (event._tag === 'Error') { |
| 63 | + logger.error(`Automation ${auto.id} agent error:`, event.error); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + const automations = readAutomations(); |
| 68 | + const idx = automations.findIndex((a) => a.id === auto.id); |
| 69 | + if (idx >= 0) { |
| 70 | + const automation = automations[idx]!; |
| 71 | + automation.lastRunAt = Date.now(); |
| 72 | + automation.lastSessionId = sessionId; |
| 73 | + |
| 74 | + if (auto.runOnce) { |
| 75 | + automations.splice(idx, 1); |
| 76 | + jobs.get(auto.id)?.stop(); |
| 77 | + jobs.delete(auto.id); |
| 78 | + } |
| 79 | + |
| 80 | + writeAutomations(automations); |
| 81 | + } |
| 82 | + |
| 83 | + logger.info(`Automation ${auto.id} completed. Session: ${sessionId}`); |
| 84 | + } catch (e) { |
| 85 | + logger.error(`Automation ${auto.id} execution failed:`, e); |
| 86 | + } finally { |
| 87 | + clearTimeout(timeout); |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + function initialize(): void { |
| 92 | + const automations = readAutomations(); |
| 93 | + for (const auto of automations) { |
| 94 | + scheduleAutomation(auto); |
| 95 | + } |
| 96 | + logger.info(`Scheduler initialized with ${jobs.size} automations`); |
| 97 | + } |
| 98 | + |
| 99 | + function list(): Automation[] { |
| 100 | + return readAutomations(); |
| 101 | + } |
| 102 | + |
| 103 | + function add(input: CreateAutomationInput): Automation { |
| 104 | + const automations = readAutomations(); |
| 105 | + const now = Date.now(); |
| 106 | + const auto: Automation = { |
| 107 | + id: randomUUID().slice(0, 8), |
| 108 | + name: input.name, |
| 109 | + description: input.description, |
| 110 | + cron: input.cron, |
| 111 | + timezone: input.timezone ?? 'Asia/Shanghai', |
| 112 | + sandbox: input.sandbox ?? 'workspace-write', |
| 113 | + enabled: true, |
| 114 | + projectCwd: input.projectCwd, |
| 115 | + runOnce: input.runOnce ?? false, |
| 116 | + createdAt: now, |
| 117 | + updatedAt: now, |
| 118 | + lastRunAt: null, |
| 119 | + lastSessionId: null, |
| 120 | + }; |
| 121 | + |
| 122 | + automations.push(auto); |
| 123 | + writeAutomations(automations); |
| 124 | + scheduleAutomation(auto); |
| 125 | + return auto; |
| 126 | + } |
| 127 | + |
| 128 | + function update(id: string, patch: UpdateAutomationInput): Automation | null { |
| 129 | + const automations = readAutomations(); |
| 130 | + const idx = automations.findIndex((a) => a.id === id); |
| 131 | + if (idx < 0) return null; |
| 132 | + |
| 133 | + const auto = automations[idx]!; |
| 134 | + Object.assign(auto, patch, { updatedAt: Date.now() }); |
| 135 | + automations[idx] = auto; |
| 136 | + writeAutomations(automations); |
| 137 | + |
| 138 | + jobs.get(id)?.stop(); |
| 139 | + jobs.delete(id); |
| 140 | + scheduleAutomation(auto); |
| 141 | + |
| 142 | + return auto; |
| 143 | + } |
| 144 | + |
| 145 | + function remove(id: string): boolean { |
| 146 | + const automations = readAutomations(); |
| 147 | + const idx = automations.findIndex((a) => a.id === id); |
| 148 | + if (idx < 0) return false; |
| 149 | + |
| 150 | + automations.splice(idx, 1); |
| 151 | + writeAutomations(automations); |
| 152 | + |
| 153 | + jobs.get(id)?.stop(); |
| 154 | + jobs.delete(id); |
| 155 | + return true; |
| 156 | + } |
| 157 | + |
| 158 | + async function runOnce(id: string): Promise<string | null> { |
| 159 | + const automations = readAutomations(); |
| 160 | + const auto = automations.find((a) => a.id === id); |
| 161 | + if (!auto) return null; |
| 162 | + |
| 163 | + const llmResult = await getLLMClient(); |
| 164 | + if (!llmResult.ok) { |
| 165 | + throw new AgentError('CONFIG_MISSING', 'Failed to get LLM client'); |
| 166 | + } |
| 167 | + |
| 168 | + const controller = new AbortController(); |
| 169 | + const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS); |
| 170 | + |
| 171 | + try { |
| 172 | + const { stream, sessionId } = await Effect.runPromise( |
| 173 | + sendMessage(undefined, auto.description, auto.projectCwd, llmResult.value, { |
| 174 | + signal: controller.signal, |
| 175 | + approvalOverride: { permissionMode: 'bypass' }, |
| 176 | + }).pipe(Effect.provide(AppLayer)) |
| 177 | + ); |
| 178 | + |
| 179 | + for await (const event of stream) { |
| 180 | + if (event._tag === 'Error') { |
| 181 | + logger.error(`Manual run for ${id} agent error:`, event.error); |
| 182 | + } |
| 183 | + } |
| 184 | + |
| 185 | + const allAutomations = readAutomations(); |
| 186 | + const idx = allAutomations.findIndex((a) => a.id === id); |
| 187 | + if (idx >= 0) { |
| 188 | + const automation = allAutomations[idx]!; |
| 189 | + automation.lastRunAt = Date.now(); |
| 190 | + automation.lastSessionId = sessionId; |
| 191 | + writeAutomations(allAutomations); |
| 192 | + } |
| 193 | + |
| 194 | + return sessionId; |
| 195 | + } finally { |
| 196 | + clearTimeout(timeout); |
| 197 | + } |
| 198 | + } |
| 199 | + |
| 200 | + function stopAll(): void { |
| 201 | + for (const [id, job] of jobs) { |
| 202 | + job.stop(); |
| 203 | + } |
| 204 | + jobs.clear(); |
| 205 | + } |
| 206 | + |
| 207 | + return { |
| 208 | + initialize, |
| 209 | + list, |
| 210 | + add, |
| 211 | + update, |
| 212 | + remove, |
| 213 | + runOnce, |
| 214 | + stopAll, |
| 215 | + }; |
| 216 | + }), |
| 217 | +}) {} |
0 commit comments