@operad-io/bot 0.3.1 → 0.4.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/bot.schema.json +1 -1
- package/package.json +6 -6
- package/src/bot.ts +1 -1
- package/src/chat-watch.ts +7 -0
- package/src/delivery.ts +48 -0
- package/src/idle.ts +40 -0
- package/src/index.ts +53 -19
- package/src/proposals.ts +17 -17
- package/src/routine.ts +304 -0
- package/src/schedule.ts +449 -330
- package/src/tidy.ts +204 -59
package/src/schedule.ts
CHANGED
|
@@ -1,17 +1,23 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* and
|
|
2
|
+
* Routines of a bot (ADR 0030 D10). The bot plugin is its own source: it reads
|
|
3
|
+
* the routine objects, fires the latest planned minute when it is due, starts a
|
|
4
|
+
* run with the prompt, and when the reply ends it records the result in the
|
|
5
|
+
* routine's history and delivers it to the bot's main chat (ADR 0030 D10).
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
7
|
+
* A run keeps its reply and process in a record the chat plugin writes, but it
|
|
8
|
+
* is not a chat: it has an `R-` id, is in no chat list, and nothing a person
|
|
9
|
+
* reads calls it a chat.
|
|
10
|
+
*
|
|
11
|
+
* A routine is an object of its own (`bot-routine`, parent its bot), not a field
|
|
12
|
+
* of the bot and not in `config.json`: a client's change is the owner's own edit
|
|
13
|
+
* and applies at once, and `serve` needs no reload. The schedule is a
|
|
14
|
+
* five-field cron expression in the machine's local time zone, with the
|
|
15
|
+
* catch-up rule of the cron source (ADR 0032 D11).
|
|
11
16
|
*/
|
|
12
17
|
|
|
13
18
|
import { messageOf } from "@operad-io/engine";
|
|
14
19
|
import { CHAT_TYPE, chatData, sendMessage } from "@operad-io/chat";
|
|
20
|
+
import { deliverToMainChat } from "./delivery.ts";
|
|
15
21
|
import { ChatWatches } from "./chat-watch.ts";
|
|
16
22
|
import {
|
|
17
23
|
cronMatches,
|
|
@@ -19,10 +25,7 @@ import {
|
|
|
19
25
|
isRecord,
|
|
20
26
|
latestCronMinute,
|
|
21
27
|
minuteStart,
|
|
22
|
-
NOTIFY_TIMEOUT_MS,
|
|
23
|
-
objectLink,
|
|
24
28
|
parseCron,
|
|
25
|
-
readConfig,
|
|
26
29
|
type ActionArgsSchema,
|
|
27
30
|
type ActionTypeDefinition,
|
|
28
31
|
type JsonValue,
|
|
@@ -33,7 +36,6 @@ import {
|
|
|
33
36
|
type SourceHandle,
|
|
34
37
|
type StoredObject,
|
|
35
38
|
} from "@operad-io/engine";
|
|
36
|
-
import { runLine } from "@operad-io/engine/platform";
|
|
37
39
|
import { BOT_TYPE, BotError } from "./bot.ts";
|
|
38
40
|
import { followUps, removeFollowUp, withBotLock, type FollowUp } from "./follow-up.ts";
|
|
39
41
|
import { SETUP_DEV_INSTRUCTION } from "./setup-dev.ts";
|
|
@@ -43,6 +45,12 @@ import { SETUP_INSTRUCTION } from "./setup.ts";
|
|
|
43
45
|
/** The source's name for a scheduled message; a message from it is a background run. */
|
|
44
46
|
export const SCHEDULE_SOURCE = "bot";
|
|
45
47
|
|
|
48
|
+
/** The object type of a routine. */
|
|
49
|
+
export const ROUTINE_TYPE = "bot-routine";
|
|
50
|
+
|
|
51
|
+
/** How long a routine keeps its runs in its history (ADR 0030 D10). */
|
|
52
|
+
export const ROUTINE_HISTORY_DAYS = 30;
|
|
53
|
+
|
|
46
54
|
/** How often the source checks the clock. */
|
|
47
55
|
const CHECK_INTERVAL_MS = 1_000;
|
|
48
56
|
/** A gap much larger than the check interval means the machine slept or the clock jumped. */
|
|
@@ -61,10 +69,12 @@ export interface ScheduledLast {
|
|
|
61
69
|
readonly schedule: string;
|
|
62
70
|
/** True when the firing caught up after earlier planned minutes were skipped. */
|
|
63
71
|
readonly skippedEarlier?: boolean | undefined;
|
|
64
|
-
/** The
|
|
65
|
-
readonly
|
|
72
|
+
/** The run the firing started. */
|
|
73
|
+
readonly runId?: string | undefined;
|
|
66
74
|
/** A short summary of the reply, or why it could not start. */
|
|
67
75
|
readonly result?: string | undefined;
|
|
76
|
+
/** True when the firing could not start or its reply failed. */
|
|
77
|
+
readonly failed?: boolean | undefined;
|
|
68
78
|
/** True once the notify command was run for `result`. */
|
|
69
79
|
readonly notified?: boolean | undefined;
|
|
70
80
|
/** True when a person ran the entry now: `firedAt` is then the run's time, and `plannedAt` is untouched. */
|
|
@@ -91,7 +101,23 @@ export const SCHEDULE_QUIET_RESULT = "Nothing to report.";
|
|
|
91
101
|
/** The line every scheduled prompt ends with: how to end quietly. */
|
|
92
102
|
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
103
|
|
|
94
|
-
/**
|
|
104
|
+
/** How one run of a routine ended. */
|
|
105
|
+
export type RoutineRunStatus = "running" | "done" | "quiet" | "failed";
|
|
106
|
+
|
|
107
|
+
/** One run in a routine's history. */
|
|
108
|
+
export interface RoutineRun {
|
|
109
|
+
/** The id of the run's record, which holds its process and reply. */
|
|
110
|
+
readonly id: string;
|
|
111
|
+
/** When the run started, in epoch milliseconds. */
|
|
112
|
+
readonly at: number;
|
|
113
|
+
readonly status: RoutineRunStatus;
|
|
114
|
+
/** A short summary of the reply, or why it failed; absent while it runs. */
|
|
115
|
+
readonly result?: string | undefined;
|
|
116
|
+
/** True when a person ran it now. */
|
|
117
|
+
readonly manual?: boolean | undefined;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** One routine of a bot. */
|
|
95
121
|
export interface ScheduledPrompt {
|
|
96
122
|
readonly name: string;
|
|
97
123
|
/** A five-field cron expression in the machine's local time zone. */
|
|
@@ -105,6 +131,8 @@ export interface ScheduledPrompt {
|
|
|
105
131
|
readonly recent?: readonly ScheduledRecent[] | undefined;
|
|
106
132
|
/** When a person asked to run it now, until the source starts that run. */
|
|
107
133
|
readonly runNow?: number | undefined;
|
|
134
|
+
/** The runs of the last 30 days, oldest first. */
|
|
135
|
+
readonly runs?: readonly RoutineRun[] | undefined;
|
|
108
136
|
}
|
|
109
137
|
|
|
110
138
|
/** The longest summary an entry keeps and a notification carries. */
|
|
@@ -125,13 +153,38 @@ function lastOf(value: unknown): ScheduledLast | undefined {
|
|
|
125
153
|
: {}),
|
|
126
154
|
schedule: value.schedule,
|
|
127
155
|
...(value.skippedEarlier === true ? { skippedEarlier: true } : {}),
|
|
128
|
-
|
|
156
|
+
// A firing recorded before routines were objects named its chat.
|
|
157
|
+
...(text(value.runId) === undefined
|
|
158
|
+
? text(value.chatId) === undefined
|
|
159
|
+
? {}
|
|
160
|
+
: { runId: value.chatId as string }
|
|
161
|
+
: { runId: value.runId as string }),
|
|
129
162
|
...(text(value.result) === undefined ? {} : { result: value.result as string }),
|
|
163
|
+
...(value.failed === true ? { failed: true } : {}),
|
|
130
164
|
...(value.notified === true ? { notified: true } : {}),
|
|
131
165
|
...(value.manual === true ? { manual: true } : {}),
|
|
132
166
|
};
|
|
133
167
|
}
|
|
134
168
|
|
|
169
|
+
function runsOf(value: unknown): readonly RoutineRun[] {
|
|
170
|
+
const found: RoutineRun[] = [];
|
|
171
|
+
if (!Array.isArray(value)) return found;
|
|
172
|
+
for (const item of value) {
|
|
173
|
+
if (!isRecord(item) || text(item.id) === undefined) continue;
|
|
174
|
+
if (typeof item.at !== "number" || !Number.isFinite(item.at)) continue;
|
|
175
|
+
const status = item.status;
|
|
176
|
+
if (status !== "running" && status !== "done" && status !== "quiet" && status !== "failed") continue;
|
|
177
|
+
found.push({
|
|
178
|
+
id: item.id as string,
|
|
179
|
+
at: item.at,
|
|
180
|
+
status,
|
|
181
|
+
...(text(item.result) === undefined ? {} : { result: item.result as string }),
|
|
182
|
+
...(item.manual === true ? { manual: true } : {}),
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
return found;
|
|
186
|
+
}
|
|
187
|
+
|
|
135
188
|
/** One scheduled prompt from stored data, or undefined when it is unusable. */
|
|
136
189
|
export function scheduledPromptOf(value: unknown): ScheduledPrompt | undefined {
|
|
137
190
|
if (!isRecord(value)) return undefined;
|
|
@@ -149,10 +202,12 @@ export function scheduledPromptOf(value: unknown): ScheduledPrompt | undefined {
|
|
|
149
202
|
recent.push({ plannedAt: item.plannedAt, result: item.result as string });
|
|
150
203
|
}
|
|
151
204
|
}
|
|
205
|
+
const runs = runsOf(value.runs);
|
|
152
206
|
return {
|
|
153
207
|
name,
|
|
154
208
|
schedule,
|
|
155
209
|
prompt,
|
|
210
|
+
...(runs.length === 0 ? {} : { runs }),
|
|
156
211
|
...(text(value.model) === undefined ? {} : { model: value.model as string }),
|
|
157
212
|
...(text(value.effort) === undefined ? {} : { effort: value.effort as string }),
|
|
158
213
|
paused: value.paused === true,
|
|
@@ -162,18 +217,71 @@ export function scheduledPromptOf(value: unknown): ScheduledPrompt | undefined {
|
|
|
162
217
|
};
|
|
163
218
|
}
|
|
164
219
|
|
|
165
|
-
/** The
|
|
166
|
-
|
|
167
|
-
const
|
|
168
|
-
|
|
220
|
+
/** The routine objects, every page. */
|
|
221
|
+
async function allRoutines(store: ObjectStore): Promise<readonly StoredObject[]> {
|
|
222
|
+
const found: StoredObject[] = [];
|
|
223
|
+
let cursor: string | undefined;
|
|
224
|
+
do {
|
|
225
|
+
const page = await store.list(ROUTINE_TYPE, { ...(cursor === undefined ? {} : { cursor }) });
|
|
226
|
+
found.push(...page.objects);
|
|
227
|
+
cursor = page.next;
|
|
228
|
+
} while (cursor !== undefined);
|
|
229
|
+
return found;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** True for a routine a person made or a bot proposed; false for a built-in one, or a removed one. */
|
|
233
|
+
function isUserRoutine(object: StoredObject): boolean {
|
|
234
|
+
return object.data.removed !== true && object.data.builtin === undefined;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** The routine objects of one bot that a person made, in id order. */
|
|
238
|
+
export async function routineObjects(store: ObjectStore, bot: string): Promise<readonly StoredObject[]> {
|
|
239
|
+
return (await allRoutines(store)).filter((object) => object.data.bot === bot && isUserRoutine(object));
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** The routines of one bot that a person made, as entries. */
|
|
243
|
+
export async function routinesOf(store: ObjectStore, bot: string): Promise<readonly ScheduledPrompt[]> {
|
|
169
244
|
const found: ScheduledPrompt[] = [];
|
|
170
|
-
for (const
|
|
245
|
+
for (const object of await routineObjects(store, bot)) {
|
|
246
|
+
const entry = scheduledPromptOf(object.data);
|
|
247
|
+
if (entry !== undefined) found.push(entry);
|
|
248
|
+
}
|
|
249
|
+
return found;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** The routine object of a bot with this name, when there is one. */
|
|
253
|
+
export async function findRoutine(store: ObjectStore, bot: string, name: string): Promise<StoredObject | undefined> {
|
|
254
|
+
return (await routineObjects(store, bot)).find((object) => object.data.name === name);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
async function nextRoutineId(store: ObjectStore): Promise<string> {
|
|
258
|
+
let highest = 0;
|
|
259
|
+
for (const object of await allRoutines(store)) {
|
|
260
|
+
const match = /^RT-(\d+)$/.exec(object.id);
|
|
261
|
+
if (match !== null) highest = Math.max(highest, Number(match[1]));
|
|
262
|
+
}
|
|
263
|
+
return `RT-${String(highest + 1).padStart(4, "0")}`;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** The entries a bot object carried before routines were objects. */
|
|
267
|
+
export function legacyScheduled(data: Readonly<Record<string, unknown>>): readonly ScheduledPrompt[] {
|
|
268
|
+
const found: ScheduledPrompt[] = [];
|
|
269
|
+
if (!Array.isArray(data.scheduled)) return found;
|
|
270
|
+
for (const value of data.scheduled) {
|
|
171
271
|
const entry = scheduledPromptOf(value);
|
|
172
272
|
if (entry !== undefined) found.push(entry);
|
|
173
273
|
}
|
|
174
274
|
return found;
|
|
175
275
|
}
|
|
176
276
|
|
|
277
|
+
/** Moves the entries a bot object still carries into routine objects of their own. */
|
|
278
|
+
export async function migrateScheduled(store: ObjectStore, bot: string, data: Readonly<Record<string, unknown>>): Promise<void> {
|
|
279
|
+
for (const entry of legacyScheduled(data)) {
|
|
280
|
+
if ((await findRoutine(store, bot, entry.name)) !== undefined) continue;
|
|
281
|
+
await store.put(ROUTINE_TYPE, await nextRoutineId(store), { ...stored(entry), bot }, "migrate:bot/routine");
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
177
285
|
/** What a chat's schedule command asks a person to decide. */
|
|
178
286
|
export interface ScheduleChange {
|
|
179
287
|
readonly action: "add" | "edit" | "remove";
|
|
@@ -215,14 +323,57 @@ function stored(entry: ScheduledPrompt): Record<string, JsonValue> {
|
|
|
215
323
|
? {}
|
|
216
324
|
: { recent: entry.recent as unknown as JsonValue }),
|
|
217
325
|
...(entry.runNow === undefined ? {} : { runNow: entry.runNow }),
|
|
326
|
+
...(entry.runs === undefined || entry.runs.length === 0
|
|
327
|
+
? {}
|
|
328
|
+
: { runs: entry.runs as unknown as JsonValue }),
|
|
218
329
|
};
|
|
219
330
|
}
|
|
220
331
|
|
|
332
|
+
/** The runs after one is added or updated; a run older than the history keeps is dropped. */
|
|
333
|
+
export function withRun(runs: readonly RoutineRun[] | undefined, run: RoutineRun, now: number): readonly RoutineRun[] {
|
|
334
|
+
const oldest = now - ROUTINE_HISTORY_DAYS * DAY_MS;
|
|
335
|
+
return [...(runs ?? []).filter((item) => item.id !== run.id && item.at >= oldest), run];
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** The ids of the runs `withRun` drops: older than the history keeps, and not the run being recorded. */
|
|
339
|
+
export function droppedRuns(runs: readonly RoutineRun[] | undefined, run: RoutineRun, now: number): readonly string[] {
|
|
340
|
+
const oldest = now - ROUTINE_HISTORY_DAYS * DAY_MS;
|
|
341
|
+
return (runs ?? []).filter((item) => item.id !== run.id && item.at < oldest).map((item) => item.id);
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Removes the records of runs that left a routine's history; a missing record is left alone. */
|
|
345
|
+
export async function forgetRuns(store: ObjectStore, ids: readonly string[]): Promise<void> {
|
|
346
|
+
for (const id of ids) await store.remove(CHAT_TYPE, id);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** Drops, from every routine, the runs older than the history keeps; the last results on the routine stay. Returns how many routines changed. */
|
|
350
|
+
export async function pruneRoutineRuns(store: ObjectStore, now: number): Promise<number> {
|
|
351
|
+
const oldest = now - ROUTINE_HISTORY_DAYS * DAY_MS;
|
|
352
|
+
let changed = 0;
|
|
353
|
+
for (const object of await allRoutines(store)) {
|
|
354
|
+
const entry = scheduledPromptOf(object.data);
|
|
355
|
+
if (entry === undefined || entry.runs === undefined) continue;
|
|
356
|
+
const kept = entry.runs.filter((run) => run.at >= oldest || run.status === "running");
|
|
357
|
+
if (kept.length === entry.runs.length) continue;
|
|
358
|
+
const dropped = entry.runs.filter((run) => !kept.includes(run)).map((run) => run.id);
|
|
359
|
+
const { runs: _dropped, ...rest } = object.data;
|
|
360
|
+
await store.put(
|
|
361
|
+
ROUTINE_TYPE,
|
|
362
|
+
object.id,
|
|
363
|
+
kept.length === 0 ? rest : { ...rest, runs: kept as unknown as JsonValue },
|
|
364
|
+
"cleanup:bot/routine-history",
|
|
365
|
+
);
|
|
366
|
+
await forgetRuns(store, dropped);
|
|
367
|
+
changed += 1;
|
|
368
|
+
}
|
|
369
|
+
return changed;
|
|
370
|
+
}
|
|
371
|
+
|
|
221
372
|
/** The name a client uses to choose an entry; unique within one bot. */
|
|
222
373
|
export function checkPromptName(name: string): string {
|
|
223
374
|
const trimmed = name.trim();
|
|
224
|
-
if (trimmed.length === 0) throw new BotError("a
|
|
225
|
-
if (trimmed.length > 120) throw new BotError("a
|
|
375
|
+
if (trimmed.length === 0) throw new BotError("a routine needs a name");
|
|
376
|
+
if (trimmed.length > 120) throw new BotError("a routine's name is at most 120 characters");
|
|
226
377
|
return trimmed;
|
|
227
378
|
}
|
|
228
379
|
|
|
@@ -269,9 +420,9 @@ function recentText(result: string): string {
|
|
|
269
420
|
: `${result.slice(0, SCHEDULE_RECENT_MAX - 1)}…`;
|
|
270
421
|
}
|
|
271
422
|
|
|
272
|
-
/** True while the last firing's
|
|
423
|
+
/** True while the last firing's run has started and its result is not yet recorded. */
|
|
273
424
|
function isReplying(last: ScheduledLast | undefined): boolean {
|
|
274
|
-
return last?.
|
|
425
|
+
return last?.runId !== undefined && last.result === undefined;
|
|
275
426
|
}
|
|
276
427
|
|
|
277
428
|
/**
|
|
@@ -293,7 +444,7 @@ export function scheduledInstruction(entry: ScheduledPrompt): string {
|
|
|
293
444
|
if (recent.length > 0) {
|
|
294
445
|
const lines = recent.map((item) => `- ${localStamp(item.plannedAt)}: ${recentText(item.result)}`);
|
|
295
446
|
parts.push(
|
|
296
|
-
`Earlier results of this
|
|
447
|
+
`Earlier results of this routine, oldest first; the person has already seen them, so do not repeat them:\n${lines.join("\n")}`,
|
|
297
448
|
);
|
|
298
449
|
}
|
|
299
450
|
parts.push(SCHEDULE_PREAMBLE);
|
|
@@ -301,9 +452,9 @@ export function scheduledInstruction(entry: ScheduledPrompt): string {
|
|
|
301
452
|
return parts.join("\n\n");
|
|
302
453
|
}
|
|
303
454
|
|
|
304
|
-
/** The instruction of the firing of the named
|
|
305
|
-
export function scheduledInstructionFor(
|
|
306
|
-
const entry =
|
|
455
|
+
/** The instruction of the firing of the named routine now recorded on a bot; undefined when it has none. */
|
|
456
|
+
export async function scheduledInstructionFor(store: ObjectStore, bot: string, name: string): Promise<string | undefined> {
|
|
457
|
+
const entry = scheduledPromptOf((await findRoutine(store, bot, name))?.data);
|
|
307
458
|
return entry === undefined ? undefined : scheduledInstruction(entry);
|
|
308
459
|
}
|
|
309
460
|
|
|
@@ -345,43 +496,6 @@ export function nextRun(entry: ScheduledPrompt, now: number): number | null {
|
|
|
345
496
|
return null;
|
|
346
497
|
}
|
|
347
498
|
|
|
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
499
|
/** A short, one-line summary of a reply. */
|
|
386
500
|
export function replySummary(message: string): string {
|
|
387
501
|
const oneLine = message.replace(/\s+/g, " ").trim();
|
|
@@ -391,38 +505,38 @@ export function replySummary(message: string): string {
|
|
|
391
505
|
: `${oneLine.slice(0, SCHEDULE_SUMMARY_MAX - 1)}…`;
|
|
392
506
|
}
|
|
393
507
|
|
|
394
|
-
/** What a
|
|
508
|
+
/** What a finished routine run delivers. */
|
|
395
509
|
export interface ScheduleNotice {
|
|
396
|
-
|
|
510
|
+
/** The routine's object id. */
|
|
511
|
+
readonly routineId: string;
|
|
512
|
+
/** The run's record id. */
|
|
513
|
+
readonly runId: string;
|
|
397
514
|
readonly title: string;
|
|
515
|
+
/** A short summary; it is what rides on the main chat's next message. */
|
|
398
516
|
readonly summary: string;
|
|
517
|
+
/** The whole result, shown in the main chat and sent to a bound Telegram chat. */
|
|
518
|
+
readonly text: string;
|
|
519
|
+
/** True when the run failed. */
|
|
520
|
+
readonly failed: boolean;
|
|
521
|
+
/** The bot whose main chat gets it. */
|
|
522
|
+
readonly bot: string;
|
|
399
523
|
}
|
|
400
524
|
|
|
401
|
-
/**
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
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
|
-
}
|
|
525
|
+
/**
|
|
526
|
+
* The delivery a routine's result makes: a message in the bot's main chat
|
|
527
|
+
* (see {@link deliverToMainChat}). A host with no way to write facts delivers
|
|
528
|
+
* nothing and the result stays in the routine's history.
|
|
529
|
+
*/
|
|
530
|
+
export function mainChatDelivery(
|
|
531
|
+
ctx: { readonly store: ObjectStore; readonly facts?: SourceContext["facts"] | undefined; readonly logger: { write(text: string): Promise<string> } },
|
|
532
|
+
): (notice: ScheduleNotice) => Promise<void> {
|
|
533
|
+
return async (notice) => {
|
|
534
|
+
const bot = notice.bot;
|
|
535
|
+
const { facts } = ctx;
|
|
536
|
+
if (facts === undefined) return;
|
|
537
|
+
const delivered = await deliverToMainChat({ store: ctx.store, facts }, bot, notice);
|
|
538
|
+
if (!delivered) await ctx.logger.write(`routine "${notice.title}" of bot ${bot}: the bot has no open chat; the result stays in the routine's history\n`);
|
|
539
|
+
};
|
|
426
540
|
}
|
|
427
541
|
|
|
428
542
|
/** Reads a bot object, or says why it cannot be used. */
|
|
@@ -433,7 +547,7 @@ async function botObject(store: ObjectStore, bot: string): Promise<StoredObject>
|
|
|
433
547
|
return object;
|
|
434
548
|
}
|
|
435
549
|
|
|
436
|
-
/** Replaces one
|
|
550
|
+
/** Replaces one routine of the bot, leaving the others and the bot's settings alone. */
|
|
437
551
|
async function replaceEntry(
|
|
438
552
|
store: ObjectStore,
|
|
439
553
|
bot: string,
|
|
@@ -442,43 +556,25 @@ async function replaceEntry(
|
|
|
442
556
|
cause: string,
|
|
443
557
|
): Promise<ScheduledPrompt | undefined> {
|
|
444
558
|
return withBotLock(store, bot, async () => {
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
if (
|
|
451
|
-
|
|
452
|
-
|
|
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;
|
|
559
|
+
await botObject(store, bot);
|
|
560
|
+
const object = await findRoutine(store, bot, name);
|
|
561
|
+
const entry = scheduledPromptOf(object?.data);
|
|
562
|
+
if (object === undefined || entry === undefined) return undefined;
|
|
563
|
+
const changed = change(entry);
|
|
564
|
+
if (changed === undefined) return undefined;
|
|
565
|
+
await store.put(ROUTINE_TYPE, object.id, { ...stored(changed), bot }, cause);
|
|
566
|
+
return changed;
|
|
465
567
|
});
|
|
466
568
|
}
|
|
467
569
|
|
|
468
|
-
/** Removes one
|
|
570
|
+
/** Removes one routine: its object stays, marked removed, and is in no list of routines. */
|
|
469
571
|
async function removeEntry(store: ObjectStore, bot: string, name: string): Promise<boolean> {
|
|
470
572
|
return withBotLock(store, bot, async () => {
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
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;
|
|
573
|
+
await botObject(store, bot);
|
|
574
|
+
const object = await findRoutine(store, bot, name);
|
|
575
|
+
if (object === undefined) return false;
|
|
576
|
+
await store.put(ROUTINE_TYPE, object.id, { ...object.data, removed: true }, "action:bot/schedule-remove");
|
|
577
|
+
return true;
|
|
482
578
|
});
|
|
483
579
|
}
|
|
484
580
|
|
|
@@ -508,7 +604,7 @@ export async function applyScheduleChange(
|
|
|
508
604
|
change: ScheduleChange,
|
|
509
605
|
): Promise<void> {
|
|
510
606
|
if (change.action === "add") {
|
|
511
|
-
if (change.after === null) throw new BotError("the proposal has no
|
|
607
|
+
if (change.after === null) throw new BotError("the proposal has no routine to add");
|
|
512
608
|
await addEntry(store, bot, change.after);
|
|
513
609
|
return;
|
|
514
610
|
}
|
|
@@ -516,7 +612,7 @@ export async function applyScheduleChange(
|
|
|
516
612
|
const before = change.before;
|
|
517
613
|
const after = change.after;
|
|
518
614
|
if (before === null || after === null) {
|
|
519
|
-
throw new BotError("the proposal has no
|
|
615
|
+
throw new BotError("the proposal has no routine to change");
|
|
520
616
|
}
|
|
521
617
|
const changed = await replaceEntry(
|
|
522
618
|
store,
|
|
@@ -528,37 +624,31 @@ export async function applyScheduleChange(
|
|
|
528
624
|
"action:bot/schedule-edit",
|
|
529
625
|
);
|
|
530
626
|
if (changed === undefined) {
|
|
531
|
-
throw new BotError(`bot ${bot} has no
|
|
627
|
+
throw new BotError(`bot ${bot} has no routine "${before.name}"`);
|
|
532
628
|
}
|
|
533
629
|
return;
|
|
534
630
|
}
|
|
535
631
|
if (change.before === null) {
|
|
536
|
-
throw new BotError("the proposal has no
|
|
632
|
+
throw new BotError("the proposal has no routine to remove");
|
|
537
633
|
}
|
|
538
634
|
if (!(await removeEntry(store, bot, change.before.name))) {
|
|
539
|
-
throw new BotError(`bot ${bot} has no
|
|
635
|
+
throw new BotError(`bot ${bot} has no routine "${change.before.name}"`);
|
|
540
636
|
}
|
|
541
637
|
}
|
|
542
638
|
|
|
543
|
-
/** Adds one
|
|
639
|
+
/** Adds one routine to the bot. */
|
|
544
640
|
async function addEntry(
|
|
545
641
|
store: ObjectStore,
|
|
546
642
|
bot: string,
|
|
547
643
|
entry: ScheduledPrompt,
|
|
548
644
|
): Promise<ScheduledPrompt> {
|
|
549
645
|
return withBotLock(store, bot, async () => {
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
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;
|
|
646
|
+
await botObject(store, bot);
|
|
647
|
+
if ((await findRoutine(store, bot, entry.name)) !== undefined) {
|
|
648
|
+
throw new BotError(`bot ${bot} already has a routine "${entry.name}"`);
|
|
649
|
+
}
|
|
650
|
+
await store.put(ROUTINE_TYPE, await nextRoutineId(store), { ...stored(entry), bot }, "action:bot/schedule-add");
|
|
651
|
+
return entry;
|
|
562
652
|
});
|
|
563
653
|
}
|
|
564
654
|
|
|
@@ -570,7 +660,7 @@ function entryArgs(required: boolean): ActionTypeDefinition["args"] {
|
|
|
570
660
|
type: "string",
|
|
571
661
|
minLength: 1,
|
|
572
662
|
maxLength: 120,
|
|
573
|
-
...(required ? {} : { description: "The
|
|
663
|
+
...(required ? {} : { description: "The routine to change." }),
|
|
574
664
|
},
|
|
575
665
|
schedule: {
|
|
576
666
|
type: "string",
|
|
@@ -581,15 +671,15 @@ function entryArgs(required: boolean): ActionTypeDefinition["args"] {
|
|
|
581
671
|
type: "string",
|
|
582
672
|
role: "note",
|
|
583
673
|
minLength: 1,
|
|
584
|
-
description: "
|
|
674
|
+
description: "What the routine asks the agent each time it runs.",
|
|
585
675
|
},
|
|
586
676
|
model: {
|
|
587
677
|
type: "string",
|
|
588
|
-
description: "The model
|
|
678
|
+
description: "The model a run uses; the bot's model when left out. An empty value clears it.",
|
|
589
679
|
},
|
|
590
680
|
effort: {
|
|
591
681
|
type: "string",
|
|
592
|
-
description: "The effort
|
|
682
|
+
description: "The effort a run uses; the bot's effort when left out. An empty value clears it.",
|
|
593
683
|
},
|
|
594
684
|
},
|
|
595
685
|
...(required ? { required: ["name", "schedule", "prompt"] } : { required: ["name"] }),
|
|
@@ -601,18 +691,141 @@ function nameArg(): ActionTypeDefinition["args"] {
|
|
|
601
691
|
return {
|
|
602
692
|
type: "object",
|
|
603
693
|
properties: {
|
|
604
|
-
name: { type: "string", minLength: 1, description: "The
|
|
694
|
+
name: { type: "string", minLength: 1, description: "The routine's name." },
|
|
605
695
|
},
|
|
606
696
|
required: ["name"],
|
|
607
697
|
additionalProperties: false,
|
|
608
698
|
};
|
|
609
699
|
}
|
|
610
700
|
|
|
611
|
-
/**
|
|
701
|
+
/** What `add` takes. */
|
|
702
|
+
export interface AddInput {
|
|
703
|
+
readonly name: string;
|
|
704
|
+
readonly schedule: string;
|
|
705
|
+
readonly prompt: string;
|
|
706
|
+
readonly model?: string | undefined;
|
|
707
|
+
readonly effort?: string | undefined;
|
|
708
|
+
readonly paused?: boolean | undefined;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/** What `edit` takes: only what is given changes. */
|
|
712
|
+
export interface EditInput {
|
|
713
|
+
readonly schedule?: string | undefined;
|
|
714
|
+
readonly prompt?: string | undefined;
|
|
715
|
+
readonly model?: string | undefined;
|
|
716
|
+
readonly effort?: string | undefined;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/** Adds a routine to a bot. */
|
|
720
|
+
export async function addRoutine(store: ObjectStore, bot: string, input: AddInput): Promise<string> {
|
|
721
|
+
const entry: ScheduledPrompt = {
|
|
722
|
+
name: checkPromptName(input.name),
|
|
723
|
+
schedule: checkSchedule(input.schedule),
|
|
724
|
+
prompt: input.prompt.trim(),
|
|
725
|
+
...(text(input.model) === undefined ? {} : { model: input.model as string }),
|
|
726
|
+
...(text(input.effort) === undefined ? {} : { effort: input.effort as string }),
|
|
727
|
+
paused: input.paused === true,
|
|
728
|
+
};
|
|
729
|
+
if (entry.prompt.length === 0) throw new BotError("a routine needs a prompt");
|
|
730
|
+
await addEntry(store, bot, entry);
|
|
731
|
+
return `added routine "${entry.name}" to bot ${bot}`;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
/** Changes a routine; what is left out stays, and an empty model or effort clears it. */
|
|
735
|
+
export async function editRoutine(store: ObjectStore, bot: string, name: string, input: EditInput): Promise<string> {
|
|
736
|
+
const changed = await replaceEntry(
|
|
737
|
+
store,
|
|
738
|
+
bot,
|
|
739
|
+
name,
|
|
740
|
+
(entry) => {
|
|
741
|
+
const schedule = input.schedule === undefined ? entry.schedule : checkSchedule(input.schedule);
|
|
742
|
+
const prompt = input.prompt === undefined ? entry.prompt : input.prompt.trim();
|
|
743
|
+
if (prompt.length === 0) throw new BotError("a routine needs a prompt");
|
|
744
|
+
const model = input.model === undefined ? entry.model : text(input.model);
|
|
745
|
+
const effort = input.effort === undefined ? entry.effort : text(input.effort);
|
|
746
|
+
return {
|
|
747
|
+
...entry,
|
|
748
|
+
schedule,
|
|
749
|
+
prompt,
|
|
750
|
+
...(model === undefined ? { model: undefined } : { model }),
|
|
751
|
+
...(effort === undefined ? { effort: undefined } : { effort }),
|
|
752
|
+
// A changed schedule keeps `last`: the poll sees its schedule is not the
|
|
753
|
+
// entry's, starts from a new baseline and keeps the run of a firing
|
|
754
|
+
// that still awaits its notification, so no missed time is caught up.
|
|
755
|
+
};
|
|
756
|
+
},
|
|
757
|
+
"action:bot/schedule-edit",
|
|
758
|
+
);
|
|
759
|
+
if (changed === undefined) throw new BotError(`bot ${bot} has no routine "${name}"`);
|
|
760
|
+
return `edited routine "${name}" of bot ${bot}`;
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
/** Pauses a routine. */
|
|
764
|
+
export async function pauseRoutine(store: ObjectStore, bot: string, name: string): Promise<string> {
|
|
765
|
+
const changed = await replaceEntry(
|
|
766
|
+
store,
|
|
767
|
+
bot,
|
|
768
|
+
name,
|
|
769
|
+
(entry) => (entry.paused ? undefined : { ...entry, paused: true }),
|
|
770
|
+
"action:bot/schedule-pause",
|
|
771
|
+
);
|
|
772
|
+
if (changed === undefined) return `routine "${name}" is already paused`;
|
|
773
|
+
return `paused routine "${name}" of bot ${bot}`;
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
/** Resumes a paused routine. */
|
|
777
|
+
export async function resumeRoutine(store: ObjectStore, bot: string, name: string): Promise<string> {
|
|
778
|
+
const changed = await replaceEntry(
|
|
779
|
+
store,
|
|
780
|
+
bot,
|
|
781
|
+
name,
|
|
782
|
+
(entry) => (entry.paused ? { ...entry, paused: false } : undefined),
|
|
783
|
+
"action:bot/schedule-resume",
|
|
784
|
+
);
|
|
785
|
+
if (changed === undefined) return `routine "${name}" is already running`;
|
|
786
|
+
return `resumed routine "${name}" of bot ${bot}`;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/** Asks the source to run a routine once now; its next timed run is unchanged. */
|
|
790
|
+
export async function runRoutineNow(store: ObjectStore, bot: string, name: string): Promise<string> {
|
|
791
|
+
const current = scheduledPromptOf((await findRoutine(store, bot, name))?.data);
|
|
792
|
+
if (current !== undefined && isReplying(current.last)) {
|
|
793
|
+
throw new BotError(
|
|
794
|
+
`routine "${name}" of bot ${bot} is still running its previous run; run it now after that run ends`,
|
|
795
|
+
);
|
|
796
|
+
}
|
|
797
|
+
const changed = await replaceEntry(
|
|
798
|
+
store,
|
|
799
|
+
bot,
|
|
800
|
+
name,
|
|
801
|
+
(entry) => ({ ...entry, runNow: entry.runNow ?? Date.now() }),
|
|
802
|
+
"action:bot/schedule-run-now",
|
|
803
|
+
);
|
|
804
|
+
if (changed === undefined) throw new BotError(`bot ${bot} has no routine "${name}"`);
|
|
805
|
+
return `running routine "${name}" of bot ${bot} now; its next timed run is unchanged`;
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/** Removes a routine. */
|
|
809
|
+
export async function removeRoutine(store: ObjectStore, bot: string, name: string): Promise<string> {
|
|
810
|
+
if (!(await removeEntry(store, bot, name))) throw new BotError(`bot ${bot} has no routine "${name}"`);
|
|
811
|
+
return `removed routine "${name}" from bot ${bot}`;
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
const botUsable = (state: Readonly<Record<string, unknown>>): boolean => state.removed !== true;
|
|
815
|
+
const botWhy = (object: StoredObject): string | undefined =>
|
|
816
|
+
object.data.removed === true ? `bot ${object.id} is no longer in the settings` : undefined;
|
|
817
|
+
|
|
818
|
+
/**
|
|
819
|
+
* The actions on a bot that manage its routines. They keep the `schedule-*`
|
|
820
|
+
* names: the command line, the MCP tools and the clients call them by those
|
|
821
|
+
* names with the routine's name as an argument, and renaming them would break
|
|
822
|
+
* every one of those. A routine's own page has the same actions without the name.
|
|
823
|
+
*/
|
|
612
824
|
export const scheduleActions: readonly ActionTypeDefinition[] = [
|
|
613
825
|
{
|
|
614
826
|
name: "schedule-add",
|
|
615
827
|
on: BOT_TYPE,
|
|
828
|
+
creates: ROUTINE_TYPE,
|
|
616
829
|
args: {
|
|
617
830
|
...(entryArgs(true) as ActionArgsSchema),
|
|
618
831
|
properties: {
|
|
@@ -620,159 +833,60 @@ export const scheduleActions: readonly ActionTypeDefinition[] = [
|
|
|
620
833
|
paused: {
|
|
621
834
|
type: "boolean",
|
|
622
835
|
default: false,
|
|
623
|
-
description: "Start paused; it does not
|
|
836
|
+
description: "Start paused; it does not run until resumed.",
|
|
624
837
|
},
|
|
625
838
|
},
|
|
626
839
|
},
|
|
627
|
-
when:
|
|
628
|
-
why:
|
|
629
|
-
|
|
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
|
-
},
|
|
840
|
+
when: botUsable,
|
|
841
|
+
why: botWhy,
|
|
842
|
+
run: async (ctx, args) => addRoutine(ctx.store, ctx.object.id, args as unknown as AddInput),
|
|
651
843
|
},
|
|
652
844
|
{
|
|
653
845
|
name: "schedule-edit",
|
|
654
846
|
on: BOT_TYPE,
|
|
655
847
|
args: entryArgs(false),
|
|
656
|
-
when:
|
|
657
|
-
why:
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
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}`;
|
|
848
|
+
when: botUsable,
|
|
849
|
+
why: botWhy,
|
|
850
|
+
run: async (ctx, args) => {
|
|
851
|
+
const input = args as unknown as EditInput & { readonly name: string };
|
|
852
|
+
return editRoutine(ctx.store, ctx.object.id, checkPromptName(input.name), input);
|
|
694
853
|
},
|
|
695
854
|
},
|
|
696
855
|
{
|
|
697
856
|
name: "schedule-pause",
|
|
698
857
|
on: BOT_TYPE,
|
|
699
858
|
args: nameArg(),
|
|
700
|
-
when:
|
|
701
|
-
why:
|
|
702
|
-
|
|
703
|
-
|
|
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
|
-
},
|
|
859
|
+
when: botUsable,
|
|
860
|
+
why: botWhy,
|
|
861
|
+
run: async (ctx, args) =>
|
|
862
|
+
pauseRoutine(ctx.store, ctx.object.id, checkPromptName((args as { readonly name: string }).name)),
|
|
715
863
|
},
|
|
716
864
|
{
|
|
717
865
|
name: "schedule-resume",
|
|
718
866
|
on: BOT_TYPE,
|
|
719
867
|
args: nameArg(),
|
|
720
|
-
when:
|
|
721
|
-
why:
|
|
722
|
-
|
|
723
|
-
|
|
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
|
-
},
|
|
868
|
+
when: botUsable,
|
|
869
|
+
why: botWhy,
|
|
870
|
+
run: async (ctx, args) =>
|
|
871
|
+
resumeRoutine(ctx.store, ctx.object.id, checkPromptName((args as { readonly name: string }).name)),
|
|
735
872
|
},
|
|
736
873
|
{
|
|
737
874
|
name: "schedule-run-now",
|
|
738
875
|
on: BOT_TYPE,
|
|
739
876
|
args: nameArg(),
|
|
740
|
-
when:
|
|
741
|
-
why:
|
|
742
|
-
|
|
743
|
-
|
|
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
|
-
},
|
|
877
|
+
when: botUsable,
|
|
878
|
+
why: botWhy,
|
|
879
|
+
run: async (ctx, args) =>
|
|
880
|
+
runRoutineNow(ctx.store, ctx.object.id, checkPromptName((args as { readonly name: string }).name)),
|
|
761
881
|
},
|
|
762
882
|
{
|
|
763
883
|
name: "schedule-remove",
|
|
764
884
|
on: BOT_TYPE,
|
|
765
885
|
args: nameArg(),
|
|
766
|
-
when:
|
|
767
|
-
why:
|
|
768
|
-
|
|
769
|
-
|
|
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
|
-
},
|
|
886
|
+
when: botUsable,
|
|
887
|
+
why: botWhy,
|
|
888
|
+
run: async (ctx, args) =>
|
|
889
|
+
removeRoutine(ctx.store, ctx.object.id, checkPromptName((args as { readonly name: string }).name)),
|
|
776
890
|
},
|
|
777
891
|
];
|
|
778
892
|
|
|
@@ -789,23 +903,6 @@ export function markdownText(value: string): string {
|
|
|
789
903
|
return value.replace(/([\\`*_{}\[\]<>#|~!])/g, "\\$1").replace(/\r?\n/g, " ");
|
|
790
904
|
}
|
|
791
905
|
|
|
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
906
|
interface ScheduledSource {
|
|
810
907
|
readonly store: ObjectStore;
|
|
811
908
|
readonly home: string;
|
|
@@ -834,10 +931,14 @@ export class BotScheduleSource {
|
|
|
834
931
|
options: { readonly notify?: ((notice: ScheduleNotice) => Promise<void>) | undefined } = {},
|
|
835
932
|
) {
|
|
836
933
|
this.ctx = ctx;
|
|
837
|
-
this.notify = options.notify ?? ((notice) =>
|
|
934
|
+
this.notify = options.notify ?? ((notice) => this.deliverFor(notice));
|
|
838
935
|
this.chatWatches = new ChatWatches(ctx.logger, ctx.store, ctx.runs);
|
|
839
936
|
}
|
|
840
937
|
|
|
938
|
+
private deliverFor(notice: ScheduleNotice): Promise<void> {
|
|
939
|
+
return mainChatDelivery(this.ctx)(notice);
|
|
940
|
+
}
|
|
941
|
+
|
|
841
942
|
/** Waits for the checks that are running now; a test calls this after a reply. */
|
|
842
943
|
async settled(): Promise<void> {
|
|
843
944
|
await this.chatWatches.settled();
|
|
@@ -856,7 +957,7 @@ export class BotScheduleSource {
|
|
|
856
957
|
for (const object of objects) {
|
|
857
958
|
if (object.data.removed === true) continue;
|
|
858
959
|
const bot = object.id;
|
|
859
|
-
for (const entry of
|
|
960
|
+
for (const entry of await routinesOf(this.ctx.store, bot)) {
|
|
860
961
|
if (entry.runNow !== undefined) {
|
|
861
962
|
// The entry read here is stale after this; the next check handles its timed run.
|
|
862
963
|
await this.runNow(bot, entry, now);
|
|
@@ -941,7 +1042,7 @@ export class BotScheduleSource {
|
|
|
941
1042
|
...(entry.last?.result === undefined
|
|
942
1043
|
? {}
|
|
943
1044
|
: { result: entry.last.result, ...(entry.last.notified === true ? { notified: true } : {}) }),
|
|
944
|
-
...(entry.last?.
|
|
1045
|
+
...(entry.last?.runId === undefined ? {} : { runId: entry.last.runId }),
|
|
945
1046
|
plannedAt: baseline,
|
|
946
1047
|
schedule: entry.schedule,
|
|
947
1048
|
});
|
|
@@ -982,7 +1083,7 @@ export class BotScheduleSource {
|
|
|
982
1083
|
// A firing started since the request was made still owns `last`: drop the request.
|
|
983
1084
|
if (isReplying(cleared.last)) {
|
|
984
1085
|
await this.chatWatches.log(
|
|
985
|
-
`
|
|
1086
|
+
`routine "${entry.name}" of bot ${bot}: run now dropped, the previous firing is still replying`,
|
|
986
1087
|
);
|
|
987
1088
|
return;
|
|
988
1089
|
}
|
|
@@ -1009,7 +1110,7 @@ export class BotScheduleSource {
|
|
|
1009
1110
|
};
|
|
1010
1111
|
await this.setLast(bot, entry.name, recorded);
|
|
1011
1112
|
const title = `${entry.name} (${localDate(manual ? now : minute)})`.slice(0, 120);
|
|
1012
|
-
let
|
|
1113
|
+
let runId: string | undefined;
|
|
1013
1114
|
try {
|
|
1014
1115
|
const run = await this.ctx.client.act("bot:chat", `${BOT_TYPE}:${bot}`, {
|
|
1015
1116
|
args: {
|
|
@@ -1019,10 +1120,11 @@ export class BotScheduleSource {
|
|
|
1019
1120
|
...(entry.model === undefined ? {} : { model: entry.model }),
|
|
1020
1121
|
...(entry.effort === undefined ? {} : { effort: entry.effort }),
|
|
1021
1122
|
},
|
|
1022
|
-
// The
|
|
1123
|
+
// The routine's name is the origin recorded on the run; an actor from
|
|
1124
|
+
// this source makes the action start a run, not a chat.
|
|
1023
1125
|
actor: { via: SCHEDULE_SOURCE, id: entry.name },
|
|
1024
1126
|
});
|
|
1025
|
-
|
|
1127
|
+
runId = run.opens?.startsWith(`${CHAT_TYPE}:`) === true
|
|
1026
1128
|
? run.opens.slice(CHAT_TYPE.length + 1)
|
|
1027
1129
|
: undefined;
|
|
1028
1130
|
} catch (error) {
|
|
@@ -1030,28 +1132,36 @@ export class BotScheduleSource {
|
|
|
1030
1132
|
await this.setLast(bot, entry.name, {
|
|
1031
1133
|
...recorded,
|
|
1032
1134
|
result: replySummary(`Could not start: ${message}`),
|
|
1135
|
+
failed: true,
|
|
1033
1136
|
});
|
|
1034
1137
|
return;
|
|
1035
1138
|
}
|
|
1036
|
-
if (
|
|
1037
|
-
await this.chatWatches.log(`
|
|
1139
|
+
if (runId === undefined) {
|
|
1140
|
+
await this.chatWatches.log(`routine "${entry.name}" of bot ${bot} started no run`);
|
|
1038
1141
|
return;
|
|
1039
1142
|
}
|
|
1143
|
+
const startedRun: RoutineRun = { id: runId, at: now, status: "running", ...(manual ? { manual: true } : {}) };
|
|
1144
|
+
const dropped: string[] = [];
|
|
1040
1145
|
const changed = await replaceEntry(
|
|
1041
1146
|
this.ctx.store,
|
|
1042
1147
|
bot,
|
|
1043
1148
|
entry.name,
|
|
1044
1149
|
(current) =>
|
|
1045
1150
|
current.last?.plannedAt === minute
|
|
1046
|
-
? {
|
|
1151
|
+
? {
|
|
1152
|
+
...current,
|
|
1153
|
+
last: { ...current.last, runId },
|
|
1154
|
+
runs: (dropped.push(...droppedRuns(current.runs, startedRun, now)), withRun(current.runs, startedRun, now)),
|
|
1155
|
+
}
|
|
1047
1156
|
: undefined,
|
|
1048
1157
|
"step:bot/scheduled",
|
|
1049
1158
|
);
|
|
1159
|
+
await forgetRuns(this.ctx.store, dropped);
|
|
1050
1160
|
if (changed === undefined) return;
|
|
1051
|
-
await this.watch(bot, entry.name, manual ? now : minute,
|
|
1161
|
+
await this.watch(bot, entry.name, manual ? now : minute, runId);
|
|
1052
1162
|
if (skipped.length > 0) {
|
|
1053
1163
|
await this.chatWatches.log(
|
|
1054
|
-
`
|
|
1164
|
+
`routine "${entry.name}" of bot ${bot}: skipped ${skipped
|
|
1055
1165
|
.map((time) => new Date(time).toISOString())
|
|
1056
1166
|
.join(", ")}; only the latest missed run is caught up`,
|
|
1057
1167
|
);
|
|
@@ -1068,19 +1178,20 @@ export class BotScheduleSource {
|
|
|
1068
1178
|
);
|
|
1069
1179
|
}
|
|
1070
1180
|
|
|
1071
|
-
private async watch(bot: string, name: string, plannedAt: number,
|
|
1072
|
-
const key = `${bot}\u0000${name}\u0000${plannedAt}\u0000${
|
|
1181
|
+
private async watch(bot: string, name: string, plannedAt: number, runId: string): Promise<void> {
|
|
1182
|
+
const key = `${bot}\u0000${name}\u0000${plannedAt}\u0000${runId}`;
|
|
1073
1183
|
this.chatWatches.watchChatReply(
|
|
1074
1184
|
key,
|
|
1075
|
-
|
|
1185
|
+
runId,
|
|
1076
1186
|
async (read) => {
|
|
1077
|
-
const
|
|
1078
|
-
if (
|
|
1187
|
+
const record = await this.ctx.store.get(CHAT_TYPE, runId);
|
|
1188
|
+
if (record === undefined) return undefined;
|
|
1079
1189
|
const reply = [...read.messages].reverse().find((message) => message.role === "assistant");
|
|
1080
1190
|
const failure = [...read.entries].reverse().find((item) => item.kind === "failure");
|
|
1081
1191
|
// A failure after the reply means the run did not end quietly.
|
|
1082
1192
|
const failedAfter = reply !== undefined && failure !== undefined && failure.sequence > reply.sequence;
|
|
1083
1193
|
const quiet = reply !== undefined && !failedAfter && isQuietReply(reply.text);
|
|
1194
|
+
const failed = reply === undefined || failedAfter;
|
|
1084
1195
|
const result = quiet
|
|
1085
1196
|
? SCHEDULE_QUIET_RESULT
|
|
1086
1197
|
: reply === undefined
|
|
@@ -1091,34 +1202,42 @@ export class BotScheduleSource {
|
|
|
1091
1202
|
? replySummary(failure.text ?? "The reply failed.")
|
|
1092
1203
|
: replySummary(reply.text);
|
|
1093
1204
|
if (result === undefined) return undefined;
|
|
1094
|
-
const
|
|
1095
|
-
return { result,
|
|
1205
|
+
const text = reply !== undefined && !failedAfter ? reply.text : result;
|
|
1206
|
+
return { result, quiet, failed, text };
|
|
1096
1207
|
},
|
|
1097
|
-
async ({ result,
|
|
1208
|
+
async ({ result, quiet, failed, text }) => {
|
|
1209
|
+
const now = this.ctx.clock();
|
|
1210
|
+
const status: RoutineRunStatus = quiet ? "quiet" : failed ? "failed" : "done";
|
|
1211
|
+
const dropped: string[] = [];
|
|
1098
1212
|
await replaceEntry(
|
|
1099
1213
|
this.ctx.store,
|
|
1100
1214
|
bot,
|
|
1101
1215
|
name,
|
|
1102
|
-
(entry) =>
|
|
1103
|
-
entry.last?.
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
}
|
|
1112
|
-
|
|
1216
|
+
(entry) => {
|
|
1217
|
+
if (entry.last?.runId !== runId) return undefined;
|
|
1218
|
+
const finished: RoutineRun = { id: runId, at: entry.runs?.find((item) => item.id === runId)?.at ?? now, status, result, ...(entry.last.manual === true ? { manual: true } : {}) };
|
|
1219
|
+
dropped.push(...droppedRuns(entry.runs, finished, now));
|
|
1220
|
+
return {
|
|
1221
|
+
...entry,
|
|
1222
|
+
last: { ...entry.last, result, notified: quiet, ...(failed ? { failed: true } : {}) },
|
|
1223
|
+
recent: [
|
|
1224
|
+
...(entry.recent ?? []).filter((item) => item.plannedAt !== plannedAt),
|
|
1225
|
+
{ plannedAt, result },
|
|
1226
|
+
].slice(-SCHEDULE_RECENT_COUNT),
|
|
1227
|
+
runs: withRun(entry.runs, finished, now),
|
|
1228
|
+
};
|
|
1229
|
+
},
|
|
1113
1230
|
"step:bot/scheduled",
|
|
1114
1231
|
);
|
|
1115
|
-
|
|
1232
|
+
await forgetRuns(this.ctx.store, dropped);
|
|
1233
|
+
// A quiet ending records its result and delivers nothing; a failure is always delivered.
|
|
1116
1234
|
if (quiet) return;
|
|
1117
1235
|
try {
|
|
1118
|
-
await this.
|
|
1236
|
+
const routine = await findRoutine(this.ctx.store, bot, name);
|
|
1237
|
+
await this.notify({ routineId: routine?.id ?? "", runId, title: name, summary: result, text, failed, bot });
|
|
1119
1238
|
} catch (error) {
|
|
1120
1239
|
await this.chatWatches.log(
|
|
1121
|
-
`
|
|
1240
|
+
`routine "${name}" of bot ${bot}: notify: ${messageOf(error)}`,
|
|
1122
1241
|
);
|
|
1123
1242
|
}
|
|
1124
1243
|
await replaceEntry(
|
|
@@ -1126,7 +1245,7 @@ export class BotScheduleSource {
|
|
|
1126
1245
|
bot,
|
|
1127
1246
|
name,
|
|
1128
1247
|
(entry) =>
|
|
1129
|
-
entry.last?.
|
|
1248
|
+
entry.last?.runId === runId
|
|
1130
1249
|
? { ...entry, last: { ...entry.last, notified: true } }
|
|
1131
1250
|
: undefined,
|
|
1132
1251
|
"step:bot/scheduled",
|
|
@@ -1139,10 +1258,10 @@ export class BotScheduleSource {
|
|
|
1139
1258
|
private async resumeWatches(): Promise<void> {
|
|
1140
1259
|
for (const object of await this.bots()) {
|
|
1141
1260
|
if (object.data.removed === true) continue;
|
|
1142
|
-
for (const entry of
|
|
1261
|
+
for (const entry of await routinesOf(this.ctx.store, object.id)) {
|
|
1143
1262
|
const last = entry.last;
|
|
1144
|
-
if (last?.
|
|
1145
|
-
await this.watch(object.id, entry.name, last.manual === true && last.firedAt !== undefined ? last.firedAt : last.plannedAt, last.
|
|
1263
|
+
if (last?.runId === undefined || last.notified === true) continue;
|
|
1264
|
+
await this.watch(object.id, entry.name, last.manual === true && last.firedAt !== undefined ? last.firedAt : last.plannedAt, last.runId);
|
|
1146
1265
|
}
|
|
1147
1266
|
}
|
|
1148
1267
|
}
|
|
@@ -1168,7 +1287,7 @@ export class BotScheduleSource {
|
|
|
1168
1287
|
try {
|
|
1169
1288
|
await this.ctx.client.list(BOT_TYPE);
|
|
1170
1289
|
} catch (error) {
|
|
1171
|
-
await this.chatWatches.log(`
|
|
1290
|
+
await this.chatWatches.log(`routines: ${messageOf(error)}`);
|
|
1172
1291
|
}
|
|
1173
1292
|
await this.resumeWatches();
|
|
1174
1293
|
await this.poll();
|