@keyou007/agent-bot 0.1.25-alpha.0 → 0.1.25-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +60 -5
  3. package/README.zh.md +60 -5
  4. package/config.example.yaml +1 -3
  5. package/dist/cli/controlProtocol.js.map +1 -1
  6. package/dist/cli/help.js +14 -0
  7. package/dist/cli/help.js.map +1 -1
  8. package/dist/cli.js +32 -0
  9. package/dist/cli.js.map +1 -1
  10. package/dist/codex/CodexRuntime.js +15 -5
  11. package/dist/codex/CodexRuntime.js.map +1 -1
  12. package/dist/commands/CommandRouter.js +7 -0
  13. package/dist/commands/CommandRouter.js.map +1 -1
  14. package/dist/config/SettingsStore.js +341 -0
  15. package/dist/config/SettingsStore.js.map +1 -0
  16. package/dist/config/loadConfig.js +1 -2
  17. package/dist/config/loadConfig.js.map +1 -1
  18. package/dist/config/schema.js +0 -1
  19. package/dist/config/schema.js.map +1 -1
  20. package/dist/console/ConsoleTurnPresenter.js +3 -0
  21. package/dist/console/ConsoleTurnPresenter.js.map +1 -1
  22. package/dist/feishu/CardRenderer.js +32 -96
  23. package/dist/feishu/CardRenderer.js.map +1 -1
  24. package/dist/feishu/FeishuConnector.js +9 -0
  25. package/dist/feishu/FeishuConnector.js.map +1 -1
  26. package/dist/feishu/FeishuMessageClient.js +35 -14
  27. package/dist/feishu/FeishuMessageClient.js.map +1 -1
  28. package/dist/feishu/FeishuTurnPresenter.js +36 -23
  29. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  30. package/dist/feishu/LocalCardImage.js.map +1 -1
  31. package/dist/feishu/LocalImageMarkdown.js +59 -3
  32. package/dist/feishu/LocalImageMarkdown.js.map +1 -1
  33. package/dist/feishu/SettingsCard.js +199 -0
  34. package/dist/feishu/SettingsCard.js.map +1 -0
  35. package/dist/index.js +17 -6
  36. package/dist/index.js.map +1 -1
  37. package/dist/local-files/TurnPreviewPage.js +8 -4
  38. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  39. package/dist/presentation/TurnStateReducer.js +21 -2
  40. package/dist/presentation/TurnStateReducer.js.map +1 -1
  41. package/dist/presentation/turnStatus.js +34 -0
  42. package/dist/presentation/turnStatus.js.map +1 -0
  43. package/dist/proxy/ProxySessionController.js +688 -153
  44. package/dist/proxy/ProxySessionController.js.map +1 -1
  45. package/dist/runtime/submissionErrors.js +15 -0
  46. package/dist/runtime/submissionErrors.js.map +1 -0
  47. package/dist/scheduling/ScheduleCards.js +240 -0
  48. package/dist/scheduling/ScheduleCards.js.map +1 -0
  49. package/dist/scheduling/ScheduleCommand.js +67 -0
  50. package/dist/scheduling/ScheduleCommand.js.map +1 -0
  51. package/dist/scheduling/ScheduledTaskStore.js +226 -0
  52. package/dist/scheduling/ScheduledTaskStore.js.map +1 -0
  53. package/dist/scheduling/TaskScheduler.js +132 -0
  54. package/dist/scheduling/TaskScheduler.js.map +1 -0
  55. package/dist/scheduling/types.js +89 -0
  56. package/dist/scheduling/types.js.map +1 -0
  57. package/dist/state/ExecutionProvenanceStore.js +58 -0
  58. package/dist/state/ExecutionProvenanceStore.js.map +1 -0
  59. package/dist/state/StateStore.js +145 -45
  60. package/dist/state/StateStore.js.map +1 -1
  61. package/dist/state/migrations.js +37 -0
  62. package/dist/state/migrations.js.map +1 -1
  63. package/dist/supervision/SafeRestartNotifier.js +1 -1
  64. package/dist/supervision/SafeRestartNotifier.js.map +1 -1
  65. package/docs/technical-reference.md +11 -8
  66. package/docs/technical-reference.zh.md +11 -8
  67. package/npm-shrinkwrap.json +24 -2
  68. package/package.json +2 -1
  69. package/skills/agent-bot/SKILL.md +33 -3
  70. package/src/cli/controlProtocol.ts +1 -0
  71. package/src/cli/help.ts +14 -0
  72. package/src/cli.ts +25 -0
  73. package/src/codex/CodexRuntime.ts +14 -5
  74. package/src/commands/CommandRouter.ts +7 -0
  75. package/src/commands/commandTypes.ts +2 -0
  76. package/src/config/SettingsStore.ts +588 -0
  77. package/src/config/loadConfig.ts +1 -2
  78. package/src/config/schema.ts +0 -1
  79. package/src/console/ConsoleTurnPresenter.ts +2 -0
  80. package/src/feishu/CardRenderer.ts +33 -110
  81. package/src/feishu/FeishuConnector.ts +9 -0
  82. package/src/feishu/FeishuMessageClient.ts +39 -17
  83. package/src/feishu/FeishuTurnPresenter.ts +33 -22
  84. package/src/feishu/LocalCardImage.ts +0 -1
  85. package/src/feishu/LocalImageMarkdown.ts +54 -3
  86. package/src/feishu/SettingsCard.ts +231 -0
  87. package/src/index.ts +17 -6
  88. package/src/local-files/TurnPreviewPage.ts +8 -4
  89. package/src/presentation/TurnStateReducer.ts +21 -2
  90. package/src/presentation/turnStatus.ts +38 -0
  91. package/src/presentation/turnViewTypes.ts +3 -0
  92. package/src/proxy/ProxySessionController.ts +628 -152
  93. package/src/runtime/submissionErrors.ts +15 -0
  94. package/src/runtime/types.ts +1 -0
  95. package/src/scheduling/ScheduleCards.ts +317 -0
  96. package/src/scheduling/ScheduleCommand.ts +76 -0
  97. package/src/scheduling/ScheduledTaskStore.ts +332 -0
  98. package/src/scheduling/TaskScheduler.ts +171 -0
  99. package/src/scheduling/types.ts +151 -0
  100. package/src/state/ExecutionProvenanceStore.ts +100 -0
  101. package/src/state/StateStore.ts +167 -44
  102. package/src/state/migrations.ts +37 -0
  103. package/src/supervision/SafeRestartNotifier.ts +1 -1
@@ -0,0 +1,332 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type Database from "better-sqlite3";
3
+ import {
4
+ nextScheduleTime,
5
+ scheduleInputSchema,
6
+ type ScheduleInput,
7
+ type ScheduledJob,
8
+ type ScheduledRun,
9
+ type ScheduledRunStatus,
10
+ } from "./types.js";
11
+
12
+ interface JsonRow {
13
+ value_json: string;
14
+ }
15
+ const active = "'queued','dispatching','submitting','running','unknown'";
16
+
17
+ export class ScheduledTaskStore {
18
+ constructor(private readonly db: Database.Database) {}
19
+
20
+ create(
21
+ input: ScheduleInput,
22
+ target: Pick<
23
+ ScheduledJob,
24
+ "localSessionId" | "contextKey" | "replyMessageId" | "ownerId"
25
+ >,
26
+ now = Date.now(),
27
+ ): ScheduledJob {
28
+ const spec = scheduleInputSchema.parse(input);
29
+ if (!nextScheduleTime(spec, now)) throw new Error("执行时间必须在将来。");
30
+ const job: ScheduledJob = {
31
+ id: `sched_${randomUUID().replaceAll("-", "").slice(0, 12)}`,
32
+ revision: 1,
33
+ status: "draft",
34
+ ...target,
35
+ spec,
36
+ createdAt: now,
37
+ updatedAt: now,
38
+ };
39
+ this.db
40
+ .prepare(
41
+ `INSERT INTO scheduled_jobs (id, local_session_id, context_key, status, next_run_at, revision, value_json)
42
+ VALUES (?, ?, ?, ?, NULL, ?, ?)`,
43
+ )
44
+ .run(
45
+ job.id,
46
+ job.localSessionId,
47
+ job.contextKey,
48
+ job.status,
49
+ job.revision,
50
+ JSON.stringify(job),
51
+ );
52
+ return job;
53
+ }
54
+
55
+ get(id: string): ScheduledJob | undefined {
56
+ const row = this.db
57
+ .prepare("SELECT value_json FROM scheduled_jobs WHERE id = ?")
58
+ .get(id) as JsonRow | undefined;
59
+ return row ? (JSON.parse(row.value_json) as ScheduledJob) : undefined;
60
+ }
61
+
62
+ list(contextKey?: string, limit = 10, offset = 0): ScheduledJob[] {
63
+ const rows = this.db
64
+ .prepare(
65
+ `SELECT value_json FROM scheduled_jobs WHERE status != 'deleted'
66
+ AND (? IS NULL OR context_key = ?) ORDER BY rowid DESC LIMIT ? OFFSET ?`,
67
+ )
68
+ .all(
69
+ contextKey ?? null,
70
+ contextKey ?? null,
71
+ Math.min(100, limit),
72
+ offset,
73
+ ) as JsonRow[];
74
+ return rows.map((row) => JSON.parse(row.value_json) as ScheduledJob);
75
+ }
76
+
77
+ due(now: number): ScheduledJob[] {
78
+ return (
79
+ this.db
80
+ .prepare(
81
+ `SELECT value_json FROM scheduled_jobs WHERE status = 'enabled'
82
+ AND next_run_at <= ? ORDER BY next_run_at LIMIT 50`,
83
+ )
84
+ .all(now) as JsonRow[]
85
+ ).map((row) => JSON.parse(row.value_json) as ScheduledJob);
86
+ }
87
+
88
+ update(job: ScheduledJob, now = Date.now()): ScheduledJob {
89
+ const updated = { ...job, revision: job.revision + 1, updatedAt: now };
90
+ const result = this.db
91
+ .prepare(
92
+ `UPDATE scheduled_jobs SET status = ?, next_run_at = ?, revision = ?, value_json = ?
93
+ WHERE id = ? AND revision = ?`,
94
+ )
95
+ .run(
96
+ updated.status,
97
+ updated.nextRunAt ?? null,
98
+ updated.revision,
99
+ JSON.stringify(updated),
100
+ job.id,
101
+ job.revision,
102
+ );
103
+ if (!result.changes) throw new Error("计划已变化,请刷新后重试。");
104
+ return updated;
105
+ }
106
+
107
+ change(
108
+ id: string,
109
+ revision: number,
110
+ operation: "confirm" | "pause" | "resume" | "delete",
111
+ now = Date.now(),
112
+ ): ScheduledJob {
113
+ return this.db.transaction(() => {
114
+ const job = this.require(id, revision);
115
+ if (operation === "confirm" && job.status !== "draft")
116
+ throw new Error("计划草稿已失效。");
117
+ if (operation === "pause" && job.status === "draft")
118
+ throw new Error("草稿尚未启用。");
119
+ if (operation === "resume" && job.status !== "paused")
120
+ throw new Error("仅已暂停的计划可以恢复;草稿需先确认。");
121
+ if (operation === "confirm" || operation === "resume") {
122
+ job.nextRunAt = nextScheduleTime(job.spec, now);
123
+ if (job.nextRunAt === undefined)
124
+ throw new Error("一次性时间已过期,请编辑计划。");
125
+ job.status = "enabled";
126
+ } else {
127
+ job.status = operation === "delete" ? "deleted" : "paused";
128
+ job.nextRunAt = undefined;
129
+ this.cancelPending(id, "计划已暂停或删除。");
130
+ }
131
+ job.notice = undefined;
132
+ return this.update(job, now);
133
+ })();
134
+ }
135
+
136
+ edit(
137
+ id: string,
138
+ revision: number,
139
+ input: ScheduleInput,
140
+ now = Date.now(),
141
+ ): ScheduledJob {
142
+ const spec = scheduleInputSchema.parse(input);
143
+ if (nextScheduleTime(spec, now) === undefined)
144
+ throw new Error("执行时间必须在将来。");
145
+ return this.db.transaction(() => {
146
+ const job = this.require(id, revision);
147
+ this.cancelPending(id, "计划已编辑,等待重新确认。");
148
+ return this.update(
149
+ { ...job, spec, status: "draft", nextRunAt: undefined },
150
+ now,
151
+ );
152
+ })();
153
+ }
154
+
155
+ require(id: string, revision?: number): ScheduledJob {
156
+ const job = this.get(id);
157
+ if (!job || job.status === "deleted")
158
+ throw new Error("计划不存在或已删除。");
159
+ if (revision !== undefined && job.revision !== revision)
160
+ throw new Error("计划卡片已过期,请刷新。");
161
+ return job;
162
+ }
163
+
164
+ runs(id: string, limit = 10): ScheduledRun[] {
165
+ return (
166
+ this.db
167
+ .prepare(
168
+ "SELECT value_json FROM scheduled_runs WHERE job_id = ? ORDER BY rowid DESC LIMIT ?",
169
+ )
170
+ .all(id, Math.min(100, limit)) as JsonRow[]
171
+ ).map((row) => JSON.parse(row.value_json) as ScheduledRun);
172
+ }
173
+
174
+ getRun(id: string): ScheduledRun | undefined {
175
+ const row = this.db
176
+ .prepare("SELECT value_json FROM scheduled_runs WHERE id = ?")
177
+ .get(id) as JsonRow | undefined;
178
+ return row ? (JSON.parse(row.value_json) as ScheduledRun) : undefined;
179
+ }
180
+
181
+ ownsTurn(turnId: string): boolean {
182
+ return Boolean(
183
+ this.db
184
+ .prepare(
185
+ `SELECT 1 FROM scheduled_runs s JOIN turn_attempts t ON t.attempt_id = s.id
186
+ WHERE t.turn_id = ? OR t.pending_turn_id = ? LIMIT 1`,
187
+ )
188
+ .get(turnId, turnId),
189
+ );
190
+ }
191
+
192
+ saveRun(run: ScheduledRun): void {
193
+ this.db
194
+ .prepare(
195
+ "UPDATE scheduled_runs SET status = ?, value_json = ? WHERE id = ?",
196
+ )
197
+ .run(run.status, JSON.stringify(run), run.id);
198
+ }
199
+
200
+ pendingRuns(): ScheduledRun[] {
201
+ return (
202
+ this.db
203
+ .prepare(
204
+ "SELECT value_json FROM scheduled_runs WHERE status IN ('queued','dispatching','submitting','running') ORDER BY rowid LIMIT 500",
205
+ )
206
+ .all() as JsonRow[]
207
+ ).map((row) => JSON.parse(row.value_json) as ScheduledRun);
208
+ }
209
+
210
+ dispatch(
211
+ job: ScheduledJob,
212
+ scheduledFor: number,
213
+ now: number,
214
+ options: { manual?: boolean; skip?: string } = {},
215
+ ): ScheduledRun | undefined {
216
+ return this.db.transaction(() => {
217
+ const current = this.require(job.id, job.revision);
218
+ if (current.status !== "enabled" && !options.manual) return undefined;
219
+ if (current.status === "draft") throw new Error("草稿需要先确认。");
220
+ const manual = options.manual === true;
221
+ const busy = this.db
222
+ .prepare(
223
+ `SELECT 1 FROM scheduled_runs WHERE job_id = ? AND status IN (${active}) LIMIT 1`,
224
+ )
225
+ .get(job.id);
226
+ const detail = options.skip ?? (busy ? "上次运行尚未结束。" : undefined);
227
+ const run: ScheduledRun = {
228
+ id: `schedule_run_${randomUUID()}`,
229
+ jobId: job.id,
230
+ scheduledFor,
231
+ deadline: scheduledFor + job.spec.maxDelayMinutes * 60_000,
232
+ manual,
233
+ status: detail ? "skipped" : "queued",
234
+ detail,
235
+ };
236
+ const inserted = this.db
237
+ .prepare(
238
+ `INSERT OR IGNORE INTO scheduled_runs (id, job_id, occurrence_key, status, value_json)
239
+ VALUES (?, ?, ?, ?, ?)`,
240
+ )
241
+ .run(
242
+ run.id,
243
+ job.id,
244
+ manual ? run.id : String(scheduledFor),
245
+ run.status,
246
+ JSON.stringify(run),
247
+ );
248
+ if (!inserted.changes) return undefined;
249
+ if (!detail) {
250
+ this.db
251
+ .prepare(
252
+ `INSERT INTO queued_prompts (prompt_id, local_session_id, context_key, prompt_text,
253
+ display_prompt, local_image_paths_json, reply_message_id, created_at) VALUES (?, ?, ?, ?, ?, '[]', ?, ?)`,
254
+ )
255
+ .run(
256
+ run.id,
257
+ job.localSessionId,
258
+ job.contextKey,
259
+ job.spec.prompt,
260
+ `[定时任务:${job.spec.name} · ${new Date(scheduledFor).toISOString()}]\n${job.spec.prompt}`,
261
+ job.replyMessageId ?? null,
262
+ new Date(now).toISOString(),
263
+ );
264
+ }
265
+ if (!manual) {
266
+ current.nextRunAt = nextScheduleTime(current.spec, now);
267
+ if (current.nextRunAt === undefined) current.status = "completed";
268
+ this.update(current, now);
269
+ }
270
+ return run;
271
+ })();
272
+ }
273
+
274
+ claimStart(id: string, now = Date.now()): boolean {
275
+ const run = this.getRun(id);
276
+ if (!run) return true;
277
+ if (run.status !== "queued") return false;
278
+ if (!this.canSubmit(id, now)) return false;
279
+ const job = this.get(run.jobId);
280
+ const session = job
281
+ ? (this.db
282
+ .prepare("SELECT status FROM sessions WHERE local_session_id = ?")
283
+ .get(job.localSessionId) as { status: string } | undefined)
284
+ : undefined;
285
+ if (!session || session.status === "closed") {
286
+ this.finish(id, "cancelled", "目标任务已关闭。");
287
+ return false;
288
+ }
289
+ this.saveRun({ ...run, status: "dispatching", startedAt: now });
290
+ return true;
291
+ }
292
+
293
+ canSubmit(id: string, now = Date.now()): boolean {
294
+ const run = this.getRun(id);
295
+ if (!run || !["queued", "dispatching"].includes(run.status)) return false;
296
+ const job = this.get(run.jobId);
297
+ const allowed =
298
+ job &&
299
+ (job.status === "enabled" ||
300
+ job.status === "completed" ||
301
+ (run.manual && job.status === "paused"));
302
+ if (!allowed || now > run.deadline) {
303
+ this.saveRun({
304
+ ...run,
305
+ status: allowed ? "expired" : "cancelled",
306
+ detail: allowed ? "超过最晚开始时间。" : "计划已暂停、编辑或删除。",
307
+ });
308
+ return false;
309
+ }
310
+ return true;
311
+ }
312
+
313
+ finish(id: string, status: ScheduledRunStatus, detail?: string): void {
314
+ const run = this.getRun(id);
315
+ if (run) this.saveRun({ ...run, status, detail });
316
+ }
317
+
318
+ cancelPending(id: string, detail: string): void {
319
+ const rows = this.db
320
+ .prepare(
321
+ "SELECT value_json FROM scheduled_runs WHERE job_id = ? AND status IN ('queued','dispatching')",
322
+ )
323
+ .all(id) as JsonRow[];
324
+ for (const row of rows) {
325
+ const run = JSON.parse(row.value_json) as ScheduledRun;
326
+ this.saveRun({ ...run, status: "cancelled", detail });
327
+ this.db
328
+ .prepare("DELETE FROM queued_prompts WHERE prompt_id = ?")
329
+ .run(run.id);
330
+ }
331
+ }
332
+ }
@@ -0,0 +1,171 @@
1
+ import type { Logger } from "pino";
2
+ import type { StateStore } from "../state/StateStore.js";
3
+ import { latestScheduleTime, type ScheduledJob } from "./types.js";
4
+
5
+ interface SchedulerOptions {
6
+ store: StateStore;
7
+ logger: Pick<Logger, "warn">;
8
+ canDispatch(): boolean;
9
+ ownerId(): string | undefined;
10
+ drain(localSessionId: string): Promise<void>;
11
+ notify(job: ScheduledJob, text: string): Promise<void>;
12
+ now?: () => number;
13
+ }
14
+
15
+ export class TaskScheduler {
16
+ private timer?: ReturnType<typeof setInterval>;
17
+ private work?: Promise<void>;
18
+ private stopped = true;
19
+ private startedAt = 0;
20
+ private readonly now: () => number;
21
+
22
+ constructor(private readonly options: SchedulerOptions) {
23
+ this.now = options.now ?? Date.now;
24
+ }
25
+
26
+ async start(): Promise<void> {
27
+ if (!this.stopped) return;
28
+ this.stopped = false;
29
+ this.startedAt = this.now();
30
+ this.work = this.tick(true);
31
+ try {
32
+ await this.work;
33
+ } finally {
34
+ this.work = undefined;
35
+ }
36
+ if (this.stopped) return;
37
+ this.timer = setInterval(() => {
38
+ if (this.work) return;
39
+ this.work = this.tick()
40
+ .catch((error: unknown) => {
41
+ this.options.logger.warn({ error }, "Scheduled task polling failed.");
42
+ })
43
+ .finally(() => {
44
+ this.work = undefined;
45
+ });
46
+ }, 5_000);
47
+ this.timer.unref();
48
+ }
49
+
50
+ async stop(): Promise<void> {
51
+ this.stopped = true;
52
+ clearInterval(this.timer);
53
+ await this.work;
54
+ }
55
+
56
+ async tick(startup = false): Promise<void> {
57
+ const { store } = this.options;
58
+ const now = this.now();
59
+ const drain = new Set<string>();
60
+ for (const run of store.schedules.pendingRuns()) {
61
+ const job = store.schedules.get(run.jobId);
62
+ if (!job) continue;
63
+ const attempt = store.getTurnAttempt(run.id);
64
+ if (
65
+ run.status !== "unknown" &&
66
+ attempt &&
67
+ ["completed", "failed", "cancelled", "interrupted"].includes(
68
+ attempt.status,
69
+ )
70
+ ) {
71
+ const status =
72
+ attempt.status === "interrupted"
73
+ ? "unknown"
74
+ : (attempt.status as "completed" | "failed" | "cancelled");
75
+ store.schedules.saveRun({ ...run, turnId: attempt.turnId, status });
76
+ } else if (
77
+ startup &&
78
+ ["dispatching", "submitting"].includes(run.status) &&
79
+ !attempt?.turnId
80
+ ) {
81
+ store.schedules.finish(
82
+ run.id,
83
+ "unknown",
84
+ "重启后无法确认是否已提交,未自动重发。请核实执行记录。",
85
+ );
86
+ } else if (run.status === "queued") {
87
+ if (!store.schedules.canSubmit(run.id, now)) {
88
+ store.cancelQueuedPrompt(run.id, job.localSessionId);
89
+ await this.notice(
90
+ job,
91
+ store.schedules.getRun(run.id)?.detail ?? "本次运行已取消。",
92
+ );
93
+ } else if (!store.hasQueuedPrompt(run.id)) {
94
+ store.schedules.finish(run.id, "cancelled", "排队任务已取消。");
95
+ } else drain.add(job.localSessionId);
96
+ }
97
+ const session = store.getSession(job.localSessionId);
98
+ if (
99
+ job.status === "enabled" &&
100
+ (!session ||
101
+ session.status === "closed" ||
102
+ job.ownerId !== this.options.ownerId())
103
+ ) {
104
+ const changed = store.schedules.change(
105
+ job.id,
106
+ job.revision,
107
+ "pause",
108
+ now,
109
+ );
110
+ await this.notice(
111
+ changed,
112
+ "目标任务已关闭或所有者已变化,定时计划已暂停。",
113
+ );
114
+ }
115
+ }
116
+ if (!this.options.canDispatch() || (this.stopped && !startup)) return;
117
+ for (const job of store.schedules.due(now)) {
118
+ if (!this.options.canDispatch()) break;
119
+ const session = store.getSession(job.localSessionId);
120
+ if (
121
+ !session ||
122
+ session.status === "closed" ||
123
+ job.ownerId !== this.options.ownerId()
124
+ ) {
125
+ const changed = store.schedules.change(
126
+ job.id,
127
+ job.revision,
128
+ "pause",
129
+ now,
130
+ );
131
+ await this.notice(
132
+ changed,
133
+ "目标任务已关闭或所有者已变化,定时计划已暂停。",
134
+ );
135
+ continue;
136
+ }
137
+ const missed =
138
+ startup ||
139
+ job.nextRunAt! <= this.startedAt ||
140
+ now - job.nextRunAt! > 60_000;
141
+ const scheduledFor = missed
142
+ ? latestScheduleTime(job.spec, now)
143
+ : job.nextRunAt!;
144
+ const skip =
145
+ missed &&
146
+ (job.spec.catchUpMinutes === 0 ||
147
+ now - scheduledFor > job.spec.catchUpMinutes * 60_000)
148
+ ? "停服、休眠或调度延迟,已跳过错过的计划。"
149
+ : undefined;
150
+ const run = store.schedules.dispatch(job, scheduledFor, now, { skip });
151
+ if (run?.status === "queued") drain.add(job.localSessionId);
152
+ else if (run && skip)
153
+ await this.notice(store.schedules.get(job.id)!, run.detail!);
154
+ }
155
+ for (const sessionId of drain) {
156
+ if (!this.options.canDispatch()) break;
157
+ await this.options.drain(sessionId);
158
+ }
159
+ }
160
+
161
+ private async notice(job: ScheduledJob, text: string): Promise<void> {
162
+ try {
163
+ await this.options.notify(job, `定时任务「${job.spec.name}」:${text}`);
164
+ } catch (error) {
165
+ this.options.logger.warn(
166
+ { error, scheduleId: job.id },
167
+ "Failed to deliver scheduled task notice.",
168
+ );
169
+ }
170
+ }
171
+ }
@@ -0,0 +1,151 @@
1
+ import { z } from "zod";
2
+ import { CronExpressionParser } from "cron-parser";
3
+
4
+ export const scheduleInputSchema = z
5
+ .object({
6
+ name: z.string().trim().min(1).max(120).default("定时任务"),
7
+ prompt: z.string().trim().min(1).max(1_000),
8
+ cron: z.string().trim().min(1).max(120).optional(),
9
+ at: z.string().trim().datetime({ offset: true }).optional(),
10
+ timeZone: z
11
+ .string()
12
+ .trim()
13
+ .default(Intl.DateTimeFormat().resolvedOptions().timeZone),
14
+ maxDelayMinutes: z.number().int().min(1).max(10_080).default(60),
15
+ catchUpMinutes: z.number().int().min(0).max(10_080).default(0),
16
+ })
17
+ .strict()
18
+ .superRefine((value, context) => {
19
+ if (Boolean(value.cron) === Boolean(value.at)) {
20
+ context.addIssue({
21
+ code: "custom",
22
+ message: "请且仅指定 Cron 或带时区的 ISO 执行时间。",
23
+ });
24
+ }
25
+ try {
26
+ new Intl.DateTimeFormat("en", { timeZone: value.timeZone }).format();
27
+ if (value.cron) {
28
+ if (value.cron.split(/\s+/).length !== 5)
29
+ throw new Error("Cron 使用五段格式,最小间隔一分钟。");
30
+ CronExpressionParser.parse(value.cron, { tz: value.timeZone }).next();
31
+ }
32
+ } catch (error) {
33
+ context.addIssue({
34
+ code: "custom",
35
+ message: error instanceof Error ? error.message : "时间规则无效。",
36
+ });
37
+ }
38
+ });
39
+
40
+ export type ScheduleInput = z.input<typeof scheduleInputSchema>;
41
+ export type ScheduleSpec = z.output<typeof scheduleInputSchema>;
42
+ export type ScheduleOperation =
43
+ | "list"
44
+ | "add"
45
+ | "edit"
46
+ | "show"
47
+ | "history"
48
+ | "pause"
49
+ | "resume"
50
+ | "run"
51
+ | "delete";
52
+ export interface ScheduleCommand {
53
+ operation: ScheduleOperation;
54
+ id?: string;
55
+ input?: ScheduleInput;
56
+ page?: number;
57
+ }
58
+ export const scheduleCommandSchema = z
59
+ .object({
60
+ operation: z.enum([
61
+ "list",
62
+ "add",
63
+ "edit",
64
+ "show",
65
+ "history",
66
+ "pause",
67
+ "resume",
68
+ "run",
69
+ "delete",
70
+ ]),
71
+ id: z.string().min(1).max(100).optional(),
72
+ input: scheduleInputSchema.optional(),
73
+ page: z.number().int().min(0).max(10_000).optional(),
74
+ })
75
+ .strict();
76
+ export interface ScheduledJob {
77
+ id: string;
78
+ revision: number;
79
+ status: "draft" | "enabled" | "paused" | "completed" | "deleted";
80
+ localSessionId: string;
81
+ contextKey: string;
82
+ replyMessageId?: string;
83
+ ownerId?: string;
84
+ spec: ScheduleSpec;
85
+ nextRunAt?: number;
86
+ createdAt: number;
87
+ updatedAt: number;
88
+ notice?: string;
89
+ }
90
+ export type ScheduledRunStatus =
91
+ | "queued"
92
+ | "dispatching"
93
+ | "submitting"
94
+ | "running"
95
+ | "completed"
96
+ | "failed"
97
+ | "cancelled"
98
+ | "expired"
99
+ | "skipped"
100
+ | "unknown";
101
+ export interface ScheduledRun {
102
+ id: string;
103
+ jobId: string;
104
+ scheduledFor: number;
105
+ deadline: number;
106
+ status: ScheduledRunStatus;
107
+ manual: boolean;
108
+ startedAt?: number;
109
+ turnId?: string;
110
+ detail?: string;
111
+ }
112
+
113
+ export function nextScheduleTime(
114
+ spec: ScheduleSpec,
115
+ after: number,
116
+ ): number | undefined {
117
+ if (spec.at) {
118
+ const time = Date.parse(spec.at);
119
+ return time > after ? time : undefined;
120
+ }
121
+ return CronExpressionParser.parse(spec.cron!, {
122
+ currentDate: new Date(after),
123
+ tz: spec.timeZone,
124
+ })
125
+ .next()
126
+ .getTime();
127
+ }
128
+
129
+ export function latestScheduleTime(spec: ScheduleSpec, now: number): number {
130
+ if (spec.at) return Date.parse(spec.at);
131
+ return CronExpressionParser.parse(spec.cron!, {
132
+ currentDate: new Date(now + 1),
133
+ tz: spec.timeZone,
134
+ })
135
+ .prev()
136
+ .getTime();
137
+ }
138
+
139
+ export function scheduleTime(
140
+ time: number | undefined,
141
+ timeZone: string,
142
+ ): string {
143
+ return time === undefined
144
+ ? "—"
145
+ : new Intl.DateTimeFormat("zh-CN", {
146
+ timeZone,
147
+ dateStyle: "short",
148
+ timeStyle: "medium",
149
+ hour12: false,
150
+ }).format(time);
151
+ }