@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.
- package/README.md +1 -1
- package/bot.schema.json +40 -2
- package/package.json +6 -4
- package/src/bot.ts +588 -70
- package/src/chat-watch.ts +101 -0
- package/src/create.ts +230 -0
- package/src/follow-up.ts +313 -0
- package/src/index.ts +544 -29
- package/src/login.ts +226 -0
- package/src/mcp-proposals.ts +2 -2
- package/src/proposals.ts +392 -79
- package/src/schedule.ts +1184 -0
- package/src/setup-dev.ts +282 -0
- package/src/setup-git.ts +323 -0
- package/src/setup.ts +113 -0
- package/src/tidy.ts +1021 -0
package/src/tidy.ts
ADDED
|
@@ -0,0 +1,1021 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A bot's nightly memory tidy: the check that costs no model call, the pending
|
|
3
|
+
* card with Run and Skip, the automatic run, and the one commit the run leaves.
|
|
4
|
+
* The memory plugin owns what changed and the rewrite guard; this module owns
|
|
5
|
+
* when the botanist wakes and what a person sees.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { messageOf } from "@operad-io/engine";
|
|
9
|
+
import { join, resolve } from "node:path";
|
|
10
|
+
import {
|
|
11
|
+
CHAT_TYPE,
|
|
12
|
+
allEntries,
|
|
13
|
+
allMessages,
|
|
14
|
+
chatData,
|
|
15
|
+
chatFacts,
|
|
16
|
+
costText,
|
|
17
|
+
writingReplyNow,
|
|
18
|
+
} from "@operad-io/chat";
|
|
19
|
+
import {
|
|
20
|
+
cut,
|
|
21
|
+
isRecord,
|
|
22
|
+
type ActionTypeDefinition,
|
|
23
|
+
type ClientApi,
|
|
24
|
+
type HarnessCapabilities,
|
|
25
|
+
type JsonValue,
|
|
26
|
+
type ObjectRow,
|
|
27
|
+
type ObjectStore,
|
|
28
|
+
type ObjectViews,
|
|
29
|
+
type RunControl,
|
|
30
|
+
type SectionContent,
|
|
31
|
+
type StoredObject,
|
|
32
|
+
} from "@operad-io/engine";
|
|
33
|
+
import {
|
|
34
|
+
EMPTY_LINK_REPORT,
|
|
35
|
+
TIDY_COMMIT_FACT,
|
|
36
|
+
TIDY_ORIGIN,
|
|
37
|
+
ensureMemoryLayout,
|
|
38
|
+
ensureRepository,
|
|
39
|
+
linkReport,
|
|
40
|
+
memoryEnabled,
|
|
41
|
+
memoryTidyState,
|
|
42
|
+
openMemorySearch,
|
|
43
|
+
tidyCommitForChat,
|
|
44
|
+
tidyCommitSummary,
|
|
45
|
+
wikiDirectoryOfHome,
|
|
46
|
+
type LinkReport,
|
|
47
|
+
} from "@operad-io/memory";
|
|
48
|
+
import {
|
|
49
|
+
BOT_TYPE,
|
|
50
|
+
BotError,
|
|
51
|
+
ensureBotMemory,
|
|
52
|
+
readBots,
|
|
53
|
+
workingDirectory,
|
|
54
|
+
type BotSettings,
|
|
55
|
+
} from "./bot.ts";
|
|
56
|
+
import { ChatWatches } from "./chat-watch.ts";
|
|
57
|
+
import {
|
|
58
|
+
SCHEDULE_SOURCE,
|
|
59
|
+
localDate,
|
|
60
|
+
notifyScheduledReply,
|
|
61
|
+
replySummary,
|
|
62
|
+
type ScheduleNotice,
|
|
63
|
+
} from "./schedule.ts";
|
|
64
|
+
|
|
65
|
+
/** The internal object type of one bot's tidy state and card. */
|
|
66
|
+
export const TIDY_TYPE = "bot-tidy";
|
|
67
|
+
|
|
68
|
+
/** The default time the nightly check runs, in local time. */
|
|
69
|
+
export const DEFAULT_TIDY_TIME = "03:30";
|
|
70
|
+
|
|
71
|
+
/** The longest an automatic tidy's notice is. */
|
|
72
|
+
const NOTICE_MAX = 300;
|
|
73
|
+
|
|
74
|
+
export type TidyState =
|
|
75
|
+
| "idle"
|
|
76
|
+
| "pending"
|
|
77
|
+
| "requested"
|
|
78
|
+
| "running"
|
|
79
|
+
| "result"
|
|
80
|
+
| "failed"
|
|
81
|
+
| "skipped";
|
|
82
|
+
|
|
83
|
+
/** How much work the last check found. */
|
|
84
|
+
export interface TidyCounts {
|
|
85
|
+
readonly notes: number;
|
|
86
|
+
readonly chats: number;
|
|
87
|
+
readonly indexOver: boolean;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** What a finished tidy did and cost. */
|
|
91
|
+
export interface TidyOutcome {
|
|
92
|
+
readonly chatId: string;
|
|
93
|
+
readonly at: number;
|
|
94
|
+
readonly costMicros: number | null;
|
|
95
|
+
readonly changed: boolean;
|
|
96
|
+
readonly voided: boolean;
|
|
97
|
+
/** The run's diff-stat line from the last tidy commit, or why the run failed. */
|
|
98
|
+
readonly summary: string;
|
|
99
|
+
/** The agent's own one-line reply, when it gave one. */
|
|
100
|
+
readonly reply: string;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The state stored on one bot's tidy object. */
|
|
104
|
+
export interface TidyData {
|
|
105
|
+
readonly [key: string]: unknown;
|
|
106
|
+
readonly bot: string;
|
|
107
|
+
readonly state: TidyState;
|
|
108
|
+
/** The latest planned check already handled. */
|
|
109
|
+
readonly plannedAt: number;
|
|
110
|
+
readonly checkedAt?: number;
|
|
111
|
+
readonly counts: TidyCounts;
|
|
112
|
+
readonly requestedAt?: number | undefined;
|
|
113
|
+
readonly chatId?: string | undefined;
|
|
114
|
+
readonly auto?: boolean | undefined;
|
|
115
|
+
readonly outcome?: TidyOutcome | undefined;
|
|
116
|
+
readonly lastOutcome?: TidyOutcome | undefined;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** A note whose text the tidy sees. */
|
|
120
|
+
export interface TidyNote {
|
|
121
|
+
readonly path: string;
|
|
122
|
+
readonly content: string;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** One chat in the period the tidy checks. */
|
|
126
|
+
export interface TidyChat {
|
|
127
|
+
readonly id: string;
|
|
128
|
+
readonly title: string;
|
|
129
|
+
readonly messages: readonly {
|
|
130
|
+
readonly role: string;
|
|
131
|
+
readonly text: string;
|
|
132
|
+
readonly at: number;
|
|
133
|
+
}[];
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The link lists for the shared wiki and this bot's memory. */
|
|
137
|
+
export interface TidyLinks {
|
|
138
|
+
readonly wiki: LinkReport;
|
|
139
|
+
readonly memory: LinkReport;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** What the check found: the work the card counts and the run reads. */
|
|
143
|
+
export interface TidyWork {
|
|
144
|
+
readonly notes: readonly TidyNote[];
|
|
145
|
+
readonly chats: readonly TidyChat[];
|
|
146
|
+
readonly links: TidyLinks;
|
|
147
|
+
readonly indexOver: boolean;
|
|
148
|
+
readonly indexBytes: number;
|
|
149
|
+
readonly baseline: string | undefined;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function integer(value: unknown, fallback = 0): number {
|
|
153
|
+
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function countsOf(value: unknown): TidyCounts {
|
|
157
|
+
if (!isRecord(value)) return { notes: 0, chats: 0, indexOver: false };
|
|
158
|
+
return {
|
|
159
|
+
notes: integer(value.notes),
|
|
160
|
+
chats: integer(value.chats),
|
|
161
|
+
indexOver: value.indexOver === true,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function outcomeOf(value: unknown): TidyOutcome | undefined {
|
|
166
|
+
if (!isRecord(value) || typeof value.chatId !== "string" || typeof value.summary !== "string") {
|
|
167
|
+
return undefined;
|
|
168
|
+
}
|
|
169
|
+
return {
|
|
170
|
+
chatId: value.chatId,
|
|
171
|
+
at: integer(value.at),
|
|
172
|
+
costMicros:
|
|
173
|
+
typeof value.costMicros === "number" && Number.isFinite(value.costMicros)
|
|
174
|
+
? value.costMicros
|
|
175
|
+
: null,
|
|
176
|
+
changed: value.changed === true,
|
|
177
|
+
voided: value.voided === true,
|
|
178
|
+
summary: value.summary,
|
|
179
|
+
reply: typeof value.reply === "string" ? value.reply : "",
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const STATES: ReadonlySet<string> = new Set([
|
|
184
|
+
"idle",
|
|
185
|
+
"pending",
|
|
186
|
+
"requested",
|
|
187
|
+
"running",
|
|
188
|
+
"result",
|
|
189
|
+
"failed",
|
|
190
|
+
"skipped",
|
|
191
|
+
]);
|
|
192
|
+
|
|
193
|
+
/** Reads a tidy object, or undefined when its state is unusable. */
|
|
194
|
+
export function tidyDataOf(value: Readonly<Record<string, unknown>>): TidyData | undefined {
|
|
195
|
+
if (typeof value.bot !== "string" || !STATES.has(String(value.state))) return undefined;
|
|
196
|
+
const outcome = outcomeOf(value.outcome);
|
|
197
|
+
const last = outcomeOf(value.lastOutcome);
|
|
198
|
+
return {
|
|
199
|
+
bot: value.bot,
|
|
200
|
+
state: value.state as TidyState,
|
|
201
|
+
plannedAt: integer(value.plannedAt),
|
|
202
|
+
...(typeof value.checkedAt === "number" ? { checkedAt: value.checkedAt } : {}),
|
|
203
|
+
counts: countsOf(value.counts),
|
|
204
|
+
...(typeof value.requestedAt === "number" ? { requestedAt: value.requestedAt } : {}),
|
|
205
|
+
...(typeof value.chatId === "string" ? { chatId: value.chatId } : {}),
|
|
206
|
+
...(value.auto === true ? { auto: true } : {}),
|
|
207
|
+
...(outcome === undefined ? {} : { outcome }),
|
|
208
|
+
...(last === undefined ? {} : { lastOutcome: last }),
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** The tidy time a bot names, as hour and minute; the default is between 3 and 4. */
|
|
213
|
+
export function tidyClock(settings: BotSettings): { readonly hour: number; readonly minute: number } {
|
|
214
|
+
const written = typeof settings.tidyTime === "string" ? settings.tidyTime : DEFAULT_TIDY_TIME;
|
|
215
|
+
const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(written);
|
|
216
|
+
if (match === null) return { hour: 3, minute: 30 };
|
|
217
|
+
return { hour: Number(match[1]), minute: Number(match[2]) };
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** The latest planned check at or before now, in the machine's local time zone. */
|
|
221
|
+
export function latestTidyMinute(settings: BotSettings, now: number): number {
|
|
222
|
+
const { hour, minute } = tidyClock(settings);
|
|
223
|
+
const date = new Date(now);
|
|
224
|
+
const today = new Date(
|
|
225
|
+
date.getFullYear(),
|
|
226
|
+
date.getMonth(),
|
|
227
|
+
date.getDate(),
|
|
228
|
+
hour,
|
|
229
|
+
minute,
|
|
230
|
+
0,
|
|
231
|
+
0,
|
|
232
|
+
).getTime();
|
|
233
|
+
if (today <= now) return today;
|
|
234
|
+
return new Date(
|
|
235
|
+
date.getFullYear(),
|
|
236
|
+
date.getMonth(),
|
|
237
|
+
date.getDate() - 1,
|
|
238
|
+
hour,
|
|
239
|
+
minute,
|
|
240
|
+
0,
|
|
241
|
+
0,
|
|
242
|
+
).getTime();
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function listAll(store: ObjectStore, type: string): Promise<readonly StoredObject[]> {
|
|
246
|
+
const found: StoredObject[] = [];
|
|
247
|
+
let cursor: string | undefined;
|
|
248
|
+
do {
|
|
249
|
+
const page = await store.list(type, { ...(cursor === undefined ? {} : { cursor }) });
|
|
250
|
+
found.push(...page.objects);
|
|
251
|
+
cursor = page.next;
|
|
252
|
+
} while (cursor !== undefined);
|
|
253
|
+
return found;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** The chats of one bot whose messages fall in the tidy period. */
|
|
257
|
+
async function chatsToCheck(
|
|
258
|
+
store: ObjectStore,
|
|
259
|
+
bot: string,
|
|
260
|
+
since: number | undefined,
|
|
261
|
+
): Promise<readonly TidyChat[]> {
|
|
262
|
+
const found: TidyChat[] = [];
|
|
263
|
+
for (const object of await listAll(store, CHAT_TYPE)) {
|
|
264
|
+
const chat = chatData(object.data);
|
|
265
|
+
if (chat.parent !== `${BOT_TYPE}:${bot}`) continue;
|
|
266
|
+
if (chat.scheduled?.entry === TIDY_ORIGIN) continue;
|
|
267
|
+
const messages = allMessages(store, object.id)
|
|
268
|
+
.filter((message) => since === undefined || message.at >= since)
|
|
269
|
+
.map((message) => ({
|
|
270
|
+
role: message.role,
|
|
271
|
+
text: cut(message.text, 1_500),
|
|
272
|
+
at: message.at,
|
|
273
|
+
}));
|
|
274
|
+
if (messages.length === 0) continue;
|
|
275
|
+
found.push({ id: object.id, title: chat.title, messages });
|
|
276
|
+
}
|
|
277
|
+
return found.sort((left, right) => left.id.localeCompare(right.id));
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function emptyTidyLinks(): TidyLinks {
|
|
281
|
+
return { wiki: EMPTY_LINK_REPORT, memory: EMPTY_LINK_REPORT };
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** The link table's lists for the wiki and this bot's memory; never blocks the check. */
|
|
285
|
+
async function linkLists(
|
|
286
|
+
store: ObjectStore,
|
|
287
|
+
cwd: string,
|
|
288
|
+
home: string | undefined,
|
|
289
|
+
): Promise<TidyLinks> {
|
|
290
|
+
if (home === undefined) return emptyTidyLinks();
|
|
291
|
+
const settings = { wikiDir: wikiDirectoryOfHome(home) };
|
|
292
|
+
try {
|
|
293
|
+
const search = openMemorySearch(home, settings);
|
|
294
|
+
try {
|
|
295
|
+
await search.refresh(store);
|
|
296
|
+
return {
|
|
297
|
+
wiki: linkReport(search, { scope: "wiki" }),
|
|
298
|
+
memory: linkReport(search, { scope: "memory", owner: resolve(cwd) }),
|
|
299
|
+
};
|
|
300
|
+
} finally {
|
|
301
|
+
search.close();
|
|
302
|
+
}
|
|
303
|
+
} catch {
|
|
304
|
+
return emptyTidyLinks();
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** The work one bot's memory has for a tidy now. */
|
|
309
|
+
export async function tidyWork(
|
|
310
|
+
store: ObjectStore,
|
|
311
|
+
bot: string,
|
|
312
|
+
cwd: string,
|
|
313
|
+
options: { readonly home?: string | undefined } = {},
|
|
314
|
+
): Promise<TidyWork> {
|
|
315
|
+
const memoryDir = join(cwd, "memory");
|
|
316
|
+
ensureMemoryLayout(memoryDir);
|
|
317
|
+
const memory = memoryTidyState(memoryDir, bot);
|
|
318
|
+
const notes: TidyNote[] = [];
|
|
319
|
+
for (const path of memory.notes) {
|
|
320
|
+
try {
|
|
321
|
+
notes.push({
|
|
322
|
+
path,
|
|
323
|
+
content: cut(await Bun.file(join(memoryDir, ...path.split("/"))).text(), 8_000),
|
|
324
|
+
});
|
|
325
|
+
} catch {
|
|
326
|
+
// A note that vanished between the check and this read is not work.
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return {
|
|
330
|
+
notes,
|
|
331
|
+
chats: await chatsToCheck(store, bot, memory.since),
|
|
332
|
+
links: await linkLists(store, cwd, options.home),
|
|
333
|
+
indexOver: memory.indexOver,
|
|
334
|
+
indexBytes: memory.indexBytes,
|
|
335
|
+
baseline: memory.baseline,
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Whether any chat of this bot is writing a reply now. A latest run that the
|
|
341
|
+
* host says has ended is not writing, even when a crash left no failure or
|
|
342
|
+
* stopped entry for it; a host that cannot tell keeps the fact-only answer.
|
|
343
|
+
*/
|
|
344
|
+
export async function botChatReplying(
|
|
345
|
+
store: ObjectStore,
|
|
346
|
+
bot: string,
|
|
347
|
+
runs?: RunControl,
|
|
348
|
+
): Promise<boolean> {
|
|
349
|
+
for (const object of await listAll(store, CHAT_TYPE)) {
|
|
350
|
+
const chat = chatData(object.data);
|
|
351
|
+
if (chat.parent !== `${BOT_TYPE}:${bot}`) continue;
|
|
352
|
+
const writing = await writingReplyNow(chatFacts(store, object.id), allMessages(store, object.id), allEntries(store, object.id), runs);
|
|
353
|
+
if (writing !== undefined) return true;
|
|
354
|
+
}
|
|
355
|
+
return false;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** The link lists for one scope, with no heading when every list is empty. */
|
|
359
|
+
function linkSection(title: string, report: LinkReport): string[] {
|
|
360
|
+
const lines: string[] = [];
|
|
361
|
+
if (report.broken.length > 0) {
|
|
362
|
+
lines.push("", `Broken links (${report.broken.length}):`);
|
|
363
|
+
for (const link of report.broken) {
|
|
364
|
+
lines.push(`- ${link.path}:${link.line} -> ${link.target}`);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
if (report.orphans.length > 0) {
|
|
368
|
+
lines.push("", `Notes nothing links to (${report.orphans.length}):`);
|
|
369
|
+
for (const path of report.orphans) lines.push(`- ${path}`);
|
|
370
|
+
}
|
|
371
|
+
if (report.wanted.length > 0) {
|
|
372
|
+
lines.push("", `Targets several notes link to (${report.wanted.length}):`);
|
|
373
|
+
for (const wanted of report.wanted) {
|
|
374
|
+
lines.push(`- ${wanted.target} (linked from ${wanted.notes} notes)`);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
if (report.unlinked.length > 0) {
|
|
378
|
+
lines.push("", `Mentions that are not links (${report.unlinked.length}):`);
|
|
379
|
+
for (const mention of report.unlinked) {
|
|
380
|
+
lines.push(`- ${mention.path} mentions "${mention.title}" (${mention.target})`);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
return lines.length === 0 ? [] : [`### ${title}`, ...lines];
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** The link guidance and lists, or nothing when there is no link work. */
|
|
387
|
+
function linkPrompt(links: TidyLinks): string[] {
|
|
388
|
+
const wiki = linkSection("Wiki", links.wiki);
|
|
389
|
+
const memory = linkSection("Bot memory", links.memory);
|
|
390
|
+
if (wiki.length === 0 && memory.length === 0) return [];
|
|
391
|
+
return [
|
|
392
|
+
"",
|
|
393
|
+
"## Links to look after",
|
|
394
|
+
"Fix a broken link when the right target is clear. Leave a link to a page nobody wrote yet. Consider linking an orphan from the index or a related note. Suggest, never force, turning a mention into a link. Never put an untrusted note into the index.",
|
|
395
|
+
...wiki,
|
|
396
|
+
...memory,
|
|
397
|
+
];
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** The prompt a tidy chat starts with. */
|
|
401
|
+
export function tidyPrompt(bot: string, work: TidyWork): string {
|
|
402
|
+
const out = [
|
|
403
|
+
`Tidy the memory of bot ${bot}.`,
|
|
404
|
+
"",
|
|
405
|
+
"This is the nightly memory tidy. Work only from the notes and chat records below.",
|
|
406
|
+
"Fix notes that are wrong or out of date: the newer fact replaces the older one, and the old note stays where it is, marked as replaced; do not delete it.",
|
|
407
|
+
`Keep memory/index.md under 8,000 characters by moving detail into topic notes. It is ${work.indexBytes} bytes now.`,
|
|
408
|
+
"Check only the period since the last tidy. Do not change instructions.md. End with a short summary of what changed.",
|
|
409
|
+
"",
|
|
410
|
+
`## Notes added or changed since the last tidy (${work.notes.length})`,
|
|
411
|
+
];
|
|
412
|
+
if (work.notes.length === 0) out.push("None.");
|
|
413
|
+
for (const note of work.notes) {
|
|
414
|
+
out.push("", `### ${note.path}`, "```markdown", note.content, "```");
|
|
415
|
+
}
|
|
416
|
+
out.push("", `## Chats in the period (${work.chats.length})`);
|
|
417
|
+
if (work.chats.length === 0) out.push("None.");
|
|
418
|
+
for (const chat of work.chats) {
|
|
419
|
+
out.push("", `### Chat ${chat.id}: ${chat.title}`);
|
|
420
|
+
for (const message of chat.messages) {
|
|
421
|
+
out.push(`${message.role}: ${message.text}`);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
out.push(...linkPrompt(work.links));
|
|
425
|
+
return out.join("\n");
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function costPart(outcome: TidyOutcome): string {
|
|
429
|
+
return outcome.costMicros === null
|
|
430
|
+
? "cost unknown"
|
|
431
|
+
: `cost ${costText(outcome.costMicros, undefined)}`;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** The one line a tidy sends through the notify command. */
|
|
435
|
+
export function tidyOutcomeLine(bot: string, outcome: TidyOutcome): string {
|
|
436
|
+
const changed = outcome.changed
|
|
437
|
+
? outcome.summary
|
|
438
|
+
: outcome.summary === "No file statistics." || /^no memory change\.?$/i.test(outcome.summary)
|
|
439
|
+
? "no memory change"
|
|
440
|
+
: outcome.summary;
|
|
441
|
+
const voided = outcome.voided ? "; only additions were kept" : "";
|
|
442
|
+
return `${bot}: ${changed}; ${costPart(outcome)}${voided}`;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/** What a person reads on a bot's tidy card. */
|
|
446
|
+
export function tidyCardPrompt(data: TidyData): string {
|
|
447
|
+
if (data.state === "pending" || data.state === "requested") {
|
|
448
|
+
const lines = [
|
|
449
|
+
`Memory tidy for bot ${data.bot}: ${data.counts.notes} new or changed note${data.counts.notes === 1 ? "" : "s"}, ${data.counts.chats} chat${data.counts.chats === 1 ? "" : "s"} to check.`,
|
|
450
|
+
data.counts.indexOver ? "The memory index is over its limit." : "The memory index is within its limit.",
|
|
451
|
+
];
|
|
452
|
+
if (data.state === "requested") lines.push("It runs as soon as no chat of this bot is replying.");
|
|
453
|
+
return lines.join(" ");
|
|
454
|
+
}
|
|
455
|
+
if (data.state === "running") {
|
|
456
|
+
return `Memory tidy for bot ${data.bot} is running in chat ${data.chatId ?? "…"}.`;
|
|
457
|
+
}
|
|
458
|
+
const outcome = data.outcome ?? data.lastOutcome;
|
|
459
|
+
if (data.state === "failed") {
|
|
460
|
+
const reason = outcome === undefined ? "no reason was recorded" : outcome.summary;
|
|
461
|
+
return `Memory tidy for bot ${data.bot} failed: ${reason.replace(/\.$/, "")}.`;
|
|
462
|
+
}
|
|
463
|
+
if (outcome === undefined) return `Memory tidy for bot ${data.bot}: nothing to show.`;
|
|
464
|
+
return `Memory tidy for bot ${data.bot} finished. ${tidyOutcomeLine(data.bot, outcome)}.${outcome.reply.length === 0 ? "" : ` Reply: ${outcome.reply}`}`;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** The actions a tidy card offers: Run and Skip. */
|
|
468
|
+
export const tidyActions: readonly ActionTypeDefinition[] = [
|
|
469
|
+
{
|
|
470
|
+
name: "run",
|
|
471
|
+
on: TIDY_TYPE,
|
|
472
|
+
when: (state) => state.state === "pending" || state.state === "failed",
|
|
473
|
+
async run(ctx) {
|
|
474
|
+
const data = tidyDataOf(ctx.object.data);
|
|
475
|
+
if (data === undefined) throw new BotError("this tidy card has no usable state");
|
|
476
|
+
await ctx.store.put(
|
|
477
|
+
TIDY_TYPE,
|
|
478
|
+
data.bot,
|
|
479
|
+
{ ...data, state: "requested", requestedAt: Date.now(), outcome: undefined } as unknown as Record<string, JsonValue>,
|
|
480
|
+
"action:bot/run",
|
|
481
|
+
);
|
|
482
|
+
return `memory tidy for bot ${data.bot} will run when no chat of the bot is replying`;
|
|
483
|
+
},
|
|
484
|
+
},
|
|
485
|
+
{
|
|
486
|
+
name: "skip",
|
|
487
|
+
on: TIDY_TYPE,
|
|
488
|
+
when: (state) => state.state === "pending" || state.state === "failed",
|
|
489
|
+
async run(ctx) {
|
|
490
|
+
const data = tidyDataOf(ctx.object.data);
|
|
491
|
+
if (data === undefined) throw new BotError("this tidy card has no usable state");
|
|
492
|
+
await ctx.store.put(
|
|
493
|
+
TIDY_TYPE,
|
|
494
|
+
data.bot,
|
|
495
|
+
{ ...data, state: "skipped", requestedAt: undefined } as unknown as Record<string, JsonValue>,
|
|
496
|
+
"action:bot/skip",
|
|
497
|
+
);
|
|
498
|
+
return `skipped the memory tidy of bot ${data.bot} until the next check finds work`;
|
|
499
|
+
},
|
|
500
|
+
},
|
|
501
|
+
];
|
|
502
|
+
|
|
503
|
+
/** The pending items the tidy cards make. */
|
|
504
|
+
export async function tidyItems(
|
|
505
|
+
store: ObjectStore,
|
|
506
|
+
): Promise<
|
|
507
|
+
readonly {
|
|
508
|
+
readonly id: string;
|
|
509
|
+
readonly prompt: string;
|
|
510
|
+
readonly object: { readonly type: string; readonly id: string };
|
|
511
|
+
}[]
|
|
512
|
+
> {
|
|
513
|
+
const items = [];
|
|
514
|
+
for (const object of await listAll(store, TIDY_TYPE)) {
|
|
515
|
+
const data = tidyDataOf(object.data);
|
|
516
|
+
if (data === undefined) continue;
|
|
517
|
+
if (data.state !== "pending" && data.state !== "failed") continue;
|
|
518
|
+
const bot = await store.get(BOT_TYPE, data.bot);
|
|
519
|
+
if (bot === undefined || bot.data.removed === true) continue;
|
|
520
|
+
items.push({
|
|
521
|
+
id: object.id,
|
|
522
|
+
prompt: tidyCardPrompt(data),
|
|
523
|
+
object: { type: TIDY_TYPE, id: object.id },
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
return items;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function tidyRow(object: StoredObject): ObjectRow {
|
|
530
|
+
const data = tidyDataOf(object.data);
|
|
531
|
+
if (data === undefined) {
|
|
532
|
+
return { id: object.id, title: "Memory tidy", state: "broken", parent: `${BOT_TYPE}:${object.id}` };
|
|
533
|
+
}
|
|
534
|
+
return {
|
|
535
|
+
id: object.id,
|
|
536
|
+
title: `Memory tidy for ${data.bot}`,
|
|
537
|
+
state: data.state,
|
|
538
|
+
parent: `${BOT_TYPE}:${data.bot}`,
|
|
539
|
+
...(data.state === "pending" || data.state === "failed"
|
|
540
|
+
? { waiting: true as const }
|
|
541
|
+
: {}),
|
|
542
|
+
...(data.counts.notes === 0 && data.counts.chats === 0
|
|
543
|
+
? {}
|
|
544
|
+
: { note: `${data.counts.notes} notes, ${data.counts.chats} chats` }),
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/** How a tidy card shows when it is read as an object. */
|
|
549
|
+
export const tidyViews: ObjectViews = {
|
|
550
|
+
row: tidyRow,
|
|
551
|
+
sections: () => [{ id: "tidy", title: "Memory tidy" }],
|
|
552
|
+
load: (_ctx, object): SectionContent => {
|
|
553
|
+
const data = tidyDataOf(object.data);
|
|
554
|
+
return {
|
|
555
|
+
markdown: data === undefined ? "This tidy card has no usable state." : tidyCardPrompt(data),
|
|
556
|
+
};
|
|
557
|
+
},
|
|
558
|
+
};
|
|
559
|
+
|
|
560
|
+
export interface TidySourceContext {
|
|
561
|
+
readonly store: ObjectStore;
|
|
562
|
+
/** Tells whether the latest run of a chat is still running; absent when the host cannot tell. */
|
|
563
|
+
readonly runs?: RunControl | undefined;
|
|
564
|
+
readonly home: string;
|
|
565
|
+
readonly settings: Readonly<Record<string, JsonValue>>;
|
|
566
|
+
readonly clock: () => number;
|
|
567
|
+
readonly logger: { write(text: string): Promise<string> };
|
|
568
|
+
readonly client: ClientApi;
|
|
569
|
+
readonly harnesses?: readonly string[] | undefined;
|
|
570
|
+
readonly harnessCapabilities?: ((harness: string) => HarnessCapabilities | undefined) | undefined;
|
|
571
|
+
/** How the check reads its work; a test replaces it to see whether it ran. */
|
|
572
|
+
readonly work?: ((store: ObjectStore, bot: string, cwd: string) => Promise<TidyWork>) | undefined;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
function backgroundModel(
|
|
576
|
+
settings: BotSettings,
|
|
577
|
+
ctx: TidySourceContext,
|
|
578
|
+
): string | undefined {
|
|
579
|
+
if (typeof settings.backgroundModel === "string" && settings.backgroundModel.length > 0) {
|
|
580
|
+
return settings.backgroundModel;
|
|
581
|
+
}
|
|
582
|
+
// The chat starts at "ask": the first agent that carries it, else the first loaded one.
|
|
583
|
+
const harness = settings.harness ??
|
|
584
|
+
ctx.harnesses?.find((name) => (ctx.harnessCapabilities?.(name)?.accessLevels ?? []).includes("ask")) ??
|
|
585
|
+
ctx.harnesses?.[0];
|
|
586
|
+
return harness === undefined ? undefined : ctx.harnessCapabilities?.(harness)?.backgroundModel;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
function outcomeSummary(outcome: TidyOutcome): string {
|
|
590
|
+
const line = `${outcome.summary}${outcome.voided ? "; only additions were kept" : ""}`;
|
|
591
|
+
return line.length <= NOTICE_MAX ? line : `${line.slice(0, NOTICE_MAX - 1)}…`;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/** The bot's nightly tidy source. */
|
|
595
|
+
export class BotTidySource {
|
|
596
|
+
private readonly ctx: TidySourceContext;
|
|
597
|
+
private readonly notify: (notice: ScheduleNotice) => Promise<void>;
|
|
598
|
+
private readonly chatWatches: ChatWatches;
|
|
599
|
+
private timer: ReturnType<typeof setInterval> | undefined;
|
|
600
|
+
private stopped = false;
|
|
601
|
+
private busy = false;
|
|
602
|
+
private lastCheck: number | undefined;
|
|
603
|
+
|
|
604
|
+
constructor(
|
|
605
|
+
ctx: TidySourceContext,
|
|
606
|
+
options: { readonly notify?: ((notice: ScheduleNotice) => Promise<void>) | undefined } = {},
|
|
607
|
+
) {
|
|
608
|
+
this.ctx = ctx;
|
|
609
|
+
this.notify = options.notify ?? ((notice) => notifyScheduledReply(ctx.home, notice));
|
|
610
|
+
this.chatWatches = new ChatWatches(ctx.logger, ctx.store, ctx.runs);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/** Waits for the checks that are running now; a test calls this after a reply. */
|
|
614
|
+
async settled(): Promise<void> {
|
|
615
|
+
await this.chatWatches.settled();
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
private async put(bot: string, data: TidyData, cause: string): Promise<void> {
|
|
619
|
+
await this.ctx.store.put(TIDY_TYPE, bot, data as unknown as Record<string, JsonValue>, cause);
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
private async bots(): Promise<readonly StoredObject[]> {
|
|
623
|
+
return listAll(this.ctx.store, BOT_TYPE);
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
private async tidyObjects(): Promise<readonly StoredObject[]> {
|
|
627
|
+
return listAll(this.ctx.store, TIDY_TYPE);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/** Creates the first baseline, then checks at the planned time and catches up once. */
|
|
631
|
+
async poll(): Promise<void> {
|
|
632
|
+
if (this.stopped || this.busy) return;
|
|
633
|
+
this.busy = true;
|
|
634
|
+
try {
|
|
635
|
+
const now = this.ctx.clock();
|
|
636
|
+
this.lastCheck = now;
|
|
637
|
+
for (const object of await this.bots()) {
|
|
638
|
+
if (object.data.removed === true) continue;
|
|
639
|
+
await this.one(object, now);
|
|
640
|
+
}
|
|
641
|
+
} finally {
|
|
642
|
+
this.busy = false;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
private async one(object: StoredObject, now: number): Promise<void> {
|
|
647
|
+
const bot = object.id;
|
|
648
|
+
let settings: BotSettings | undefined;
|
|
649
|
+
try {
|
|
650
|
+
settings = readBots(this.ctx.home, this.ctx.settings)[bot];
|
|
651
|
+
} catch (error) {
|
|
652
|
+
await this.chatWatches.log(`memory tidy: ${messageOf(error)}`);
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
if (settings === undefined || !memoryEnabled(this.ctx.home)) return;
|
|
656
|
+
let cwd: string;
|
|
657
|
+
try {
|
|
658
|
+
cwd = workingDirectory(this.ctx.home, bot, settings);
|
|
659
|
+
ensureBotMemory(cwd, this.ctx.home);
|
|
660
|
+
} catch (error) {
|
|
661
|
+
await this.chatWatches.log(`memory tidy ${bot}: ${messageOf(error)}`);
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
const stored = await this.ctx.store.get(TIDY_TYPE, bot);
|
|
665
|
+
if (stored === undefined) {
|
|
666
|
+
await this.put(
|
|
667
|
+
bot,
|
|
668
|
+
{
|
|
669
|
+
bot,
|
|
670
|
+
state: "idle",
|
|
671
|
+
plannedAt: latestTidyMinute(settings, now),
|
|
672
|
+
checkedAt: now,
|
|
673
|
+
counts: { notes: 0, chats: 0, indexOver: false },
|
|
674
|
+
},
|
|
675
|
+
"source:bot/tidy",
|
|
676
|
+
);
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
const data = tidyDataOf(stored.data);
|
|
680
|
+
if (data === undefined) return;
|
|
681
|
+
if (data.state === "running") return;
|
|
682
|
+
if (data.state === "requested") {
|
|
683
|
+
// Wait for the chats to finish before the check spawns git or reads notes.
|
|
684
|
+
if (await botChatReplying(this.ctx.store, bot, this.ctx.runs)) return;
|
|
685
|
+
const work = await this.workFor(bot, cwd);
|
|
686
|
+
if (work.notes.length === 0 && !work.indexOver) {
|
|
687
|
+
await this.put(
|
|
688
|
+
bot,
|
|
689
|
+
{ ...data, state: "idle", counts: { notes: 0, chats: 0, indexOver: false } },
|
|
690
|
+
"source:bot/tidy",
|
|
691
|
+
);
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
await this.launch(bot, cwd, settings, data.plannedAt, work, false);
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
const latest = latestTidyMinute(settings, now);
|
|
698
|
+
if (latest <= data.plannedAt) return;
|
|
699
|
+
if (settings.runWithoutAsking === true) {
|
|
700
|
+
// A reply is being written: try again on the next tick, without moving the
|
|
701
|
+
// planned time past a night that has not run, and without checking its work.
|
|
702
|
+
if (await botChatReplying(this.ctx.store, bot, this.ctx.runs)) return;
|
|
703
|
+
const work = await this.workFor(bot, cwd);
|
|
704
|
+
if (work.notes.length === 0 && !work.indexOver) {
|
|
705
|
+
const keep = data.state === "result" || data.state === "failed" ? data.state : "idle";
|
|
706
|
+
await this.put(
|
|
707
|
+
bot,
|
|
708
|
+
{ ...data, state: keep, plannedAt: latest, checkedAt: now, counts: { notes: 0, chats: 0, indexOver: false } },
|
|
709
|
+
"source:bot/tidy",
|
|
710
|
+
);
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
await this.launch(bot, cwd, settings, latest, work, true);
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
const work = await this.workFor(bot, cwd);
|
|
717
|
+
const counts: TidyCounts = {
|
|
718
|
+
notes: work.notes.length,
|
|
719
|
+
chats: work.chats.length,
|
|
720
|
+
indexOver: work.indexOver,
|
|
721
|
+
};
|
|
722
|
+
if (work.notes.length === 0 && !work.indexOver) {
|
|
723
|
+
const keep = data.state === "result" || data.state === "failed" ? data.state : "idle";
|
|
724
|
+
await this.put(
|
|
725
|
+
bot,
|
|
726
|
+
{ ...data, state: keep, plannedAt: latest, checkedAt: now, counts: { notes: 0, chats: 0, indexOver: false } },
|
|
727
|
+
"source:bot/tidy",
|
|
728
|
+
);
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
await this.put(
|
|
732
|
+
bot,
|
|
733
|
+
{
|
|
734
|
+
...data,
|
|
735
|
+
state: "pending",
|
|
736
|
+
plannedAt: latest,
|
|
737
|
+
checkedAt: now,
|
|
738
|
+
counts,
|
|
739
|
+
auto: false,
|
|
740
|
+
outcome: undefined,
|
|
741
|
+
},
|
|
742
|
+
"source:bot/tidy",
|
|
743
|
+
);
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
private workFor(bot: string, cwd: string): Promise<TidyWork> {
|
|
747
|
+
if (this.ctx.work !== undefined) return this.ctx.work(this.ctx.store, bot, cwd);
|
|
748
|
+
return tidyWork(this.ctx.store, bot, cwd, { home: this.ctx.home });
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
/** A run that started but can no longer be watched is reported, not left running. */
|
|
752
|
+
private async failStart(bot: string, data: TidyData, summary: string): Promise<void> {
|
|
753
|
+
const now = this.ctx.clock();
|
|
754
|
+
const outcome: TidyOutcome = {
|
|
755
|
+
chatId: data.chatId ?? "",
|
|
756
|
+
at: now,
|
|
757
|
+
costMicros: null,
|
|
758
|
+
changed: false,
|
|
759
|
+
voided: false,
|
|
760
|
+
summary: replySummary(summary),
|
|
761
|
+
reply: "",
|
|
762
|
+
};
|
|
763
|
+
const auto = data.auto === true;
|
|
764
|
+
await this.put(
|
|
765
|
+
bot,
|
|
766
|
+
{
|
|
767
|
+
...data,
|
|
768
|
+
state: auto ? "idle" : "failed",
|
|
769
|
+
...(auto ? { outcome: undefined, lastOutcome: outcome } : { outcome }),
|
|
770
|
+
},
|
|
771
|
+
"source:bot/tidy",
|
|
772
|
+
);
|
|
773
|
+
if (auto) {
|
|
774
|
+
try {
|
|
775
|
+
await this.notify({
|
|
776
|
+
chatId: outcome.chatId,
|
|
777
|
+
title: "Memory tidy",
|
|
778
|
+
summary: tidyOutcomeLine(bot, outcome),
|
|
779
|
+
});
|
|
780
|
+
} catch (error) {
|
|
781
|
+
await this.chatWatches.log(
|
|
782
|
+
`memory tidy of bot ${bot}: notify: ${messageOf(error)}`,
|
|
783
|
+
);
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
private async launch(
|
|
789
|
+
bot: string,
|
|
790
|
+
cwd: string,
|
|
791
|
+
settings: BotSettings,
|
|
792
|
+
plannedAt: number,
|
|
793
|
+
work: TidyWork,
|
|
794
|
+
auto: boolean,
|
|
795
|
+
): Promise<void> {
|
|
796
|
+
const now = this.ctx.clock();
|
|
797
|
+
const counts: TidyCounts = {
|
|
798
|
+
notes: work.notes.length,
|
|
799
|
+
chats: work.chats.length,
|
|
800
|
+
indexOver: work.indexOver,
|
|
801
|
+
};
|
|
802
|
+
const running: TidyData = {
|
|
803
|
+
bot,
|
|
804
|
+
state: "running",
|
|
805
|
+
plannedAt,
|
|
806
|
+
checkedAt: now,
|
|
807
|
+
counts,
|
|
808
|
+
auto,
|
|
809
|
+
};
|
|
810
|
+
await this.put(bot, running, "source:bot/tidy");
|
|
811
|
+
const model = backgroundModel(settings, this.ctx);
|
|
812
|
+
let chatId: string | undefined;
|
|
813
|
+
try {
|
|
814
|
+
const run = await this.ctx.client.act("bot:chat", `${BOT_TYPE}:${bot}`, {
|
|
815
|
+
args: {
|
|
816
|
+
title: `Memory tidy (${localDate(now)})`.slice(0, 120),
|
|
817
|
+
message: tidyPrompt(bot, work),
|
|
818
|
+
...(model === undefined ? {} : { model }),
|
|
819
|
+
},
|
|
820
|
+
actor: { via: SCHEDULE_SOURCE, id: TIDY_ORIGIN },
|
|
821
|
+
});
|
|
822
|
+
chatId = run.opens?.startsWith(`${CHAT_TYPE}:`) === true
|
|
823
|
+
? run.opens.slice(CHAT_TYPE.length + 1)
|
|
824
|
+
: undefined;
|
|
825
|
+
} catch (error) {
|
|
826
|
+
const message = messageOf(error);
|
|
827
|
+
await this.failStart(bot, running, `Could not start: ${message}`);
|
|
828
|
+
await this.chatWatches.log(`memory tidy of bot ${bot} could not start: ${message}`);
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
if (chatId === undefined) {
|
|
832
|
+
await this.failStart(bot, running, "Could not start: it opened no chat");
|
|
833
|
+
await this.chatWatches.log(`memory tidy of bot ${bot} opened no chat`);
|
|
834
|
+
return;
|
|
835
|
+
}
|
|
836
|
+
await this.put(bot, { ...running, chatId }, "source:bot/tidy");
|
|
837
|
+
await this.watch(bot, chatId, auto);
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
private async watch(bot: string, chatId: string, auto: boolean): Promise<void> {
|
|
841
|
+
this.chatWatches.watchChatReply(
|
|
842
|
+
chatId,
|
|
843
|
+
chatId,
|
|
844
|
+
async (read) => {
|
|
845
|
+
const committed = read.facts.some(
|
|
846
|
+
(fact) =>
|
|
847
|
+
fact.type === TIDY_COMMIT_FACT &&
|
|
848
|
+
isRecord(fact.data) &&
|
|
849
|
+
fact.data["chat"] === chatId,
|
|
850
|
+
);
|
|
851
|
+
if (!committed) return undefined;
|
|
852
|
+
const stored = await this.ctx.store.get(CHAT_TYPE, chatId);
|
|
853
|
+
if (stored === undefined) return undefined;
|
|
854
|
+
const reply = [...read.messages].reverse().find((message) => message.role === "assistant");
|
|
855
|
+
const failure = [...read.entries].reverse().find((item) => item.kind === "failure");
|
|
856
|
+
if (reply === undefined && failure === undefined) return undefined;
|
|
857
|
+
return { stored, replyText: reply?.text, failureText: failure?.text };
|
|
858
|
+
},
|
|
859
|
+
async ({ stored, replyText, failureText }) => {
|
|
860
|
+
await this.finish(bot, chatId, stored, auto, replyText, failureText);
|
|
861
|
+
},
|
|
862
|
+
);
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
private async finish(
|
|
866
|
+
bot: string,
|
|
867
|
+
chatId: string,
|
|
868
|
+
stored: StoredObject,
|
|
869
|
+
auto: boolean,
|
|
870
|
+
replyText: string | undefined,
|
|
871
|
+
failureText: string | undefined,
|
|
872
|
+
): Promise<void> {
|
|
873
|
+
const now = this.ctx.clock();
|
|
874
|
+
const chat = chatData(stored.data);
|
|
875
|
+
const memoryDir = join(chat.cwd, "memory");
|
|
876
|
+
ensureMemoryLayout(memoryDir);
|
|
877
|
+
const repository = ensureRepository(memoryDir);
|
|
878
|
+
const commit = tidyCommitForChat(repository, memoryDir, chatId);
|
|
879
|
+
const summary =
|
|
880
|
+
commit === undefined
|
|
881
|
+
? undefined
|
|
882
|
+
: tidyCommitSummary(repository, commit, { directory: memoryDir, bot });
|
|
883
|
+
const costMicros =
|
|
884
|
+
typeof stored.data.costMicros === "number" && Number.isFinite(stored.data.costMicros)
|
|
885
|
+
? stored.data.costMicros
|
|
886
|
+
: null;
|
|
887
|
+
const outcome: TidyOutcome = {
|
|
888
|
+
chatId,
|
|
889
|
+
at: now,
|
|
890
|
+
costMicros,
|
|
891
|
+
changed: summary?.changed === true,
|
|
892
|
+
voided: summary?.voided === true,
|
|
893
|
+
summary:
|
|
894
|
+
failureText === undefined
|
|
895
|
+
? summary?.summary ?? "No memory change."
|
|
896
|
+
: replySummary(failureText),
|
|
897
|
+
reply: replyText === undefined ? "" : replySummary(replyText),
|
|
898
|
+
};
|
|
899
|
+
const data = tidyDataOf((await this.ctx.store.get(TIDY_TYPE, bot))?.data ?? {});
|
|
900
|
+
if (auto) {
|
|
901
|
+
await this.put(
|
|
902
|
+
bot,
|
|
903
|
+
{
|
|
904
|
+
...(data ?? {
|
|
905
|
+
bot,
|
|
906
|
+
state: "idle",
|
|
907
|
+
plannedAt: now,
|
|
908
|
+
counts: { notes: 0, chats: 0, indexOver: false },
|
|
909
|
+
}),
|
|
910
|
+
state: "idle",
|
|
911
|
+
chatId: undefined,
|
|
912
|
+
outcome: undefined,
|
|
913
|
+
lastOutcome: outcome,
|
|
914
|
+
},
|
|
915
|
+
"source:bot/tidy",
|
|
916
|
+
);
|
|
917
|
+
if (outcome.changed || failureText !== undefined) {
|
|
918
|
+
try {
|
|
919
|
+
await this.notify({
|
|
920
|
+
chatId,
|
|
921
|
+
title: typeof stored.data.title === "string" ? stored.data.title : "Memory tidy",
|
|
922
|
+
summary: tidyOutcomeLine(bot, { ...outcome, summary: outcomeSummary(outcome) }),
|
|
923
|
+
});
|
|
924
|
+
} catch (error) {
|
|
925
|
+
await this.chatWatches.log(
|
|
926
|
+
`memory tidy of bot ${bot}: notify: ${messageOf(error)}`,
|
|
927
|
+
);
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
if (failureText !== undefined) {
|
|
933
|
+
await this.put(
|
|
934
|
+
bot,
|
|
935
|
+
{
|
|
936
|
+
...(data ?? {
|
|
937
|
+
bot,
|
|
938
|
+
state: "failed",
|
|
939
|
+
plannedAt: now,
|
|
940
|
+
counts: { notes: 0, chats: 0, indexOver: false },
|
|
941
|
+
}),
|
|
942
|
+
state: "failed",
|
|
943
|
+
chatId: undefined,
|
|
944
|
+
outcome,
|
|
945
|
+
},
|
|
946
|
+
"source:bot/tidy",
|
|
947
|
+
);
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
950
|
+
await this.put(
|
|
951
|
+
bot,
|
|
952
|
+
{
|
|
953
|
+
...(data ?? {
|
|
954
|
+
bot,
|
|
955
|
+
state: "result",
|
|
956
|
+
plannedAt: now,
|
|
957
|
+
counts: { notes: 0, chats: 0, indexOver: false },
|
|
958
|
+
}),
|
|
959
|
+
state: "result",
|
|
960
|
+
chatId: undefined,
|
|
961
|
+
outcome,
|
|
962
|
+
},
|
|
963
|
+
"source:bot/tidy",
|
|
964
|
+
);
|
|
965
|
+
try {
|
|
966
|
+
await this.notify({
|
|
967
|
+
chatId,
|
|
968
|
+
title: typeof stored.data.title === "string" ? stored.data.title : "Memory tidy",
|
|
969
|
+
summary: tidyOutcomeLine(bot, { ...outcome, summary: outcomeSummary(outcome) }),
|
|
970
|
+
});
|
|
971
|
+
} catch (error) {
|
|
972
|
+
await this.chatWatches.log(
|
|
973
|
+
`memory tidy of bot ${bot}: notify: ${messageOf(error)}`,
|
|
974
|
+
);
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
private async resume(): Promise<void> {
|
|
979
|
+
for (const object of await this.tidyObjects()) {
|
|
980
|
+
const data = tidyDataOf(object.data);
|
|
981
|
+
if (data?.state !== "running") continue;
|
|
982
|
+
if (data.chatId === undefined) {
|
|
983
|
+
// The process died after marking the run but before recording its chat.
|
|
984
|
+
await this.failStart(data.bot, data, "Could not start: the tidy chat was not recorded");
|
|
985
|
+
continue;
|
|
986
|
+
}
|
|
987
|
+
await this.watch(data.bot, data.chatId, data.auto === true);
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
start(): { stop: () => void } {
|
|
992
|
+
this.timer = setInterval(() => {
|
|
993
|
+
this.chatWatches.track(this.poll());
|
|
994
|
+
}, 1_000);
|
|
995
|
+
if (typeof this.timer === "object" && "unref" in this.timer) {
|
|
996
|
+
this.timer.unref();
|
|
997
|
+
}
|
|
998
|
+
return {
|
|
999
|
+
stop: () => {
|
|
1000
|
+
this.stopped = true;
|
|
1001
|
+
if (this.timer !== undefined) clearInterval(this.timer);
|
|
1002
|
+
this.chatWatches.stopAll();
|
|
1003
|
+
},
|
|
1004
|
+
};
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
/** The source's first pass, after the bot plugin has made its objects. */
|
|
1008
|
+
async begin(): Promise<void> {
|
|
1009
|
+
await this.resume();
|
|
1010
|
+
await this.poll();
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
/** Starts the tidy source; `begin` runs before the first interval. */
|
|
1015
|
+
export async function startTidy(
|
|
1016
|
+
ctx: TidySourceContext,
|
|
1017
|
+
): Promise<{ stop: () => void }> {
|
|
1018
|
+
const source = new BotTidySource(ctx);
|
|
1019
|
+
await source.begin();
|
|
1020
|
+
return source.start();
|
|
1021
|
+
}
|