@operad-io/bot 0.1.1 → 0.3.0

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.
@@ -0,0 +1,1184 @@
1
+ /**
2
+ * Scheduled prompts of a bot. The bot plugin is its own source: it reads the
3
+ * entries from its bot objects, fires the latest planned minute when it is due,
4
+ * opens a chat with the prompt, and when the reply ends it records the result
5
+ * and runs the same notify command a wait uses.
6
+ *
7
+ * An entry lives on the bot object (`scheduled`), not in `config.json`: a
8
+ * client's change is the owner's own edit and applies at once, and `serve` needs
9
+ * no reload. The schedule is a five-field cron expression in the machine's local
10
+ * time zone, with the catch-up rule of the cron source (ADR 0032 D11).
11
+ */
12
+
13
+ import { messageOf } from "@operad-io/engine";
14
+ import { CHAT_TYPE, chatData, sendMessage } from "@operad-io/chat";
15
+ import { ChatWatches } from "./chat-watch.ts";
16
+ import {
17
+ cronMatches,
18
+ cronMinutesBetween,
19
+ isRecord,
20
+ latestCronMinute,
21
+ minuteStart,
22
+ NOTIFY_TIMEOUT_MS,
23
+ objectLink,
24
+ parseCron,
25
+ readConfig,
26
+ type ActionArgsSchema,
27
+ type ActionTypeDefinition,
28
+ type JsonValue,
29
+ type ObjectStore,
30
+ type PluginBaseContext,
31
+ type RunControl,
32
+ type SourceContext,
33
+ type SourceHandle,
34
+ type StoredObject,
35
+ } from "@operad-io/engine";
36
+ import { runLine } from "@operad-io/engine/platform";
37
+ import { BOT_TYPE, BotError } from "./bot.ts";
38
+ import { followUps, removeFollowUp, withBotLock, type FollowUp } from "./follow-up.ts";
39
+ import { SETUP_DEV_INSTRUCTION } from "./setup-dev.ts";
40
+ import { SETUP_GIT_INSTRUCTION } from "./setup-git.ts";
41
+ import { SETUP_INSTRUCTION } from "./setup.ts";
42
+
43
+ /** The source's name for a scheduled message; a message from it is a background run. */
44
+ export const SCHEDULE_SOURCE = "bot";
45
+
46
+ /** How often the source checks the clock. */
47
+ const CHECK_INTERVAL_MS = 1_000;
48
+ /** A gap much larger than the check interval means the machine slept or the clock jumped. */
49
+ const WAKE_GAP_MS = 60_000;
50
+ /** How far back a catch-up looks. */
51
+ const CATCH_UP_DAYS = 7;
52
+ const DAY_MS = 24 * 60 * 60_000;
53
+
54
+ /** What the last firing was and how it ended. */
55
+ export interface ScheduledLast {
56
+ /** The planned minute, in epoch milliseconds. */
57
+ readonly plannedAt: number;
58
+ /** When the source fired it; absent when this is only a baseline. */
59
+ readonly firedAt?: number | undefined;
60
+ /** The schedule this planned time belongs to. */
61
+ readonly schedule: string;
62
+ /** True when the firing caught up after earlier planned minutes were skipped. */
63
+ readonly skippedEarlier?: boolean | undefined;
64
+ /** The chat the firing opened. */
65
+ readonly chatId?: string | undefined;
66
+ /** A short summary of the reply, or why it could not start. */
67
+ readonly result?: string | undefined;
68
+ /** True once the notify command was run for `result`. */
69
+ readonly notified?: boolean | undefined;
70
+ /** True when a person ran the entry now: `firedAt` is then the run's time, and `plannedAt` is untouched. */
71
+ readonly manual?: boolean | undefined;
72
+ }
73
+
74
+ /** One finished firing kept for the next prompt. */
75
+ export interface ScheduledRecent {
76
+ /** The planned minute of the firing, in epoch milliseconds. */
77
+ readonly plannedAt: number;
78
+ readonly result: string;
79
+ }
80
+
81
+ /** How many finished results an entry keeps and its next prompt carries. */
82
+ export const SCHEDULE_RECENT_COUNT = 3;
83
+ /** The longest a kept result is in the next prompt. */
84
+ export const SCHEDULE_RECENT_MAX = 120;
85
+
86
+ /** The reply that means a firing has nothing to report. */
87
+ export const SCHEDULE_QUIET_MARKER = "NOTHING_TO_REPORT";
88
+ /** What a quiet firing records as its result. */
89
+ export const SCHEDULE_QUIET_RESULT = "Nothing to report.";
90
+
91
+ /** The line every scheduled prompt ends with: how to end quietly. */
92
+ export const SCHEDULE_PREAMBLE = `If there is nothing new to report, reply with exactly ${SCHEDULE_QUIET_MARKER} and nothing else; the person is then not notified. Otherwise reply as usual.`;
93
+
94
+ /** One scheduled prompt of a bot. */
95
+ export interface ScheduledPrompt {
96
+ readonly name: string;
97
+ /** A five-field cron expression in the machine's local time zone. */
98
+ readonly schedule: string;
99
+ readonly prompt: string;
100
+ readonly model?: string | undefined;
101
+ readonly effort?: string | undefined;
102
+ readonly paused: boolean;
103
+ readonly last?: ScheduledLast | undefined;
104
+ /** The last few finished results, oldest first. */
105
+ readonly recent?: readonly ScheduledRecent[] | undefined;
106
+ /** When a person asked to run it now, until the source starts that run. */
107
+ readonly runNow?: number | undefined;
108
+ }
109
+
110
+ /** The longest summary an entry keeps and a notification carries. */
111
+ export const SCHEDULE_SUMMARY_MAX = 300;
112
+
113
+ function text(value: unknown): string | undefined {
114
+ return typeof value === "string" && value.trim().length > 0 ? value : undefined;
115
+ }
116
+
117
+ function lastOf(value: unknown): ScheduledLast | undefined {
118
+ if (!isRecord(value)) return undefined;
119
+ if (typeof value.plannedAt !== "number" || !Number.isFinite(value.plannedAt)) return undefined;
120
+ if (typeof value.schedule !== "string") return undefined;
121
+ return {
122
+ plannedAt: value.plannedAt,
123
+ ...(typeof value.firedAt === "number" && Number.isFinite(value.firedAt)
124
+ ? { firedAt: value.firedAt }
125
+ : {}),
126
+ schedule: value.schedule,
127
+ ...(value.skippedEarlier === true ? { skippedEarlier: true } : {}),
128
+ ...(text(value.chatId) === undefined ? {} : { chatId: value.chatId as string }),
129
+ ...(text(value.result) === undefined ? {} : { result: value.result as string }),
130
+ ...(value.notified === true ? { notified: true } : {}),
131
+ ...(value.manual === true ? { manual: true } : {}),
132
+ };
133
+ }
134
+
135
+ /** One scheduled prompt from stored data, or undefined when it is unusable. */
136
+ export function scheduledPromptOf(value: unknown): ScheduledPrompt | undefined {
137
+ if (!isRecord(value)) return undefined;
138
+ const name = text(value.name);
139
+ const schedule = text(value.schedule);
140
+ const prompt = text(value.prompt);
141
+ if (name === undefined || schedule === undefined || prompt === undefined) return undefined;
142
+ const last = lastOf(value.last);
143
+ const recent: ScheduledRecent[] = [];
144
+ if (Array.isArray(value.recent)) {
145
+ for (const item of value.recent) {
146
+ if (!isRecord(item)) continue;
147
+ if (typeof item.plannedAt !== "number" || !Number.isFinite(item.plannedAt)) continue;
148
+ if (text(item.result) === undefined) continue;
149
+ recent.push({ plannedAt: item.plannedAt, result: item.result as string });
150
+ }
151
+ }
152
+ return {
153
+ name,
154
+ schedule,
155
+ prompt,
156
+ ...(text(value.model) === undefined ? {} : { model: value.model as string }),
157
+ ...(text(value.effort) === undefined ? {} : { effort: value.effort as string }),
158
+ paused: value.paused === true,
159
+ ...(last === undefined ? {} : { last }),
160
+ ...(recent.length === 0 ? {} : { recent: recent.slice(-SCHEDULE_RECENT_COUNT) }),
161
+ ...(typeof value.runNow === "number" && Number.isFinite(value.runNow) ? { runNow: value.runNow } : {}),
162
+ };
163
+ }
164
+
165
+ /** The scheduled prompts written on a bot object, skipping an unusable entry. */
166
+ export function scheduledPrompts(data: Readonly<Record<string, unknown>>): readonly ScheduledPrompt[] {
167
+ const raw = data.scheduled;
168
+ if (!Array.isArray(raw)) return [];
169
+ const found: ScheduledPrompt[] = [];
170
+ for (const value of raw) {
171
+ const entry = scheduledPromptOf(value);
172
+ if (entry !== undefined) found.push(entry);
173
+ }
174
+ return found;
175
+ }
176
+
177
+ /** What a chat's schedule command asks a person to decide. */
178
+ export interface ScheduleChange {
179
+ readonly action: "add" | "edit" | "remove";
180
+ /** The schedule in words, as the agent wrote it. */
181
+ readonly words?: string | undefined;
182
+ readonly before: ScheduledPrompt | null;
183
+ readonly after: ScheduledPrompt | null;
184
+ }
185
+
186
+ /** Reads the schedule change a proposal stores, or undefined when it is unusable. */
187
+ export function scheduleChangeOf(value: unknown): ScheduleChange | undefined {
188
+ if (!isRecord(value)) return undefined;
189
+ if (value.action !== "add" && value.action !== "edit" && value.action !== "remove") {
190
+ return undefined;
191
+ }
192
+ const before = value.before === null ? null : scheduledPromptOf(value.before);
193
+ const after = value.after === null ? null : scheduledPromptOf(value.after);
194
+ if (before === undefined || after === undefined) return undefined;
195
+ if (value.words !== undefined && typeof value.words !== "string") return undefined;
196
+ return {
197
+ action: value.action,
198
+ ...(value.words === undefined ? {} : { words: value.words }),
199
+ before,
200
+ after,
201
+ };
202
+ }
203
+
204
+ /** One entry as the bot object stores it. */
205
+ function stored(entry: ScheduledPrompt): Record<string, JsonValue> {
206
+ return {
207
+ name: entry.name,
208
+ schedule: entry.schedule,
209
+ prompt: entry.prompt,
210
+ ...(entry.model === undefined ? {} : { model: entry.model }),
211
+ ...(entry.effort === undefined ? {} : { effort: entry.effort }),
212
+ paused: entry.paused,
213
+ ...(entry.last === undefined ? {} : { last: entry.last as unknown as JsonValue }),
214
+ ...(entry.recent === undefined || entry.recent.length === 0
215
+ ? {}
216
+ : { recent: entry.recent as unknown as JsonValue }),
217
+ ...(entry.runNow === undefined ? {} : { runNow: entry.runNow }),
218
+ };
219
+ }
220
+
221
+ /** The name a client uses to choose an entry; unique within one bot. */
222
+ export function checkPromptName(name: string): string {
223
+ const trimmed = name.trim();
224
+ if (trimmed.length === 0) throw new BotError("a scheduled prompt needs a name");
225
+ if (trimmed.length > 120) throw new BotError("a scheduled prompt's name is at most 120 characters");
226
+ return trimmed;
227
+ }
228
+
229
+ /** A schedule as it is stored: trimmed, and checked as a five-field cron expression. */
230
+ export function checkSchedule(expression: string): string {
231
+ const trimmed = expression.trim();
232
+ parseCron(trimmed);
233
+ return trimmed;
234
+ }
235
+
236
+ /** The local date of a time, `YYYY-MM-DD`. */
237
+ export function localDate(time: number): string {
238
+ const date = new Date(time);
239
+ const pad = (value: number): string => String(value).padStart(2, "0");
240
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
241
+ }
242
+
243
+ /** The local time of a time, `YYYY-MM-DD HH:mm`. */
244
+ export function localStamp(time: number): string {
245
+ const date = new Date(time);
246
+ const pad = (value: number): string => String(value).padStart(2, "0");
247
+ return `${localDate(time)} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
248
+ }
249
+
250
+ /** How long a catch-up is late, in words a person reads. */
251
+ export function lateText(seconds: number): string {
252
+ if (seconds < 60) return `${seconds} seconds`;
253
+ const minutes = Math.floor(seconds / 60);
254
+ if (minutes < 60) return `${minutes} minute${minutes === 1 ? "" : "s"}`;
255
+ const hours = Math.floor(minutes / 60);
256
+ const rest = minutes % 60;
257
+ return `${hours} hour${hours === 1 ? "" : "s"}${rest === 0 ? "" : ` ${rest} minute${rest === 1 ? "" : "s"}`}`;
258
+ }
259
+
260
+ /** The one line a catch-up adds to the prompt. It is not added to an on-time run. */
261
+ export function latenessLine(scheduledAt: number, lateSecs: number): string {
262
+ return `Scheduled for ${localStamp(scheduledAt)}; this run is ${lateText(lateSecs)} late.`;
263
+ }
264
+
265
+ /** The result of a finished firing, cut to what the next prompt carries. */
266
+ function recentText(result: string): string {
267
+ return result.length <= SCHEDULE_RECENT_MAX
268
+ ? result
269
+ : `${result.slice(0, SCHEDULE_RECENT_MAX - 1)}…`;
270
+ }
271
+
272
+ /** True while the last firing's chat has started and its result is not yet recorded. */
273
+ function isReplying(last: ScheduledLast | undefined): boolean {
274
+ return last?.chatId !== undefined && last.result === undefined;
275
+ }
276
+
277
+ /**
278
+ * What a firing tells the agent beyond the person's own prompt: the earlier
279
+ * results of the same entry so it does not repeat them, the quiet-ending line,
280
+ * and for a catch-up the lateness line. The chat does not show it.
281
+ */
282
+ export function scheduledInstruction(entry: ScheduledPrompt): string {
283
+ // `last` is recorded when the firing starts, so it says what was planned and when it ran.
284
+ const last = entry.last;
285
+ const late =
286
+ last?.firedAt !== undefined &&
287
+ last.manual !== true &&
288
+ (last.plannedAt < minuteStart(last.firedAt) || last.skippedEarlier === true)
289
+ ? { scheduledAt: last.plannedAt, lateSecs: Math.floor((last.firedAt - last.plannedAt) / 1_000) }
290
+ : undefined;
291
+ const parts: string[] = [];
292
+ const recent = (entry.recent ?? []).slice(-SCHEDULE_RECENT_COUNT);
293
+ if (recent.length > 0) {
294
+ const lines = recent.map((item) => `- ${localStamp(item.plannedAt)}: ${recentText(item.result)}`);
295
+ parts.push(
296
+ `Earlier results of this scheduled prompt, oldest first; the person has already seen them, so do not repeat them:\n${lines.join("\n")}`,
297
+ );
298
+ }
299
+ parts.push(SCHEDULE_PREAMBLE);
300
+ if (late !== undefined) parts.push(latenessLine(late.scheduledAt, late.lateSecs));
301
+ return parts.join("\n\n");
302
+ }
303
+
304
+ /** The instruction of the firing of the named entry now recorded on a bot; undefined when it has none. */
305
+ export function scheduledInstructionFor(data: Readonly<Record<string, unknown>>, name: string): string | undefined {
306
+ const entry = scheduledPrompts(data).find((item) => item.name === name);
307
+ return entry === undefined ? undefined : scheduledInstruction(entry);
308
+ }
309
+
310
+ /** True when a reply is exactly the quiet marker. */
311
+ export function isQuietReply(message: string): boolean {
312
+ return message.trim() === SCHEDULE_QUIET_MARKER;
313
+ }
314
+
315
+ /** What a bot chat's first session starts with: a schedule it writes is a proposal. */
316
+ export const SCHEDULE_INSTRUCTION =
317
+ "To schedule something for me, propose it: call the operad `command` tool with plugin `bot`, verb `schedule`, action `add` (or `edit` or `remove`). Give the schedule both as a five-field cron expression and in words. Nothing takes effect until I approve it in Pending.";
318
+
319
+ /** The line telling the agent how to set a follow-up for itself in this chat (ADR 0030 D16). */
320
+ export function followUpInstruction(chat: string): string {
321
+ return `To look at something again later in this chat (chat ${chat}), set a follow-up: call the operad \`command\` tool with plugin \`bot\`, verb \`follow-up\`, args [\`${chat}\`, \`--at\`, <a time such as "2026-12-01 09:00" or "+2h">, \`--do\`, <one sentence of what to do>]. It takes effect at once; at most 5 not yet due per chat and at most 30 days ahead. Verb \`follow-ups\` with args [\`${chat}\`] lists them, and with \`--cancel\`, <id> cancels one. When it is due you are sent that sentence here.`;
322
+ }
323
+
324
+ /** The text and place a bot chat starts with. */
325
+ export function scheduledChatContext(chat: string): { readonly text: string; readonly where: string } {
326
+ const line = `${SCHEDULE_INSTRUCTION} ${followUpInstruction(chat)} ${SETUP_DEV_INSTRUCTION} ${SETUP_GIT_INSTRUCTION} ${SETUP_INSTRUCTION}`;
327
+ return { text: line, where: line };
328
+ }
329
+
330
+ /** The next planned minute after `now`, or null when none is within two years. */
331
+ export function nextRun(entry: ScheduledPrompt, now: number): number | null {
332
+ if (entry.paused) return null;
333
+ let schedule: ReturnType<typeof parseCron>;
334
+ try {
335
+ schedule = parseCron(entry.schedule);
336
+ } catch {
337
+ return null;
338
+ }
339
+ const limit = minuteStart(now) + 366 * 2 * DAY_MS;
340
+ let candidate = minuteStart(now) + 60_000;
341
+ while (candidate <= limit) {
342
+ if (cronMatches(schedule, new Date(candidate))) return candidate;
343
+ candidate += 60_000;
344
+ }
345
+ return null;
346
+ }
347
+
348
+ /** One scheduled prompt as a client reads it from a bot row, without parsing Markdown. */
349
+ export interface ScheduledPromptView {
350
+ readonly name: string;
351
+ readonly schedule: string;
352
+ readonly prompt: string;
353
+ readonly model: string | null;
354
+ readonly effort: string | null;
355
+ readonly paused: boolean;
356
+ /** The next planned minute as an ISO time; null when paused or none is within two years. */
357
+ readonly nextRun: string | null;
358
+ /** The last reply's summary, or why it could not start; null before the first firing. */
359
+ readonly lastResult: string | null;
360
+ /** The chat the last firing opened; null before the first firing. */
361
+ readonly lastChatId: string | null;
362
+ }
363
+
364
+ /** The structured entries a bot row gives a client. */
365
+ export function scheduledData(
366
+ entries: readonly ScheduledPrompt[],
367
+ now: number,
368
+ ): readonly ScheduledPromptView[] {
369
+ return entries.map((entry) => {
370
+ const next = nextRun(entry, now);
371
+ return {
372
+ name: entry.name,
373
+ schedule: entry.schedule,
374
+ prompt: entry.prompt,
375
+ model: entry.model ?? null,
376
+ effort: entry.effort ?? null,
377
+ paused: entry.paused,
378
+ nextRun: next === null ? null : new Date(next).toISOString(),
379
+ lastResult: entry.last?.result ?? null,
380
+ lastChatId: entry.last?.chatId ?? null,
381
+ };
382
+ });
383
+ }
384
+
385
+ /** A short, one-line summary of a reply. */
386
+ export function replySummary(message: string): string {
387
+ const oneLine = message.replace(/\s+/g, " ").trim();
388
+ if (oneLine.length === 0) return "The reply was empty.";
389
+ return oneLine.length <= SCHEDULE_SUMMARY_MAX
390
+ ? oneLine
391
+ : `${oneLine.slice(0, SCHEDULE_SUMMARY_MAX - 1)}…`;
392
+ }
393
+
394
+ /** What a notification command is given. */
395
+ export interface ScheduleNotice {
396
+ readonly chatId: string;
397
+ readonly title: string;
398
+ readonly summary: string;
399
+ }
400
+
401
+ /** Runs the configured notify command for a finished scheduled reply. */
402
+ export async function notifyScheduledReply(
403
+ home: string,
404
+ notice: ScheduleNotice,
405
+ ): Promise<void> {
406
+ const config = await readConfig(home);
407
+ const command = config.notify.command;
408
+ if (command === null) return;
409
+ const outcome = await runLine({
410
+ line: command,
411
+ cwd: home,
412
+ env: {
413
+ OPERAD_ID: `${CHAT_TYPE}:${notice.chatId}`,
414
+ OPERAD_TITLE: notice.title,
415
+ OPERAD_REASON: notice.summary,
416
+ OPERAD_LINK: objectLink(CHAT_TYPE, notice.chatId),
417
+ },
418
+ timeoutMs: NOTIFY_TIMEOUT_MS,
419
+ signal: new AbortController().signal,
420
+ });
421
+ if (outcome.exitCode !== 0 || outcome.timedOut || outcome.spawnError !== undefined) {
422
+ throw new Error(
423
+ `the notify command ${outcome.timedOut ? "timed out" : `exited ${outcome.exitCode ?? "without a code"}`}`,
424
+ );
425
+ }
426
+ }
427
+
428
+ /** Reads a bot object, or says why it cannot be used. */
429
+ async function botObject(store: ObjectStore, bot: string): Promise<StoredObject> {
430
+ const object = await store.get(BOT_TYPE, bot);
431
+ if (object === undefined) throw new BotError(`there is no bot "${bot}"`);
432
+ if (object.data.removed === true) throw new BotError(`bot ${bot} is no longer in the settings`);
433
+ return object;
434
+ }
435
+
436
+ /** Replaces one entry on the bot object, leaving the others and the bot's settings alone. */
437
+ async function replaceEntry(
438
+ store: ObjectStore,
439
+ bot: string,
440
+ name: string,
441
+ change: (entry: ScheduledPrompt) => ScheduledPrompt | undefined,
442
+ cause: string,
443
+ ): Promise<ScheduledPrompt | undefined> {
444
+ return withBotLock(store, bot, async () => {
445
+ const object = await botObject(store, bot);
446
+ const entries = scheduledPrompts(object.data);
447
+ let changed: ScheduledPrompt | undefined;
448
+ const next: ScheduledPrompt[] = [];
449
+ for (const entry of entries) {
450
+ if (entry.name !== name) {
451
+ next.push(entry);
452
+ continue;
453
+ }
454
+ changed = change(entry);
455
+ if (changed !== undefined) next.push(changed);
456
+ }
457
+ if (changed === undefined) return undefined;
458
+ await store.put(
459
+ BOT_TYPE,
460
+ bot,
461
+ { ...object.data, scheduled: next.map(stored) as unknown as JsonValue[] },
462
+ cause,
463
+ );
464
+ return changed;
465
+ });
466
+ }
467
+
468
+ /** Removes one entry from the bot object. */
469
+ async function removeEntry(store: ObjectStore, bot: string, name: string): Promise<boolean> {
470
+ return withBotLock(store, bot, async () => {
471
+ const object = await botObject(store, bot);
472
+ const entries = scheduledPrompts(object.data);
473
+ const next = entries.filter((entry) => entry.name !== name);
474
+ if (next.length === entries.length) return false;
475
+ await store.put(
476
+ BOT_TYPE,
477
+ bot,
478
+ { ...object.data, scheduled: next.map(stored) as unknown as JsonValue[] },
479
+ "action:bot/schedule-remove",
480
+ );
481
+ return true;
482
+ });
483
+ }
484
+
485
+ /** The current entry with the fields the proposal changed, from `before` to `after`, applied. */
486
+ function mergedEdit(
487
+ current: ScheduledPrompt,
488
+ before: ScheduledPrompt,
489
+ after: ScheduledPrompt,
490
+ ): ScheduledPrompt {
491
+ const schedule = after.schedule === before.schedule ? current.schedule : after.schedule;
492
+ const model = after.model === before.model ? current.model : after.model;
493
+ const effort = after.effort === before.effort ? current.effort : after.effort;
494
+ return {
495
+ ...current,
496
+ name: after.name,
497
+ schedule,
498
+ prompt: after.prompt === before.prompt ? current.prompt : after.prompt,
499
+ ...(model === undefined ? { model: undefined } : { model }),
500
+ ...(effort === undefined ? { effort: undefined } : { effort }),
501
+ };
502
+ }
503
+
504
+ /** Applies a schedule proposal: the add, edit or remove the person approved. */
505
+ export async function applyScheduleChange(
506
+ store: ObjectStore,
507
+ bot: string,
508
+ change: ScheduleChange,
509
+ ): Promise<void> {
510
+ if (change.action === "add") {
511
+ if (change.after === null) throw new BotError("the proposal has no scheduled prompt to add");
512
+ await addEntry(store, bot, change.after);
513
+ return;
514
+ }
515
+ if (change.action === "edit") {
516
+ const before = change.before;
517
+ const after = change.after;
518
+ if (before === null || after === null) {
519
+ throw new BotError("the proposal has no scheduled prompt to change");
520
+ }
521
+ const changed = await replaceEntry(
522
+ store,
523
+ bot,
524
+ before.name,
525
+ // Only what the proposal changed is applied: the pause state, last run
526
+ // and any edit made since the proposal stay as they are now.
527
+ (current) => mergedEdit(current, before, after),
528
+ "action:bot/schedule-edit",
529
+ );
530
+ if (changed === undefined) {
531
+ throw new BotError(`bot ${bot} has no scheduled prompt "${before.name}"`);
532
+ }
533
+ return;
534
+ }
535
+ if (change.before === null) {
536
+ throw new BotError("the proposal has no scheduled prompt to remove");
537
+ }
538
+ if (!(await removeEntry(store, bot, change.before.name))) {
539
+ throw new BotError(`bot ${bot} has no scheduled prompt "${change.before.name}"`);
540
+ }
541
+ }
542
+
543
+ /** Adds one entry to the bot object. */
544
+ async function addEntry(
545
+ store: ObjectStore,
546
+ bot: string,
547
+ entry: ScheduledPrompt,
548
+ ): Promise<ScheduledPrompt> {
549
+ return withBotLock(store, bot, async () => {
550
+ const object = await botObject(store, bot);
551
+ const entries = scheduledPrompts(object.data);
552
+ if (entries.some((item) => item.name === entry.name)) {
553
+ throw new BotError(`bot ${bot} already has a scheduled prompt "${entry.name}"`);
554
+ }
555
+ await store.put(
556
+ BOT_TYPE,
557
+ bot,
558
+ { ...object.data, scheduled: [...entries, entry].map(stored) as unknown as JsonValue[] },
559
+ "action:bot/schedule-add",
560
+ );
561
+ return entry;
562
+ });
563
+ }
564
+
565
+ function entryArgs(required: boolean): ActionTypeDefinition["args"] {
566
+ return {
567
+ type: "object",
568
+ properties: {
569
+ name: {
570
+ type: "string",
571
+ minLength: 1,
572
+ maxLength: 120,
573
+ ...(required ? {} : { description: "The scheduled prompt to change." }),
574
+ },
575
+ schedule: {
576
+ type: "string",
577
+ minLength: 1,
578
+ description: "A five-field cron schedule in the machine's local time zone, such as `0 8 * * *`.",
579
+ },
580
+ prompt: {
581
+ type: "string",
582
+ role: "note",
583
+ minLength: 1,
584
+ description: "The first message of the new chat.",
585
+ },
586
+ model: {
587
+ type: "string",
588
+ description: "The model the new chat uses; the bot's model when left out. An empty value clears it.",
589
+ },
590
+ effort: {
591
+ type: "string",
592
+ description: "The effort the new chat uses; the bot's effort when left out. An empty value clears it.",
593
+ },
594
+ },
595
+ ...(required ? { required: ["name", "schedule", "prompt"] } : { required: ["name"] }),
596
+ additionalProperties: false,
597
+ };
598
+ }
599
+
600
+ function nameArg(): ActionTypeDefinition["args"] {
601
+ return {
602
+ type: "object",
603
+ properties: {
604
+ name: { type: "string", minLength: 1, description: "The scheduled prompt's name." },
605
+ },
606
+ required: ["name"],
607
+ additionalProperties: false,
608
+ };
609
+ }
610
+
611
+ /** The actions a client uses to manage a bot's scheduled prompts. */
612
+ export const scheduleActions: readonly ActionTypeDefinition[] = [
613
+ {
614
+ name: "schedule-add",
615
+ on: BOT_TYPE,
616
+ args: {
617
+ ...(entryArgs(true) as ActionArgsSchema),
618
+ properties: {
619
+ ...((entryArgs(true) as ActionArgsSchema).properties ?? {}),
620
+ paused: {
621
+ type: "boolean",
622
+ default: false,
623
+ description: "Start paused; it does not fire until resumed.",
624
+ },
625
+ },
626
+ },
627
+ when: (state) => state.removed !== true,
628
+ why: (object) =>
629
+ object.data.removed === true ? `bot ${object.id} is no longer in the settings` : undefined,
630
+ async run(ctx, args) {
631
+ const input = args as {
632
+ readonly name: string;
633
+ readonly schedule: string;
634
+ readonly prompt: string;
635
+ readonly model?: string;
636
+ readonly effort?: string;
637
+ readonly paused?: boolean;
638
+ };
639
+ const entry: ScheduledPrompt = {
640
+ name: checkPromptName(input.name),
641
+ schedule: checkSchedule(input.schedule),
642
+ prompt: input.prompt.trim(),
643
+ ...(text(input.model) === undefined ? {} : { model: input.model as string }),
644
+ ...(text(input.effort) === undefined ? {} : { effort: input.effort as string }),
645
+ paused: input.paused === true,
646
+ };
647
+ if (entry.prompt.length === 0) throw new BotError("a scheduled prompt needs a prompt");
648
+ await addEntry(ctx.store, ctx.object.id, entry);
649
+ return `scheduled prompt "${entry.name}" for bot ${ctx.object.id}`;
650
+ },
651
+ },
652
+ {
653
+ name: "schedule-edit",
654
+ on: BOT_TYPE,
655
+ args: entryArgs(false),
656
+ when: (state) => state.removed !== true,
657
+ why: (object) =>
658
+ object.data.removed === true ? `bot ${object.id} is no longer in the settings` : undefined,
659
+ async run(ctx, args) {
660
+ const input = args as {
661
+ readonly name: string;
662
+ readonly schedule?: string;
663
+ readonly prompt?: string;
664
+ readonly model?: string;
665
+ readonly effort?: string;
666
+ };
667
+ const name = checkPromptName(input.name);
668
+ const changed = await replaceEntry(
669
+ ctx.store,
670
+ ctx.object.id,
671
+ name,
672
+ (entry) => {
673
+ const schedule = input.schedule === undefined ? entry.schedule : checkSchedule(input.schedule);
674
+ const prompt = input.prompt === undefined ? entry.prompt : input.prompt.trim();
675
+ if (prompt.length === 0) throw new BotError("a scheduled prompt needs a prompt");
676
+ const model = input.model === undefined ? entry.model : text(input.model);
677
+ const effort = input.effort === undefined ? entry.effort : text(input.effort);
678
+ return {
679
+ ...entry,
680
+ schedule,
681
+ prompt,
682
+ // An empty value clears the field; leaving it out keeps the old one.
683
+ ...(model === undefined ? { model: undefined } : { model }),
684
+ ...(effort === undefined ? { effort: undefined } : { effort }),
685
+ // A changed schedule keeps `last`: the poll sees its schedule is not the
686
+ // entry's, starts from a new baseline and keeps the chat of a firing
687
+ // that still awaits its notification, so no missed time is caught up.
688
+ };
689
+ },
690
+ "action:bot/schedule-edit",
691
+ );
692
+ if (changed === undefined) throw new BotError(`bot ${ctx.object.id} has no scheduled prompt "${name}"`);
693
+ return `edited scheduled prompt "${name}" for bot ${ctx.object.id}`;
694
+ },
695
+ },
696
+ {
697
+ name: "schedule-pause",
698
+ on: BOT_TYPE,
699
+ args: nameArg(),
700
+ when: (state) => state.removed !== true,
701
+ why: (object) =>
702
+ object.data.removed === true ? `bot ${object.id} is no longer in the settings` : undefined,
703
+ async run(ctx, args) {
704
+ const name = checkPromptName((args as { readonly name: string }).name);
705
+ const changed = await replaceEntry(
706
+ ctx.store,
707
+ ctx.object.id,
708
+ name,
709
+ (entry) => (entry.paused ? undefined : { ...entry, paused: true }),
710
+ "action:bot/schedule-pause",
711
+ );
712
+ if (changed === undefined) return `scheduled prompt "${name}" is already paused`;
713
+ return `paused scheduled prompt "${name}" for bot ${ctx.object.id}`;
714
+ },
715
+ },
716
+ {
717
+ name: "schedule-resume",
718
+ on: BOT_TYPE,
719
+ args: nameArg(),
720
+ when: (state) => state.removed !== true,
721
+ why: (object) =>
722
+ object.data.removed === true ? `bot ${object.id} is no longer in the settings` : undefined,
723
+ async run(ctx, args) {
724
+ const name = checkPromptName((args as { readonly name: string }).name);
725
+ const changed = await replaceEntry(
726
+ ctx.store,
727
+ ctx.object.id,
728
+ name,
729
+ (entry) => (entry.paused ? { ...entry, paused: false } : undefined),
730
+ "action:bot/schedule-resume",
731
+ );
732
+ if (changed === undefined) return `scheduled prompt "${name}" is already running`;
733
+ return `resumed scheduled prompt "${name}" for bot ${ctx.object.id}`;
734
+ },
735
+ },
736
+ {
737
+ name: "schedule-run-now",
738
+ on: BOT_TYPE,
739
+ args: nameArg(),
740
+ when: (state) => state.removed !== true,
741
+ why: (object) =>
742
+ object.data.removed === true ? `bot ${object.id} is no longer in the settings` : undefined,
743
+ async run(ctx, args) {
744
+ const name = checkPromptName((args as { readonly name: string }).name);
745
+ const current = scheduledPrompts(ctx.object.data).find((entry) => entry.name === name);
746
+ if (current !== undefined && isReplying(current.last)) {
747
+ throw new BotError(
748
+ `scheduled prompt "${name}" of bot ${ctx.object.id} is still replying to its previous firing (chat ${current.last?.chatId ?? ""}); run it now after that reply ends`,
749
+ );
750
+ }
751
+ const changed = await replaceEntry(
752
+ ctx.store,
753
+ ctx.object.id,
754
+ name,
755
+ (entry) => ({ ...entry, runNow: entry.runNow ?? Date.now() }),
756
+ "action:bot/schedule-run-now",
757
+ );
758
+ if (changed === undefined) throw new BotError(`bot ${ctx.object.id} has no scheduled prompt "${name}"`);
759
+ return `running scheduled prompt "${name}" of bot ${ctx.object.id} now; its next timed run is unchanged`;
760
+ },
761
+ },
762
+ {
763
+ name: "schedule-remove",
764
+ on: BOT_TYPE,
765
+ args: nameArg(),
766
+ when: (state) => state.removed !== true,
767
+ why: (object) =>
768
+ object.data.removed === true ? `bot ${object.id} is no longer in the settings` : undefined,
769
+ async run(ctx, args) {
770
+ const name = checkPromptName((args as { readonly name: string }).name);
771
+ if (!(await removeEntry(ctx.store, ctx.object.id, name))) {
772
+ throw new BotError(`bot ${ctx.object.id} has no scheduled prompt "${name}"`);
773
+ }
774
+ return `removed scheduled prompt "${name}" from bot ${ctx.object.id}`;
775
+ },
776
+ },
777
+ ];
778
+
779
+ /** A value shown literally in Markdown: a code span that survives a backtick inside it. */
780
+ export function markdownCode(value: string): string {
781
+ const longest = Math.max(0, ...[...value.matchAll(/`+/g)].map((run) => run[0].length));
782
+ const fence = "`".repeat(longest + 1);
783
+ const pad = value.startsWith("`") || value.endsWith("`") ? " " : "";
784
+ return `${fence}${pad}${value}${pad}${fence}`;
785
+ }
786
+
787
+ /** A user's text shown as text in Markdown: the characters that format are escaped. */
788
+ export function markdownText(value: string): string {
789
+ return value.replace(/([\\`*_{}\[\]<>#|~!])/g, "\\$1").replace(/\r?\n/g, " ");
790
+ }
791
+
792
+ /** The lines a bot page shows for its scheduled prompts. */
793
+ export function scheduledMarkdown(entries: readonly ScheduledPrompt[], now: number): string[] {
794
+ if (entries.length === 0) return ["Scheduled: none."];
795
+ const lines = ["Scheduled:"];
796
+ for (const entry of entries) {
797
+ const next = nextRun(entry, now);
798
+ const state = entry.paused ? " (paused)" : next === null ? "" : `, next ${localStamp(next)}`;
799
+ const last = entry.last;
800
+ const ended =
801
+ last?.result === undefined
802
+ ? ""
803
+ : `; last ${last.chatId === undefined ? "" : `chat ${last.chatId}: `}${markdownText(last.result)}`;
804
+ lines.push(`- ${markdownText(entry.name)} (${markdownCode(entry.schedule)}${state})${ended}`);
805
+ }
806
+ return lines;
807
+ }
808
+
809
+ interface ScheduledSource {
810
+ readonly store: ObjectStore;
811
+ readonly home: string;
812
+ readonly settings: Readonly<Record<string, JsonValue>>;
813
+ readonly clock: () => number;
814
+ readonly logger: PluginBaseContext["logger"];
815
+ readonly client: SourceContext["client"];
816
+ readonly runs?: RunControl | undefined;
817
+ /** What a follow-up needs to put its message in the chat; without them none is sent. */
818
+ readonly facts?: SourceContext["facts"] | undefined;
819
+ readonly emit?: SourceContext["emit"] | undefined;
820
+ }
821
+
822
+ /** The bot's own source for scheduled prompts. */
823
+ export class BotScheduleSource {
824
+ private readonly ctx: ScheduledSource;
825
+ private readonly notify: (notice: ScheduleNotice) => Promise<void>;
826
+ private readonly chatWatches: ChatWatches;
827
+ private timer: ReturnType<typeof setInterval> | undefined;
828
+ private stopped = false;
829
+ private busy = false;
830
+ private lastCheck: number | undefined;
831
+
832
+ constructor(
833
+ ctx: ScheduledSource,
834
+ options: { readonly notify?: ((notice: ScheduleNotice) => Promise<void>) | undefined } = {},
835
+ ) {
836
+ this.ctx = ctx;
837
+ this.notify = options.notify ?? ((notice) => notifyScheduledReply(ctx.home, notice));
838
+ this.chatWatches = new ChatWatches(ctx.logger, ctx.store, ctx.runs);
839
+ }
840
+
841
+ /** Waits for the checks that are running now; a test calls this after a reply. */
842
+ async settled(): Promise<void> {
843
+ await this.chatWatches.settled();
844
+ }
845
+
846
+ /** Emits at most one tick per entry, for the latest due or missed minute. */
847
+ async poll(): Promise<void> {
848
+ if (this.stopped || this.busy) return;
849
+ this.busy = true;
850
+ try {
851
+ const now = this.ctx.clock();
852
+ const previous = this.lastCheck;
853
+ this.lastCheck = now;
854
+ const catchUp = previous === undefined || now - previous > WAKE_GAP_MS;
855
+ const objects = await this.bots();
856
+ for (const object of objects) {
857
+ if (object.data.removed === true) continue;
858
+ const bot = object.id;
859
+ for (const entry of scheduledPrompts(object.data)) {
860
+ if (entry.runNow !== undefined) {
861
+ // The entry read here is stale after this; the next check handles its timed run.
862
+ await this.runNow(bot, entry, now);
863
+ continue;
864
+ }
865
+ await this.one(bot, entry, now, catchUp);
866
+ }
867
+ for (const followUp of followUps(object.data)) {
868
+ if (followUp.at <= now) await this.followUp(bot, followUp, now);
869
+ }
870
+ }
871
+ } finally {
872
+ this.busy = false;
873
+ }
874
+ }
875
+
876
+ /**
877
+ * Sends a due follow-up into its chat (ADR 0030 D16). The entry is removed
878
+ * first, so a crash loses it rather than sends it twice. A late one, such as
879
+ * after `serve` was down, says when it was set for and how late it is.
880
+ */
881
+ private async followUp(bot: string, entry: FollowUp, now: number): Promise<void> {
882
+ const { facts, emit } = this.ctx;
883
+ if (facts === undefined || emit === undefined) return;
884
+ if (!(await removeFollowUp(this.ctx.store, bot, entry.id, "source:bot/follow-up"))) return;
885
+ const chat = await this.ctx.store.get(CHAT_TYPE, entry.chat);
886
+ if (chat === undefined || chatData(chat.data).closed) {
887
+ await this.chatWatches.log(`follow-up ${entry.id} of bot ${bot}: chat ${entry.chat} is closed or gone; dropped`);
888
+ return;
889
+ }
890
+ const lateMs = now - entry.at;
891
+ const parts = [`Follow-up you set for yourself: ${entry.text}`];
892
+ if (lateMs >= WAKE_GAP_MS) parts.push(latenessLine(entry.at, Math.floor(lateMs / 1_000)));
893
+ try {
894
+ await sendMessage(
895
+ { facts, emit: (event) => emit({ source: event.source, type: event.type, key: event.key, object: event.object ?? `${CHAT_TYPE}:${entry.chat}` }), store: this.ctx.store, home: this.ctx.home, actor: { via: SCHEDULE_SOURCE, id: "follow-up" }, source: SCHEDULE_SOURCE },
896
+ entry.chat,
897
+ parts.join("\n\n"),
898
+ );
899
+ } catch (error) {
900
+ await this.chatWatches.log(`follow-up ${entry.id} of bot ${bot}: ${messageOf(error)}`);
901
+ }
902
+ }
903
+
904
+ private async bots(): Promise<readonly StoredObject[]> {
905
+ const found: StoredObject[] = [];
906
+ let cursor: string | undefined;
907
+ do {
908
+ const page = await this.ctx.store.list(BOT_TYPE, {
909
+ ...(cursor === undefined ? {} : { cursor }),
910
+ });
911
+ found.push(...page.objects);
912
+ cursor = page.next;
913
+ } while (cursor !== undefined);
914
+ return found;
915
+ }
916
+
917
+ private async one(bot: string, entry: ScheduledPrompt, now: number, catchUp: boolean): Promise<void> {
918
+ const latest = latestCronMinute(parseCron(entry.schedule), now, CATCH_UP_DAYS);
919
+ const baseline = latest ?? minuteStart(now);
920
+ if (entry.paused) {
921
+ // A paused entry does not collect missed times: its planned time follows
922
+ // the clock, so resuming waits for the next planned minute. Its last
923
+ // result is kept.
924
+ const kept =
925
+ entry.last !== undefined && entry.last.schedule === entry.schedule
926
+ ? entry.last
927
+ : undefined;
928
+ if (kept?.plannedAt !== baseline) {
929
+ await this.setLast(bot, entry.name, {
930
+ ...(kept ?? {}),
931
+ plannedAt: baseline,
932
+ schedule: entry.schedule,
933
+ });
934
+ }
935
+ return;
936
+ }
937
+ const last =
938
+ entry.last !== undefined && entry.last.schedule === entry.schedule ? entry.last : undefined;
939
+ if (last === undefined) {
940
+ await this.setLast(bot, entry.name, {
941
+ ...(entry.last?.result === undefined
942
+ ? {}
943
+ : { result: entry.last.result, ...(entry.last.notified === true ? { notified: true } : {}) }),
944
+ ...(entry.last?.chatId === undefined ? {} : { chatId: entry.last.chatId }),
945
+ plannedAt: baseline,
946
+ schedule: entry.schedule,
947
+ });
948
+ return;
949
+ }
950
+ let minute: number | null;
951
+ let skipped: readonly number[] = [];
952
+ if (catchUp) {
953
+ if (latest === null || latest <= last.plannedAt) return;
954
+ const windowStart = Math.max(last.plannedAt, minuteStart(now) - CATCH_UP_DAYS * DAY_MS);
955
+ if (latest <= windowStart) {
956
+ await this.setLast(bot, entry.name, { ...last, plannedAt: latest });
957
+ return;
958
+ }
959
+ skipped = cronMinutesBetween(parseCron(entry.schedule), windowStart, latest).slice(0, -1);
960
+ minute = latest;
961
+ } else {
962
+ minute = latest !== null && latest > last.plannedAt ? latest : null;
963
+ }
964
+ if (minute === null) return;
965
+ await this.fire(bot, entry, minute, now, skipped);
966
+ }
967
+
968
+ /**
969
+ * Fires an entry once because a person asked. The request is cleared first, so
970
+ * a crash loses it rather than runs it twice. The planned time and schedule of
971
+ * `last` stay what the timed runs expect, so the next timed run is unchanged.
972
+ */
973
+ private async runNow(bot: string, entry: ScheduledPrompt, now: number): Promise<void> {
974
+ const cleared = await replaceEntry(
975
+ this.ctx.store,
976
+ bot,
977
+ entry.name,
978
+ (current) => (current.runNow === undefined ? undefined : { ...current, runNow: undefined }),
979
+ "source:bot/run-now",
980
+ );
981
+ if (cleared === undefined) return;
982
+ // A firing started since the request was made still owns `last`: drop the request.
983
+ if (isReplying(cleared.last)) {
984
+ await this.chatWatches.log(
985
+ `scheduled prompt "${entry.name}" of bot ${bot}: run now dropped, the previous firing is still replying`,
986
+ );
987
+ return;
988
+ }
989
+ const last = entry.last !== undefined && entry.last.schedule === entry.schedule ? entry.last : undefined;
990
+ const latest = latestCronMinute(parseCron(entry.schedule), now, CATCH_UP_DAYS);
991
+ const planned = last?.plannedAt ?? latest ?? minuteStart(now);
992
+ await this.fire(bot, entry, planned, now, [], true);
993
+ }
994
+
995
+ private async fire(
996
+ bot: string,
997
+ entry: ScheduledPrompt,
998
+ minute: number,
999
+ now: number,
1000
+ skipped: readonly number[],
1001
+ manual = false,
1002
+ ): Promise<void> {
1003
+ const recorded = {
1004
+ plannedAt: minute,
1005
+ firedAt: now,
1006
+ schedule: entry.schedule,
1007
+ ...(skipped.length > 0 ? { skippedEarlier: true } : {}),
1008
+ ...(manual ? { manual: true } : {}),
1009
+ };
1010
+ await this.setLast(bot, entry.name, recorded);
1011
+ const title = `${entry.name} (${localDate(manual ? now : minute)})`.slice(0, 120);
1012
+ let chatId: string | undefined;
1013
+ try {
1014
+ const run = await this.ctx.client.act("bot:chat", `${BOT_TYPE}:${bot}`, {
1015
+ args: {
1016
+ title,
1017
+ // The person's own prompt; the bot:chat action adds what only the agent needs.
1018
+ message: entry.prompt,
1019
+ ...(entry.model === undefined ? {} : { model: entry.model }),
1020
+ ...(entry.effort === undefined ? {} : { effort: entry.effort }),
1021
+ },
1022
+ // The entry's name is the origin recorded on the new chat.
1023
+ actor: { via: SCHEDULE_SOURCE, id: entry.name },
1024
+ });
1025
+ chatId = run.opens?.startsWith(`${CHAT_TYPE}:`) === true
1026
+ ? run.opens.slice(CHAT_TYPE.length + 1)
1027
+ : undefined;
1028
+ } catch (error) {
1029
+ const message = messageOf(error);
1030
+ await this.setLast(bot, entry.name, {
1031
+ ...recorded,
1032
+ result: replySummary(`Could not start: ${message}`),
1033
+ });
1034
+ return;
1035
+ }
1036
+ if (chatId === undefined) {
1037
+ await this.chatWatches.log(`scheduled prompt "${entry.name}" of bot ${bot} opened no chat`);
1038
+ return;
1039
+ }
1040
+ const changed = await replaceEntry(
1041
+ this.ctx.store,
1042
+ bot,
1043
+ entry.name,
1044
+ (current) =>
1045
+ current.last?.plannedAt === minute
1046
+ ? { ...current, last: { ...current.last, chatId } }
1047
+ : undefined,
1048
+ "step:bot/scheduled",
1049
+ );
1050
+ if (changed === undefined) return;
1051
+ await this.watch(bot, entry.name, manual ? now : minute, chatId);
1052
+ if (skipped.length > 0) {
1053
+ await this.chatWatches.log(
1054
+ `scheduled prompt "${entry.name}" of bot ${bot}: skipped ${skipped
1055
+ .map((time) => new Date(time).toISOString())
1056
+ .join(", ")}; only the latest missed run is caught up`,
1057
+ );
1058
+ }
1059
+ }
1060
+
1061
+ private async setLast(bot: string, name: string, last: ScheduledLast): Promise<void> {
1062
+ await replaceEntry(
1063
+ this.ctx.store,
1064
+ bot,
1065
+ name,
1066
+ (entry) => ({ ...entry, last }),
1067
+ "source:bot/scheduled",
1068
+ );
1069
+ }
1070
+
1071
+ private async watch(bot: string, name: string, plannedAt: number, chatId: string): Promise<void> {
1072
+ const key = `${bot}\u0000${name}\u0000${plannedAt}\u0000${chatId}`;
1073
+ this.chatWatches.watchChatReply(
1074
+ key,
1075
+ chatId,
1076
+ async (read) => {
1077
+ const chat = await this.ctx.store.get(CHAT_TYPE, chatId);
1078
+ if (chat === undefined) return undefined;
1079
+ const reply = [...read.messages].reverse().find((message) => message.role === "assistant");
1080
+ const failure = [...read.entries].reverse().find((item) => item.kind === "failure");
1081
+ // A failure after the reply means the run did not end quietly.
1082
+ const failedAfter = reply !== undefined && failure !== undefined && failure.sequence > reply.sequence;
1083
+ const quiet = reply !== undefined && !failedAfter && isQuietReply(reply.text);
1084
+ const result = quiet
1085
+ ? SCHEDULE_QUIET_RESULT
1086
+ : reply === undefined
1087
+ ? failure === undefined
1088
+ ? undefined
1089
+ : replySummary(failure.text ?? "The reply failed.")
1090
+ : failedAfter
1091
+ ? replySummary(failure.text ?? "The reply failed.")
1092
+ : replySummary(reply.text);
1093
+ if (result === undefined) return undefined;
1094
+ const title = typeof chat.data.title === "string" ? chat.data.title : chatId;
1095
+ return { result, title, quiet };
1096
+ },
1097
+ async ({ result, title, quiet }) => {
1098
+ await replaceEntry(
1099
+ this.ctx.store,
1100
+ bot,
1101
+ name,
1102
+ (entry) =>
1103
+ entry.last?.chatId === chatId
1104
+ ? {
1105
+ ...entry,
1106
+ last: { ...entry.last, result, notified: quiet },
1107
+ recent: [
1108
+ ...(entry.recent ?? []).filter((item) => item.plannedAt !== plannedAt),
1109
+ { plannedAt, result },
1110
+ ].slice(-SCHEDULE_RECENT_COUNT),
1111
+ }
1112
+ : undefined,
1113
+ "step:bot/scheduled",
1114
+ );
1115
+ // A quiet ending records its result and runs no notify command.
1116
+ if (quiet) return;
1117
+ try {
1118
+ await this.notify({ chatId, title, summary: result });
1119
+ } catch (error) {
1120
+ await this.chatWatches.log(
1121
+ `scheduled prompt "${name}" of bot ${bot}: notify: ${messageOf(error)}`,
1122
+ );
1123
+ }
1124
+ await replaceEntry(
1125
+ this.ctx.store,
1126
+ bot,
1127
+ name,
1128
+ (entry) =>
1129
+ entry.last?.chatId === chatId
1130
+ ? { ...entry, last: { ...entry.last, notified: true } }
1131
+ : undefined,
1132
+ "step:bot/scheduled",
1133
+ );
1134
+ },
1135
+ );
1136
+ }
1137
+
1138
+ /** Watches a firing that was already started, such as one from before a restart. */
1139
+ private async resumeWatches(): Promise<void> {
1140
+ for (const object of await this.bots()) {
1141
+ if (object.data.removed === true) continue;
1142
+ for (const entry of scheduledPrompts(object.data)) {
1143
+ const last = entry.last;
1144
+ if (last?.chatId === undefined || last.notified === true) continue;
1145
+ await this.watch(object.id, entry.name, last.manual === true && last.firedAt !== undefined ? last.firedAt : last.plannedAt, last.chatId);
1146
+ }
1147
+ }
1148
+ }
1149
+
1150
+ start(): SourceHandle {
1151
+ this.timer = setInterval(() => {
1152
+ this.chatWatches.track(this.poll());
1153
+ }, CHECK_INTERVAL_MS);
1154
+ if (typeof this.timer === "object" && "unref" in this.timer) {
1155
+ this.timer.unref();
1156
+ }
1157
+ return {
1158
+ stop: () => {
1159
+ this.stopped = true;
1160
+ if (this.timer !== undefined) clearInterval(this.timer);
1161
+ this.chatWatches.stopAll();
1162
+ },
1163
+ };
1164
+ }
1165
+
1166
+ /** The source's first pass, after the bot plugin has made its objects. */
1167
+ async begin(): Promise<void> {
1168
+ try {
1169
+ await this.ctx.client.list(BOT_TYPE);
1170
+ } catch (error) {
1171
+ await this.chatWatches.log(`scheduled prompts: ${messageOf(error)}`);
1172
+ }
1173
+ await this.resumeWatches();
1174
+ await this.poll();
1175
+ }
1176
+ }
1177
+
1178
+ /** The source the bot plugin declares; `begin` runs before the first interval. */
1179
+ export async function startScheduled(ctx: SourceContext): Promise<SourceHandle> {
1180
+ const source = new BotScheduleSource(ctx);
1181
+ await source.begin();
1182
+ return source.start();
1183
+ }
1184
+