@operad-io/bot 0.1.1 → 0.2.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.
- package/README.md +1 -1
- package/bot.schema.json +40 -2
- package/package.json +5 -4
- package/src/bot.ts +588 -70
- package/src/chat-watch.ts +101 -0
- package/src/create.ts +230 -0
- package/src/index.ts +466 -22
- package/src/login.ts +226 -0
- package/src/mcp-proposals.ts +2 -2
- package/src/proposals.ts +358 -78
- package/src/schedule.ts +959 -0
- package/src/setup-dev.ts +254 -0
- package/src/setup.ts +113 -0
- package/src/tidy.ts +1018 -0
package/src/schedule.ts
ADDED
|
@@ -0,0 +1,959 @@
|
|
|
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 } 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 { SETUP_DEV_INSTRUCTION } from "./setup-dev.ts";
|
|
39
|
+
import { SETUP_INSTRUCTION } from "./setup.ts";
|
|
40
|
+
|
|
41
|
+
/** The source's name for a scheduled message; a message from it is a background run. */
|
|
42
|
+
export const SCHEDULE_SOURCE = "bot";
|
|
43
|
+
|
|
44
|
+
/** How often the source checks the clock. */
|
|
45
|
+
const CHECK_INTERVAL_MS = 1_000;
|
|
46
|
+
/** A gap much larger than the check interval means the machine slept or the clock jumped. */
|
|
47
|
+
const WAKE_GAP_MS = 60_000;
|
|
48
|
+
/** How far back a catch-up looks. */
|
|
49
|
+
const CATCH_UP_DAYS = 7;
|
|
50
|
+
const DAY_MS = 24 * 60 * 60_000;
|
|
51
|
+
|
|
52
|
+
/** What the last firing was and how it ended. */
|
|
53
|
+
export interface ScheduledLast {
|
|
54
|
+
/** The planned minute, in epoch milliseconds. */
|
|
55
|
+
readonly plannedAt: number;
|
|
56
|
+
/** When the source fired it; absent when this is only a baseline. */
|
|
57
|
+
readonly firedAt?: number | undefined;
|
|
58
|
+
/** The schedule this planned time belongs to. */
|
|
59
|
+
readonly schedule: string;
|
|
60
|
+
/** The chat the firing opened. */
|
|
61
|
+
readonly chatId?: string | undefined;
|
|
62
|
+
/** A short summary of the reply, or why it could not start. */
|
|
63
|
+
readonly result?: string | undefined;
|
|
64
|
+
/** True once the notify command was run for `result`. */
|
|
65
|
+
readonly notified?: boolean | undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** One scheduled prompt of a bot. */
|
|
69
|
+
export interface ScheduledPrompt {
|
|
70
|
+
readonly name: string;
|
|
71
|
+
/** A five-field cron expression in the machine's local time zone. */
|
|
72
|
+
readonly schedule: string;
|
|
73
|
+
readonly prompt: string;
|
|
74
|
+
readonly model?: string | undefined;
|
|
75
|
+
readonly effort?: string | undefined;
|
|
76
|
+
readonly paused: boolean;
|
|
77
|
+
readonly last?: ScheduledLast | undefined;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The longest summary an entry keeps and a notification carries. */
|
|
81
|
+
export const SCHEDULE_SUMMARY_MAX = 300;
|
|
82
|
+
|
|
83
|
+
function text(value: unknown): string | undefined {
|
|
84
|
+
return typeof value === "string" && value.trim().length > 0 ? value : undefined;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function lastOf(value: unknown): ScheduledLast | undefined {
|
|
88
|
+
if (!isRecord(value)) return undefined;
|
|
89
|
+
if (typeof value.plannedAt !== "number" || !Number.isFinite(value.plannedAt)) return undefined;
|
|
90
|
+
if (typeof value.schedule !== "string") return undefined;
|
|
91
|
+
return {
|
|
92
|
+
plannedAt: value.plannedAt,
|
|
93
|
+
...(typeof value.firedAt === "number" && Number.isFinite(value.firedAt)
|
|
94
|
+
? { firedAt: value.firedAt }
|
|
95
|
+
: {}),
|
|
96
|
+
schedule: value.schedule,
|
|
97
|
+
...(text(value.chatId) === undefined ? {} : { chatId: value.chatId as string }),
|
|
98
|
+
...(text(value.result) === undefined ? {} : { result: value.result as string }),
|
|
99
|
+
...(value.notified === true ? { notified: true } : {}),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** One scheduled prompt from stored data, or undefined when it is unusable. */
|
|
104
|
+
export function scheduledPromptOf(value: unknown): ScheduledPrompt | undefined {
|
|
105
|
+
if (!isRecord(value)) return undefined;
|
|
106
|
+
const name = text(value.name);
|
|
107
|
+
const schedule = text(value.schedule);
|
|
108
|
+
const prompt = text(value.prompt);
|
|
109
|
+
if (name === undefined || schedule === undefined || prompt === undefined) return undefined;
|
|
110
|
+
const last = lastOf(value.last);
|
|
111
|
+
return {
|
|
112
|
+
name,
|
|
113
|
+
schedule,
|
|
114
|
+
prompt,
|
|
115
|
+
...(text(value.model) === undefined ? {} : { model: value.model as string }),
|
|
116
|
+
...(text(value.effort) === undefined ? {} : { effort: value.effort as string }),
|
|
117
|
+
paused: value.paused === true,
|
|
118
|
+
...(last === undefined ? {} : { last }),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** The scheduled prompts written on a bot object, skipping an unusable entry. */
|
|
123
|
+
export function scheduledPrompts(data: Readonly<Record<string, unknown>>): readonly ScheduledPrompt[] {
|
|
124
|
+
const raw = data.scheduled;
|
|
125
|
+
if (!Array.isArray(raw)) return [];
|
|
126
|
+
const found: ScheduledPrompt[] = [];
|
|
127
|
+
for (const value of raw) {
|
|
128
|
+
const entry = scheduledPromptOf(value);
|
|
129
|
+
if (entry !== undefined) found.push(entry);
|
|
130
|
+
}
|
|
131
|
+
return found;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** What a chat's schedule command asks a person to decide. */
|
|
135
|
+
export interface ScheduleChange {
|
|
136
|
+
readonly action: "add" | "edit" | "remove";
|
|
137
|
+
/** The schedule in words, as the agent wrote it. */
|
|
138
|
+
readonly words?: string | undefined;
|
|
139
|
+
readonly before: ScheduledPrompt | null;
|
|
140
|
+
readonly after: ScheduledPrompt | null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Reads the schedule change a proposal stores, or undefined when it is unusable. */
|
|
144
|
+
export function scheduleChangeOf(value: unknown): ScheduleChange | undefined {
|
|
145
|
+
if (!isRecord(value)) return undefined;
|
|
146
|
+
if (value.action !== "add" && value.action !== "edit" && value.action !== "remove") {
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
const before = value.before === null ? null : scheduledPromptOf(value.before);
|
|
150
|
+
const after = value.after === null ? null : scheduledPromptOf(value.after);
|
|
151
|
+
if (before === undefined || after === undefined) return undefined;
|
|
152
|
+
if (value.words !== undefined && typeof value.words !== "string") return undefined;
|
|
153
|
+
return {
|
|
154
|
+
action: value.action,
|
|
155
|
+
...(value.words === undefined ? {} : { words: value.words }),
|
|
156
|
+
before,
|
|
157
|
+
after,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** One entry as the bot object stores it. */
|
|
162
|
+
function stored(entry: ScheduledPrompt): Record<string, JsonValue> {
|
|
163
|
+
return {
|
|
164
|
+
name: entry.name,
|
|
165
|
+
schedule: entry.schedule,
|
|
166
|
+
prompt: entry.prompt,
|
|
167
|
+
...(entry.model === undefined ? {} : { model: entry.model }),
|
|
168
|
+
...(entry.effort === undefined ? {} : { effort: entry.effort }),
|
|
169
|
+
paused: entry.paused,
|
|
170
|
+
...(entry.last === undefined ? {} : { last: entry.last as unknown as JsonValue }),
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The name a client uses to choose an entry; unique within one bot. */
|
|
175
|
+
export function checkPromptName(name: string): string {
|
|
176
|
+
const trimmed = name.trim();
|
|
177
|
+
if (trimmed.length === 0) throw new BotError("a scheduled prompt needs a name");
|
|
178
|
+
if (trimmed.length > 120) throw new BotError("a scheduled prompt's name is at most 120 characters");
|
|
179
|
+
return trimmed;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** A schedule as it is stored: trimmed, and checked as a five-field cron expression. */
|
|
183
|
+
export function checkSchedule(expression: string): string {
|
|
184
|
+
const trimmed = expression.trim();
|
|
185
|
+
parseCron(trimmed);
|
|
186
|
+
return trimmed;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** The local date of a time, `YYYY-MM-DD`. */
|
|
190
|
+
export function localDate(time: number): string {
|
|
191
|
+
const date = new Date(time);
|
|
192
|
+
const pad = (value: number): string => String(value).padStart(2, "0");
|
|
193
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** The local time of a time, `YYYY-MM-DD HH:mm`. */
|
|
197
|
+
export function localStamp(time: number): string {
|
|
198
|
+
const date = new Date(time);
|
|
199
|
+
const pad = (value: number): string => String(value).padStart(2, "0");
|
|
200
|
+
return `${localDate(time)} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** How long a catch-up is late, in words a person reads. */
|
|
204
|
+
export function lateText(seconds: number): string {
|
|
205
|
+
if (seconds < 60) return `${seconds} seconds`;
|
|
206
|
+
const minutes = Math.floor(seconds / 60);
|
|
207
|
+
if (minutes < 60) return `${minutes} minute${minutes === 1 ? "" : "s"}`;
|
|
208
|
+
const hours = Math.floor(minutes / 60);
|
|
209
|
+
const rest = minutes % 60;
|
|
210
|
+
return `${hours} hour${hours === 1 ? "" : "s"}${rest === 0 ? "" : ` ${rest} minute${rest === 1 ? "" : "s"}`}`;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** The one line a catch-up adds to the prompt. It is not added to an on-time run. */
|
|
214
|
+
export function latenessLine(scheduledAt: number, lateSecs: number): string {
|
|
215
|
+
return `Scheduled for ${localStamp(scheduledAt)}; this run is ${lateText(lateSecs)} late.`;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** What a bot chat's first session starts with: a schedule it writes is a proposal. */
|
|
219
|
+
export const SCHEDULE_INSTRUCTION =
|
|
220
|
+
"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.";
|
|
221
|
+
|
|
222
|
+
/** The text and place a bot chat starts with. */
|
|
223
|
+
export function scheduledChatContext(): { readonly text: string; readonly where: string } {
|
|
224
|
+
const line = `${SCHEDULE_INSTRUCTION} ${SETUP_DEV_INSTRUCTION} ${SETUP_INSTRUCTION}`;
|
|
225
|
+
return { text: line, where: line };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** The next planned minute after `now`, or null when none is within two years. */
|
|
229
|
+
export function nextRun(entry: ScheduledPrompt, now: number): number | null {
|
|
230
|
+
if (entry.paused) return null;
|
|
231
|
+
let schedule: ReturnType<typeof parseCron>;
|
|
232
|
+
try {
|
|
233
|
+
schedule = parseCron(entry.schedule);
|
|
234
|
+
} catch {
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
const limit = minuteStart(now) + 366 * 2 * DAY_MS;
|
|
238
|
+
let candidate = minuteStart(now) + 60_000;
|
|
239
|
+
while (candidate <= limit) {
|
|
240
|
+
if (cronMatches(schedule, new Date(candidate))) return candidate;
|
|
241
|
+
candidate += 60_000;
|
|
242
|
+
}
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** One scheduled prompt as a client reads it from a bot row, without parsing Markdown. */
|
|
247
|
+
export interface ScheduledPromptView {
|
|
248
|
+
readonly name: string;
|
|
249
|
+
readonly schedule: string;
|
|
250
|
+
readonly prompt: string;
|
|
251
|
+
readonly model: string | null;
|
|
252
|
+
readonly effort: string | null;
|
|
253
|
+
readonly paused: boolean;
|
|
254
|
+
/** The next planned minute as an ISO time; null when paused or none is within two years. */
|
|
255
|
+
readonly nextRun: string | null;
|
|
256
|
+
/** The last reply's summary, or why it could not start; null before the first firing. */
|
|
257
|
+
readonly lastResult: string | null;
|
|
258
|
+
/** The chat the last firing opened; null before the first firing. */
|
|
259
|
+
readonly lastChatId: string | null;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** The structured entries a bot row gives a client. */
|
|
263
|
+
export function scheduledData(
|
|
264
|
+
entries: readonly ScheduledPrompt[],
|
|
265
|
+
now: number,
|
|
266
|
+
): readonly ScheduledPromptView[] {
|
|
267
|
+
return entries.map((entry) => {
|
|
268
|
+
const next = nextRun(entry, now);
|
|
269
|
+
return {
|
|
270
|
+
name: entry.name,
|
|
271
|
+
schedule: entry.schedule,
|
|
272
|
+
prompt: entry.prompt,
|
|
273
|
+
model: entry.model ?? null,
|
|
274
|
+
effort: entry.effort ?? null,
|
|
275
|
+
paused: entry.paused,
|
|
276
|
+
nextRun: next === null ? null : new Date(next).toISOString(),
|
|
277
|
+
lastResult: entry.last?.result ?? null,
|
|
278
|
+
lastChatId: entry.last?.chatId ?? null,
|
|
279
|
+
};
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** A short, one-line summary of a reply. */
|
|
284
|
+
export function replySummary(message: string): string {
|
|
285
|
+
const oneLine = message.replace(/\s+/g, " ").trim();
|
|
286
|
+
if (oneLine.length === 0) return "The reply was empty.";
|
|
287
|
+
return oneLine.length <= SCHEDULE_SUMMARY_MAX
|
|
288
|
+
? oneLine
|
|
289
|
+
: `${oneLine.slice(0, SCHEDULE_SUMMARY_MAX - 1)}…`;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** What a notification command is given. */
|
|
293
|
+
export interface ScheduleNotice {
|
|
294
|
+
readonly chatId: string;
|
|
295
|
+
readonly title: string;
|
|
296
|
+
readonly summary: string;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Runs the configured notify command for a finished scheduled reply. */
|
|
300
|
+
export async function notifyScheduledReply(
|
|
301
|
+
home: string,
|
|
302
|
+
notice: ScheduleNotice,
|
|
303
|
+
): Promise<void> {
|
|
304
|
+
const config = await readConfig(home);
|
|
305
|
+
const command = config.notify.command;
|
|
306
|
+
if (command === null) return;
|
|
307
|
+
const outcome = await runLine({
|
|
308
|
+
line: command,
|
|
309
|
+
cwd: home,
|
|
310
|
+
env: {
|
|
311
|
+
OPERAD_ID: `${CHAT_TYPE}:${notice.chatId}`,
|
|
312
|
+
OPERAD_TITLE: notice.title,
|
|
313
|
+
OPERAD_REASON: notice.summary,
|
|
314
|
+
OPERAD_LINK: objectLink(CHAT_TYPE, notice.chatId),
|
|
315
|
+
},
|
|
316
|
+
timeoutMs: NOTIFY_TIMEOUT_MS,
|
|
317
|
+
signal: new AbortController().signal,
|
|
318
|
+
});
|
|
319
|
+
if (outcome.exitCode !== 0 || outcome.timedOut || outcome.spawnError !== undefined) {
|
|
320
|
+
throw new Error(
|
|
321
|
+
`the notify command ${outcome.timedOut ? "timed out" : `exited ${outcome.exitCode ?? "without a code"}`}`,
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** Reads a bot object, or says why it cannot be used. */
|
|
327
|
+
async function botObject(store: ObjectStore, bot: string): Promise<StoredObject> {
|
|
328
|
+
const object = await store.get(BOT_TYPE, bot);
|
|
329
|
+
if (object === undefined) throw new BotError(`there is no bot "${bot}"`);
|
|
330
|
+
if (object.data.removed === true) throw new BotError(`bot ${bot} is no longer in the settings`);
|
|
331
|
+
return object;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** Replaces one entry on the bot object, leaving the others and the bot's settings alone. */
|
|
335
|
+
async function replaceEntry(
|
|
336
|
+
store: ObjectStore,
|
|
337
|
+
bot: string,
|
|
338
|
+
name: string,
|
|
339
|
+
change: (entry: ScheduledPrompt) => ScheduledPrompt | undefined,
|
|
340
|
+
cause: string,
|
|
341
|
+
): Promise<ScheduledPrompt | undefined> {
|
|
342
|
+
const object = await botObject(store, bot);
|
|
343
|
+
const entries = scheduledPrompts(object.data);
|
|
344
|
+
let changed: ScheduledPrompt | undefined;
|
|
345
|
+
const next: ScheduledPrompt[] = [];
|
|
346
|
+
for (const entry of entries) {
|
|
347
|
+
if (entry.name !== name) {
|
|
348
|
+
next.push(entry);
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
changed = change(entry);
|
|
352
|
+
if (changed !== undefined) next.push(changed);
|
|
353
|
+
}
|
|
354
|
+
if (changed === undefined) return undefined;
|
|
355
|
+
await store.put(
|
|
356
|
+
BOT_TYPE,
|
|
357
|
+
bot,
|
|
358
|
+
{ ...object.data, scheduled: next.map(stored) as unknown as JsonValue[] },
|
|
359
|
+
cause,
|
|
360
|
+
);
|
|
361
|
+
return changed;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** Removes one entry from the bot object. */
|
|
365
|
+
async function removeEntry(store: ObjectStore, bot: string, name: string): Promise<boolean> {
|
|
366
|
+
const object = await botObject(store, bot);
|
|
367
|
+
const entries = scheduledPrompts(object.data);
|
|
368
|
+
const next = entries.filter((entry) => entry.name !== name);
|
|
369
|
+
if (next.length === entries.length) return false;
|
|
370
|
+
await store.put(
|
|
371
|
+
BOT_TYPE,
|
|
372
|
+
bot,
|
|
373
|
+
{ ...object.data, scheduled: next.map(stored) as unknown as JsonValue[] },
|
|
374
|
+
"action:bot/schedule-remove",
|
|
375
|
+
);
|
|
376
|
+
return true;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** The current entry with the fields the proposal changed, from `before` to `after`, applied. */
|
|
380
|
+
function mergedEdit(
|
|
381
|
+
current: ScheduledPrompt,
|
|
382
|
+
before: ScheduledPrompt,
|
|
383
|
+
after: ScheduledPrompt,
|
|
384
|
+
): ScheduledPrompt {
|
|
385
|
+
const schedule = after.schedule === before.schedule ? current.schedule : after.schedule;
|
|
386
|
+
const model = after.model === before.model ? current.model : after.model;
|
|
387
|
+
const effort = after.effort === before.effort ? current.effort : after.effort;
|
|
388
|
+
return {
|
|
389
|
+
...current,
|
|
390
|
+
name: after.name,
|
|
391
|
+
schedule,
|
|
392
|
+
prompt: after.prompt === before.prompt ? current.prompt : after.prompt,
|
|
393
|
+
...(model === undefined ? { model: undefined } : { model }),
|
|
394
|
+
...(effort === undefined ? { effort: undefined } : { effort }),
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** Applies a schedule proposal: the add, edit or remove the person approved. */
|
|
399
|
+
export async function applyScheduleChange(
|
|
400
|
+
store: ObjectStore,
|
|
401
|
+
bot: string,
|
|
402
|
+
change: ScheduleChange,
|
|
403
|
+
): Promise<void> {
|
|
404
|
+
if (change.action === "add") {
|
|
405
|
+
if (change.after === null) throw new BotError("the proposal has no scheduled prompt to add");
|
|
406
|
+
await addEntry(store, bot, change.after);
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
if (change.action === "edit") {
|
|
410
|
+
const before = change.before;
|
|
411
|
+
const after = change.after;
|
|
412
|
+
if (before === null || after === null) {
|
|
413
|
+
throw new BotError("the proposal has no scheduled prompt to change");
|
|
414
|
+
}
|
|
415
|
+
const changed = await replaceEntry(
|
|
416
|
+
store,
|
|
417
|
+
bot,
|
|
418
|
+
before.name,
|
|
419
|
+
// Only what the proposal changed is applied: the pause state, last run
|
|
420
|
+
// and any edit made since the proposal stay as they are now.
|
|
421
|
+
(current) => mergedEdit(current, before, after),
|
|
422
|
+
"action:bot/schedule-edit",
|
|
423
|
+
);
|
|
424
|
+
if (changed === undefined) {
|
|
425
|
+
throw new BotError(`bot ${bot} has no scheduled prompt "${before.name}"`);
|
|
426
|
+
}
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
if (change.before === null) {
|
|
430
|
+
throw new BotError("the proposal has no scheduled prompt to remove");
|
|
431
|
+
}
|
|
432
|
+
if (!(await removeEntry(store, bot, change.before.name))) {
|
|
433
|
+
throw new BotError(`bot ${bot} has no scheduled prompt "${change.before.name}"`);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** Adds one entry to the bot object. */
|
|
438
|
+
async function addEntry(
|
|
439
|
+
store: ObjectStore,
|
|
440
|
+
bot: string,
|
|
441
|
+
entry: ScheduledPrompt,
|
|
442
|
+
): Promise<ScheduledPrompt> {
|
|
443
|
+
const object = await botObject(store, bot);
|
|
444
|
+
const entries = scheduledPrompts(object.data);
|
|
445
|
+
if (entries.some((item) => item.name === entry.name)) {
|
|
446
|
+
throw new BotError(`bot ${bot} already has a scheduled prompt "${entry.name}"`);
|
|
447
|
+
}
|
|
448
|
+
await store.put(
|
|
449
|
+
BOT_TYPE,
|
|
450
|
+
bot,
|
|
451
|
+
{ ...object.data, scheduled: [...entries, entry].map(stored) as unknown as JsonValue[] },
|
|
452
|
+
"action:bot/schedule-add",
|
|
453
|
+
);
|
|
454
|
+
return entry;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function entryArgs(required: boolean): ActionTypeDefinition["args"] {
|
|
458
|
+
return {
|
|
459
|
+
type: "object",
|
|
460
|
+
properties: {
|
|
461
|
+
name: {
|
|
462
|
+
type: "string",
|
|
463
|
+
minLength: 1,
|
|
464
|
+
maxLength: 120,
|
|
465
|
+
...(required ? {} : { description: "The scheduled prompt to change." }),
|
|
466
|
+
},
|
|
467
|
+
schedule: {
|
|
468
|
+
type: "string",
|
|
469
|
+
minLength: 1,
|
|
470
|
+
description: "A five-field cron schedule in the machine's local time zone, such as `0 8 * * *`.",
|
|
471
|
+
},
|
|
472
|
+
prompt: {
|
|
473
|
+
type: "string",
|
|
474
|
+
role: "note",
|
|
475
|
+
minLength: 1,
|
|
476
|
+
description: "The first message of the new chat.",
|
|
477
|
+
},
|
|
478
|
+
model: {
|
|
479
|
+
type: "string",
|
|
480
|
+
description: "The model the new chat uses; the bot's model when left out. An empty value clears it.",
|
|
481
|
+
},
|
|
482
|
+
effort: {
|
|
483
|
+
type: "string",
|
|
484
|
+
description: "The effort the new chat uses; the bot's effort when left out. An empty value clears it.",
|
|
485
|
+
},
|
|
486
|
+
},
|
|
487
|
+
...(required ? { required: ["name", "schedule", "prompt"] } : { required: ["name"] }),
|
|
488
|
+
additionalProperties: false,
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function nameArg(): ActionTypeDefinition["args"] {
|
|
493
|
+
return {
|
|
494
|
+
type: "object",
|
|
495
|
+
properties: {
|
|
496
|
+
name: { type: "string", minLength: 1, description: "The scheduled prompt's name." },
|
|
497
|
+
},
|
|
498
|
+
required: ["name"],
|
|
499
|
+
additionalProperties: false,
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/** The actions a client uses to manage a bot's scheduled prompts. */
|
|
504
|
+
export const scheduleActions: readonly ActionTypeDefinition[] = [
|
|
505
|
+
{
|
|
506
|
+
name: "schedule-add",
|
|
507
|
+
on: BOT_TYPE,
|
|
508
|
+
args: {
|
|
509
|
+
...(entryArgs(true) as ActionArgsSchema),
|
|
510
|
+
properties: {
|
|
511
|
+
...((entryArgs(true) as ActionArgsSchema).properties ?? {}),
|
|
512
|
+
paused: {
|
|
513
|
+
type: "boolean",
|
|
514
|
+
default: false,
|
|
515
|
+
description: "Start paused; it does not fire until resumed.",
|
|
516
|
+
},
|
|
517
|
+
},
|
|
518
|
+
},
|
|
519
|
+
when: (state) => state.removed !== true,
|
|
520
|
+
why: (object) =>
|
|
521
|
+
object.data.removed === true ? `bot ${object.id} is no longer in the settings` : undefined,
|
|
522
|
+
async run(ctx, args) {
|
|
523
|
+
const input = args as {
|
|
524
|
+
readonly name: string;
|
|
525
|
+
readonly schedule: string;
|
|
526
|
+
readonly prompt: string;
|
|
527
|
+
readonly model?: string;
|
|
528
|
+
readonly effort?: string;
|
|
529
|
+
readonly paused?: boolean;
|
|
530
|
+
};
|
|
531
|
+
const entry: ScheduledPrompt = {
|
|
532
|
+
name: checkPromptName(input.name),
|
|
533
|
+
schedule: checkSchedule(input.schedule),
|
|
534
|
+
prompt: input.prompt.trim(),
|
|
535
|
+
...(text(input.model) === undefined ? {} : { model: input.model as string }),
|
|
536
|
+
...(text(input.effort) === undefined ? {} : { effort: input.effort as string }),
|
|
537
|
+
paused: input.paused === true,
|
|
538
|
+
};
|
|
539
|
+
if (entry.prompt.length === 0) throw new BotError("a scheduled prompt needs a prompt");
|
|
540
|
+
await addEntry(ctx.store, ctx.object.id, entry);
|
|
541
|
+
return `scheduled prompt "${entry.name}" for bot ${ctx.object.id}`;
|
|
542
|
+
},
|
|
543
|
+
},
|
|
544
|
+
{
|
|
545
|
+
name: "schedule-edit",
|
|
546
|
+
on: BOT_TYPE,
|
|
547
|
+
args: entryArgs(false),
|
|
548
|
+
when: (state) => state.removed !== true,
|
|
549
|
+
why: (object) =>
|
|
550
|
+
object.data.removed === true ? `bot ${object.id} is no longer in the settings` : undefined,
|
|
551
|
+
async run(ctx, args) {
|
|
552
|
+
const input = args as {
|
|
553
|
+
readonly name: string;
|
|
554
|
+
readonly schedule?: string;
|
|
555
|
+
readonly prompt?: string;
|
|
556
|
+
readonly model?: string;
|
|
557
|
+
readonly effort?: string;
|
|
558
|
+
};
|
|
559
|
+
const name = checkPromptName(input.name);
|
|
560
|
+
const changed = await replaceEntry(
|
|
561
|
+
ctx.store,
|
|
562
|
+
ctx.object.id,
|
|
563
|
+
name,
|
|
564
|
+
(entry) => {
|
|
565
|
+
const schedule = input.schedule === undefined ? entry.schedule : checkSchedule(input.schedule);
|
|
566
|
+
const prompt = input.prompt === undefined ? entry.prompt : input.prompt.trim();
|
|
567
|
+
if (prompt.length === 0) throw new BotError("a scheduled prompt needs a prompt");
|
|
568
|
+
const model = input.model === undefined ? entry.model : text(input.model);
|
|
569
|
+
const effort = input.effort === undefined ? entry.effort : text(input.effort);
|
|
570
|
+
return {
|
|
571
|
+
...entry,
|
|
572
|
+
schedule,
|
|
573
|
+
prompt,
|
|
574
|
+
// An empty value clears the field; leaving it out keeps the old one.
|
|
575
|
+
...(model === undefined ? { model: undefined } : { model }),
|
|
576
|
+
...(effort === undefined ? { effort: undefined } : { effort }),
|
|
577
|
+
// A changed schedule keeps `last`: the poll sees its schedule is not the
|
|
578
|
+
// entry's, starts from a new baseline and keeps the chat of a firing
|
|
579
|
+
// that still awaits its notification, so no missed time is caught up.
|
|
580
|
+
};
|
|
581
|
+
},
|
|
582
|
+
"action:bot/schedule-edit",
|
|
583
|
+
);
|
|
584
|
+
if (changed === undefined) throw new BotError(`bot ${ctx.object.id} has no scheduled prompt "${name}"`);
|
|
585
|
+
return `edited scheduled prompt "${name}" for bot ${ctx.object.id}`;
|
|
586
|
+
},
|
|
587
|
+
},
|
|
588
|
+
{
|
|
589
|
+
name: "schedule-pause",
|
|
590
|
+
on: BOT_TYPE,
|
|
591
|
+
args: nameArg(),
|
|
592
|
+
when: (state) => state.removed !== true,
|
|
593
|
+
why: (object) =>
|
|
594
|
+
object.data.removed === true ? `bot ${object.id} is no longer in the settings` : undefined,
|
|
595
|
+
async run(ctx, args) {
|
|
596
|
+
const name = checkPromptName((args as { readonly name: string }).name);
|
|
597
|
+
const changed = await replaceEntry(
|
|
598
|
+
ctx.store,
|
|
599
|
+
ctx.object.id,
|
|
600
|
+
name,
|
|
601
|
+
(entry) => (entry.paused ? undefined : { ...entry, paused: true }),
|
|
602
|
+
"action:bot/schedule-pause",
|
|
603
|
+
);
|
|
604
|
+
if (changed === undefined) return `scheduled prompt "${name}" is already paused`;
|
|
605
|
+
return `paused scheduled prompt "${name}" for bot ${ctx.object.id}`;
|
|
606
|
+
},
|
|
607
|
+
},
|
|
608
|
+
{
|
|
609
|
+
name: "schedule-resume",
|
|
610
|
+
on: BOT_TYPE,
|
|
611
|
+
args: nameArg(),
|
|
612
|
+
when: (state) => state.removed !== true,
|
|
613
|
+
why: (object) =>
|
|
614
|
+
object.data.removed === true ? `bot ${object.id} is no longer in the settings` : undefined,
|
|
615
|
+
async run(ctx, args) {
|
|
616
|
+
const name = checkPromptName((args as { readonly name: string }).name);
|
|
617
|
+
const changed = await replaceEntry(
|
|
618
|
+
ctx.store,
|
|
619
|
+
ctx.object.id,
|
|
620
|
+
name,
|
|
621
|
+
(entry) => (entry.paused ? { ...entry, paused: false } : undefined),
|
|
622
|
+
"action:bot/schedule-resume",
|
|
623
|
+
);
|
|
624
|
+
if (changed === undefined) return `scheduled prompt "${name}" is already running`;
|
|
625
|
+
return `resumed scheduled prompt "${name}" for bot ${ctx.object.id}`;
|
|
626
|
+
},
|
|
627
|
+
},
|
|
628
|
+
{
|
|
629
|
+
name: "schedule-remove",
|
|
630
|
+
on: BOT_TYPE,
|
|
631
|
+
args: nameArg(),
|
|
632
|
+
when: (state) => state.removed !== true,
|
|
633
|
+
why: (object) =>
|
|
634
|
+
object.data.removed === true ? `bot ${object.id} is no longer in the settings` : undefined,
|
|
635
|
+
async run(ctx, args) {
|
|
636
|
+
const name = checkPromptName((args as { readonly name: string }).name);
|
|
637
|
+
if (!(await removeEntry(ctx.store, ctx.object.id, name))) {
|
|
638
|
+
throw new BotError(`bot ${ctx.object.id} has no scheduled prompt "${name}"`);
|
|
639
|
+
}
|
|
640
|
+
return `removed scheduled prompt "${name}" from bot ${ctx.object.id}`;
|
|
641
|
+
},
|
|
642
|
+
},
|
|
643
|
+
];
|
|
644
|
+
|
|
645
|
+
/** The lines a bot page shows for its scheduled prompts. */
|
|
646
|
+
export function scheduledMarkdown(entries: readonly ScheduledPrompt[], now: number): string[] {
|
|
647
|
+
if (entries.length === 0) return ["Scheduled: none."];
|
|
648
|
+
const lines = ["Scheduled:"];
|
|
649
|
+
for (const entry of entries) {
|
|
650
|
+
const next = nextRun(entry, now);
|
|
651
|
+
const state = entry.paused ? " (paused)" : next === null ? "" : `, next ${localStamp(next)}`;
|
|
652
|
+
const last = entry.last;
|
|
653
|
+
const ended =
|
|
654
|
+
last?.result === undefined
|
|
655
|
+
? ""
|
|
656
|
+
: `; last ${last.chatId === undefined ? "" : `chat ${last.chatId}: `}${last.result}`;
|
|
657
|
+
lines.push(`- ${entry.name} (${entry.schedule}${state})${ended}`);
|
|
658
|
+
}
|
|
659
|
+
return lines;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
interface ScheduledSource {
|
|
663
|
+
readonly store: ObjectStore;
|
|
664
|
+
readonly home: string;
|
|
665
|
+
readonly settings: Readonly<Record<string, JsonValue>>;
|
|
666
|
+
readonly clock: () => number;
|
|
667
|
+
readonly logger: PluginBaseContext["logger"];
|
|
668
|
+
readonly client: SourceContext["client"];
|
|
669
|
+
readonly runs?: RunControl | undefined;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/** The bot's own source for scheduled prompts. */
|
|
673
|
+
export class BotScheduleSource {
|
|
674
|
+
private readonly ctx: ScheduledSource;
|
|
675
|
+
private readonly notify: (notice: ScheduleNotice) => Promise<void>;
|
|
676
|
+
private readonly chatWatches: ChatWatches;
|
|
677
|
+
private timer: ReturnType<typeof setInterval> | undefined;
|
|
678
|
+
private stopped = false;
|
|
679
|
+
private busy = false;
|
|
680
|
+
private lastCheck: number | undefined;
|
|
681
|
+
|
|
682
|
+
constructor(
|
|
683
|
+
ctx: ScheduledSource,
|
|
684
|
+
options: { readonly notify?: ((notice: ScheduleNotice) => Promise<void>) | undefined } = {},
|
|
685
|
+
) {
|
|
686
|
+
this.ctx = ctx;
|
|
687
|
+
this.notify = options.notify ?? ((notice) => notifyScheduledReply(ctx.home, notice));
|
|
688
|
+
this.chatWatches = new ChatWatches(ctx.logger, ctx.store, ctx.runs);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/** Waits for the checks that are running now; a test calls this after a reply. */
|
|
692
|
+
async settled(): Promise<void> {
|
|
693
|
+
await this.chatWatches.settled();
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
/** Emits at most one tick per entry, for the latest due or missed minute. */
|
|
697
|
+
async poll(): Promise<void> {
|
|
698
|
+
if (this.stopped || this.busy) return;
|
|
699
|
+
this.busy = true;
|
|
700
|
+
try {
|
|
701
|
+
const now = this.ctx.clock();
|
|
702
|
+
const previous = this.lastCheck;
|
|
703
|
+
this.lastCheck = now;
|
|
704
|
+
const catchUp = previous === undefined || now - previous > WAKE_GAP_MS;
|
|
705
|
+
const objects = await this.bots();
|
|
706
|
+
for (const object of objects) {
|
|
707
|
+
if (object.data.removed === true) continue;
|
|
708
|
+
const bot = object.id;
|
|
709
|
+
for (const entry of scheduledPrompts(object.data)) {
|
|
710
|
+
await this.one(bot, entry, now, catchUp);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
} finally {
|
|
714
|
+
this.busy = false;
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
private async bots(): Promise<readonly StoredObject[]> {
|
|
719
|
+
const found: StoredObject[] = [];
|
|
720
|
+
let cursor: string | undefined;
|
|
721
|
+
do {
|
|
722
|
+
const page = await this.ctx.store.list(BOT_TYPE, {
|
|
723
|
+
...(cursor === undefined ? {} : { cursor }),
|
|
724
|
+
});
|
|
725
|
+
found.push(...page.objects);
|
|
726
|
+
cursor = page.next;
|
|
727
|
+
} while (cursor !== undefined);
|
|
728
|
+
return found;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
private async one(bot: string, entry: ScheduledPrompt, now: number, catchUp: boolean): Promise<void> {
|
|
732
|
+
const latest = latestCronMinute(parseCron(entry.schedule), now, CATCH_UP_DAYS);
|
|
733
|
+
const baseline = latest ?? minuteStart(now);
|
|
734
|
+
if (entry.paused) {
|
|
735
|
+
// A paused entry does not collect missed times: its planned time follows
|
|
736
|
+
// the clock, so resuming waits for the next planned minute. Its last
|
|
737
|
+
// result is kept.
|
|
738
|
+
const kept =
|
|
739
|
+
entry.last !== undefined && entry.last.schedule === entry.schedule
|
|
740
|
+
? entry.last
|
|
741
|
+
: undefined;
|
|
742
|
+
if (kept?.plannedAt !== baseline) {
|
|
743
|
+
await this.setLast(bot, entry.name, {
|
|
744
|
+
...(kept ?? {}),
|
|
745
|
+
plannedAt: baseline,
|
|
746
|
+
schedule: entry.schedule,
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
const last =
|
|
752
|
+
entry.last !== undefined && entry.last.schedule === entry.schedule ? entry.last : undefined;
|
|
753
|
+
if (last === undefined) {
|
|
754
|
+
await this.setLast(bot, entry.name, {
|
|
755
|
+
...(entry.last?.result === undefined
|
|
756
|
+
? {}
|
|
757
|
+
: { result: entry.last.result, ...(entry.last.notified === true ? { notified: true } : {}) }),
|
|
758
|
+
...(entry.last?.chatId === undefined ? {} : { chatId: entry.last.chatId }),
|
|
759
|
+
plannedAt: baseline,
|
|
760
|
+
schedule: entry.schedule,
|
|
761
|
+
});
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
let minute: number | null;
|
|
765
|
+
let skipped: readonly number[] = [];
|
|
766
|
+
if (catchUp) {
|
|
767
|
+
if (latest === null || latest <= last.plannedAt) return;
|
|
768
|
+
const windowStart = Math.max(last.plannedAt, minuteStart(now) - CATCH_UP_DAYS * DAY_MS);
|
|
769
|
+
if (latest <= windowStart) {
|
|
770
|
+
await this.setLast(bot, entry.name, { ...last, plannedAt: latest });
|
|
771
|
+
return;
|
|
772
|
+
}
|
|
773
|
+
skipped = cronMinutesBetween(parseCron(entry.schedule), windowStart, latest).slice(0, -1);
|
|
774
|
+
minute = latest;
|
|
775
|
+
} else {
|
|
776
|
+
minute = latest !== null && latest > last.plannedAt ? latest : null;
|
|
777
|
+
}
|
|
778
|
+
if (minute === null) return;
|
|
779
|
+
const late = minute < minuteStart(now) || skipped.length > 0;
|
|
780
|
+
await this.fire(bot, entry, minute, now, late, skipped);
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
private async fire(
|
|
784
|
+
bot: string,
|
|
785
|
+
entry: ScheduledPrompt,
|
|
786
|
+
minute: number,
|
|
787
|
+
now: number,
|
|
788
|
+
late: boolean,
|
|
789
|
+
skipped: readonly number[],
|
|
790
|
+
): Promise<void> {
|
|
791
|
+
const lateSecs = Math.floor((now - minute) / 1_000);
|
|
792
|
+
await this.setLast(bot, entry.name, {
|
|
793
|
+
plannedAt: minute,
|
|
794
|
+
firedAt: now,
|
|
795
|
+
schedule: entry.schedule,
|
|
796
|
+
});
|
|
797
|
+
const prompt = late
|
|
798
|
+
? `${entry.prompt}\n\n${latenessLine(minute, lateSecs)}`
|
|
799
|
+
: entry.prompt;
|
|
800
|
+
const title = `${entry.name} (${localDate(minute)})`.slice(0, 120);
|
|
801
|
+
let chatId: string | undefined;
|
|
802
|
+
try {
|
|
803
|
+
const run = await this.ctx.client.act("bot:chat", `${BOT_TYPE}:${bot}`, {
|
|
804
|
+
args: {
|
|
805
|
+
title,
|
|
806
|
+
message: prompt,
|
|
807
|
+
...(entry.model === undefined ? {} : { model: entry.model }),
|
|
808
|
+
...(entry.effort === undefined ? {} : { effort: entry.effort }),
|
|
809
|
+
},
|
|
810
|
+
// The entry's name is the origin recorded on the new chat.
|
|
811
|
+
actor: { via: SCHEDULE_SOURCE, id: entry.name },
|
|
812
|
+
});
|
|
813
|
+
chatId = run.opens?.startsWith(`${CHAT_TYPE}:`) === true
|
|
814
|
+
? run.opens.slice(CHAT_TYPE.length + 1)
|
|
815
|
+
: undefined;
|
|
816
|
+
} catch (error) {
|
|
817
|
+
const message = messageOf(error);
|
|
818
|
+
await this.setLast(bot, entry.name, {
|
|
819
|
+
plannedAt: minute,
|
|
820
|
+
firedAt: now,
|
|
821
|
+
schedule: entry.schedule,
|
|
822
|
+
result: replySummary(`Could not start: ${message}`),
|
|
823
|
+
});
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
if (chatId === undefined) {
|
|
827
|
+
await this.chatWatches.log(`scheduled prompt "${entry.name}" of bot ${bot} opened no chat`);
|
|
828
|
+
return;
|
|
829
|
+
}
|
|
830
|
+
const changed = await replaceEntry(
|
|
831
|
+
this.ctx.store,
|
|
832
|
+
bot,
|
|
833
|
+
entry.name,
|
|
834
|
+
(current) =>
|
|
835
|
+
current.last?.plannedAt === minute
|
|
836
|
+
? { ...current, last: { ...current.last, chatId } }
|
|
837
|
+
: undefined,
|
|
838
|
+
"step:bot/scheduled",
|
|
839
|
+
);
|
|
840
|
+
if (changed === undefined) return;
|
|
841
|
+
await this.watch(bot, entry.name, minute, chatId);
|
|
842
|
+
if (skipped.length > 0) {
|
|
843
|
+
await this.chatWatches.log(
|
|
844
|
+
`scheduled prompt "${entry.name}" of bot ${bot}: skipped ${skipped
|
|
845
|
+
.map((time) => new Date(time).toISOString())
|
|
846
|
+
.join(", ")}; only the latest missed run is caught up`,
|
|
847
|
+
);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
private async setLast(bot: string, name: string, last: ScheduledLast): Promise<void> {
|
|
852
|
+
await replaceEntry(
|
|
853
|
+
this.ctx.store,
|
|
854
|
+
bot,
|
|
855
|
+
name,
|
|
856
|
+
(entry) => ({ ...entry, last }),
|
|
857
|
+
"source:bot/scheduled",
|
|
858
|
+
);
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
private async watch(bot: string, name: string, plannedAt: number, chatId: string): Promise<void> {
|
|
862
|
+
const key = `${bot}\u0000${name}\u0000${plannedAt}\u0000${chatId}`;
|
|
863
|
+
this.chatWatches.watchChatReply(
|
|
864
|
+
key,
|
|
865
|
+
chatId,
|
|
866
|
+
async (read) => {
|
|
867
|
+
const chat = await this.ctx.store.get(CHAT_TYPE, chatId);
|
|
868
|
+
if (chat === undefined) return undefined;
|
|
869
|
+
const reply = [...read.messages].reverse().find((message) => message.role === "assistant");
|
|
870
|
+
const failure = [...read.entries].reverse().find((item) => item.kind === "failure");
|
|
871
|
+
const result =
|
|
872
|
+
reply === undefined
|
|
873
|
+
? failure === undefined
|
|
874
|
+
? undefined
|
|
875
|
+
: replySummary(failure.text ?? "The reply failed.")
|
|
876
|
+
: replySummary(reply.text);
|
|
877
|
+
if (result === undefined) return undefined;
|
|
878
|
+
const title = typeof chat.data.title === "string" ? chat.data.title : chatId;
|
|
879
|
+
return { result, title };
|
|
880
|
+
},
|
|
881
|
+
async ({ result, title }) => {
|
|
882
|
+
await replaceEntry(
|
|
883
|
+
this.ctx.store,
|
|
884
|
+
bot,
|
|
885
|
+
name,
|
|
886
|
+
(entry) =>
|
|
887
|
+
entry.last?.chatId === chatId
|
|
888
|
+
? { ...entry, last: { ...entry.last, result, notified: false } }
|
|
889
|
+
: undefined,
|
|
890
|
+
"step:bot/scheduled",
|
|
891
|
+
);
|
|
892
|
+
try {
|
|
893
|
+
await this.notify({ chatId, title, summary: result });
|
|
894
|
+
} catch (error) {
|
|
895
|
+
await this.chatWatches.log(
|
|
896
|
+
`scheduled prompt "${name}" of bot ${bot}: notify: ${messageOf(error)}`,
|
|
897
|
+
);
|
|
898
|
+
}
|
|
899
|
+
await replaceEntry(
|
|
900
|
+
this.ctx.store,
|
|
901
|
+
bot,
|
|
902
|
+
name,
|
|
903
|
+
(entry) =>
|
|
904
|
+
entry.last?.chatId === chatId
|
|
905
|
+
? { ...entry, last: { ...entry.last, notified: true } }
|
|
906
|
+
: undefined,
|
|
907
|
+
"step:bot/scheduled",
|
|
908
|
+
);
|
|
909
|
+
},
|
|
910
|
+
);
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/** Watches a firing that was already started, such as one from before a restart. */
|
|
914
|
+
private async resumeWatches(): Promise<void> {
|
|
915
|
+
for (const object of await this.bots()) {
|
|
916
|
+
if (object.data.removed === true) continue;
|
|
917
|
+
for (const entry of scheduledPrompts(object.data)) {
|
|
918
|
+
const last = entry.last;
|
|
919
|
+
if (last?.chatId === undefined || last.notified === true) continue;
|
|
920
|
+
await this.watch(object.id, entry.name, last.plannedAt, last.chatId);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
start(): SourceHandle {
|
|
926
|
+
this.timer = setInterval(() => {
|
|
927
|
+
this.chatWatches.track(this.poll());
|
|
928
|
+
}, CHECK_INTERVAL_MS);
|
|
929
|
+
if (typeof this.timer === "object" && "unref" in this.timer) {
|
|
930
|
+
this.timer.unref();
|
|
931
|
+
}
|
|
932
|
+
return {
|
|
933
|
+
stop: () => {
|
|
934
|
+
this.stopped = true;
|
|
935
|
+
if (this.timer !== undefined) clearInterval(this.timer);
|
|
936
|
+
this.chatWatches.stopAll();
|
|
937
|
+
},
|
|
938
|
+
};
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
/** The source's first pass, after the bot plugin has made its objects. */
|
|
942
|
+
async begin(): Promise<void> {
|
|
943
|
+
try {
|
|
944
|
+
await this.ctx.client.list(BOT_TYPE);
|
|
945
|
+
} catch (error) {
|
|
946
|
+
await this.chatWatches.log(`scheduled prompts: ${messageOf(error)}`);
|
|
947
|
+
}
|
|
948
|
+
await this.resumeWatches();
|
|
949
|
+
await this.poll();
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
/** The source the bot plugin declares; `begin` runs before the first interval. */
|
|
954
|
+
export async function startScheduled(ctx: SourceContext): Promise<SourceHandle> {
|
|
955
|
+
const source = new BotScheduleSource(ctx);
|
|
956
|
+
await source.begin();
|
|
957
|
+
return source.start();
|
|
958
|
+
}
|
|
959
|
+
|