@operad-io/bot 0.2.0 → 0.3.1
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/package.json +6 -5
- package/src/follow-up.ts +313 -0
- package/src/index.ts +99 -28
- package/src/proposals.ts +37 -4
- package/src/schedule.ts +252 -27
- package/src/setup-dev.ts +37 -9
- package/src/setup-git.ts +323 -0
- package/src/tidy.ts +4 -1
package/package.json
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@operad-io/bot",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": "./src/index.ts"
|
|
7
7
|
},
|
|
8
8
|
"dependencies": {
|
|
9
|
-
"@operad-io/chat": "0.
|
|
10
|
-
"@operad-io/
|
|
11
|
-
"@operad-io/
|
|
12
|
-
"@operad-io/
|
|
9
|
+
"@operad-io/chat": "0.3.1",
|
|
10
|
+
"@operad-io/dev": "0.3.1",
|
|
11
|
+
"@operad-io/engine": "0.3.1",
|
|
12
|
+
"@operad-io/access-match": "0.3.1",
|
|
13
|
+
"@operad-io/memory": "0.3.1"
|
|
13
14
|
},
|
|
14
15
|
"description": "operad: the bot plugin",
|
|
15
16
|
"repository": {
|
package/src/follow-up.ts
ADDED
|
@@ -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
|
+
];
|