@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.
@@ -0,0 +1,323 @@
1
+ /**
2
+ * "Set up git here" (ADR 0039 D8): the bot's side. A task needs git, and a
3
+ * folder may have none; at the first task the bot's agent calls the agent-only
4
+ * verb `setup-git` and a pending item titled "Set up git here" (在这里设置 git)
5
+ * shows the `.gitignore`, the files the first commit would hold and the name and
6
+ * email the commit is made with. Nothing is written into the folder, and git is
7
+ * not run in it, until the person approves; approval leaves a request that
8
+ * `dev` carries out (`dev/src/setup-git.ts`).
9
+ */
10
+
11
+ import { randomUUID } from "node:crypto";
12
+ import { mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
13
+ import { hostname, userInfo } from "node:os";
14
+ import { isAbsolute, join, resolve } from "node:path";
15
+ import {
16
+ DEFAULT_GITIGNORE,
17
+ DEV_GIT_GUIDE,
18
+ existingGitignore,
19
+ firstCommitList,
20
+ gitStateOf,
21
+ type FirstCommitList,
22
+ } from "@operad-io/dev";
23
+ import { isRecord, messageOf, type CommandContext } from "@operad-io/engine";
24
+ import type { GitFinderHost } from "@operad-io/engine/platform";
25
+ import { BotError, readBots } from "./bot.ts";
26
+ import { readPiped, type PipedInput } from "./setup-dev.ts";
27
+ import { renderGuide } from "./setup.ts";
28
+
29
+ /** The directory under the home where requests for `dev` are left (the one Setup Dev uses). */
30
+ const REQUESTS_DIRECTORY = "dev-register";
31
+
32
+ /** The title of the pending item, in English and in Chinese. */
33
+ export const SETUP_GIT_TITLE = "Set up git here";
34
+ export const SETUP_GIT_TITLE_ZH = "在这里设置 git";
35
+
36
+ /** The paths a review lists before it says how many more there are. */
37
+ const REVIEW_PATHS = 200;
38
+
39
+ /** The name and email a commit is made with. */
40
+ export interface GitIdentityFields {
41
+ readonly name: string;
42
+ readonly email: string;
43
+ }
44
+
45
+ /** What a "Set up git here" proposal stores. */
46
+ export interface GitChange {
47
+ /** The folder, resolved. */
48
+ readonly repo: string;
49
+ /** The `.gitignore` text that is written and committed. */
50
+ readonly gitignore: string;
51
+ /** The folder's own `.gitignore` text now; null when it has none. */
52
+ readonly before: string | null;
53
+ /** The files the first commit holds, exactly; approval commits these and nothing else. */
54
+ readonly files: readonly string[];
55
+ /** Folders that are repositories of their own; they are not committed. */
56
+ readonly nested: readonly string[];
57
+ /** The sentence that asks to check the `.gitignore` first, when the folder is large. */
58
+ readonly note: string | null;
59
+ /** The name and email to store in the repository; null when git already has an identity. */
60
+ readonly identity: GitIdentityFields | null;
61
+ /** True when the folder has no repository yet; false when it has one without a commit. */
62
+ readonly init: boolean;
63
+ /** The language of the pending item's title. */
64
+ readonly language: "en" | "zh";
65
+ }
66
+
67
+ const USAGE =
68
+ 'usage: operad bot setup-git <bot> <folder> [< {"gitignore": "...", "identity": {"name": "...", "email": "..."}}]';
69
+
70
+ /** The line a bot chat starts with: when the agent proposes the git setup, and that git is never asked about before. */
71
+ export const SETUP_GIT_INSTRUCTION =
72
+ "When I want a task in a folder and operad answers that git is not installed or not set up there, call the operad `command` tool with plugin `bot`, verb `setup-git`, my bot and the folder, with no input: it answers with the steps. Never ask me about git before that; chatting and changing files need none. Nothing is installed or written until I approve it in Pending.";
73
+
74
+ /** The language of the title: Chinese when the computer's locale is. */
75
+ export function titleLanguage(env: NodeJS.ProcessEnv = process.env): "en" | "zh" {
76
+ const locale = env.LC_ALL ?? env.LC_MESSAGES ?? env.LANG ?? "";
77
+ return /^zh/i.test(locale) ? "zh" : "en";
78
+ }
79
+
80
+ /** The title of the pending item. */
81
+ export function gitTitle(language: "en" | "zh"): string {
82
+ return language === "zh" ? SETUP_GIT_TITLE_ZH : SETUP_GIT_TITLE;
83
+ }
84
+
85
+ /** What the computer account says about the person, to prefill the commit's name and email. */
86
+ export interface AccountHost {
87
+ readonly username: () => string;
88
+ readonly hostname: () => string;
89
+ }
90
+
91
+ const realAccount: AccountHost = { username: () => userInfo().username, hostname: () => hostname() };
92
+
93
+ /** The name and email prefilled from the computer account; the person confirms them in the chat. */
94
+ export function accountIdentity(host: AccountHost = realAccount): GitIdentityFields {
95
+ const name = host.username();
96
+ return { name, email: `${name}@${host.hostname()}` };
97
+ }
98
+
99
+ function parseInput(text: string): { gitignore: string | undefined; identity: GitIdentityFields | undefined } {
100
+ let parsed: unknown;
101
+ try {
102
+ parsed = JSON.parse(text);
103
+ } catch (error) {
104
+ throw new BotError(`setup-git: the input is not JSON: ${messageOf(error)}`);
105
+ }
106
+ if (!isRecord(parsed)) throw new BotError("setup-git: the input must be a JSON object");
107
+ const gitignore = parsed.gitignore;
108
+ if (gitignore !== undefined && typeof gitignore !== "string") {
109
+ throw new BotError("setup-git: gitignore must be text");
110
+ }
111
+ let identity: GitIdentityFields | undefined;
112
+ if (parsed.identity !== undefined) {
113
+ const given = parsed.identity;
114
+ if (!isRecord(given) || typeof given.name !== "string" || typeof given.email !== "string") {
115
+ throw new BotError("setup-git: identity must have a name and an email, both text");
116
+ }
117
+ const name = given.name.trim();
118
+ const email = given.email.trim();
119
+ if (name === "" || !/^[^\s@]+@[^\s@]+$/.test(email)) {
120
+ throw new BotError("setup-git: identity needs a name and an email address such as name@example.com");
121
+ }
122
+ identity = { name, email };
123
+ }
124
+ return { gitignore, identity };
125
+ }
126
+
127
+ // The folder's own text with the default lines it does not have yet added after it.
128
+ function withDefaults(existing: string): string {
129
+ const have = new Set(existing.split("\n").map((line) => line.trim()));
130
+ const added = DEFAULT_GITIGNORE.split("\n").filter(
131
+ (line) => line.trim() !== "" && !line.startsWith("#") && !have.has(line.trim()),
132
+ );
133
+ if (added.length === 0) return existing;
134
+ return `${existing.endsWith("\n") || existing === "" ? existing : `${existing}\n`}${added.join("\n")}\n`;
135
+ }
136
+
137
+ function folderOf(path: string): string {
138
+ if (statSync(path, { throwIfNoEntry: false })?.isDirectory() !== true) {
139
+ throw new BotError(`setup-git: there is no directory "${path}"`);
140
+ }
141
+ return realpathSync(path);
142
+ }
143
+
144
+ /** What a test may stand in for. */
145
+ export interface ProposeGitOptions {
146
+ readonly env?: NodeJS.ProcessEnv;
147
+ readonly account?: AccountHost;
148
+ /** The home folder that is refused; the default is the computer account's. */
149
+ readonly homeFolder?: string;
150
+ /** The machine the git program is looked up on; a test injects one without git. */
151
+ readonly finder?: GitFinderHost;
152
+ }
153
+
154
+ /** Makes the proposal for a folder; nothing is written into it. */
155
+ export function proposeGit(
156
+ home: string,
157
+ bot: string,
158
+ folderPath: string,
159
+ inputText: string,
160
+ cwd: string,
161
+ options: ProposeGitOptions = {},
162
+ ): GitChange {
163
+ if (readBots(home)[bot] === undefined) throw new BotError(`there is no bot "${bot}"`);
164
+ const folder = folderOf(isAbsolute(folderPath) ? folderPath : resolve(cwd, folderPath));
165
+ const input = parseInput(inputText);
166
+ const state = gitStateOf(folder, {
167
+ ...(options.env === undefined ? {} : { env: options.env }),
168
+ ...(options.finder === undefined ? {} : { finder: options.finder }),
169
+ });
170
+ switch (state.state) {
171
+ case "no program":
172
+ throw new BotError(
173
+ "setup-git: git is not installed on this machine. Follow the steps for installing git (each command is a pending item the person approves), then call setup-git again.",
174
+ );
175
+ case "subfolder":
176
+ throw new BotError(
177
+ `setup-git: "${folder}" is inside the git repository at "${state.root}"; set up nothing here and use "${state.root}" instead`,
178
+ );
179
+ case "ready":
180
+ throw new BotError(`setup-git: "${folder}" already has git and a first commit; there is nothing to set up`);
181
+ default:
182
+ break;
183
+ }
184
+ const own = existingGitignore(folder);
185
+ const text = input.gitignore ?? (own === undefined ? DEFAULT_GITIGNORE : withDefaults(own));
186
+ let list: FirstCommitList;
187
+ try {
188
+ list = firstCommitList(folder, text, {
189
+ ...(options.homeFolder === undefined ? {} : { home: options.homeFolder }),
190
+ ...(options.env === undefined ? {} : { env: options.env }),
191
+ });
192
+ } catch (error) {
193
+ throw new BotError(`setup-git: ${messageOf(error)}`);
194
+ }
195
+ return {
196
+ repo: folder,
197
+ gitignore: text,
198
+ before: list.existingGitignore ?? null,
199
+ files: list.files,
200
+ nested: list.nested,
201
+ note: list.note ?? null,
202
+ identity: state.identity.set ? null : (input.identity ?? accountIdentity(options.account)),
203
+ init: state.state === "no repository",
204
+ language: titleLanguage(options.env),
205
+ };
206
+ }
207
+
208
+ /** The review of a "Set up git here" proposal. */
209
+ export function gitReview(bot: string, change: GitChange): string {
210
+ const out = [
211
+ `## ${gitTitle(change.language)}: ${change.repo}`,
212
+ "",
213
+ `Proposed by bot ${bot}. Approve ${
214
+ change.init ? "starts git in this folder and " : ""
215
+ }makes the first commit of the files below; the folder then works in a branch with no remote. Nothing is pushed. Reject changes nothing.`,
216
+ ];
217
+ if (change.note !== null) out.push("", `**${change.note}**`);
218
+ out.push(
219
+ "",
220
+ change.before === null ? "### .gitignore (new)" : "### .gitignore (yours, with additions)",
221
+ "",
222
+ "```",
223
+ change.gitignore.trimEnd(),
224
+ "```",
225
+ "",
226
+ `### Files in the first commit (${change.files.length})`,
227
+ "",
228
+ "```",
229
+ ...change.files.slice(0, REVIEW_PATHS),
230
+ );
231
+ if (change.files.length > REVIEW_PATHS) out.push(`... and ${change.files.length - REVIEW_PATHS} more`);
232
+ out.push("```");
233
+ if (change.nested.length > 0) {
234
+ out.push("", "### Folders that are repositories of their own (not committed)", "", ...change.nested.map((path) => `- ${path}`));
235
+ }
236
+ if (change.identity === null) {
237
+ out.push("", "### Name and email", "", "Git already has them on this computer; they are used.");
238
+ } else {
239
+ out.push(
240
+ "",
241
+ "### Name and email for the commit",
242
+ "",
243
+ `- name: ${change.identity.name}`,
244
+ `- email: ${change.identity.email}`,
245
+ "",
246
+ "Stored in this folder's git settings only. Prefilled from the computer account; the bot asks you to confirm or change them.",
247
+ );
248
+ }
249
+ return out.join("\n");
250
+ }
251
+
252
+ /** The pending item's prompt. */
253
+ export function gitPrompt(bot: string, change: GitChange | undefined): string {
254
+ if (change === undefined) return `${SETUP_GIT_TITLE} (proposed by bot ${bot}) is waiting for your review`;
255
+ return `${gitTitle(change.language)}: ${change.repo} (proposed by bot ${bot}) is waiting for your review`;
256
+ }
257
+
258
+ /** Approval: leaves the request `dev` sets git up from. */
259
+ export function applyGit(home: string, change: GitChange): void {
260
+ const requests = join(home, REQUESTS_DIRECTORY);
261
+ mkdirSync(requests, { recursive: true });
262
+ const body = {
263
+ kind: "setup-git",
264
+ path: change.repo,
265
+ gitignore: change.gitignore,
266
+ paths: change.files,
267
+ ...(change.identity === null ? {} : { identity: change.identity }),
268
+ };
269
+ writeFileSync(join(requests, `${randomUUID()}.json`), `${JSON.stringify(body)}\n`);
270
+ }
271
+
272
+ /** Reads a stored change; undefined when it is not one. */
273
+ export function gitChangeOf(value: unknown): GitChange | undefined {
274
+ if (
275
+ !isRecord(value) ||
276
+ typeof value.repo !== "string" ||
277
+ typeof value.gitignore !== "string" ||
278
+ !(value.before === null || typeof value.before === "string") ||
279
+ !Array.isArray(value.files) ||
280
+ !Array.isArray(value.nested) ||
281
+ !(value.note === null || typeof value.note === "string") ||
282
+ typeof value.init !== "boolean"
283
+ ) {
284
+ return undefined;
285
+ }
286
+ const identity =
287
+ isRecord(value.identity) && typeof value.identity.name === "string" && typeof value.identity.email === "string"
288
+ ? { name: value.identity.name, email: value.identity.email }
289
+ : null;
290
+ const strings = (items: readonly unknown[]): string[] => items.filter((item): item is string => typeof item === "string");
291
+ return {
292
+ repo: value.repo,
293
+ gitignore: value.gitignore,
294
+ before: value.before,
295
+ files: strings(value.files),
296
+ nested: strings(value.nested),
297
+ note: value.note,
298
+ identity,
299
+ init: value.init,
300
+ language: value.language === "zh" ? "zh" : "en",
301
+ };
302
+ }
303
+
304
+ /** The steps the agent follows for a folder: the guide with the bot and the folder filled in. */
305
+ export function setupGitSteps(bot: string, folder: string): string {
306
+ return renderGuide(readFileSync(DEV_GIT_GUIDE, "utf8"), bot, folder);
307
+ }
308
+
309
+ /** `bot setup-git <bot> <folder>`: with no input the steps, with the `.gitignore` and identity on stdin the proposal. */
310
+ export async function runSetupGitCommand(
311
+ ctx: CommandContext,
312
+ argv: readonly string[],
313
+ propose: (bot: string, change: GitChange) => Promise<string>,
314
+ piped: PipedInput = {},
315
+ ): Promise<string> {
316
+ const bot = argv[0];
317
+ const folder = argv[1];
318
+ if (bot === undefined || folder === undefined || argv.length > 2) throw new BotError(USAGE);
319
+ if (readBots(ctx.home)[bot] === undefined) throw new BotError(`there is no bot "${bot}"`);
320
+ const text = (await readPiped(ctx.input, piped)).trim();
321
+ if (text.length === 0) return setupGitSteps(bot, isAbsolute(folder) ? folder : resolve(ctx.cwd, folder));
322
+ return propose(bot, proposeGit(ctx.home, bot, folder, text, ctx.cwd));
323
+ }
package/src/tidy.ts CHANGED
@@ -579,7 +579,10 @@ function backgroundModel(
579
579
  if (typeof settings.backgroundModel === "string" && settings.backgroundModel.length > 0) {
580
580
  return settings.backgroundModel;
581
581
  }
582
- const harness = settings.harness ?? ctx.harnesses?.[0];
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];
583
586
  return harness === undefined ? undefined : ctx.harnessCapabilities?.(harness)?.backgroundModel;
584
587
  }
585
588