@operad-io/bot 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bot.schema.json +1 -1
- package/package.json +6 -6
- package/src/bot.ts +1 -1
- package/src/chat-watch.ts +7 -0
- package/src/delivery.ts +48 -0
- package/src/idle.ts +40 -0
- package/src/index.ts +53 -19
- package/src/proposals.ts +17 -17
- package/src/routine.ts +304 -0
- package/src/schedule.ts +449 -330
- package/src/tidy.ts +204 -59
package/bot.schema.json
CHANGED
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
"title": "Access level",
|
|
58
58
|
"enum": ["plan", "ask", "edits", "full"],
|
|
59
59
|
"default": "ask",
|
|
60
|
-
"description": "The level a chat on this bot starts at, when opened from the desktop, the CLI, the MCP server or Telegram; a
|
|
60
|
+
"description": "The level a chat on this bot starts at, when opened from the desktop, the CLI, the MCP server or Telegram; a run of a routine starts at full. Unlike `access`, which can only tighten the profile, this can loosen it: `full` asks nothing but the deny rules. A chat that chose a level with /access keeps it; a chat that did not follows this setting. See docs/user/access.md."
|
|
61
61
|
},
|
|
62
62
|
"writeWiki": {
|
|
63
63
|
"type": "boolean",
|
package/package.json
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@operad-io/bot",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
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/dev": "0.
|
|
11
|
-
"@operad-io/engine": "0.
|
|
12
|
-
"@operad-io/access-match": "0.
|
|
13
|
-
"@operad-io/memory": "0.
|
|
9
|
+
"@operad-io/chat": "0.4.0",
|
|
10
|
+
"@operad-io/dev": "0.4.0",
|
|
11
|
+
"@operad-io/engine": "0.4.0",
|
|
12
|
+
"@operad-io/access-match": "0.4.0",
|
|
13
|
+
"@operad-io/memory": "0.4.0"
|
|
14
14
|
},
|
|
15
15
|
"description": "operad: the bot plugin",
|
|
16
16
|
"repository": {
|
package/src/bot.ts
CHANGED
|
@@ -95,7 +95,7 @@ export const BOT_SETTINGS: ActionArgsSchema = {
|
|
|
95
95
|
enum: ["plan", "ask", "edits", "full"],
|
|
96
96
|
default: "ask",
|
|
97
97
|
description:
|
|
98
|
-
"The level a chat on this bot starts at, when opened from the desktop, the CLI, the MCP server or Telegram; a
|
|
98
|
+
"The level a chat on this bot starts at, when opened from the desktop, the CLI, the MCP server or Telegram; a run of a routine starts at full. Unlike `access`, which can only tighten the profile, this can loosen it: `full` asks nothing but the deny rules. A chat that chose a level with /access keeps it; a chat that did not follows this setting. See docs/user/access.md.",
|
|
99
99
|
},
|
|
100
100
|
writeWiki: {
|
|
101
101
|
type: "boolean",
|
package/src/chat-watch.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { CHAT_TYPE, readChat, writingReplyNow, type ChatRead } from "@operad-io/
|
|
|
10
10
|
/** One chat's watch: how to stop it. */
|
|
11
11
|
interface ChatWatch {
|
|
12
12
|
readonly stop: () => void;
|
|
13
|
+
readonly recheck: () => void;
|
|
13
14
|
}
|
|
14
15
|
|
|
15
16
|
/** The watches of one bot source, and the work they and its polls started. */
|
|
@@ -39,6 +40,11 @@ export class ChatWatches {
|
|
|
39
40
|
while (this.work.size > 0) await Promise.allSettled([...this.work]);
|
|
40
41
|
}
|
|
41
42
|
|
|
43
|
+
/** Reads every watched chat again: an end that leaves no new fact is found by it. */
|
|
44
|
+
recheckAll(): void {
|
|
45
|
+
for (const watch of [...this.watches.values()]) watch.recheck();
|
|
46
|
+
}
|
|
47
|
+
|
|
42
48
|
stopAll(): void {
|
|
43
49
|
for (const watch of [...this.watches.values()]) watch.stop();
|
|
44
50
|
this.watches.clear();
|
|
@@ -91,6 +97,7 @@ export class ChatWatches {
|
|
|
91
97
|
unsubscribe?.();
|
|
92
98
|
this.watches.delete(key);
|
|
93
99
|
},
|
|
100
|
+
recheck: () => this.track(check()),
|
|
94
101
|
};
|
|
95
102
|
this.watches.set(key, blocking);
|
|
96
103
|
unsubscribe = this.store.subscribe({ type: CHAT_TYPE, id: chatId }, {}, () => {
|
package/src/delivery.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How a routine's result reaches the bot's main chat (ADR 0030 D10, ADR 0026
|
|
3
|
+
* D19). A result with content is one message in the main chat, headed with the
|
|
4
|
+
* routine's name; a bound Telegram chat is sent it like any message of the
|
|
5
|
+
* chat. It starts no reply: its summary, not its whole text, rides on the
|
|
6
|
+
* chat's next message, and the whole run stays readable on demand.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { deliverResult, mainChatOf } from "@operad-io/chat";
|
|
10
|
+
import type { FactWriter, ObjectStore } from "@operad-io/engine";
|
|
11
|
+
import { BOT_TYPE } from "./bot.ts";
|
|
12
|
+
import { ROUTINE_TYPE } from "./schedule.ts";
|
|
13
|
+
|
|
14
|
+
/** What a routine run hands over. */
|
|
15
|
+
export interface RoutineResult {
|
|
16
|
+
readonly bot: string;
|
|
17
|
+
/** The routine's bare object id, when it has one. */
|
|
18
|
+
readonly routineId?: string | undefined;
|
|
19
|
+
readonly title: string;
|
|
20
|
+
readonly runId: string;
|
|
21
|
+
readonly summary: string;
|
|
22
|
+
readonly text: string;
|
|
23
|
+
readonly failed: boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Delivers one result to the bot's main chat. False when the bot has no open
|
|
28
|
+
* chat, so there is nowhere to put it; true when the message is there, also
|
|
29
|
+
* when an earlier call already put it.
|
|
30
|
+
*/
|
|
31
|
+
export async function deliverToMainChat(
|
|
32
|
+
ctx: { readonly store: ObjectStore; readonly facts: FactWriter },
|
|
33
|
+
bot: string,
|
|
34
|
+
result: Omit<RoutineResult, "bot">,
|
|
35
|
+
): Promise<boolean> {
|
|
36
|
+
const chat = await mainChatOf(ctx.store, `${BOT_TYPE}:${bot}`);
|
|
37
|
+
if (chat === undefined) return false;
|
|
38
|
+
await deliverResult(ctx, chat, {
|
|
39
|
+
routine: result.title,
|
|
40
|
+
...(result.routineId === undefined || result.routineId.length === 0 ? {} : { routineId: `${ROUTINE_TYPE}:${result.routineId}` }),
|
|
41
|
+
runId: result.runId,
|
|
42
|
+
summary: result.summary,
|
|
43
|
+
text: result.text,
|
|
44
|
+
...(result.failed ? { failed: true } : {}),
|
|
45
|
+
from: { via: "bot", id: result.title },
|
|
46
|
+
});
|
|
47
|
+
return true;
|
|
48
|
+
}
|
package/src/idle.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cleanup of chats nobody writes in (docs/backlog/operad-long-chat.md, ADR 0026,
|
|
3
|
+
* ADR 0030): a bot's chat bound to no channel closes by itself after 7 days with
|
|
4
|
+
* no message; a chat bound to a channel never does, because the channel's next
|
|
5
|
+
* message would only open a new one. Repository chats are not swept: they hold a
|
|
6
|
+
* worktree and may be tied to a task, which this plugin cannot see.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { CHAT_TYPE, chatData, chatFacts } from "@operad-io/chat";
|
|
10
|
+
import type { ClientApi, ObjectStore } from "@operad-io/engine";
|
|
11
|
+
import { BOT_TYPE } from "./bot.ts";
|
|
12
|
+
import { SCHEDULE_SOURCE } from "./schedule.ts";
|
|
13
|
+
|
|
14
|
+
/** How many days a chat bound to no channel may go without a message. */
|
|
15
|
+
export const CHAT_IDLE_DAYS = 7;
|
|
16
|
+
|
|
17
|
+
const DAY_MS = 24 * 60 * 60_000;
|
|
18
|
+
|
|
19
|
+
/** Closes the bot chats that are open, bound to no channel and idle; returns how many. */
|
|
20
|
+
export async function closeIdleChats(store: ObjectStore, client: ClientApi, now: number): Promise<number> {
|
|
21
|
+
let closed = 0;
|
|
22
|
+
let cursor: string | undefined;
|
|
23
|
+
do {
|
|
24
|
+
const page = await store.list(CHAT_TYPE, { ...(cursor === undefined ? {} : { cursor }) });
|
|
25
|
+
for (const object of page.objects) {
|
|
26
|
+
const chat = chatData(object.data);
|
|
27
|
+
if (chat.closed || chat.run === true || chat.channels.length > 0) continue;
|
|
28
|
+
if (chat.parent === undefined || !chat.parent.startsWith(`${BOT_TYPE}:`)) continue;
|
|
29
|
+
const last = chatFacts(store, object.id).at(-1)?.at ?? object.at;
|
|
30
|
+
if (now - last < CHAT_IDLE_DAYS * DAY_MS) continue;
|
|
31
|
+
await client.act("chat:close", `${CHAT_TYPE}:${object.id}`, {
|
|
32
|
+
actor: { via: SCHEDULE_SOURCE, id: "idle" },
|
|
33
|
+
yes: true,
|
|
34
|
+
});
|
|
35
|
+
closed += 1;
|
|
36
|
+
}
|
|
37
|
+
cursor = page.next;
|
|
38
|
+
} while (cursor !== undefined);
|
|
39
|
+
return closed;
|
|
40
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -14,7 +14,7 @@ import pkg from "../package.json" with { type: "json" };
|
|
|
14
14
|
import { mkdirSync } from "node:fs";
|
|
15
15
|
import { basename, isAbsolute, join, resolve } from "node:path";
|
|
16
16
|
import { fileURLToPath } from "node:url";
|
|
17
|
-
import { CHAT_TYPE, MESSAGE_EVENT, levelRefusal, agentConditionals, type AgentChoices, type ScheduledChat, chatData, createChat, sendMessage, startingEffort, startingModel, titleFromMessage } from "@operad-io/chat";
|
|
17
|
+
import { CHAT_TYPE, MESSAGE_EVENT, mainChatOf, levelRefusal, agentConditionals, type AgentChoices, type ScheduledChat, chatData, createChat, sendMessage, startingEffort, startingModel, titleFromMessage } from "@operad-io/chat";
|
|
18
18
|
import { definePlugin, isRecord, modelIds, type ActionArgSchema, type ActionArgsSchema, type ActionTypeDefinition, type HarnessCapabilities, type HarnessModelInfo, type HarnessModels, type JsonValue, type ObjectRow, type ObjectStore, type ObjectViews, type PluginStepResult, type SectionContent, type StepContext, type StoredObject } from "@operad-io/engine";
|
|
19
19
|
import {
|
|
20
20
|
BOT_SETTINGS,
|
|
@@ -24,6 +24,7 @@ import {
|
|
|
24
24
|
botDir,
|
|
25
25
|
defaultBotHomeMigrated,
|
|
26
26
|
ensureBotMemory,
|
|
27
|
+
memoryDir,
|
|
27
28
|
migrateDefaultBotDir,
|
|
28
29
|
readBots,
|
|
29
30
|
repositoryPaths,
|
|
@@ -33,7 +34,7 @@ import {
|
|
|
33
34
|
type BotSettings,
|
|
34
35
|
type ResolvedBot,
|
|
35
36
|
} from "./bot.ts";
|
|
36
|
-
import { MEMORY_COMMIT_STEP, memoryNotes } from "@operad-io/memory";
|
|
37
|
+
import { MEMORY_COMMIT_STEP, memoryNotes, wikiDirectoryOfHome } from "@operad-io/memory";
|
|
37
38
|
import { createBot, knownMcpServers, knownSkills } from "./create.ts";
|
|
38
39
|
import { LOGIN_EVENT, LOGIN_SOURCE, loginAction, loginFlow, loginItems, runLogin as runLoginStep } from "./login.ts";
|
|
39
40
|
import { chatSetupAction, runSetup, setupDevPrompt, setupPrompt, setupTitle } from "./setup.ts";
|
|
@@ -50,17 +51,20 @@ import {
|
|
|
50
51
|
runSkillCommand,
|
|
51
52
|
} from "./proposals.ts";
|
|
52
53
|
import {
|
|
54
|
+
ROUTINE_TYPE,
|
|
53
55
|
SCHEDULE_SOURCE,
|
|
56
|
+
migrateScheduled,
|
|
54
57
|
scheduleActions,
|
|
55
58
|
scheduledChatContext,
|
|
56
|
-
scheduledData,
|
|
57
59
|
scheduledInstructionFor,
|
|
58
60
|
markdownCode,
|
|
59
61
|
markdownText,
|
|
60
|
-
|
|
61
|
-
scheduledPrompts,
|
|
62
|
+
routinesOf,
|
|
62
63
|
startScheduled,
|
|
63
64
|
} from "./schedule.ts";
|
|
65
|
+
import { closeIdleChats } from "./idle.ts";
|
|
66
|
+
import { pruneRoutineRuns } from "./schedule.ts";
|
|
67
|
+
import { closeOldScheduledChats, routineActions, routineMarkdown, routineViews, ROUTINE_FILTERS } from "./routine.ts";
|
|
64
68
|
import { followUpActions, followUpData, followUpMarkdown, followUps, runFollowUpCommand, runFollowUpsCommand } from "./follow-up.ts";
|
|
65
69
|
import {
|
|
66
70
|
TIDY_TYPE,
|
|
@@ -167,9 +171,9 @@ export async function syncBots(
|
|
|
167
171
|
data = { name, removed: false, problem: error.message };
|
|
168
172
|
}
|
|
169
173
|
const current = await store.get(BOT_TYPE, name);
|
|
170
|
-
//
|
|
171
|
-
if (Array.isArray(current
|
|
172
|
-
|
|
174
|
+
// Routines used to be a field of the bot object; each one is an object of its own now.
|
|
175
|
+
if (current !== undefined && Array.isArray(current.data.scheduled)) {
|
|
176
|
+
await migrateScheduled(store, name, current.data);
|
|
173
177
|
}
|
|
174
178
|
// So are its follow-ups (ADR 0030 D16).
|
|
175
179
|
if (Array.isArray(current?.data.followUps)) {
|
|
@@ -208,8 +212,10 @@ export interface OpenChat {
|
|
|
208
212
|
readonly title?: string | undefined;
|
|
209
213
|
/** The channels (`telegram:<chat>`) whose messages land in this chat. */
|
|
210
214
|
readonly channels?: readonly string[] | undefined;
|
|
211
|
-
/** The
|
|
215
|
+
/** The routine that starts the run; absent when a person opens a chat. */
|
|
212
216
|
readonly scheduled?: ScheduledChat | undefined;
|
|
217
|
+
/** True for the record of a run of a routine, which is not a chat. */
|
|
218
|
+
readonly run?: boolean | undefined;
|
|
213
219
|
readonly cause: string;
|
|
214
220
|
}
|
|
215
221
|
|
|
@@ -278,6 +284,7 @@ export async function openChat(input: OpenChat): Promise<string> {
|
|
|
278
284
|
title: input.title ?? `Bot (${bot.name})`,
|
|
279
285
|
...(input.channels === undefined ? {} : { channels: input.channels }),
|
|
280
286
|
...(input.scheduled === undefined ? {} : { scheduled: input.scheduled }),
|
|
287
|
+
...(input.run === true ? { run: true } : {}),
|
|
281
288
|
refresh: SETTINGS_STEP,
|
|
282
289
|
},
|
|
283
290
|
input.cause,
|
|
@@ -561,7 +568,7 @@ const chatAction: ActionTypeDefinition = {
|
|
|
561
568
|
effort: input.effort,
|
|
562
569
|
title: input.title ?? (input.message === undefined ? undefined : titleFromMessage(input.message)),
|
|
563
570
|
channels: input.channels,
|
|
564
|
-
...(scheduled === undefined ? {} : { scheduled }),
|
|
571
|
+
...(scheduled === undefined ? {} : { scheduled, run: true }),
|
|
565
572
|
cause: "action:bot/chat",
|
|
566
573
|
});
|
|
567
574
|
const sent =
|
|
@@ -573,7 +580,7 @@ const chatAction: ActionTypeDefinition = {
|
|
|
573
580
|
input.message,
|
|
574
581
|
undefined,
|
|
575
582
|
[],
|
|
576
|
-
scheduled === undefined ? undefined : scheduledInstructionFor(ctx.object.
|
|
583
|
+
scheduled === undefined ? undefined : await scheduledInstructionFor(ctx.store, ctx.object.id, scheduled.entry),
|
|
577
584
|
);
|
|
578
585
|
return { text: `opened chat ${id}${sent === undefined ? "" : `; ${sent}`}`, opens: `chat:${id}` };
|
|
579
586
|
},
|
|
@@ -719,9 +726,12 @@ export async function runSettings(ctx: StepContext, params: unknown): Promise<Pl
|
|
|
719
726
|
// The memory index and the person's instructions ride on the message,
|
|
720
727
|
// whole when this session has not seen them, under ADR 0026 D18.
|
|
721
728
|
notes: memoryNotes(join(bot.cwd, "memory")) as unknown as JsonValue,
|
|
729
|
+
// What a stretch that is not remembered may read and may not write.
|
|
730
|
+
memoryPaths: [memoryDir(bot.cwd), wikiDirectoryOfHome(ctx.home)],
|
|
722
731
|
// The memory plugin records what this reply wrote, once the round ends.
|
|
723
732
|
...(ctx.stepLoaded !== undefined && ctx.stepLoaded(MEMORY_COMMIT_STEP) ? { after: MEMORY_COMMIT_STEP } : {}),
|
|
724
|
-
|
|
733
|
+
// A run of a routine is not a chat: it proposes no schedule and sets no follow-up.
|
|
734
|
+
...(chatData(stored.data).run === true ? {} : { context: scheduledChatContext(stored.id) }),
|
|
725
735
|
},
|
|
726
736
|
};
|
|
727
737
|
} catch (error) {
|
|
@@ -729,7 +739,7 @@ export async function runSettings(ctx: StepContext, params: unknown): Promise<Pl
|
|
|
729
739
|
}
|
|
730
740
|
}
|
|
731
741
|
|
|
732
|
-
function botMarkdown(object: StoredObject): string {
|
|
742
|
+
async function botMarkdown(store: ObjectStore, object: StoredObject): Promise<string> {
|
|
733
743
|
const data = object.data;
|
|
734
744
|
const lines = [`**${object.id}**`];
|
|
735
745
|
if (typeof data.problem === "string") lines.push(`Cannot be used: ${markdownText(data.problem)}`);
|
|
@@ -748,7 +758,7 @@ function botMarkdown(object: StoredObject): string {
|
|
|
748
758
|
`They are mounted in chats on ${MCP_HARNESSES.join(" and ")}. A chat on pi does not mount them: pi takes no MCP servers yet, so it cannot use ${servers.join(", ")}.`,
|
|
749
759
|
);
|
|
750
760
|
}
|
|
751
|
-
lines.push(
|
|
761
|
+
lines.push(routineMarkdown(await routinesOf(store, object.id), Date.now()).join("\n"));
|
|
752
762
|
lines.push(followUpMarkdown(followUps(data)).join("\n"));
|
|
753
763
|
return lines.join("\n\n");
|
|
754
764
|
}
|
|
@@ -765,13 +775,19 @@ export const botViews: ObjectViews = {
|
|
|
765
775
|
title: object.id,
|
|
766
776
|
state: object.data.removed === true ? "removed" : "open",
|
|
767
777
|
data: {
|
|
768
|
-
scheduled: scheduledData(scheduledPrompts(object.data), Date.now()) as unknown as JsonValue,
|
|
769
778
|
timeZone: serverTimeZone(),
|
|
770
779
|
followUps: followUpData(followUps(object.data)) as unknown as JsonValue,
|
|
771
780
|
},
|
|
772
781
|
}),
|
|
773
782
|
sections: () => [{ id: "bot", title: "Bot" }],
|
|
774
|
-
|
|
783
|
+
// The bot's main chat rides on its page, so a client that opens the bot can go on to it.
|
|
784
|
+
load: async (ctx, object): Promise<SectionContent> => {
|
|
785
|
+
const main = object.data.removed === true ? undefined : await mainChatOf(ctx.store, `${BOT_TYPE}:${object.id}`);
|
|
786
|
+
return {
|
|
787
|
+
markdown: await botMarkdown(ctx.store, object),
|
|
788
|
+
data: { mainChat: main === undefined ? null : `${CHAT_TYPE}:${main}` },
|
|
789
|
+
};
|
|
790
|
+
},
|
|
775
791
|
};
|
|
776
792
|
|
|
777
793
|
/** Builds the bot plugin. */
|
|
@@ -782,7 +798,7 @@ export function createBotPlugin() {
|
|
|
782
798
|
// The version comes from package.json so the two cannot drift apart.
|
|
783
799
|
version: pkg.version,
|
|
784
800
|
// Patch releases of chat only: a new minor may change what bot relies on.
|
|
785
|
-
requires: { plugins: { chat: "~0.
|
|
801
|
+
requires: { plugins: { chat: "~0.4.0" } },
|
|
786
802
|
settings: BOT_SETTINGS,
|
|
787
803
|
// A bot page is that bot's settings page; bots live under settings, not in a tab.
|
|
788
804
|
objectsUnderSettings: true,
|
|
@@ -806,6 +822,7 @@ export function createBotPlugin() {
|
|
|
806
822
|
],
|
|
807
823
|
},
|
|
808
824
|
{ name: TIDY_TYPE, index: ["bot", "state"] },
|
|
825
|
+
{ name: ROUTINE_TYPE, index: ["bot"], filters: ROUTINE_FILTERS },
|
|
809
826
|
],
|
|
810
827
|
steps: [
|
|
811
828
|
{ name: "settings", results: ["done", "failed"], run: runSettings },
|
|
@@ -831,7 +848,7 @@ export function createBotPlugin() {
|
|
|
831
848
|
mode: "auto" as const,
|
|
832
849
|
},
|
|
833
850
|
],
|
|
834
|
-
actions: [chatAction, setupDevAction, setupAction, chatSetupAction, createAction, loginAction, ...proposalActions, ...scheduleActions, ...followUpActions, ...tidyActions],
|
|
851
|
+
actions: [chatAction, setupDevAction, setupAction, chatSetupAction, createAction, loginAction, ...proposalActions, ...scheduleActions, ...routineActions, ...followUpActions, ...tidyActions],
|
|
835
852
|
commands: [
|
|
836
853
|
{
|
|
837
854
|
name: "skill",
|
|
@@ -890,16 +907,31 @@ export function createBotPlugin() {
|
|
|
890
907
|
// `serve` starts it like any source.
|
|
891
908
|
start: async (ctx) => {
|
|
892
909
|
await migrateDefaultHome(ctx.store, ctx.home, readBots(ctx.home, ctx.settings));
|
|
910
|
+
// Chats the old scheduled prompts and memory tidies opened are closed once (ADR 0030 D10).
|
|
911
|
+
await closeOldScheduledChats(ctx.store, ctx.client);
|
|
893
912
|
const scheduled = await startScheduled(ctx);
|
|
894
913
|
const tidy = await startTidy(ctx);
|
|
914
|
+
// Idle chats close and old routine runs leave, at start and then hourly (injected clock).
|
|
915
|
+
const sweep = async (): Promise<void> => {
|
|
916
|
+
try {
|
|
917
|
+
await closeIdleChats(ctx.store, ctx.client, ctx.clock());
|
|
918
|
+
await pruneRoutineRuns(ctx.store, ctx.clock());
|
|
919
|
+
} catch (error) {
|
|
920
|
+
await ctx.logger.write(`cleanup: ${error instanceof Error ? error.message : String(error)}`);
|
|
921
|
+
}
|
|
922
|
+
};
|
|
923
|
+
await sweep();
|
|
924
|
+
const sweeper = setInterval(() => void sweep(), 60 * 60_000);
|
|
925
|
+
if (typeof sweeper === "object" && "unref" in sweeper) sweeper.unref();
|
|
895
926
|
return {
|
|
896
927
|
stop: async () => {
|
|
928
|
+
clearInterval(sweeper);
|
|
897
929
|
await scheduled.stop();
|
|
898
930
|
await tidy.stop();
|
|
899
931
|
},
|
|
900
932
|
};
|
|
901
933
|
},
|
|
902
|
-
views: { [BOT_TYPE]: botViews, [PROPOSAL_TYPE]: proposalViews, [TIDY_TYPE]: tidyViews },
|
|
934
|
+
views: { [BOT_TYPE]: botViews, [PROPOSAL_TYPE]: proposalViews, [TIDY_TYPE]: tidyViews, [ROUTINE_TYPE]: routineViews },
|
|
903
935
|
});
|
|
904
936
|
}
|
|
905
937
|
|
|
@@ -913,6 +945,8 @@ export * from "./setup-dev.ts";
|
|
|
913
945
|
export * from "./setup-git.ts";
|
|
914
946
|
export * from "./setup.ts";
|
|
915
947
|
export * from "./schedule.ts";
|
|
948
|
+
export * from "./idle.ts";
|
|
949
|
+
export * from "./routine.ts";
|
|
916
950
|
export * from "./follow-up.ts";
|
|
917
951
|
export * from "./tidy.ts";
|
|
918
952
|
export * from "./mcp.ts";
|
package/src/proposals.ts
CHANGED
|
@@ -51,7 +51,7 @@ import {
|
|
|
51
51
|
checkPromptName,
|
|
52
52
|
checkSchedule,
|
|
53
53
|
scheduleChangeOf,
|
|
54
|
-
|
|
54
|
+
routinesOf,
|
|
55
55
|
type ScheduleChange,
|
|
56
56
|
type ScheduledPrompt,
|
|
57
57
|
} from "./schedule.ts";
|
|
@@ -517,15 +517,15 @@ function schedulePromptLines(entry: ScheduledPrompt): string[] {
|
|
|
517
517
|
];
|
|
518
518
|
}
|
|
519
519
|
|
|
520
|
-
/** What a person reads before a
|
|
520
|
+
/** What a person reads before a routine is added, changed or removed. */
|
|
521
521
|
function scheduleReview(bot: string, change: ScheduleChange): string {
|
|
522
522
|
const name = (change.after ?? change.before)?.name ?? "?";
|
|
523
523
|
const action =
|
|
524
524
|
change.action === "add" ? "adds" : change.action === "edit" ? "changes" : "removes";
|
|
525
525
|
const out = [
|
|
526
|
-
`##
|
|
526
|
+
`## Routine ${name} for bot ${bot}`,
|
|
527
527
|
"",
|
|
528
|
-
`This proposal ${action} a
|
|
528
|
+
`This proposal ${action} a routine on bot ${bot}. Approve applies it; reject leaves the bot as it is.`,
|
|
529
529
|
];
|
|
530
530
|
if (change.before !== null) {
|
|
531
531
|
out.push(
|
|
@@ -556,7 +556,7 @@ export function proposalReview(object: StoredObject): string {
|
|
|
556
556
|
if (data.kind === "schedule") {
|
|
557
557
|
const change = scheduleChangeOf(data.schedule);
|
|
558
558
|
return change === undefined
|
|
559
|
-
? "No
|
|
559
|
+
? "No routine is recorded for this proposal."
|
|
560
560
|
: scheduleReview(data.bot, change);
|
|
561
561
|
}
|
|
562
562
|
if (data.kind === "mcp") {
|
|
@@ -746,7 +746,7 @@ function optionalText(value: string | undefined): string | undefined {
|
|
|
746
746
|
}
|
|
747
747
|
|
|
748
748
|
/**
|
|
749
|
-
* Proposes adding, changing or removing one of a bot's
|
|
749
|
+
* Proposes adding, changing or removing one of a bot's routines. The
|
|
750
750
|
* owner's direct actions apply at once; this path is the one a chat's agent
|
|
751
751
|
* uses, so nothing fires until a person approves the proposal.
|
|
752
752
|
*/
|
|
@@ -760,12 +760,12 @@ export async function proposeSchedule(
|
|
|
760
760
|
const object = await store.get(BOT_TYPE, bot);
|
|
761
761
|
if (object === undefined) throw new BotError(`there is no bot "${bot}"`);
|
|
762
762
|
const name = checkPromptName(input.name);
|
|
763
|
-
const current =
|
|
763
|
+
const current = (await routinesOf(store, bot)).find((entry) => entry.name === name);
|
|
764
764
|
if (input.action === "add" && current !== undefined) {
|
|
765
|
-
throw new BotError(`bot ${bot} already has a
|
|
765
|
+
throw new BotError(`bot ${bot} already has a routine "${name}"`);
|
|
766
766
|
}
|
|
767
767
|
if (input.action !== "add" && current === undefined) {
|
|
768
|
-
throw new BotError(`bot ${bot} has no
|
|
768
|
+
throw new BotError(`bot ${bot} has no routine "${name}"`);
|
|
769
769
|
}
|
|
770
770
|
if (
|
|
771
771
|
input.action === "remove" &&
|
|
@@ -775,7 +775,7 @@ export async function proposeSchedule(
|
|
|
775
775
|
input.effort !== undefined)
|
|
776
776
|
) {
|
|
777
777
|
throw new BotError(
|
|
778
|
-
"removing a
|
|
778
|
+
"removing a routine takes only its name and, optionally, the schedule in words",
|
|
779
779
|
);
|
|
780
780
|
}
|
|
781
781
|
const words = optionalText(input.words);
|
|
@@ -787,10 +787,10 @@ export async function proposeSchedule(
|
|
|
787
787
|
let after: ScheduledPrompt | null = null;
|
|
788
788
|
if (input.action === "add") {
|
|
789
789
|
if (input.schedule === undefined) {
|
|
790
|
-
throw new BotError("adding a
|
|
790
|
+
throw new BotError("adding a routine needs --schedule, a five-field cron expression");
|
|
791
791
|
}
|
|
792
792
|
const prompt = input.prompt === undefined ? "" : input.prompt.trim();
|
|
793
|
-
if (prompt.length === 0) throw new BotError("a
|
|
793
|
+
if (prompt.length === 0) throw new BotError("a routine needs a prompt");
|
|
794
794
|
const model = optionalText(input.model);
|
|
795
795
|
const effort = optionalText(input.effort);
|
|
796
796
|
after = {
|
|
@@ -809,12 +809,12 @@ export async function proposeSchedule(
|
|
|
809
809
|
input.effort === undefined
|
|
810
810
|
) {
|
|
811
811
|
throw new BotError(
|
|
812
|
-
"editing a
|
|
812
|
+
"editing a routine needs a field to change: --schedule, --prompt, --model or --effort",
|
|
813
813
|
);
|
|
814
814
|
}
|
|
815
815
|
const schedule = input.schedule === undefined ? current.schedule : checkSchedule(input.schedule);
|
|
816
816
|
const prompt = input.prompt === undefined ? current.prompt : input.prompt.trim();
|
|
817
|
-
if (prompt.length === 0) throw new BotError("a
|
|
817
|
+
if (prompt.length === 0) throw new BotError("a routine needs a prompt");
|
|
818
818
|
const model = input.model === undefined ? current.model : optionalText(input.model);
|
|
819
819
|
const effort = input.effort === undefined ? current.effort : optionalText(input.effort);
|
|
820
820
|
after = {
|
|
@@ -840,14 +840,14 @@ export async function proposeSchedule(
|
|
|
840
840
|
const data: ProposalData = {
|
|
841
841
|
bot,
|
|
842
842
|
kind: "schedule",
|
|
843
|
-
title: `
|
|
843
|
+
title: `Routine ${name}`,
|
|
844
844
|
state: "pending",
|
|
845
845
|
createdAt: Date.now(),
|
|
846
846
|
schedule: change,
|
|
847
847
|
};
|
|
848
848
|
const id = `p-${randomUUID()}`;
|
|
849
849
|
await store.put(PROPOSAL_TYPE, id, data as unknown as Record<string, JsonValue>, "command:bot/schedule");
|
|
850
|
-
return `proposed
|
|
850
|
+
return `proposed routine "${name}" for bot ${bot}; review it in pending`;
|
|
851
851
|
}
|
|
852
852
|
|
|
853
853
|
function skillData(value: unknown): ProposalData["skill"] | undefined {
|
|
@@ -940,7 +940,7 @@ export async function applyProposal(
|
|
|
940
940
|
applyGit(home, change);
|
|
941
941
|
} else if (data.kind === "schedule") {
|
|
942
942
|
const change = scheduleChangeOf(data.schedule);
|
|
943
|
-
if (change === undefined) throw new BotError(`proposal ${id} has no
|
|
943
|
+
if (change === undefined) throw new BotError(`proposal ${id} has no routine to apply`);
|
|
944
944
|
await applyScheduleChange(store, data.bot, change);
|
|
945
945
|
} else if (data.kind === "mcp") {
|
|
946
946
|
const change = mcpChangeOf(data.mcp);
|