@operad-io/bot 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Watching a chat's reply from a bot source: one read per check, no second
3
+ * check while one runs, and a stopped watch that no longer reads. Both the
4
+ * scheduled prompts and the nightly tidy end a reply this way.
5
+ */
6
+
7
+ import { messageOf, type ObjectStore, type RunControl } from "@operad-io/engine";
8
+ import { CHAT_TYPE, readChat, writingReplyNow, type ChatRead } from "@operad-io/chat";
9
+
10
+ /** One chat's watch: how to stop it. */
11
+ interface ChatWatch {
12
+ readonly stop: () => void;
13
+ }
14
+
15
+ /** The watches of one bot source, and the work they and its polls started. */
16
+ export class ChatWatches {
17
+ private readonly watches = new Map<string, ChatWatch>();
18
+ private readonly work = new Set<Promise<void>>();
19
+
20
+ constructor(
21
+ private readonly logger: { write(text: string): Promise<string> },
22
+ private readonly store: ObjectStore,
23
+ private readonly runs?: RunControl | undefined,
24
+ ) {}
25
+
26
+ async log(message: string): Promise<void> {
27
+ await this.logger.write(message);
28
+ }
29
+
30
+ track(work: Promise<void>): void {
31
+ const tracked = work
32
+ .catch((error: unknown) => this.log(messageOf(error)))
33
+ .finally(() => this.work.delete(tracked));
34
+ this.work.add(tracked);
35
+ }
36
+
37
+ /** Waits for the checks that are running now; a test calls this after a reply. */
38
+ async settled(): Promise<void> {
39
+ while (this.work.size > 0) await Promise.allSettled([...this.work]);
40
+ }
41
+
42
+ stopAll(): void {
43
+ for (const watch of [...this.watches.values()]) watch.stop();
44
+ this.watches.clear();
45
+ }
46
+
47
+ /**
48
+ * Watches one chat until `ready` answers a value: a reply that is still
49
+ * writing is not ready, and a watch stopped by its key or by `stopAll` reads
50
+ * no more. `done` runs once, after the watch stopped.
51
+ */
52
+ watchChatReply<Value>(
53
+ key: string,
54
+ chatId: string,
55
+ ready: (read: ChatRead) => Promise<Value | undefined> | Value | undefined,
56
+ done: (value: Value) => Promise<void>,
57
+ ): void {
58
+ if (this.watches.has(key)) return;
59
+ let running = false;
60
+ let again = false;
61
+ let stopped = false;
62
+ let unsubscribe: (() => void) | undefined;
63
+ const check = async (): Promise<void> => {
64
+ if (running) {
65
+ again = true;
66
+ return;
67
+ }
68
+ if (stopped) return;
69
+ running = true;
70
+ try {
71
+ const read = readChat(this.store, chatId);
72
+ // A reply that goes round again is not finished at its first message.
73
+ if ((await writingReplyNow(read.facts, read.messages, read.entries, this.runs)) !== undefined) return;
74
+ const value = await ready(read);
75
+ if (value === undefined) return;
76
+ stopped = true;
77
+ unsubscribe?.();
78
+ this.watches.delete(key);
79
+ await done(value);
80
+ } finally {
81
+ running = false;
82
+ if (again && !stopped) {
83
+ again = false;
84
+ this.track(check());
85
+ }
86
+ }
87
+ };
88
+ const blocking: ChatWatch = {
89
+ stop: () => {
90
+ stopped = true;
91
+ unsubscribe?.();
92
+ this.watches.delete(key);
93
+ },
94
+ };
95
+ this.watches.set(key, blocking);
96
+ unsubscribe = this.store.subscribe({ type: CHAT_TYPE, id: chatId }, {}, () => {
97
+ this.track(check());
98
+ });
99
+ this.track(check());
100
+ }
101
+ }
package/src/create.ts ADDED
@@ -0,0 +1,230 @@
1
+ /**
2
+ * Making a bot from what this home already knows: the skills other bots mount,
3
+ * the skills in the standard directories, and the MCP servers a person has
4
+ * already approved on another bot. Only what is chosen is written; nothing is
5
+ * inherited from `default`.
6
+ */
7
+
8
+ import { homedir } from "node:os";
9
+ import { join, resolve } from "node:path";
10
+ import {
11
+ BotError,
12
+ DEFAULT_BOT,
13
+ botDir,
14
+ expandPath,
15
+ listedSkills,
16
+ readBots,
17
+ resolveBot,
18
+ skillName,
19
+ validateBotName,
20
+ workingDirectory,
21
+ type BotSettings,
22
+ type McpServerSettings,
23
+ } from "./bot.ts";
24
+ import { secretName } from "./mcp.ts";
25
+ import { updateBotsFile, validateBots } from "./proposals.ts";
26
+
27
+ /** One skill this home already knows, by the name a bot page shows. */
28
+ export interface SkillChoice {
29
+ readonly name: string;
30
+ readonly path: string;
31
+ }
32
+
33
+ /** One MCP server a person approved on a bot, and the bot it came from. */
34
+ export interface McpServerChoice {
35
+ /** The value a person chooses: the server name, or `<bot>/<server>` when two bots differ. */
36
+ readonly key: string;
37
+ readonly bot: string;
38
+ readonly server: string;
39
+ readonly entry: McpServerSettings;
40
+ }
41
+
42
+ /** The working directory used to read a bot's relative skill paths, even when the bot is broken. */
43
+ function cwdOf(home: string, name: string, settings: BotSettings): string {
44
+ try {
45
+ return workingDirectory(home, name, settings);
46
+ } catch {
47
+ return join(botDir(home), name);
48
+ }
49
+ }
50
+
51
+ function addSkill(found: Map<string, SkillChoice>, path: string): void {
52
+ const normal = resolve(path);
53
+ if (found.has(normal)) return;
54
+ found.set(normal, { name: skillName(normal), path: normal });
55
+ }
56
+
57
+ /**
58
+ * The skills this home already knows: every bot's listed skills, including the
59
+ * ones inside a listed directory, and the skills in `~/.agents/skills` when it
60
+ * exists. A bot that cannot be used contributes the paths that can be read.
61
+ */
62
+ export function knownSkills(home: string, userHome: string = homedir()): readonly SkillChoice[] {
63
+ const found = new Map<string, SkillChoice>();
64
+ for (const [name, settings] of Object.entries(readBots(home))) {
65
+ const cwd = cwdOf(home, name, settings);
66
+ for (const written of settings.skills ?? []) {
67
+ for (const path of listedSkills(written, cwd).directories) addSkill(found, path);
68
+ }
69
+ }
70
+ const standard = join(userHome, ".agents", "skills");
71
+ for (const path of listedSkills(standard, userHome).directories) addSkill(found, path);
72
+ return [...found.values()].sort(
73
+ (left, right) => left.name.localeCompare(right.name) || left.path.localeCompare(right.path),
74
+ );
75
+ }
76
+
77
+ /**
78
+ * The MCP servers approved on a bot. An entry is approved when its tool digest
79
+ * is set, which is what makes a chat mount it. A name approved with different
80
+ * entries on several bots is offered as `<bot>/<server>`.
81
+ */
82
+ export function knownMcpServers(home: string): readonly McpServerChoice[] {
83
+ const grouped = new Map<string, { readonly bot: string; readonly entry: McpServerSettings }[]>();
84
+ for (const [bot, settings] of Object.entries(readBots(home))) {
85
+ for (const [server, entry] of Object.entries(settings.mcpServers ?? {})) {
86
+ if (entry.digest === undefined) continue;
87
+ const group = grouped.get(server) ?? [];
88
+ group.push({ bot, entry });
89
+ grouped.set(server, group);
90
+ }
91
+ }
92
+ const found: McpServerChoice[] = [];
93
+ for (const [server, group] of grouped) {
94
+ const same = new Set(group.map((item) => JSON.stringify(item.entry))).size === 1;
95
+ if (group.length === 1 || same) {
96
+ const first = group[0];
97
+ if (first !== undefined) found.push({ key: server, bot: first.bot, server, entry: first.entry });
98
+ continue;
99
+ }
100
+ for (const item of group) {
101
+ found.push({ key: `${item.bot}/${server}`, bot: item.bot, server, entry: item.entry });
102
+ }
103
+ }
104
+ return found.sort((left, right) => left.key.localeCompare(right.key));
105
+ }
106
+
107
+ /** One server entry as it was approved, copied field by field. */
108
+ function copyEntry(entry: McpServerSettings): McpServerSettings {
109
+ return {
110
+ command: entry.command,
111
+ ...(entry.args === undefined ? {} : { args: [...entry.args] }),
112
+ ...(entry.package === undefined ? {} : { package: entry.package }),
113
+ ...(entry.version === undefined ? {} : { version: entry.version }),
114
+ ...(entry.secrets === undefined ? {} : { secrets: [...entry.secrets] }),
115
+ ...(entry.tools === undefined
116
+ ? {}
117
+ : { tools: entry.tools.map((tool) => ({ name: tool.name, description: tool.description })) }),
118
+ ...(entry.digest === undefined ? {} : { digest: entry.digest }),
119
+ };
120
+ }
121
+
122
+ function add(list: string[], value: string): void {
123
+ const normal = resolve(value);
124
+ if (!list.includes(normal)) list.push(normal);
125
+ }
126
+
127
+ export interface CreateBotInput {
128
+ readonly name: string;
129
+ readonly agent: string;
130
+ readonly model?: string | undefined;
131
+ readonly effort?: string | undefined;
132
+ readonly speaker?: string | undefined;
133
+ /** Known skills by name, or paths a bot's `skills` setting accepts. */
134
+ readonly skills?: readonly string[] | undefined;
135
+ /** Approved MCP servers, as their choice key. */
136
+ readonly mcpServers?: readonly string[] | undefined;
137
+ }
138
+
139
+ export interface CreateBotOptions {
140
+ /** Where a relative skill path is read from; the home when absent. */
141
+ readonly cwd?: string | undefined;
142
+ readonly userHome?: string | undefined;
143
+ }
144
+
145
+ /** What creating a bot wrote, and the secrets its servers need to start. */
146
+ export interface CreatedBot {
147
+ readonly settings: BotSettings;
148
+ /** The secret names of the copied servers, as `<server>.<variable>`. */
149
+ readonly secrets: readonly string[];
150
+ }
151
+
152
+ /**
153
+ * Writes a new bot with exactly the given fields. The name is the same one a
154
+ * bot directory uses and an existing one is refused; skills are the known ones
155
+ * chosen or the paths given; each MCP server is copied from the bot that
156
+ * approved it. No setting comes from `default`.
157
+ */
158
+ export async function createBot(
159
+ home: string,
160
+ input: CreateBotInput,
161
+ options: CreateBotOptions = {},
162
+ ): Promise<CreatedBot> {
163
+ validateBotName(input.name);
164
+ if (input.agent.trim().length === 0) throw new BotError("a new bot needs an agent");
165
+ const bots = readBots(home);
166
+ if (bots[input.name] !== undefined) throw new BotError(`there is already a bot "${input.name}"`);
167
+
168
+ const known = knownSkills(home, options.userHome);
169
+ const byName = new Map<string, SkillChoice>();
170
+ const byPath = new Map<string, SkillChoice>();
171
+ for (const skill of known) {
172
+ if (!byName.has(skill.name)) byName.set(skill.name, skill);
173
+ byPath.set(resolve(skill.path), skill);
174
+ }
175
+ const cwd = options.cwd ?? home;
176
+ const skills: string[] = [];
177
+ const paths: string[] = [];
178
+ for (const value of input.skills ?? []) {
179
+ const chosen = byPath.get(resolve(value)) ?? byName.get(value);
180
+ if (chosen !== undefined) add(skills, chosen.path);
181
+ else paths.push(value);
182
+ }
183
+ for (const value of paths) {
184
+ const expanded = expandPath(value, cwd);
185
+ const listed = listedSkills(value, cwd);
186
+ if (listed.directories.length === 0 && !listed.agents) {
187
+ throw new BotError(`skill "${value}": there is no SKILL.md in ${expanded}`);
188
+ }
189
+ add(skills, expanded);
190
+ }
191
+
192
+ const knownServers = knownMcpServers(home);
193
+ const servers: Record<string, McpServerSettings> = {};
194
+ for (const value of input.mcpServers ?? []) {
195
+ const chosen = knownServers.find((item) => item.key === value);
196
+ if (chosen === undefined) {
197
+ throw new BotError(
198
+ `MCP server "${value}" is not approved on another bot; add it with operad bot mcp`,
199
+ );
200
+ }
201
+ servers[chosen.server] = copyEntry(chosen.entry);
202
+ }
203
+
204
+ const settings: Record<string, unknown> = { harness: input.agent };
205
+ if (input.model !== undefined) settings.model = input.model;
206
+ if (input.effort !== undefined) settings.effort = input.effort;
207
+ if (input.speaker !== undefined) settings.speaker = input.speaker;
208
+ if (skills.length > 0) settings.skills = skills;
209
+ if (Object.keys(servers).length > 0) settings.mcpServers = servers;
210
+
211
+ validateBots({ [input.name]: settings });
212
+ // Refuse a result that could not be used now, such as a skill that vanished.
213
+ resolveBot(home, input.name, settings as BotSettings);
214
+
215
+ await updateBotsFile(home, (written) => {
216
+ if (written[input.name] !== undefined) {
217
+ throw new BotError(`there is already a bot "${input.name}"`);
218
+ }
219
+ const next = { ...written, [input.name]: settings };
220
+ validateBots(next);
221
+ return next;
222
+ });
223
+
224
+ const secrets: string[] = [];
225
+ for (const [server, entry] of Object.entries(servers)) {
226
+ for (const variable of entry.secrets ?? []) secrets.push(secretName(server, variable));
227
+ }
228
+ return { settings: settings as BotSettings, secrets };
229
+ }
230
+
@@ -0,0 +1,313 @@
1
+ /**
2
+ * Follow-ups of a bot (ADR 0030 D16): a one-time deadline an agent sets for
3
+ * itself in a chat. An entry is stored on the bot object (`followUps`), so it
4
+ * survives a restart; the bot's source sends its sentence into the same chat
5
+ * when it is due.
6
+ */
7
+
8
+ import { CHAT_TYPE, chatData } from "@operad-io/chat";
9
+ import type {
10
+ ActionTypeDefinition,
11
+ CommandContext,
12
+ JsonValue,
13
+ ObjectStore,
14
+ StoredObject,
15
+ } from "@operad-io/engine";
16
+ import { BOT_TYPE, BotError } from "./bot.ts";
17
+ import { localStamp, markdownText } from "./schedule.ts";
18
+
19
+ /** At most this many not-yet-due follow-ups in one chat. */
20
+ export const FOLLOW_UP_PER_CHAT = 5;
21
+ /** A follow-up is due at most this many days ahead. */
22
+ export const FOLLOW_UP_DAYS = 30;
23
+ /** The longest sentence a follow-up keeps. */
24
+ export const FOLLOW_UP_TEXT_MAX = 500;
25
+ const DAY_MS = 24 * 60 * 60_000;
26
+
27
+ /** One follow-up, as the bot object stores it. */
28
+ export interface FollowUp {
29
+ readonly id: string;
30
+ /** The chat it was set in and returns to. */
31
+ readonly chat: string;
32
+ /** When it is due, in epoch milliseconds. */
33
+ readonly at: number;
34
+ /** One sentence of what to do. */
35
+ readonly text: string;
36
+ /** When it was set, in epoch milliseconds. */
37
+ readonly setAt: number;
38
+ }
39
+
40
+ function followUpOf(value: unknown): FollowUp | undefined {
41
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
42
+ const item = value as Record<string, unknown>;
43
+ const { id, chat, at, text, setAt } = item;
44
+ if (typeof id !== "string" || id.length === 0) return undefined;
45
+ if (typeof chat !== "string" || chat.length === 0) return undefined;
46
+ if (typeof at !== "number" || !Number.isFinite(at)) return undefined;
47
+ if (typeof text !== "string" || text.length === 0) return undefined;
48
+ return { id, chat, at, text, setAt: typeof setAt === "number" && Number.isFinite(setAt) ? setAt : at };
49
+ }
50
+
51
+ /** The follow-ups written on a bot object, skipping an unusable entry. */
52
+ export function followUps(data: Readonly<Record<string, unknown>>): readonly FollowUp[] {
53
+ const raw = data.followUps;
54
+ if (!Array.isArray(raw)) return [];
55
+ const found: FollowUp[] = [];
56
+ for (const value of raw) {
57
+ const entry = followUpOf(value);
58
+ if (entry !== undefined) found.push(entry);
59
+ }
60
+ return found;
61
+ }
62
+
63
+ /** One follow-up as a client reads it from a bot row. */
64
+ export interface FollowUpView {
65
+ readonly id: string;
66
+ readonly chatId: string;
67
+ /** The due time as an ISO time. */
68
+ readonly due: string;
69
+ readonly text: string;
70
+ }
71
+
72
+ /** The structured entries a bot row gives a client, soonest first. */
73
+ export function followUpData(entries: readonly FollowUp[]): readonly FollowUpView[] {
74
+ return [...entries]
75
+ .sort((a, b) => a.at - b.at)
76
+ .map((entry) => ({
77
+ id: entry.id,
78
+ chatId: entry.chat,
79
+ due: new Date(entry.at).toISOString(),
80
+ text: entry.text,
81
+ }));
82
+ }
83
+
84
+ /** The lines a bot page shows for its follow-ups. */
85
+ export function followUpMarkdown(entries: readonly FollowUp[]): string[] {
86
+ if (entries.length === 0) return ["Follow-up: none."];
87
+ const lines = ["Follow-up:"];
88
+ for (const entry of [...entries].sort((a, b) => a.at - b.at)) {
89
+ lines.push(`- ${entry.id}: ${localStamp(entry.at)}, chat ${entry.chat}: ${markdownText(entry.text)}`);
90
+ }
91
+ return lines;
92
+ }
93
+
94
+ const UNIT_MS: Readonly<Record<string, number>> = { m: 60_000, h: 3_600_000, d: DAY_MS };
95
+
96
+ /**
97
+ * A due time from the agent's words: relative (`+30m`, `+2h`, `+3d`, `in 2
98
+ * hours`) or absolute (`YYYY-MM-DD HH:mm` or an ISO time; local time when it
99
+ * names no zone).
100
+ */
101
+ export function parseDue(input: string, now: number): number {
102
+ const text = input.trim();
103
+ const relative = /^(?:in\s+|\+)\s*(\d+)\s*(m|min|mins|minutes?|h|hrs?|hours?|d|days?)$/i.exec(text);
104
+ if (relative !== null) {
105
+ const amount = Number(relative[1]);
106
+ const unit = (relative[2] ?? "m").charAt(0).toLowerCase();
107
+ return now + amount * (UNIT_MS[unit] ?? 60_000);
108
+ }
109
+ const absolute =
110
+ /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2}))?(Z|[+-]\d{2}:?\d{2})?$/i.exec(text);
111
+ if (absolute !== null) {
112
+ if (absolute[7] !== undefined) {
113
+ const parsed = Date.parse(text.replace(" ", "T"));
114
+ if (Number.isFinite(parsed)) return parsed;
115
+ } else {
116
+ const [, y, mo, d, h, mi, s] = absolute;
117
+ const date = new Date(Number(y), Number(mo) - 1, Number(d), Number(h), Number(mi), Number(s ?? 0));
118
+ // A day the calendar rolled over (2026-02-30) is not a time.
119
+ if (date.getMonth() === Number(mo) - 1 && date.getDate() === Number(d)) return date.getTime();
120
+ }
121
+ }
122
+ throw new BotError(
123
+ `a follow-up's time is not understood: "${input}"; give a time such as "2026-12-01 09:00" or "+2h"`,
124
+ );
125
+ }
126
+
127
+ function newId(): string {
128
+ return `F-${crypto.randomUUID().slice(0, 8)}`;
129
+ }
130
+
131
+ async function botObject(store: ObjectStore, bot: string): Promise<StoredObject> {
132
+ const object = await store.get(BOT_TYPE, bot);
133
+ if (object === undefined) throw new BotError(`there is no bot "${bot}"`);
134
+ if (object.data.removed === true) throw new BotError(`bot ${bot} is no longer in the settings`);
135
+ return object;
136
+ }
137
+
138
+ const locks = new WeakMap<ObjectStore, Map<string, Promise<unknown>>>();
139
+
140
+ /**
141
+ * Runs one read-then-write of a bot object after the ones before it on the same
142
+ * bot, so two writers in this process do not overwrite each other.
143
+ */
144
+ export function withBotLock<T>(store: ObjectStore, bot: string, work: () => Promise<T>): Promise<T> {
145
+ let chains = locks.get(store);
146
+ if (chains === undefined) {
147
+ chains = new Map();
148
+ locks.set(store, chains);
149
+ }
150
+ const run = (chains.get(bot) ?? Promise.resolve()).then(work, work);
151
+ const tail = run.catch(() => undefined);
152
+ chains.set(bot, tail);
153
+ const held = chains;
154
+ void tail.then(() => {
155
+ if (held.get(bot) === tail) held.delete(bot);
156
+ });
157
+ return run;
158
+ }
159
+
160
+ /** Writes the bot's follow-ups, leaving the rest of the object as it is. */
161
+ export async function writeFollowUps(
162
+ store: ObjectStore,
163
+ object: StoredObject,
164
+ entries: readonly FollowUp[],
165
+ cause: string,
166
+ ): Promise<void> {
167
+ await store.put(BOT_TYPE, object.id, { ...object.data, followUps: entries as unknown as JsonValue[] }, cause);
168
+ }
169
+
170
+ /** The bot a chat belongs to, refusing a chat that is not a bot's (and, for a new follow-up, a closed one). */
171
+ async function botOfChat(store: ObjectStore, chatId: string, forNew: boolean): Promise<string> {
172
+ const chat = await store.get(CHAT_TYPE, chatId);
173
+ if (chat === undefined) throw new BotError(`there is no chat "${chatId}"`);
174
+ const parent = chatData(chat.data).parent ?? "";
175
+ if (!parent.startsWith(`${BOT_TYPE}:`)) throw new BotError(`chat ${chatId} is not a chat of a bot`);
176
+ if (forNew && chatData(chat.data).closed) throw new BotError(`chat ${chatId} is closed`);
177
+ return parent.slice(BOT_TYPE.length + 1);
178
+ }
179
+
180
+ /** Sets a follow-up in a chat; it takes effect at once. Returns the line to show. */
181
+ export async function setFollowUp(
182
+ store: ObjectStore,
183
+ chatId: string,
184
+ when: string,
185
+ sentence: string,
186
+ now: number,
187
+ ): Promise<string> {
188
+ const text = sentence.replace(/\s+/g, " ").trim();
189
+ if (text.length === 0) throw new BotError("a follow-up needs one sentence of what to do");
190
+ if (text.length > FOLLOW_UP_TEXT_MAX) {
191
+ throw new BotError(`a follow-up's sentence is at most ${FOLLOW_UP_TEXT_MAX} characters`);
192
+ }
193
+ const at = parseDue(when, now);
194
+ if (at <= now) throw new BotError(`a follow-up's time ${localStamp(at)} is already past`);
195
+ if (at > now + FOLLOW_UP_DAYS * DAY_MS) {
196
+ throw new BotError(`a follow-up is at most ${FOLLOW_UP_DAYS} days ahead; ${localStamp(at)} is further`);
197
+ }
198
+ const bot = await botOfChat(store, chatId, true);
199
+ return withBotLock(store, bot, async () => {
200
+ const object = await botObject(store, bot);
201
+ const entries = followUps(object.data);
202
+ const pending = entries.filter((entry) => entry.chat === chatId && entry.at > now).length;
203
+ if (pending >= FOLLOW_UP_PER_CHAT) {
204
+ throw new BotError(`chat ${chatId} already has ${FOLLOW_UP_PER_CHAT} follow-ups not yet due, the most it may have`);
205
+ }
206
+ const entry: FollowUp = { id: newId(), chat: chatId, at, text, setAt: now };
207
+ await writeFollowUps(store, object, [...entries, entry], "command:bot/follow-up");
208
+ return `follow-up ${entry.id} set for ${localStamp(at)}`;
209
+ });
210
+ }
211
+
212
+ /** Removes one follow-up; false when there is none with that id. */
213
+ export async function removeFollowUp(
214
+ store: ObjectStore,
215
+ bot: string,
216
+ id: string,
217
+ cause = "action:bot/follow-up-cancel",
218
+ ): Promise<boolean> {
219
+ return withBotLock(store, bot, async () => {
220
+ const object = await botObject(store, bot);
221
+ const entries = followUps(object.data);
222
+ const rest = entries.filter((entry) => entry.id !== id);
223
+ if (rest.length === entries.length) return false;
224
+ await writeFollowUps(store, object, rest, cause);
225
+ return true;
226
+ });
227
+ }
228
+
229
+ const FOLLOW_UP_USAGE = "usage: operad bot follow-up <chat> --at <time> --do <one sentence>";
230
+ const FOLLOW_UPS_USAGE = "usage: operad bot follow-ups <chat> [--cancel <id>]";
231
+
232
+ function options(
233
+ argv: readonly string[],
234
+ names: readonly string[],
235
+ usage: string,
236
+ ): { readonly positional: readonly string[]; readonly given: Readonly<Record<string, string>> } {
237
+ const positional: string[] = [];
238
+ const given: Record<string, string> = {};
239
+ for (let at = 0; at < argv.length; at += 1) {
240
+ const word = argv[at];
241
+ if (word === undefined) continue;
242
+ if (word.startsWith("--")) {
243
+ const name = word.slice(2);
244
+ if (!names.includes(name)) throw new BotError(`there is no option ${word}; ${usage}`);
245
+ const value = argv[at + 1];
246
+ if (value === undefined) throw new BotError(`${word} needs a value; ${usage}`);
247
+ given[name] = value;
248
+ at += 1;
249
+ continue;
250
+ }
251
+ positional.push(word);
252
+ }
253
+ return { positional, given };
254
+ }
255
+
256
+ /** `bot follow-up`: what the chat's agent calls to set a follow-up. */
257
+ export async function runFollowUpCommand(ctx: CommandContext, argv: readonly string[]): Promise<string> {
258
+ const { positional, given } = options(argv, ["at", "do"], FOLLOW_UP_USAGE);
259
+ const chat = positional[0];
260
+ const at = given.at;
261
+ const what = given.do;
262
+ if (chat === undefined || positional.length > 1 || at === undefined || what === undefined) {
263
+ throw new BotError(FOLLOW_UP_USAGE);
264
+ }
265
+ return setFollowUp(ctx.store, chat, at, what, Date.now());
266
+ }
267
+
268
+ /** `bot follow-ups`: lists the chat's follow-ups, or cancels one with `--cancel <id>`. */
269
+ export async function runFollowUpsCommand(ctx: CommandContext, argv: readonly string[]): Promise<string> {
270
+ const { positional, given } = options(argv, ["cancel"], FOLLOW_UPS_USAGE);
271
+ const chat = positional[0];
272
+ if (chat === undefined || positional.length > 1) throw new BotError(FOLLOW_UPS_USAGE);
273
+ const bot = await botOfChat(ctx.store, chat, false);
274
+ const own = followUps((await botObject(ctx.store, bot)).data).filter((entry) => entry.chat === chat);
275
+ const cancel = given.cancel;
276
+ if (cancel !== undefined) {
277
+ if (!own.some((entry) => entry.id === cancel) || !(await removeFollowUp(ctx.store, bot, cancel))) {
278
+ throw new BotError(`chat ${chat} has no follow-up "${cancel}"`);
279
+ }
280
+ return `canceled follow-up ${cancel}`;
281
+ }
282
+ if (own.length === 0) return "no follow-ups";
283
+ return [...own]
284
+ .sort((a, b) => a.at - b.at)
285
+ .map((entry) => `${entry.id}: ${localStamp(entry.at)}: ${entry.text}`)
286
+ .join("\n");
287
+ }
288
+
289
+ /** The action a person uses to cancel a follow-up. */
290
+ export const followUpActions: readonly ActionTypeDefinition[] = [
291
+ {
292
+ name: "follow-up-cancel",
293
+ on: BOT_TYPE,
294
+ args: {
295
+ type: "object",
296
+ properties: {
297
+ id: { type: "string", minLength: 1, description: "The follow-up's id, from the bot's `data.followUps`." },
298
+ },
299
+ required: ["id"],
300
+ additionalProperties: false,
301
+ },
302
+ when: (state) => state.removed !== true,
303
+ why: (object) =>
304
+ object.data.removed === true ? `bot ${object.id} is no longer in the settings` : undefined,
305
+ async run(ctx, args) {
306
+ const id = (args as { readonly id: string }).id;
307
+ if (!(await removeFollowUp(ctx.store, ctx.object.id, id))) {
308
+ throw new BotError(`bot ${ctx.object.id} has no follow-up "${id}"`);
309
+ }
310
+ return `canceled follow-up ${id}`;
311
+ },
312
+ },
313
+ ];