@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/src/routine.ts ADDED
@@ -0,0 +1,304 @@
1
+ /**
2
+ * How a routine shows and what a person does with it (ADR 0030 D10): a row with
3
+ * its name, its bot, the next run and the last result; a page with the prompt,
4
+ * the schedule and its runs as history, each run with its process and result;
5
+ * and the actions that edit, pause, resume, run now and remove it.
6
+ *
7
+ * The nightly memory tidy is a built-in routine shown as Dreaming; the tidy
8
+ * source keeps its routine object in step (see `syncDreaming`).
9
+ */
10
+
11
+ import { CHAT_TYPE, TRANSCRIPT, chatData, chatViews } from "@operad-io/chat";
12
+ import type {
13
+ ActionArgsSchema,
14
+ ActionTypeDefinition,
15
+ ClientApi,
16
+ JsonValue,
17
+ ObjectRow,
18
+ ObjectStore,
19
+ ObjectViews,
20
+ SectionContent,
21
+ StoredObject,
22
+ ViewSection,
23
+ } from "@operad-io/engine";
24
+ import { BOT_TYPE } from "./bot.ts";
25
+ import {
26
+ ROUTINE_TYPE,
27
+ SCHEDULE_QUIET_RESULT,
28
+ SCHEDULE_SOURCE,
29
+ checkPromptName,
30
+ editRoutine,
31
+ localStamp,
32
+ markdownCode,
33
+ markdownText,
34
+ nextRun,
35
+ pauseRoutine,
36
+ removeRoutine,
37
+ resumeRoutine,
38
+ runRoutineNow,
39
+ scheduledPromptOf,
40
+ type EditInput,
41
+ type RoutineRun,
42
+ type ScheduledPrompt,
43
+ } from "./schedule.ts";
44
+
45
+ /** What the built-in memory tidy is called. */
46
+ export const DREAMING_NAME = "Dreaming";
47
+
48
+ /** The `builtin` value of the routine the nightly memory tidy keeps. */
49
+ export const DREAMING_BUILTIN = "tidy";
50
+
51
+ /** The object id of one bot's Dreaming routine. */
52
+ export function dreamingId(bot: string): string {
53
+ return `dreaming-${bot}`;
54
+ }
55
+
56
+ /** How the routine list is filtered: a removed routine is in its own filter. */
57
+ export const ROUTINE_FILTERS = [
58
+ { name: "open", states: ["open", "paused"], default: true },
59
+ { name: "removed", states: ["removed"] },
60
+ ] as const;
61
+
62
+ /** The last result a row shows. */
63
+ export type RoutineResult = "done" | "nothing to report" | "failed";
64
+
65
+ /** How the last run of a routine ended; null before the first run and while one is running. */
66
+ export function lastResultOf(entry: ScheduledPrompt): RoutineResult | null {
67
+ const latest = (entry.runs ?? []).at(-1);
68
+ if (latest !== undefined) {
69
+ if (latest.status === "running") return null;
70
+ return latest.status === "quiet" ? "nothing to report" : latest.status;
71
+ }
72
+ const last = entry.last;
73
+ if (last?.result === undefined) return null;
74
+ if (last.failed === true) return "failed";
75
+ return last.result === SCHEDULE_QUIET_RESULT ? "nothing to report" : "done";
76
+ }
77
+
78
+ /** The server's IANA time zone, the one cron expressions run in. */
79
+ function zone(): string {
80
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
81
+ }
82
+
83
+ function routineRow(object: StoredObject): ObjectRow {
84
+ const entry = scheduledPromptOf(object.data);
85
+ const bot = typeof object.data.bot === "string" ? object.data.bot : "";
86
+ const builtin = typeof object.data.builtin === "string";
87
+ if (entry === undefined) {
88
+ return { id: object.id, title: "Routine", state: "broken", ...(bot === "" ? {} : { parent: `${BOT_TYPE}:${bot}` }) };
89
+ }
90
+ const now = Date.now();
91
+ const next = nextRun(entry, now);
92
+ const removed = object.data.removed === true;
93
+ const result = lastResultOf(entry);
94
+ const data: Record<string, JsonValue> = {
95
+ bot,
96
+ schedule: entry.schedule,
97
+ nextRun: next === null || removed ? null : new Date(next).toISOString(),
98
+ lastResult: result,
99
+ lastSummary: entry.last?.result ?? null,
100
+ paused: entry.paused,
101
+ builtin,
102
+ timeZone: zone(),
103
+ ...(builtin ? {} : { prompt: entry.prompt, model: entry.model ?? null, effort: entry.effort ?? null }),
104
+ };
105
+ return {
106
+ id: object.id,
107
+ title: entry.name,
108
+ state: removed ? "removed" : entry.paused ? "paused" : "open",
109
+ ...(removed ? { final: true } : {}),
110
+ note: bot,
111
+ parent: `${BOT_TYPE}:${bot}`,
112
+ ...(typeof object.data.state === "string" && object.data.state === "pending" ? { waiting: true as const } : {}),
113
+ data,
114
+ };
115
+ }
116
+
117
+ /** How many runs a routine's page lists as sections. */
118
+ const RUN_SECTIONS = 30;
119
+
120
+ function runTitle(run: RoutineRun): string {
121
+ const how = run.status === "quiet" ? "nothing to report" : run.status;
122
+ return `${localStamp(run.at)} · ${how}${run.manual === true ? " · run now" : ""}`;
123
+ }
124
+
125
+ function routineSections(object: StoredObject): readonly ViewSection[] {
126
+ const entry = scheduledPromptOf(object.data);
127
+ const runs = [...(entry?.runs ?? [])].reverse().slice(0, RUN_SECTIONS);
128
+ return [
129
+ { id: "routine", title: "Routine" },
130
+ ...runs.map((run) => ({ id: `run-${run.id}`, title: runTitle(run), ...(run.status === "running" ? { live: true } : {}) })),
131
+ ];
132
+ }
133
+
134
+ /** The lines a bot page shows for its routines. */
135
+ export function routineMarkdown(entries: readonly ScheduledPrompt[], now: number): string[] {
136
+ if (entries.length === 0) return ["Routines: none."];
137
+ const lines = ["Routines:"];
138
+ for (const entry of entries) {
139
+ const next = nextRun(entry, now);
140
+ const state = entry.paused ? " (paused)" : next === null ? "" : `, next ${localStamp(next)}`;
141
+ const result = lastResultOf(entry);
142
+ const ended =
143
+ entry.last?.result === undefined
144
+ ? ""
145
+ : `; last ${result ?? "done"}: ${markdownText(entry.last.result)}`;
146
+ lines.push(`- ${markdownText(entry.name)} (${markdownCode(entry.schedule)}${state})${ended}`);
147
+ }
148
+ return lines;
149
+ }
150
+
151
+ function pageMarkdown(object: StoredObject): string {
152
+ const entry = scheduledPromptOf(object.data);
153
+ const bot = typeof object.data.bot === "string" ? object.data.bot : "";
154
+ if (entry === undefined) return "This routine has no usable data.";
155
+ const now = Date.now();
156
+ const next = nextRun(entry, now);
157
+ const lines = [`**${markdownText(entry.name)}** · bot ${markdownText(bot)}`];
158
+ if (object.data.removed === true) lines.push("Removed.");
159
+ if (typeof object.data.builtin === "string") {
160
+ lines.push(
161
+ `Tidies this bot's memory every night at ${entry.schedule.split(" ").slice(0, 2).reverse().map((part) => part.padStart(2, "0")).join(":")}. It first shows a pending card and waits for Run or Skip, unless the bot's settings say to run without asking.`,
162
+ );
163
+ } else {
164
+ lines.push(`Prompt: ${markdownText(entry.prompt)}`);
165
+ }
166
+ lines.push(
167
+ `Schedule: ${markdownCode(entry.schedule)} (${zone()})${entry.paused ? ", paused" : next === null ? "" : `, next run ${localStamp(next)}`}`,
168
+ );
169
+ const result = lastResultOf(entry);
170
+ if (result !== null) lines.push(`Last result: ${result}${entry.last?.result === undefined ? "" : ` — ${markdownText(entry.last.result)}`}`);
171
+ const runs = entry.runs ?? [];
172
+ lines.push(runs.length === 0 ? "No runs yet." : `Runs in the last 30 days: ${runs.length}. Each one is a section of this page.`);
173
+ return lines.join("\n\n");
174
+ }
175
+
176
+ async function routineLoad(
177
+ ctx: Parameters<ObjectViews["load"]>[0],
178
+ object: StoredObject,
179
+ sectionId: string,
180
+ options: Parameters<ObjectViews["load"]>[3],
181
+ ): Promise<SectionContent> {
182
+ if (sectionId === "routine") return { markdown: pageMarkdown(object) };
183
+ if (!sectionId.startsWith("run-")) return { markdown: "" };
184
+ const runId = sectionId.slice("run-".length);
185
+ const entry = scheduledPromptOf(object.data);
186
+ const run = entry?.runs?.find((item) => item.id === runId);
187
+ if (run === undefined) return { markdown: "This run is no longer in the history." };
188
+ // The run's process and reply are in its record; the transcript renders them.
189
+ const record = await ctx.store.get(CHAT_TYPE, runId);
190
+ if (record !== undefined && chatData(record.data).run === true) {
191
+ return chatViews.load(ctx, record, TRANSCRIPT, options);
192
+ }
193
+ return { markdown: `${runTitle(run)}${run.result === undefined ? "" : `\n\n${markdownText(run.result)}`}` };
194
+ }
195
+
196
+ /** How a routine shows in a list and on its page. */
197
+ export const routineViews: ObjectViews = {
198
+ row: routineRow,
199
+ sections: routineSections,
200
+ load: routineLoad,
201
+ };
202
+
203
+ function botOf(object: { readonly data: Readonly<Record<string, unknown>> }): string {
204
+ return typeof object.data.bot === "string" ? object.data.bot : "";
205
+ }
206
+
207
+ function nameOf(object: { readonly data: Readonly<Record<string, unknown>> }): string {
208
+ return checkPromptName(typeof object.data.name === "string" ? object.data.name : "");
209
+ }
210
+
211
+ const editable = (state: Readonly<Record<string, unknown>>): boolean =>
212
+ state.removed !== true && state.builtin === undefined;
213
+
214
+ const editableWhy = (object: StoredObject): string | undefined =>
215
+ object.data.removed === true
216
+ ? `routine ${object.id} is removed`
217
+ : object.data.builtin !== undefined
218
+ ? `${DREAMING_NAME} is built in; it is changed in the bot's settings`
219
+ : undefined;
220
+
221
+ const editArgs: ActionArgsSchema = {
222
+ type: "object",
223
+ properties: {
224
+ schedule: {
225
+ type: "string",
226
+ minLength: 1,
227
+ description: "A five-field cron schedule in the machine's local time zone, such as `0 8 * * *`.",
228
+ },
229
+ prompt: {
230
+ type: "string",
231
+ role: "note",
232
+ minLength: 1,
233
+ description: "What the routine asks the agent each time it runs.",
234
+ },
235
+ model: { type: "string", description: "The model a run uses; an empty value clears it." },
236
+ effort: { type: "string", description: "The effort a run uses; an empty value clears it." },
237
+ },
238
+ additionalProperties: false,
239
+ };
240
+
241
+ /** The actions on a routine's own page. */
242
+ export const routineActions: readonly ActionTypeDefinition[] = [
243
+ {
244
+ name: "edit",
245
+ on: ROUTINE_TYPE,
246
+ args: editArgs,
247
+ when: editable,
248
+ why: editableWhy,
249
+ run: async (ctx, args) => editRoutine(ctx.store, botOf(ctx.object), nameOf(ctx.object), args as unknown as EditInput),
250
+ },
251
+ {
252
+ name: "pause",
253
+ on: ROUTINE_TYPE,
254
+ when: (state) => editable(state) && state.paused !== true,
255
+ why: editableWhy,
256
+ run: async (ctx) => pauseRoutine(ctx.store, botOf(ctx.object), nameOf(ctx.object)),
257
+ },
258
+ {
259
+ name: "resume",
260
+ on: ROUTINE_TYPE,
261
+ when: (state) => editable(state) && state.paused === true,
262
+ why: editableWhy,
263
+ run: async (ctx) => resumeRoutine(ctx.store, botOf(ctx.object), nameOf(ctx.object)),
264
+ },
265
+ {
266
+ name: "run-now",
267
+ on: ROUTINE_TYPE,
268
+ when: editable,
269
+ why: editableWhy,
270
+ run: async (ctx) => runRoutineNow(ctx.store, botOf(ctx.object), nameOf(ctx.object)),
271
+ },
272
+ {
273
+ name: "remove",
274
+ on: ROUTINE_TYPE,
275
+ confirm: true,
276
+ when: editable,
277
+ why: editableWhy,
278
+ run: async (ctx) => removeRoutine(ctx.store, botOf(ctx.object), nameOf(ctx.object)),
279
+ },
280
+ ];
281
+
282
+ /**
283
+ * Closes, once, the chats that scheduled prompts and memory tidies opened
284
+ * before runs stopped being chats (ADR 0030 D10). A run has an `R-` id and is
285
+ * never closed here; a chat already closed is left alone.
286
+ */
287
+ export async function closeOldScheduledChats(store: ObjectStore, client: ClientApi): Promise<number> {
288
+ let closed = 0;
289
+ let cursor: string | undefined;
290
+ do {
291
+ const page = await store.list(CHAT_TYPE, { ...(cursor === undefined ? {} : { cursor }) });
292
+ for (const object of page.objects) {
293
+ const chat = chatData(object.data);
294
+ if (chat.scheduled === undefined || chat.run === true || chat.closed) continue;
295
+ await client.act("chat:close", `${CHAT_TYPE}:${object.id}`, {
296
+ actor: { via: SCHEDULE_SOURCE, id: "routines" },
297
+ yes: true,
298
+ });
299
+ closed += 1;
300
+ }
301
+ cursor = page.next;
302
+ } while (cursor !== undefined);
303
+ return closed;
304
+ }