/** * 持久化调度任务 CLI — 通过运行中 Host 的 `/assistant/jobs` 操作。 * 调度器在首次启动后以数据库为准,离线改 data/schedule-jobs.json 不会生效,因此不再直接改文件。 */ import { formatDateTime } from '@zhin.js/plugin-runtime'; import { Command } from 'commander'; import { isConsoleFeatureDisabled } from '@zhin.js/console-protocol'; import { logger } from '../utils/logger.js'; import { output } from '../utils/output.js'; import { reportHostFailure } from '../utils/host-error.js'; import { isCliDebug } from '../utils/cli-flags.js'; import { type ScheduleJobRecordCli, type JobScheduleCli, parseNotifyChannel, withNotifyTarget, targetSummary, nextRunSummary, contentLines, agentSummary, normalizeCronExpression, } from '../utils/assistant-jobs.js'; import { hostGet, hostPost, ALLOW_UNVERIFIED_HOST_OPTION_DESCRIPTION, HOST_OPTION_DESCRIPTION, requireHostHttpConfig, type HostFetchResult, type HostHttpConfig, } from '../utils/host-http.js'; async function requireHost(): Promise { const { host, allowUnverifiedHost } = scheduleCommand.opts<{ host?: string; allowUnverifiedHost?: boolean }>(); return requireHostHttpConfig({ host, allowUnverifiedHost }, message => logger.error(message)); } /** Which write a refusal answers, for {@link describeScheduleRefusal}. */ export type ScheduleWriteAction = | { readonly kind: 'add' } | { readonly kind: 'resume' | 'set-agent'; readonly id: string }; const AGENT_NOT_FOUND = /Agent 不存在:(.+?)。可用的 Agent:(.*)$/u; function names(value: unknown): string[] { if (!Array.isArray(value)) return []; return [...new Set(value.filter((name): name is string => typeof name === 'string').map(name => name.trim()).filter(Boolean))]; } /** * Explanation of a schedule write the Host refused for a known reason (#1250 b55 / b61), or * `undefined` to report it as any other failure. The first line is the error, the rest are hints. * * - `schedule_target_forbidden` (403): the job delivers to an account the caller may not send from * (`endpoint.operate`); resuming it, changing its Agent or creating it would send on their behalf. * - `schedule_agent_not_found` (400): `data: { code, agent, available }`; the usable Agents are listed * (read from the message for an older Host that sends no `data`). */ export function describeScheduleRefusal(result: HostFetchResult, action: ScheduleWriteAction): string[] | undefined { if (result.ok) return undefined; const detail = result.detail && typeof result.detail === 'object' ? result.detail as Record : {}; const code = typeof detail.code === 'string' ? detail.code : result.code; const message = result.error ?? ''; if (code === 'schedule_target_forbidden') { // An older Host spelled a target without an account as `undefined / undefined`: not an account. const extracted = /需要 (.+?) 上的 endpoint\.operate/u.exec(message)?.[1]; const account = extracted && !/\bundefined\b/u.test(extracted) ? extracted : undefined; const need = account ? `(需要 ${account} 上的 endpoint.operate)` : ''; if (action.kind === 'resume') { return [ `无法恢复任务 ${action.id}:你没有权限向它的投递目标发消息${need}`, `请让管理员授予你投递账号的 endpoint.operate 权限;或删除该任务(zhin schedule remove ${action.id})后,以你有权限的投递目标重新创建`, ]; } if (action.kind === 'set-agent') { return [ `无法修改任务 ${action.id} 的 Agent:你没有权限向它的投递目标发消息${need}`, '请让管理员授予你投递账号的 endpoint.operate 权限', ]; } return [ `无法创建任务:你没有权限向投递目标发消息${need}`, '请让管理员授予你该账号的 endpoint.operate 权限,或用 --target 改投你有权限的账号', ]; } const parsed = AGENT_NOT_FOUND.exec(message); if (code !== 'schedule_agent_not_found' && !parsed) return undefined; const agent = typeof detail.agent === 'string' && detail.agent.trim() ? detail.agent.trim() : parsed?.[1]; // `data.available` with no usable name (empty or not strings): fall back to the message. const fromDetail = names(detail.available); const available = fromDetail.length > 0 ? fromDetail : names(parsed?.[2]?.split('、')); const head = agent ? `Agent 不存在:${agent}` : 'Agent 不存在'; if (available.length === 0) { return [ `${head}。当前没有可用的 Agent`, action.kind === 'add' ? '请先在配置的 ai.agents 中添加 Agent,或省略 --agent 使用默认 Agent(zhin)' : `请先在配置的 ai.agents 中添加 Agent,或用 zhin schedule set-agent ${action.id} --clear 恢复默认 Agent(zhin)`, ]; } return [ `${head}。可用的 Agent:${available.join('、')}`, action.kind === 'add' ? '用 --agent <名称> 指定其中之一,或省略 --agent 使用默认 Agent' : `用 zhin schedule set-agent ${action.id} <名称> 改选其中之一,或加 --clear 恢复默认 Agent`, ]; } async function requireOk(result: HostFetchResult, action?: ScheduleWriteAction): Promise { if (result.ok) return result.data; const refusal = action ? describeScheduleRefusal(result, action) : undefined; if (refusal) { const [first, ...hints] = refusal; logger.error(first!); for (const hint of hints) logger.info(` ${hint}`); const detail = result.detail && typeof result.detail === 'object' ? result.detail as Record : {}; const code = typeof detail.code === 'string' ? detail.code : result.code; if (isCliDebug() && code) logger.info(` 错误码: ${code}(HTTP ${result.status})`); } else if (result.status === 404 && result.error === 'assistant.enabled is false') { // Newer instances name the reason in `data` (ConsoleFeatureDisabled, #1250). const disabled = result.detail; logger.error(isConsoleFeatureDisabled(disabled) ? `${disabled.message};无法管理调度任务` : '运行中的实例未启用 assistant(assistant.enabled),无法管理调度任务'); } else { await reportHostFailure(result, `HTTP ${result.status}`); } process.exit(1); } async function mutateJob(action: 'remove' | 'pause' | 'resume', id: string): Promise { await requireOk(await hostPost(await requireHost(), `/assistant/jobs/${action}`, { id }), action === 'resume' ? { kind: 'resume', id } : undefined); } function parseEveryMs(s: string): number { const m = s.trim().match(/^(\d+)(m|h|d|s)$/i); if (!m) throw new Error(`Invalid --every format: ${s}. Use e.g. 30m, 1h, 1d`); const n = parseInt(m[1], 10); const unit = m[2].toLowerCase(); if (unit === 's') return n * 1000; if (unit === 'm') return n * 60 * 1000; if (unit === 'h') return n * 60 * 60 * 1000; if (unit === 'd') return n * 24 * 60 * 60 * 1000; throw new Error(`Unknown unit: ${unit}`); } function notifySummary(notify: ScheduleJobRecordCli['notify']): string { if (notify.channel === 'silent') return 'silent'; if (notify.channel === 'log') return 'log'; const parts: string[] = [notify.channel]; if (notify.platform) parts.push(notify.platform); if (notify.sceneId) parts.push(`scene:${notify.sceneId}`); return parts.join('/'); } function scheduleSummary(s: JobScheduleCli): string { if (s.kind === 'at') return `at ${formatDateTime(s.atMs)}`; if (s.kind === 'every') { const m = s.everyMs / (60 * 1000); if (m < 60) return `every ${m}m`; const h = m / 60; if (h < 24) return `every ${h}h`; return `every ${h / 24}d`; } // The Host may also return kinds the CLI cannot create (holiday/scatter/event). return `${s.kind} ${(s as { cron?: string }).cron ?? ''}`.trimEnd(); } /** #1250 b33: the last run's status, with its cause when it failed or was degraded. */ export function lastRunSummary(job: Pick): string | undefined { const status = job.state?.lastStatus; if (!status) return undefined; const label = status === 'ok' ? '成功' : status === 'error' ? '失败' : status === 'degraded' ? '未完成(降级)' : status === 'skipped' ? '跳过' : status; const error = (status === 'error' || status === 'degraded') && job.state.lastError ? `:${job.state.lastError}` : ''; return `${label}${error}`; } const listCommand = new Command('list') .description('列出运行中实例的持久化调度任务') .option('--json', '以 JSON 输出(含完整的任务内容)') .action(async (opts: { json?: boolean }) => { const data = await requireOk( await hostGet<{ jobs?: ScheduleJobRecordCli[]; agents?: string[] }>(await requireHost(), '/assistant/jobs'), ); if (isConsoleFeatureDisabled(data)) { logger.error(`${data.message};无法列出调度任务`); process.exit(1); } const jobs = data?.jobs ?? []; // The configured Agents (#1250 b52); absent from older instances, then nothing is flagged. const agents = Array.isArray(data?.agents) ? data.agents : undefined; if (opts.json) { output.line(JSON.stringify(jobs, null, 2)); return; } if (jobs.length === 0) { output.line('暂无调度任务。使用 zhin schedule add 添加。'); return; } output.line('\n调度任务\n'); for (const j of jobs) { const status = j.enabled ? '启用' : '暂停'; const label = j.label ? ` (${j.label})` : ''; output.line(` ${j.id}${label} [${status}]`); output.line(` 计划: ${scheduleSummary(j.schedule)}`); output.line(` 投递: ${notifySummary(j.notify)}`); output.line(` Agent: ${agentSummary(j, agents)}`); const target = targetSummary(j); if (target) output.line(` 目标: ${target}`); const next = nextRunSummary(j); if (next) output.line(` 下次: ${next}`); const last = lastRunSummary(j); if (last) output.line(` 上次: ${last}`); for (const line of contentLines(j.action.prompt)) output.line(line); } }); const addCommand = new Command('add') .description('添加持久化调度任务(6 段 cron,或 --at / --every);需要实例正在运行') .argument('[cronExpression]', 'Cron 表达式,如 "0 0 9 * * *"(与 --at/--every 二选一)') .option('--prompt ', '到点触发时发给 AI 的提示词(必填)') .option('-l, --label