@operad-io/bot 0.1.0 → 0.2.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,254 @@
1
+ /**
2
+ * Setup Dev (ADR 0030 D15): turns on `dev` for one repository through a
3
+ * proposal. The prepared prompt has a bot's agent read the repository and
4
+ * propose a `.operad/dev.json` (the prompt is the `dev` plugin's guide, read
5
+ * through `./setup.ts`); approving the proposal turns the plugins on,
6
+ * writes the file and asks `dev` to register the repository.
7
+ */
8
+
9
+ import { execFileSync } from "node:child_process";
10
+ import { randomUUID } from "node:crypto";
11
+ import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
12
+ import { isAbsolute, join, resolve } from "node:path";
13
+ import {
14
+ isMissingFile,
15
+ isRecord,
16
+ messageOf,
17
+ readConfig,
18
+ setPluginEnabled,
19
+ type CommandContext,
20
+ type ObjectStore,
21
+ } from "@operad-io/engine";
22
+ import { writeFileAtomic } from "@operad-io/engine/platform";
23
+ import { BotError, readBots } from "./bot.ts";
24
+ import { setupDevPrompt } from "./setup.ts";
25
+
26
+ /** The plugins `dev` needs, with the package each is enabled from. */
27
+ export const SETUP_DEV_PLUGINS: Readonly<Record<string, string>> = {
28
+ dev: "@operad-io/dev",
29
+ shell: "@operad-io/shell",
30
+ pool: "@operad-io/pool",
31
+ };
32
+
33
+ /** The directory under the home where a request to register a repository is left for `dev`. */
34
+ export const DEV_REGISTER_DIRECTORY = "dev-register";
35
+
36
+ /** What a `dev` proposal stores. */
37
+ export interface DevChange {
38
+ /** The repository's directory, resolved. */
39
+ readonly repo: string;
40
+ /** The `dev.json` text to write. */
41
+ readonly json: string;
42
+ /** The file's present text; null when there is none. */
43
+ readonly before: string | null;
44
+ /** The plugins that are off now and would be turned on. */
45
+ readonly plugins: readonly string[];
46
+ }
47
+
48
+ const USAGE = "usage: operad bot setup-dev <bot> <repository directory> [< dev.json]";
49
+
50
+ /** The line a bot chat starts with, so a sentence is enough to start Setup Dev. */
51
+ export const SETUP_DEV_INSTRUCTION =
52
+ "To set up dev for a repository (Setup Dev), call the operad `command` tool with plugin `bot`, verb `setup-dev`, my bot and the repository's directory and no input: it answers with the steps. Nothing is turned on until I approve the proposal in Pending.";
53
+
54
+ function git(directory: string, args: readonly string[]): string | undefined {
55
+ try {
56
+ return execFileSync("git", ["-C", directory, ...args], {
57
+ encoding: "utf8",
58
+ stdio: ["ignore", "pipe", "ignore"],
59
+ }).trim();
60
+ } catch {
61
+ return undefined;
62
+ }
63
+ }
64
+
65
+ function rootOf(path: string): string {
66
+ if (!existsSync(path) || !statSync(path).isDirectory()) {
67
+ throw new BotError(`setup-dev: there is no directory "${path}"`);
68
+ }
69
+ const real = realpathSync(path);
70
+ const top = git(real, ["rev-parse", "--show-toplevel"]);
71
+ if (top === undefined || top.length === 0 || realpathSync(top) !== real) {
72
+ throw new BotError(`setup-dev: "${path}" is not the root of a git work tree`);
73
+ }
74
+ if ((git(real, ["remote"]) ?? "").length === 0) {
75
+ throw new BotError(`setup-dev: "${path}" has no git remote; add one first`);
76
+ }
77
+ return real;
78
+ }
79
+
80
+ async function registeredPaths(store: ObjectStore): Promise<string[]> {
81
+ const found: string[] = [];
82
+ let cursor: string | undefined;
83
+ do {
84
+ const page = await store.list("repo", { ...(cursor === undefined ? {} : { cursor }) });
85
+ for (const object of page.objects) {
86
+ if (typeof object.data.path === "string" && object.data.removed !== true) found.push(object.data.path);
87
+ }
88
+ cursor = page.next;
89
+ } while (cursor !== undefined);
90
+ return found;
91
+ }
92
+
93
+ async function pluginsOff(home: string): Promise<string[]> {
94
+ const enabled: string[] = [];
95
+ try {
96
+ for (const entry of (await readConfig(home)).plugins) {
97
+ if (entry.enabled && entry.name !== undefined) enabled.push(entry.name);
98
+ }
99
+ } catch (error) {
100
+ if (!isMissingFile(error)) throw error;
101
+ }
102
+ return Object.keys(SETUP_DEV_PLUGINS).filter((name) => !enabled.includes(name));
103
+ }
104
+
105
+ /** Proposes Setup Dev for a repository; nothing is turned on or written. */
106
+ export async function proposeDev(
107
+ store: ObjectStore,
108
+ home: string,
109
+ bot: string,
110
+ repoPath: string,
111
+ jsonText: string,
112
+ cwd: string,
113
+ makeProposal: (change: DevChange) => Promise<string>,
114
+ ): Promise<string> {
115
+ if (readBots(home)[bot] === undefined) throw new BotError(`there is no bot "${bot}"`);
116
+ const repo = rootOf(isAbsolute(repoPath) ? repoPath : resolve(cwd, repoPath));
117
+ let parsed: unknown;
118
+ try {
119
+ parsed = JSON.parse(jsonText);
120
+ } catch (error) {
121
+ throw new BotError(`setup-dev: the dev.json text is not JSON: ${messageOf(error)}`);
122
+ }
123
+ if (!isRecord(parsed)) throw new BotError("setup-dev: the dev.json text must be a JSON object");
124
+ if ((await registeredPaths(store)).some((path) => resolve(path) === repo)) {
125
+ throw new BotError(`setup-dev: "${repo}" is already registered`);
126
+ }
127
+ const file = join(repo, ".operad", "dev.json");
128
+ let before: string | null = null;
129
+ try {
130
+ before = readFileSync(file, "utf8");
131
+ } catch (error) {
132
+ if (!isMissingFile(error)) throw error;
133
+ }
134
+ return makeProposal({
135
+ repo,
136
+ json: `${JSON.stringify(parsed, null, 2)}\n`,
137
+ before,
138
+ plugins: await pluginsOff(home),
139
+ });
140
+ }
141
+
142
+ /** Turns the plugins on, writes `dev.json` and leaves the request `dev` registers the repository from. */
143
+ export async function applyDev(home: string, change: DevChange): Promise<void> {
144
+ const directory = join(change.repo, ".operad");
145
+ mkdirSync(directory, { recursive: true });
146
+ await writeFileAtomic(join(directory, "dev.json"), change.json);
147
+ const requests = join(home, DEV_REGISTER_DIRECTORY);
148
+ mkdirSync(requests, { recursive: true });
149
+ writeFileSync(join(requests, `${randomUUID()}.json`), `${JSON.stringify({ path: change.repo })}\n`);
150
+ // Last, because a change of config.json reloads serve and dev then finds the request.
151
+ for (const name of await pluginsOff(home)) {
152
+ await setPluginEnabled(home, name, true, { optional: SETUP_DEV_PLUGINS });
153
+ }
154
+ }
155
+
156
+ /** The review of a `dev` proposal. */
157
+ export function devReview(bot: string, change: DevChange): string {
158
+ const out = [
159
+ `## Setup Dev for ${change.repo}`,
160
+ "",
161
+ `Proposed by bot ${bot}. Approve turns on ${
162
+ change.plugins.length === 0 ? "nothing (dev is already on)" : change.plugins.join(", ")
163
+ }, writes \`.operad/dev.json\` and registers the repository. Reject changes nothing.`,
164
+ ];
165
+ if (change.before !== null) {
166
+ out.push("", "### dev.json now", "", "```json", change.before.trimEnd(), "```");
167
+ }
168
+ out.push("", change.before === null ? "### dev.json" : "### dev.json after", "", "```json", change.json.trimEnd(), "```");
169
+ return out.join("\n");
170
+ }
171
+
172
+ /** Reads a stored change; undefined when it is not one. */
173
+ export function devChangeOf(value: unknown): DevChange | undefined {
174
+ if (
175
+ !isRecord(value) ||
176
+ typeof value.repo !== "string" ||
177
+ typeof value.json !== "string" ||
178
+ !(value.before === null || typeof value.before === "string") ||
179
+ !Array.isArray(value.plugins)
180
+ ) {
181
+ return undefined;
182
+ }
183
+ return {
184
+ repo: value.repo,
185
+ json: value.json,
186
+ before: value.before,
187
+ plugins: value.plugins.filter((item): item is string => typeof item === "string"),
188
+ };
189
+ }
190
+
191
+ /** The stream a command reads, and what a test may stand in for. */
192
+ export interface PipedInput {
193
+ /** Defaults to the process's standard input. */
194
+ readonly stream?: (AsyncIterable<Uint8Array | string> & { readonly destroy?: () => void }) | undefined;
195
+ /** Settles when a stream that has delivered nothing is given up on; defaults to a timer. */
196
+ readonly giveUp?: Promise<void> | undefined;
197
+ }
198
+
199
+ const FIRST_BYTES_MS = 2000;
200
+
201
+ /**
202
+ * The text piped to a command that was given none. A terminal, and a pipe that
203
+ * delivers nothing before the deadline, are no input; once data starts the
204
+ * read goes on to the end.
205
+ */
206
+ export async function readPiped(input: string | undefined, options: PipedInput = {}): Promise<string> {
207
+ if (input !== undefined) return input;
208
+ const stream = options.stream ?? process.stdin;
209
+ if (options.stream === undefined && process.stdin.isTTY === true) return "";
210
+ let timer: ReturnType<typeof setTimeout> | undefined;
211
+ const giveUp =
212
+ options.giveUp ??
213
+ new Promise<void>((done) => {
214
+ timer = setTimeout(done, FIRST_BYTES_MS);
215
+ });
216
+ const iterator = stream[Symbol.asyncIterator]();
217
+ try {
218
+ const first = await Promise.race([iterator.next(), giveUp.then(() => undefined)]);
219
+ if (first === undefined) {
220
+ try {
221
+ stream.destroy?.();
222
+ } catch {
223
+ // The stream already ended.
224
+ }
225
+ return "";
226
+ }
227
+ const chunks: Buffer[] = [];
228
+ let step = first;
229
+ while (!step.done) {
230
+ chunks.push(typeof step.value === "string" ? Buffer.from(step.value, "utf8") : Buffer.from(step.value));
231
+ step = await iterator.next();
232
+ }
233
+ return Buffer.concat(chunks).toString("utf8");
234
+ } finally {
235
+ if (timer !== undefined) clearTimeout(timer);
236
+ }
237
+ }
238
+
239
+ /** `bot setup-dev <bot> <directory>`: with `dev.json` on stdin it proposes, without it answers the steps. */
240
+ export async function runSetupDevCommand(
241
+ ctx: CommandContext,
242
+ argv: readonly string[],
243
+ propose: (bot: string, change: DevChange) => Promise<string>,
244
+ piped: PipedInput = {},
245
+ ): Promise<string> {
246
+ const bot = argv[0];
247
+ const repo = argv[1];
248
+ if (bot === undefined || repo === undefined || argv.length > 2) throw new BotError(USAGE);
249
+ if (readBots(ctx.home)[bot] === undefined) throw new BotError(`there is no bot "${bot}"`);
250
+ const text = (await readPiped(ctx.input, piped)).trim();
251
+ const resolved = isAbsolute(repo) ? repo : resolve(ctx.cwd, repo);
252
+ if (text.length === 0) return setupDevPrompt(ctx.setup, bot, resolved);
253
+ return proposeDev(ctx.store, ctx.home, bot, repo, text, ctx.cwd, (change) => propose(bot, change));
254
+ }
package/src/setup.ts ADDED
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Setup guides in a bot (ADR 0010 D7, ADR 0030 D15): any plugin that ships a
3
+ * guide can be set up by a bot's agent. The plugin's check says what is
4
+ * missing, its guide says how to fix it, and the entries here hand the two to
5
+ * the agent: a command it calls, an action a button runs and a chat command.
6
+ */
7
+
8
+ import { isAbsolute, resolve } from "node:path";
9
+ import { chatData, sendMessage } from "@operad-io/chat";
10
+ import type { ActionTypeDefinition, CommandContext, SetupGuide, SetupReader } from "@operad-io/engine";
11
+ import { BotError, BOT_TYPE, readBots } from "./bot.ts";
12
+
13
+ /** Every guide's title: `Setup` and the plugin's name, capitalised (Setup Dev, Setup Telegram). */
14
+ export function setupTitle(plugin: string): string {
15
+ return `Setup ${plugin.charAt(0).toUpperCase()}${plugin.slice(1)}`;
16
+ }
17
+
18
+ /** The guide's text with the bot and the target filled in. */
19
+ export function renderGuide(text: string, bot: string, target: string): string {
20
+ return text.split("{bot}").join(bot).split("{target}").join(target);
21
+ }
22
+
23
+ /** The line a bot chat starts with, so a sentence is enough to start any plugin's setup. */
24
+ export const SETUP_INSTRUCTION =
25
+ "To set up any other plugin that has a setup guide (Setup <name>), call the operad `command` tool with plugin `bot`, verb `setup`, my bot and the plugin's name: it answers with what is missing and the steps. Nothing is turned on until I approve the proposal in Pending.";
26
+
27
+ /** The plugin's guide, or the reason there is none. */
28
+ export async function guideOf(setup: SetupReader | undefined, plugin: string): Promise<SetupGuide> {
29
+ const found = await setup?.get(plugin);
30
+ if (found === undefined) {
31
+ const known = (await setup?.list())?.map((item) => item.plugin) ?? [];
32
+ throw new BotError(
33
+ `setup: the plugin "${plugin}" has no setup guide${known.length === 0 ? "" : `; plugins with one: ${known.join(", ")}`}`,
34
+ );
35
+ }
36
+ return found;
37
+ }
38
+
39
+ /** The text Setup Dev starts a chat with: the `dev` plugin's guide for one repository. */
40
+ export async function setupDevPrompt(setup: SetupReader | undefined, bot: string, repo: string): Promise<string> {
41
+ return renderGuide((await guideOf(setup, "dev")).text, bot, repo);
42
+ }
43
+
44
+ /**
45
+ * What the agent is given for a plugin: what its check finds missing, then the
46
+ * guide. A plugin with nothing missing and no target gets one sentence saying so.
47
+ */
48
+ export async function setupPrompt(
49
+ setup: SetupReader | undefined,
50
+ bot: string,
51
+ plugin: string,
52
+ target: string,
53
+ ): Promise<string> {
54
+ const guide = await guideOf(setup, plugin);
55
+ const title = setupTitle(plugin);
56
+ if (guide.missing.length === 0 && target.length === 0) {
57
+ return `${title}: nothing is missing, ${plugin} is set up. Tell me so and stop unless I ask for something to change.`;
58
+ }
59
+ const lines = [`${title}. What the plugin's own check finds missing now:`];
60
+ if (guide.missing.length === 0) lines.push("- nothing (it is set up); the target below still needs its steps");
61
+ for (const item of guide.missing) lines.push(`- ${item.name}: ${item.description}`);
62
+ lines.push("", "Follow only the steps of the guide that fix these items.", "");
63
+ return `${lines.join("\n")}\n${renderGuide(guide.text, bot, target)}`;
64
+ }
65
+
66
+ const USAGE = "usage: operad bot setup <bot> <plugin> [target]";
67
+
68
+ /** `bot setup <bot> <plugin> [target]`: the steps for the agent. */
69
+ export async function runSetup(ctx: CommandContext, argv: readonly string[]): Promise<string> {
70
+ const [bot, plugin, target] = argv;
71
+ if (bot === undefined || plugin === undefined || argv.length > 3) throw new BotError(USAGE);
72
+ if (readBots(ctx.home)[bot] === undefined) throw new BotError(`there is no bot "${bot}"`);
73
+ const where = target === undefined ? "" : isAbsolute(target) ? target : resolve(ctx.cwd, target);
74
+ return setupPrompt(ctx.setup, bot, plugin, where);
75
+ }
76
+
77
+ /** The chat command `/setup <plugin> [target]`: sends the plugin's guide to this chat, so its agent follows it. */
78
+ export const chatSetupAction: ActionTypeDefinition = {
79
+ name: "setup",
80
+ on: "chat",
81
+ command: "Set up a plugin: the bot's agent follows its setup guide. /setup <plugin> [target]",
82
+ args: {
83
+ type: "object",
84
+ properties: {
85
+ plugin: { type: "string", minLength: 1, description: "The plugin to set up, such as dev." },
86
+ target: {
87
+ type: "string",
88
+ description: "What the guide works on, when it needs one: for dev the repository's directory.",
89
+ },
90
+ },
91
+ required: ["plugin"],
92
+ },
93
+ when: (state) => botOf(state) !== undefined && chatData(state).closed !== true,
94
+ why: (object) => {
95
+ if (botOf(object.data) === undefined) return `${object.id} is not a bot chat; /setup needs a bot`;
96
+ return chatData(object.data).closed === true ? `${object.id} is closed; it takes no commands` : undefined;
97
+ },
98
+ async run(ctx, args) {
99
+ const bot = botOf(ctx.object.data);
100
+ if (bot === undefined) throw new BotError(`${ctx.object.id} is not a bot chat; /setup needs a bot`);
101
+ const given = args as { readonly plugin: string; readonly target?: string };
102
+ const target = given.target?.trim() ?? "";
103
+ const where = target.length === 0 ? "" : isAbsolute(target) ? target : resolve(ctx.cwd, target);
104
+ const prompt = await setupPrompt(ctx.setup, bot, given.plugin.trim(), where);
105
+ const sent = await sendMessage(ctx, ctx.object.id, prompt);
106
+ return `${setupTitle(given.plugin.trim())}: ${sent}`;
107
+ },
108
+ };
109
+
110
+ function botOf(data: Readonly<Record<string, unknown>>): string | undefined {
111
+ const parent = chatData(data).parent ?? "";
112
+ return parent.startsWith(`${BOT_TYPE}:`) ? parent.slice(BOT_TYPE.length + 1) : undefined;
113
+ }