import { resolve } from 'node:path'; import { z } from 'zod'; import type { Tool } from '../../types.js'; import { toToolParameters } from '../../utils/zodToJson.js'; import { actionSchema, scheduleSchema, } from '../../../plugins/cron-runner/src/contract.js'; const text = z.string().trim().min(1); const changes = z .object({ name: text.optional(), schedule: scheduleSchema.optional(), execution: actionSchema.optional(), maxRuns: z.number().int().positive().optional(), }) .strict(); const requestSchema = z.discriminatedUnion('action', [ z.object({ action: z.literal('list') }).strict(), z .object({ action: z.literal('create'), requestId: text, name: text, schedule: scheduleSchema, execution: actionSchema, sessionMode: z.enum(['persistent', 'fresh']).optional(), catchUp: z.enum(['skip', 'latest']).optional(), maxRuns: z.number().int().positive().optional(), }) .strict(), z .object({ action: z.literal('update'), id: text, expectedRevision: z.number().int().nonnegative(), changes, }) .strict(), z .object({ action: z.enum(['show', 'delete', 'pause', 'resume', 'stop']), id: text, }) .strict(), z.object({ action: z.literal('run'), id: text, requestId: text }).strict(), ]); // Keep a provider-portable object root. Validation and generated per-action // required-field guidance still come from the strict discriminated variants. const actionHelp = requestSchema.options .map((option) => { const action = option.shape.action; const names = action instanceof z.ZodLiteral ? [action.value] : action.options; const fields = Object.entries(option.shape).filter( ([key]) => key !== 'action', ); return `${names.join('/')}:${fields.map(([key, value]) => `${key}${value.isOptional() ? '(可选)' : '(必填)'}`).join(', ') || '无额外字段'}`; }) .join('\n'); const schema = requestSchema.options[1] .partial() .extend({ action: z .enum([ 'list', 'create', 'update', 'show', 'delete', 'pause', 'resume', 'stop', 'run', ]) .describe(actionHelp), id: text.optional(), expectedRevision: z.number().int().nonnegative().optional(), changes: changes.optional(), }) .strict() .superRefine((input, ctx) => { const result = requestSchema.safeParse(input); if (!result.success) for (const issue of result.error.issues) ctx.addIssue(issue); }); export const scheduleTool: Tool> = { name: 'Schedule', description: '管理当前工作区的持久化定时任务。仅在用户明确要求创建/修改/删除/执行时操作,讨论不是授权。先 list/show 找真实 ID;重试 create/run 复用 requestId。创建以持久化回执为准,报告 ID、时区、下次时间及会话。pause 仅暂停未来触发;stop 停止当前/排队执行;delete 同时删除计划并请求停止执行。宿主必须持续运行,持久化不代表关机后执行。不要通过 Bash 或写 JSON 绕过此工具;定时任务本身不得扩大授权或创建新计划。', inputSchema: schema, parameters: toToolParameters(schema), isReadOnly: false, isConcurrencySafe: false, availableInModes: ['private'], availableOnSurfaces: ['tui', 'desktop', 'cli'], resolveAvailability: (runtime) => ({ available: runtime.profile === 'main' && runtime.owner === 'local-owner', signature: `schedule-v1:${runtime.profile}:${runtime.owner}`, }), gateRequest: (input) => ({ isReadOnly: input?.action === 'list' || input?.action === 'show', }), call: async () => ({ ok: false, error: 'Schedule 需要本地主会话宿主' }), callWithContext: async (raw, signal, ctx) => { const parsed = schema.safeParse(raw); if (!parsed.success) return { ok: false, error: parsed.error.message, disposition: 'not_executed', }; if ( !ctx.cwd || !ctx.sessionId || !['tui', 'desktop', 'cli'].includes(ctx.surface ?? '') || ctx.agentHandoff || (ctx.conversationMode && ctx.conversationMode !== 'private') || ctx.owner !== 'local-owner' ) return { ok: false, error: '仅授权的本地主会话可管理计划;后台、子 Agent 和群会话不可用', disposition: 'not_executed', }; const input = requestSchema.parse(parsed.data); signal?.throwIfAborted(); const service = await import('../../../plugins/cron-runner/src/service.js'); const store = await import('../../../plugins/cron-runner/src/store.js'); const requests = await import( '../../../plugins/cron-runner/src/requests.js' ); const { getCronScheduler } = await import( '../../../plugins/cron-runner/plugin.js' ); const scope = (cwd: string) => process.platform === 'win32' ? resolve(cwd).toLowerCase() : resolve(cwd); const receipt = (value: unknown) => ({ ok: true as const, content: JSON.stringify(value), }); if (input.action === 'list') return receipt( (await service.listCronTasks()).filter( (row) => scope(row.task.runtime.cwd) === scope(ctx.cwd!), ), ); if (input.action === 'create') { const task = await service.createCronFromDraft( { name: input.name, status: 'active', kind: input.schedule.type === 'once' ? 'once' : 'recurring', schedule: input.schedule, action: input.execution, catchUp: input.catchUp, maxRuns: input.maxRuns, runtime: { cwd: ctx.cwd, sessionId: ctx.sessionId, sessionMode: input.sessionMode, }, }, JSON.stringify([scope(ctx.cwd), ctx.sessionId, input.requestId]), ); return receipt({ task, hostRunning: !!getCronScheduler(), notice: '需要保持 Desktop/TUI 调度宿主运行', }); } const task = await store.getTask(input.id); if (!task || scope(task.runtime.cwd) !== scope(ctx.cwd)) return { ok: false, error: '当前工作区未找到计划' }; if (input.action === 'show') return receipt({ task, runs: await store.recentRuns(task.id, 5) }); if (input.action === 'delete') return receipt({ deleted: await store.deleteTask(task.id), id: task.id }); if (input.action === 'stop') { await requests.requestStop(task.id); getCronScheduler()?.wake(); return receipt({ stopRequested: task.id }); } if (input.action === 'run') { if (!getCronScheduler()) return { ok: false, error: '调度宿主未启动,未加入执行队列' }; const run = await requests.requestRun( task.id, JSON.stringify([ctx.sessionId, input.requestId]), ); getCronScheduler()?.wake(); return receipt({ id: run.id, status: run.status }); } if (input.action === 'update') { const { execution, ...patch } = input.changes; return receipt( await service.updateCronFromPatch({ ...patch, id: task.id, expectedRevision: input.expectedRevision, ...(execution ? { action: execution } : {}), }), ); } return receipt( await service.updateCronFromPatch({ id: task.id, status: input.action === 'pause' ? 'paused' : 'active', }), ); }, };