@operad-io/bot 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +159 -2
- package/bot.schema.json +159 -0
- package/package.json +24 -4
- package/src/bot.ts +384 -0
- package/src/guard.ts +205 -0
- package/src/index.ts +392 -0
- package/src/mcp-client.ts +215 -0
- package/src/mcp-constants.ts +2 -0
- package/src/mcp-proposals.ts +225 -0
- package/src/mcp.ts +245 -0
- package/src/proposals.ts +917 -0
package/src/proposals.ts
ADDED
|
@@ -0,0 +1,917 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Changes a bot proposes to itself: a new or changed skill, or a change to its
|
|
3
|
+
* settings. A proposal is a stored object, shown as one pending item on its
|
|
4
|
+
* bot. Nothing on disk changes until a person approves it; rejecting it leaves
|
|
5
|
+
* every file and setting as it was.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { randomUUID } from "node:crypto";
|
|
9
|
+
import {
|
|
10
|
+
chmodSync,
|
|
11
|
+
existsSync,
|
|
12
|
+
lstatSync,
|
|
13
|
+
mkdirSync,
|
|
14
|
+
readFileSync,
|
|
15
|
+
readdirSync,
|
|
16
|
+
rmSync,
|
|
17
|
+
writeFileSync,
|
|
18
|
+
} from "node:fs";
|
|
19
|
+
import { homedir } from "node:os";
|
|
20
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
21
|
+
import {
|
|
22
|
+
configPath,
|
|
23
|
+
isRecord,
|
|
24
|
+
messageOf,
|
|
25
|
+
prepareSettings,
|
|
26
|
+
writeFileAtomic,
|
|
27
|
+
type ActionTypeDefinition,
|
|
28
|
+
type CommandContext,
|
|
29
|
+
type JsonValue,
|
|
30
|
+
type ObjectRow,
|
|
31
|
+
type ObjectStore,
|
|
32
|
+
type ObjectViews,
|
|
33
|
+
type SectionContent,
|
|
34
|
+
type StoredObject,
|
|
35
|
+
} from "@operad-io/engine";
|
|
36
|
+
import { withLockFile } from "@operad-io/engine/platform";
|
|
37
|
+
import {
|
|
38
|
+
BOT_SETTINGS,
|
|
39
|
+
BOT_TYPE,
|
|
40
|
+
BotError,
|
|
41
|
+
readBots,
|
|
42
|
+
resolveBot,
|
|
43
|
+
type BotSettings,
|
|
44
|
+
type McpServerSettings,
|
|
45
|
+
} from "./bot.ts";
|
|
46
|
+
import { commandLine, compareTools, differenceLines, secretName, storedTools } from "./mcp.ts";
|
|
47
|
+
|
|
48
|
+
/** The object type of a proposal. It is internal: a person sees its pending item. */
|
|
49
|
+
export const PROPOSAL_TYPE = "bot-proposal";
|
|
50
|
+
|
|
51
|
+
/** A proposal waiting for a person, or what became of it. */
|
|
52
|
+
export type ProposalState = "pending" | "applied" | "rejected";
|
|
53
|
+
|
|
54
|
+
/** One file in a skill directory. */
|
|
55
|
+
export interface SkillFile {
|
|
56
|
+
/** The path inside the skill directory, with `/` separators. */
|
|
57
|
+
readonly path: string;
|
|
58
|
+
readonly content: string;
|
|
59
|
+
/** A script, listed apart from the other files. */
|
|
60
|
+
readonly script: boolean;
|
|
61
|
+
readonly executable: boolean;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** A skill directory as it was or as it is proposed. */
|
|
65
|
+
export interface SkillSnapshot {
|
|
66
|
+
/** The absolute directory of the skill. */
|
|
67
|
+
readonly path: string;
|
|
68
|
+
readonly files: readonly SkillFile[];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** One bot's settings before and after a proposed change. */
|
|
72
|
+
export interface SettingsChange {
|
|
73
|
+
readonly before: Readonly<Record<string, JsonValue>>;
|
|
74
|
+
readonly after: Readonly<Record<string, JsonValue>>;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** What a proposal stores. */
|
|
78
|
+
export interface ProposalData {
|
|
79
|
+
readonly [key: string]: unknown;
|
|
80
|
+
readonly bot: string;
|
|
81
|
+
readonly kind: "skill" | "settings" | "mcp";
|
|
82
|
+
readonly title: string;
|
|
83
|
+
readonly state: ProposalState;
|
|
84
|
+
readonly createdAt: number;
|
|
85
|
+
readonly skill?: {
|
|
86
|
+
readonly name: string;
|
|
87
|
+
readonly before: SkillSnapshot | null;
|
|
88
|
+
readonly after: SkillSnapshot;
|
|
89
|
+
} | undefined;
|
|
90
|
+
readonly settings?: SettingsChange | undefined;
|
|
91
|
+
readonly mcp?: McpChange | undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** A local MCP server a proposal registers, upgrades or lets through after a change of its tools. */
|
|
95
|
+
export interface McpChange {
|
|
96
|
+
readonly server: string;
|
|
97
|
+
/** `new`: registered for the first time; `upgrade`: registered again with another command or version; `changed`: the server's own tools changed. */
|
|
98
|
+
readonly reason: "new" | "upgrade" | "changed";
|
|
99
|
+
readonly before: McpServerSettings | null;
|
|
100
|
+
readonly after: McpServerSettings;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const NAME = /^[a-z0-9][a-z0-9_-]*$/;
|
|
104
|
+
|
|
105
|
+
function dataOf(object: StoredObject): ProposalData {
|
|
106
|
+
const data = object.data;
|
|
107
|
+
if (
|
|
108
|
+
typeof data.bot !== "string" ||
|
|
109
|
+
(data.kind !== "skill" && data.kind !== "settings" && data.kind !== "mcp") ||
|
|
110
|
+
typeof data.title !== "string" ||
|
|
111
|
+
(data.state !== "pending" && data.state !== "applied" && data.state !== "rejected") ||
|
|
112
|
+
typeof data.createdAt !== "number"
|
|
113
|
+
) {
|
|
114
|
+
throw new Error(`proposal ${object.id} has an unusable shape`);
|
|
115
|
+
}
|
|
116
|
+
return data as ProposalData;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function isScript(path: string, mode: number): boolean {
|
|
120
|
+
return path === "scripts" || path.startsWith("scripts/") || (mode & 0o111) !== 0;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** The files of a skill directory now, sorted by path; missing means none. */
|
|
124
|
+
export function readSkillDirectory(path: string): SkillFile[] {
|
|
125
|
+
if (!existsSync(path)) return [];
|
|
126
|
+
const found: SkillFile[] = [];
|
|
127
|
+
const walk = (directory: string, prefix: string): void => {
|
|
128
|
+
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
|
129
|
+
if (entry.name === ".git" || entry.name === "node_modules") continue;
|
|
130
|
+
const full = join(directory, entry.name);
|
|
131
|
+
const inner = prefix.length === 0 ? entry.name : `${prefix}/${entry.name}`;
|
|
132
|
+
const info = lstatSync(full);
|
|
133
|
+
if (info.isDirectory()) {
|
|
134
|
+
walk(full, inner);
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (!info.isFile()) continue;
|
|
138
|
+
found.push({
|
|
139
|
+
path: inner,
|
|
140
|
+
content: readFileSync(full, "utf8"),
|
|
141
|
+
script: isScript(inner, info.mode),
|
|
142
|
+
executable: (info.mode & 0o111) !== 0,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
walk(path, "");
|
|
147
|
+
return found.sort((left, right) => left.path.localeCompare(right.path));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function fileOf(files: readonly SkillFile[], path: string): SkillFile | undefined {
|
|
151
|
+
return files.find((file) => file.path === path);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function expandPath(path: string, base: string): string {
|
|
155
|
+
if (path === "~") return homedir();
|
|
156
|
+
if (path.startsWith("~/")) return join(homedir(), path.slice(2));
|
|
157
|
+
return isAbsolute(path) ? resolve(path) : resolve(base, path);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** The skill directory a bot already mounts under this name, if any. */
|
|
161
|
+
function existingSkillPath(
|
|
162
|
+
home: string,
|
|
163
|
+
bot: string,
|
|
164
|
+
name: string,
|
|
165
|
+
): string | undefined {
|
|
166
|
+
const written = readBots(home)[bot];
|
|
167
|
+
if (written === undefined) return undefined;
|
|
168
|
+
const cwd = resolveBotFromSettings(home, bot, written).cwd;
|
|
169
|
+
for (const skill of written.skills ?? []) {
|
|
170
|
+
const path = expandPath(skill, cwd);
|
|
171
|
+
const expected = basename(path);
|
|
172
|
+
const marker = existsSync(join(path, "SKILL.md"))
|
|
173
|
+
? /^name:\s*(\S+)/m.exec(readFileSync(join(path, "SKILL.md"), "utf8"))?.[1]
|
|
174
|
+
: undefined;
|
|
175
|
+
if (expected === name || marker === name) return path;
|
|
176
|
+
}
|
|
177
|
+
return undefined;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function resolveBotFromSettings(
|
|
181
|
+
home: string,
|
|
182
|
+
bot: string,
|
|
183
|
+
settings: BotSettings,
|
|
184
|
+
): { readonly cwd: string } {
|
|
185
|
+
try {
|
|
186
|
+
return resolveBot(home, bot, settings);
|
|
187
|
+
} catch (error) {
|
|
188
|
+
if (error instanceof BotError) throw error;
|
|
189
|
+
throw error;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** The directory a new skill of this bot goes into. */
|
|
194
|
+
export function newSkillPath(home: string, bot: string): string {
|
|
195
|
+
const written = readBots(home)[bot];
|
|
196
|
+
if (written === undefined) throw new BotError(`there is no bot "${bot}"`);
|
|
197
|
+
const cwd = resolveBotFromSettings(home, bot, written).cwd;
|
|
198
|
+
return join(cwd, "skills");
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function pathInside(path: string, directory: string): boolean {
|
|
202
|
+
const inside = relative(directory, path);
|
|
203
|
+
return inside === "" || (!inside.startsWith("..") && !isAbsolute(inside));
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function skillTarget(home: string, bot: string, name: string): string {
|
|
207
|
+
const existing = existingSkillPath(home, bot, name);
|
|
208
|
+
return existing ?? join(newSkillPath(home, bot), name);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function validateName(name: string, what: string): void {
|
|
212
|
+
if (!NAME.test(name)) {
|
|
213
|
+
throw new BotError(
|
|
214
|
+
`${what} "${name}": a name is lowercase letters, digits, "-" and "_", and starts with a letter or digit`,
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function jsonObject(value: unknown, what: string): Record<string, unknown> {
|
|
220
|
+
if (!isRecord(value)) throw new BotError(`${what} must be a JSON object`);
|
|
221
|
+
return value;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function inputText(ctx: CommandContext): string {
|
|
225
|
+
return (ctx.input ?? "").trim();
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
interface SkillInput {
|
|
229
|
+
readonly skillMd: string | undefined;
|
|
230
|
+
readonly files: Readonly<Record<string, string>>;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function parseSkillInput(ctx: CommandContext): SkillInput {
|
|
234
|
+
const text = inputText(ctx);
|
|
235
|
+
if (text.length === 0) return { skillMd: undefined, files: {} };
|
|
236
|
+
let parsed: unknown;
|
|
237
|
+
try {
|
|
238
|
+
parsed = JSON.parse(text);
|
|
239
|
+
} catch (error) {
|
|
240
|
+
throw new BotError(`the skill input is not JSON: ${messageOf(error)}`);
|
|
241
|
+
}
|
|
242
|
+
const input = jsonObject(parsed, "the skill input");
|
|
243
|
+
const skillMd = input.skill_md;
|
|
244
|
+
if (skillMd !== undefined && typeof skillMd !== "string") {
|
|
245
|
+
throw new BotError("the skill input's skill_md must be text");
|
|
246
|
+
}
|
|
247
|
+
const files: Record<string, string> = {};
|
|
248
|
+
if (input.files !== undefined) {
|
|
249
|
+
for (const [path, content] of Object.entries(jsonObject(input.files, "the skill input's files"))) {
|
|
250
|
+
if (typeof content !== "string") {
|
|
251
|
+
throw new BotError(`the skill input's file "${path}" must be text`);
|
|
252
|
+
}
|
|
253
|
+
files[path] = content;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return { skillMd, files };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function snapshotFrom(input: SkillInput, path: string): SkillSnapshot {
|
|
260
|
+
const files = new Map<string, SkillFile>();
|
|
261
|
+
if (input.skillMd !== undefined) {
|
|
262
|
+
files.set("SKILL.md", {
|
|
263
|
+
path: "SKILL.md",
|
|
264
|
+
content: input.skillMd,
|
|
265
|
+
script: false,
|
|
266
|
+
executable: false,
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
for (const [written, content] of Object.entries(input.files)) {
|
|
270
|
+
const path = written.replaceAll("\\", "/").replace(/^\/+/, "");
|
|
271
|
+
if (path.length === 0 || path.split("/").includes("..")) {
|
|
272
|
+
throw new BotError(`the skill input's file "${written}" must stay inside the skill`);
|
|
273
|
+
}
|
|
274
|
+
files.set(path, {
|
|
275
|
+
path,
|
|
276
|
+
content,
|
|
277
|
+
script: isScript(path, 0),
|
|
278
|
+
executable: false,
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
if (!files.has("SKILL.md")) {
|
|
282
|
+
throw new BotError("a skill needs a SKILL.md");
|
|
283
|
+
}
|
|
284
|
+
return { path, files: [...files.values()].sort((left, right) => left.path.localeCompare(right.path)) };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function fromDirectory(path: string): SkillSnapshot {
|
|
288
|
+
const files = readSkillDirectory(path);
|
|
289
|
+
if (fileOf(files, "SKILL.md") === undefined) {
|
|
290
|
+
throw new BotError(`skill "${path}": there is no SKILL.md in ${path}`);
|
|
291
|
+
}
|
|
292
|
+
return { path, files };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function snapshotOf(value: unknown): SkillSnapshot | undefined {
|
|
296
|
+
if (!isRecord(value) || typeof value.path !== "string" || !Array.isArray(value.files)) {
|
|
297
|
+
return undefined;
|
|
298
|
+
}
|
|
299
|
+
const files: SkillFile[] = [];
|
|
300
|
+
for (const item of value.files) {
|
|
301
|
+
if (
|
|
302
|
+
!isRecord(item) ||
|
|
303
|
+
typeof item.path !== "string" ||
|
|
304
|
+
typeof item.content !== "string" ||
|
|
305
|
+
typeof item.script !== "boolean" ||
|
|
306
|
+
typeof item.executable !== "boolean"
|
|
307
|
+
) {
|
|
308
|
+
return undefined;
|
|
309
|
+
}
|
|
310
|
+
files.push({
|
|
311
|
+
path: item.path,
|
|
312
|
+
content: item.content,
|
|
313
|
+
script: item.script,
|
|
314
|
+
executable: item.executable,
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
return { path: value.path, files };
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function settingsChangeOf(value: unknown): SettingsChange | undefined {
|
|
321
|
+
if (
|
|
322
|
+
!isRecord(value) ||
|
|
323
|
+
!isRecord(value.before) ||
|
|
324
|
+
!isRecord(value.after)
|
|
325
|
+
) {
|
|
326
|
+
return undefined;
|
|
327
|
+
}
|
|
328
|
+
return {
|
|
329
|
+
before: value.before as Record<string, JsonValue>,
|
|
330
|
+
after: value.after as Record<string, JsonValue>,
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function proposalContent(object: StoredObject): {
|
|
335
|
+
readonly skill: ProposalData["skill"];
|
|
336
|
+
readonly settings: SettingsChange | undefined;
|
|
337
|
+
} {
|
|
338
|
+
const data = dataOf(object);
|
|
339
|
+
return {
|
|
340
|
+
skill:
|
|
341
|
+
data.skill === undefined
|
|
342
|
+
? undefined
|
|
343
|
+
: {
|
|
344
|
+
name: data.skill.name,
|
|
345
|
+
before: snapshotOf(data.skill.before) ?? null,
|
|
346
|
+
after: snapshotOf(data.skill.after) ?? { path: "", files: [] },
|
|
347
|
+
},
|
|
348
|
+
settings: settingsChangeOf(data.settings),
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function lines(text: string): string[] {
|
|
353
|
+
const split = text.replaceAll("\r\n", "\n").split("\n");
|
|
354
|
+
if (split.at(-1) === "") split.pop();
|
|
355
|
+
return split;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** A line diff of two texts, enough to review a skill change. */
|
|
359
|
+
export function diffLines(beforeText: string, afterText: string): string[] {
|
|
360
|
+
const before = lines(beforeText);
|
|
361
|
+
const after = lines(afterText);
|
|
362
|
+
const table: number[][] = Array.from({ length: before.length + 1 }, () =>
|
|
363
|
+
Array<number>(after.length + 1).fill(0),
|
|
364
|
+
);
|
|
365
|
+
for (let i = before.length - 1; i >= 0; i -= 1) {
|
|
366
|
+
const row = table[i];
|
|
367
|
+
const next = table[i + 1];
|
|
368
|
+
if (row === undefined || next === undefined) continue;
|
|
369
|
+
for (let j = after.length - 1; j >= 0; j -= 1) {
|
|
370
|
+
row[j] =
|
|
371
|
+
before[i] === after[j]
|
|
372
|
+
? (next[j + 1] ?? 0) + 1
|
|
373
|
+
: Math.max(next[j] ?? 0, row[j + 1] ?? 0);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
const out: string[] = [];
|
|
377
|
+
let i = 0;
|
|
378
|
+
let j = 0;
|
|
379
|
+
while (i < before.length || j < after.length) {
|
|
380
|
+
if (i < before.length && j < after.length && before[i] === after[j]) {
|
|
381
|
+
out.push(` ${before[i]}`);
|
|
382
|
+
i += 1;
|
|
383
|
+
j += 1;
|
|
384
|
+
continue;
|
|
385
|
+
}
|
|
386
|
+
if (j < after.length && (i === before.length || (table[i]?.[j + 1] ?? 0) >= (table[i + 1]?.[j] ?? 0))) {
|
|
387
|
+
out.push(`+${after[j]}`);
|
|
388
|
+
j += 1;
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
out.push(`-${before[i]}`);
|
|
392
|
+
i += 1;
|
|
393
|
+
}
|
|
394
|
+
return out;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function changedSkillMarkdown(
|
|
398
|
+
name: string,
|
|
399
|
+
before: SkillSnapshot,
|
|
400
|
+
after: SkillSnapshot,
|
|
401
|
+
): string[] {
|
|
402
|
+
const out: string[] = [];
|
|
403
|
+
const paths = [...new Set([...before.files, ...after.files].map((file) => file.path))].sort();
|
|
404
|
+
for (const path of paths) {
|
|
405
|
+
const old = fileOf(before.files, path);
|
|
406
|
+
const current = fileOf(after.files, path);
|
|
407
|
+
if (old?.content === current?.content) continue;
|
|
408
|
+
out.push(`### ${path}`, "");
|
|
409
|
+
if (old === undefined) {
|
|
410
|
+
out.push("New file.", "", "```", ...lines(current?.content ?? "").map((line) => `+${line}`), "```");
|
|
411
|
+
} else if (current === undefined) {
|
|
412
|
+
out.push("Removed file.", "", "```", ...lines(old.content).map((line) => `-${line}`), "```");
|
|
413
|
+
} else {
|
|
414
|
+
out.push("```diff", ...diffLines(old.content, current.content), "```");
|
|
415
|
+
}
|
|
416
|
+
out.push("");
|
|
417
|
+
}
|
|
418
|
+
return out;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function mcpChangeOf(value: unknown): McpChange | undefined {
|
|
422
|
+
if (!isRecord(value) || typeof value.server !== "string" || !isRecord(value.after)) return undefined;
|
|
423
|
+
if (value.reason !== "new" && value.reason !== "upgrade" && value.reason !== "changed") return undefined;
|
|
424
|
+
return {
|
|
425
|
+
server: value.server,
|
|
426
|
+
reason: value.reason,
|
|
427
|
+
before: isRecord(value.before) ? (value.before as unknown as McpServerSettings) : null,
|
|
428
|
+
after: value.after as unknown as McpServerSettings,
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** What a person reads before a local MCP server is registered, upgraded or let through. */
|
|
433
|
+
function mcpReview(bot: string, change: McpChange): string {
|
|
434
|
+
const { after, before } = change;
|
|
435
|
+
const heading =
|
|
436
|
+
change.reason === "new"
|
|
437
|
+
? `## MCP server ${change.server} for bot ${bot}`
|
|
438
|
+
: change.reason === "upgrade"
|
|
439
|
+
? `## Upgrade of MCP server ${change.server} for bot ${bot}`
|
|
440
|
+
: `## MCP server ${change.server} of bot ${bot} changed its tools`;
|
|
441
|
+
const out = [heading, ""];
|
|
442
|
+
out.push(
|
|
443
|
+
change.reason === "changed"
|
|
444
|
+
? `Its tools are no longer the ones that were approved, so the server is switched off in this bot's chats. Approve to accept the new tools and switch it on again; reject to keep it off.`
|
|
445
|
+
: `**Approving trusts this package.** The server is a program that runs on this machine as you, starts with every chat of this bot and stays up while it talks. Nothing contains it yet (there is no shell around it), so the access profile does not limit what the program itself does; only calls to its tools are asked about.`,
|
|
446
|
+
"",
|
|
447
|
+
);
|
|
448
|
+
out.push(`Command: \`${commandLine(after.command, after.args ?? [])}\``, "");
|
|
449
|
+
if (after.package !== undefined) {
|
|
450
|
+
out.push(
|
|
451
|
+
`Package: ${after.package}`,
|
|
452
|
+
`Version: ${after.version ?? "?"}${before?.version !== undefined && before.version !== after.version ? ` (was ${before.version})` : ""}`,
|
|
453
|
+
"",
|
|
454
|
+
);
|
|
455
|
+
} else {
|
|
456
|
+
out.push("This command is not a package from a registry; it runs a program as written.", "");
|
|
457
|
+
}
|
|
458
|
+
out.push("### Secrets", "");
|
|
459
|
+
const variables = after.secrets ?? [];
|
|
460
|
+
if (variables.length === 0) out.push("It needs no secrets.");
|
|
461
|
+
else {
|
|
462
|
+
for (const variable of variables) {
|
|
463
|
+
out.push(`- ${variable}: store it with \`operad secret set bot ${secretName(change.server, variable)}\``);
|
|
464
|
+
}
|
|
465
|
+
out.push("", "They are given to the server only when it starts, never to the agent or the transcript.");
|
|
466
|
+
}
|
|
467
|
+
const tools = storedTools(after);
|
|
468
|
+
out.push("", `### Tools (${tools.length})`, "");
|
|
469
|
+
if (tools.length === 0) out.push("It offers no tools.");
|
|
470
|
+
else {
|
|
471
|
+
out.push("A tool not on the bot's `mcpAllow` list asks before every call. What the tools return is read as material, not as instructions.", "", "```");
|
|
472
|
+
for (const tool of tools) out.push(`${tool.name}: ${tool.description}`);
|
|
473
|
+
out.push("```");
|
|
474
|
+
}
|
|
475
|
+
if (before !== null) {
|
|
476
|
+
out.push("", "### What changed", "");
|
|
477
|
+
if (before.command !== after.command || (before.args ?? []).join("\0") !== (after.args ?? []).join("\0")) {
|
|
478
|
+
out.push(`Command was: \`${commandLine(before.command, before.args ?? [])}\``, "");
|
|
479
|
+
}
|
|
480
|
+
out.push("```diff", ...differenceLines(compareTools(storedTools(before), tools)), "```");
|
|
481
|
+
}
|
|
482
|
+
return out.join("\n");
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/** The review a person reads for a proposal. */
|
|
486
|
+
export function proposalReview(object: StoredObject): string {
|
|
487
|
+
const data = dataOf(object);
|
|
488
|
+
if (data.kind === "mcp") {
|
|
489
|
+
const change = mcpChangeOf(data.mcp);
|
|
490
|
+
return change === undefined ? "No MCP server is recorded for this proposal." : mcpReview(data.bot, change);
|
|
491
|
+
}
|
|
492
|
+
const content = proposalContent(object);
|
|
493
|
+
if (data.kind === "settings") {
|
|
494
|
+
const change = content.settings;
|
|
495
|
+
if (change === undefined) return "No settings are recorded for this proposal.";
|
|
496
|
+
return [
|
|
497
|
+
`## Settings for bot ${data.bot}`,
|
|
498
|
+
"",
|
|
499
|
+
"### Before",
|
|
500
|
+
"",
|
|
501
|
+
"```json",
|
|
502
|
+
JSON.stringify(change.before, null, 2),
|
|
503
|
+
"```",
|
|
504
|
+
"",
|
|
505
|
+
"### After",
|
|
506
|
+
"",
|
|
507
|
+
"```json",
|
|
508
|
+
JSON.stringify(change.after, null, 2),
|
|
509
|
+
"```",
|
|
510
|
+
].join("\n");
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
const skill = content.skill;
|
|
514
|
+
if (skill === undefined) return "No skill is recorded for this proposal.";
|
|
515
|
+
const skillMd = fileOf(skill.after.files, "SKILL.md")?.content ?? "";
|
|
516
|
+
const scripts = skill.after.files.filter((file) => file.script && file.path !== "SKILL.md");
|
|
517
|
+
const others = skill.after.files.filter((file) => !file.script && file.path !== "SKILL.md");
|
|
518
|
+
const out = [`## Skill ${skill.name} for bot ${data.bot}`, "", `Directory: ${skill.after.path}`, ""];
|
|
519
|
+
if (skill.before === null) {
|
|
520
|
+
out.push("### SKILL.md", "", skillMd.trimEnd(), "");
|
|
521
|
+
} else {
|
|
522
|
+
out.push("### Diff", "");
|
|
523
|
+
out.push(...changedSkillMarkdown(skill.name, skill.before, skill.after));
|
|
524
|
+
}
|
|
525
|
+
out.push("### Files", "");
|
|
526
|
+
out.push(...(others.length === 0 ? ["No other files."] : others.map((file) => `- ${file.path}`)));
|
|
527
|
+
out.push("", "### Scripts", "");
|
|
528
|
+
out.push(
|
|
529
|
+
...(scripts.length === 0
|
|
530
|
+
? ["No scripts."]
|
|
531
|
+
: scripts.map((file) => `- ${file.path}${file.executable ? " (executable)" : ""}`)),
|
|
532
|
+
);
|
|
533
|
+
if (skill.before !== null) {
|
|
534
|
+
out.push("", "### SKILL.md", "", skillMd.trimEnd(), "");
|
|
535
|
+
}
|
|
536
|
+
return out.join("\n");
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
export async function readBotsFile(home: string): Promise<Record<string, unknown>> {
|
|
540
|
+
let parsed: unknown;
|
|
541
|
+
try {
|
|
542
|
+
parsed = JSON.parse(readFileSync(configPath(home), "utf8"));
|
|
543
|
+
} catch (error) {
|
|
544
|
+
if (isRecord(error) && error.code === "ENOENT") return {};
|
|
545
|
+
throw new BotError(`${configPath(home)}: cannot read the bot settings: ${messageOf(error)}`);
|
|
546
|
+
}
|
|
547
|
+
const plugins = isRecord(parsed) ? parsed.plugins : undefined;
|
|
548
|
+
const entry = isRecord(plugins) ? plugins.bot : undefined;
|
|
549
|
+
const settings = isRecord(entry) ? entry.settings : undefined;
|
|
550
|
+
const bots = isRecord(settings) ? settings.bots : undefined;
|
|
551
|
+
return isRecord(bots) ? { ...bots } : {};
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/** Writes the whole `bots` map, keeping the rest of config.json. */
|
|
555
|
+
async function writeBotsFile(
|
|
556
|
+
home: string,
|
|
557
|
+
bots: Readonly<Record<string, unknown>>,
|
|
558
|
+
): Promise<void> {
|
|
559
|
+
const file = configPath(home);
|
|
560
|
+
await withLockFile(`${file}.lock`, async () => {
|
|
561
|
+
let parsed: Record<string, unknown> = {};
|
|
562
|
+
try {
|
|
563
|
+
const raw: unknown = JSON.parse(readFileSync(file, "utf8"));
|
|
564
|
+
if (!isRecord(raw)) throw new BotError(`${file}: must be a JSON object`);
|
|
565
|
+
parsed = { ...raw };
|
|
566
|
+
} catch (error) {
|
|
567
|
+
if (!(isRecord(error) && error.code === "ENOENT")) {
|
|
568
|
+
if (error instanceof BotError) throw error;
|
|
569
|
+
throw new BotError(`${file}: cannot read the bot settings: ${messageOf(error)}`);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
const plugins = isRecord(parsed.plugins) ? { ...parsed.plugins } : {};
|
|
573
|
+
const current = plugins.bot;
|
|
574
|
+
const entry: Record<string, unknown> =
|
|
575
|
+
typeof current === "string"
|
|
576
|
+
? { module: current, enabled: true }
|
|
577
|
+
: isRecord(current)
|
|
578
|
+
? { ...current }
|
|
579
|
+
: {};
|
|
580
|
+
const settings = isRecord(entry.settings) ? entry.settings : {};
|
|
581
|
+
plugins.bot = { ...entry, settings: { ...settings, bots } };
|
|
582
|
+
parsed.plugins = plugins;
|
|
583
|
+
await writeFileAtomic(file, `${JSON.stringify(parsed, null, 2)}\n`);
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
export function validateBots(bots: Readonly<Record<string, unknown>>): void {
|
|
588
|
+
prepareSettings(BOT_SETTINGS, { bots }, "bot");
|
|
589
|
+
for (const name of Object.keys(bots)) validateName(name, "bot");
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/** Proposes a new or changed skill. Nothing is written to the skill directory. */
|
|
593
|
+
export async function proposeSkill(
|
|
594
|
+
store: ObjectStore,
|
|
595
|
+
home: string,
|
|
596
|
+
bot: string,
|
|
597
|
+
name: string,
|
|
598
|
+
options: { readonly from?: string | undefined; readonly input?: SkillInput | undefined } = {},
|
|
599
|
+
): Promise<string> {
|
|
600
|
+
validateName(name, "skill");
|
|
601
|
+
if (readBots(home)[bot] === undefined) throw new BotError(`there is no bot "${bot}"`);
|
|
602
|
+
const target = skillTarget(home, bot, name);
|
|
603
|
+
const before = existsSync(target) ? readSkillDirectory(target) : [];
|
|
604
|
+
const after =
|
|
605
|
+
options.from === undefined
|
|
606
|
+
? snapshotFrom(options.input ?? { skillMd: undefined, files: {} }, target)
|
|
607
|
+
: { path: target, files: fromDirectory(options.from).files };
|
|
608
|
+
if (fileOf(after.files, "SKILL.md") === undefined) {
|
|
609
|
+
throw new BotError("a skill needs a SKILL.md");
|
|
610
|
+
}
|
|
611
|
+
const data: ProposalData = {
|
|
612
|
+
bot,
|
|
613
|
+
kind: "skill",
|
|
614
|
+
title: `Skill ${name}`,
|
|
615
|
+
state: "pending",
|
|
616
|
+
createdAt: Date.now(),
|
|
617
|
+
skill: {
|
|
618
|
+
name,
|
|
619
|
+
before: before.length === 0 ? null : { path: target, files: before },
|
|
620
|
+
after,
|
|
621
|
+
},
|
|
622
|
+
};
|
|
623
|
+
const id = `p-${randomUUID()}`;
|
|
624
|
+
await store.put(PROPOSAL_TYPE, id, data as unknown as Record<string, JsonValue>, "command:bot/skill");
|
|
625
|
+
return `proposed skill "${name}" for bot ${bot}; review it in pending`;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/** Proposes a change to one bot's settings. Nothing is written. */
|
|
629
|
+
export async function proposeSettings(
|
|
630
|
+
store: ObjectStore,
|
|
631
|
+
home: string,
|
|
632
|
+
bot: string,
|
|
633
|
+
patch: unknown,
|
|
634
|
+
): Promise<string> {
|
|
635
|
+
validateName(bot, "bot");
|
|
636
|
+
const written = readBots(home)[bot];
|
|
637
|
+
if (written === undefined) throw new BotError(`there is no bot "${bot}"`);
|
|
638
|
+
const change = jsonObject(patch, "the settings change");
|
|
639
|
+
const before: Record<string, JsonValue> = { ...written } as Record<string, JsonValue>;
|
|
640
|
+
const after: Record<string, JsonValue> = { ...before };
|
|
641
|
+
for (const [key, value] of Object.entries(change)) {
|
|
642
|
+
if (key === "access" && isRecord(value) && isRecord(before.access)) {
|
|
643
|
+
after.access = { ...before.access, ...value } as Record<string, JsonValue>;
|
|
644
|
+
} else {
|
|
645
|
+
after[key] = value as JsonValue;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
if (change.mcpServers !== undefined) {
|
|
649
|
+
throw new BotError("MCP servers are registered with `operad bot mcp`, which shows what the server offers; a settings change cannot add or edit one");
|
|
650
|
+
}
|
|
651
|
+
validateBots({ [bot]: after });
|
|
652
|
+
const data: ProposalData = {
|
|
653
|
+
bot,
|
|
654
|
+
kind: "settings",
|
|
655
|
+
title: `Settings for ${bot}`,
|
|
656
|
+
state: "pending",
|
|
657
|
+
createdAt: Date.now(),
|
|
658
|
+
settings: { before, after },
|
|
659
|
+
};
|
|
660
|
+
const id = `p-${randomUUID()}`;
|
|
661
|
+
await store.put(PROPOSAL_TYPE, id, data as unknown as Record<string, JsonValue>, "command:bot/setting");
|
|
662
|
+
return `proposed settings for bot ${bot}; review it in pending`;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
function skillData(value: unknown): ProposalData["skill"] | undefined {
|
|
666
|
+
if (!isRecord(value) || typeof value.name !== "string") return undefined;
|
|
667
|
+
const before = value.before === null ? null : snapshotOf(value.before) ?? null;
|
|
668
|
+
const after = snapshotOf(value.after);
|
|
669
|
+
if (after === undefined) return undefined;
|
|
670
|
+
return { name: value.name, before, after };
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
function applySkill(skill: NonNullable<ProposalData["skill"]>): void {
|
|
674
|
+
const { after } = skill;
|
|
675
|
+
if (after.path.length === 0) throw new BotError("the proposal has no skill directory");
|
|
676
|
+
mkdirSync(after.path, { recursive: true });
|
|
677
|
+
for (const file of after.files) {
|
|
678
|
+
const target = resolve(after.path, file.path);
|
|
679
|
+
if (!pathInside(target, after.path)) {
|
|
680
|
+
throw new BotError(`skill file "${file.path}" leaves ${after.path}`);
|
|
681
|
+
}
|
|
682
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
683
|
+
writeFileSync(target, file.content);
|
|
684
|
+
chmodSync(target, file.executable || file.script ? 0o755 : 0o644);
|
|
685
|
+
}
|
|
686
|
+
for (const old of skill.before?.files ?? []) {
|
|
687
|
+
if (fileOf(after.files, old.path) !== undefined) continue;
|
|
688
|
+
const target = resolve(after.path, old.path);
|
|
689
|
+
if (pathInside(target, after.path)) rmSync(target, { force: true });
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
async function applySettings(home: string, bot: string, after: Readonly<Record<string, JsonValue>>): Promise<void> {
|
|
694
|
+
const bots = { ...(await readBotsFile(home)), [bot]: after };
|
|
695
|
+
validateBots(bots);
|
|
696
|
+
await writeBotsFile(home, bots);
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
async function applyMcp(home: string, bot: string, change: McpChange): Promise<void> {
|
|
700
|
+
const bots = await readBotsFile(home);
|
|
701
|
+
const raw = isRecord(bots[bot]) ? bots[bot] : {};
|
|
702
|
+
const servers = isRecord(raw.mcpServers) ? raw.mcpServers : {};
|
|
703
|
+
bots[bot] = { ...raw, mcpServers: { ...servers, [change.server]: change.after } };
|
|
704
|
+
validateBots(bots);
|
|
705
|
+
await writeBotsFile(home, bots);
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
async function ensureSkillListed(home: string, bot: string, path: string): Promise<void> {
|
|
709
|
+
const written = readBots(home)[bot];
|
|
710
|
+
if (written === undefined) throw new BotError(`there is no bot "${bot}"`);
|
|
711
|
+
if (resolveBot(home, bot, written).skills.some((item) => resolve(item) === resolve(path))) {
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
714
|
+
const bots = await readBotsFile(home);
|
|
715
|
+
const raw = isRecord(bots[bot]) ? bots[bot] : (written as unknown as Record<string, unknown>);
|
|
716
|
+
const skills = Array.isArray(raw.skills)
|
|
717
|
+
? raw.skills.filter((item): item is string => typeof item === "string")
|
|
718
|
+
: [];
|
|
719
|
+
bots[bot] = { ...raw, skills: [...skills, path] };
|
|
720
|
+
validateBots(bots);
|
|
721
|
+
await writeBotsFile(home, bots);
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/** Applies a pending proposal. A proposal already decided is left as it is. */
|
|
725
|
+
export async function applyProposal(
|
|
726
|
+
store: ObjectStore,
|
|
727
|
+
home: string,
|
|
728
|
+
id: string,
|
|
729
|
+
): Promise<string> {
|
|
730
|
+
const object = await store.get(PROPOSAL_TYPE, id);
|
|
731
|
+
if (object === undefined) throw new BotError(`there is no proposal "${id}"`);
|
|
732
|
+
const data = dataOf(object);
|
|
733
|
+
if (data.state !== "pending") {
|
|
734
|
+
return `proposal ${id} is already ${data.state}; nothing to apply`;
|
|
735
|
+
}
|
|
736
|
+
const skill = skillData(data.skill);
|
|
737
|
+
if (data.kind === "mcp") {
|
|
738
|
+
const change = mcpChangeOf(data.mcp);
|
|
739
|
+
if (change === undefined) throw new BotError(`proposal ${id} has no MCP server to apply`);
|
|
740
|
+
await applyMcp(home, data.bot, change);
|
|
741
|
+
} else if (data.kind === "skill") {
|
|
742
|
+
if (skill === undefined) throw new BotError(`proposal ${id} has no skill to apply`);
|
|
743
|
+
applySkill(skill);
|
|
744
|
+
await ensureSkillListed(home, data.bot, skill.after.path);
|
|
745
|
+
} else {
|
|
746
|
+
const change = settingsChangeOf(data.settings);
|
|
747
|
+
if (change === undefined) throw new BotError(`proposal ${id} has no settings to apply`);
|
|
748
|
+
await applySettings(home, data.bot, change.after);
|
|
749
|
+
}
|
|
750
|
+
await store.put(
|
|
751
|
+
PROPOSAL_TYPE,
|
|
752
|
+
id,
|
|
753
|
+
{ ...data, state: "applied", appliedAt: Date.now() } as unknown as Record<string, JsonValue>,
|
|
754
|
+
"action:bot/approve",
|
|
755
|
+
);
|
|
756
|
+
return `applied proposal ${id}`;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/** Rejects a pending proposal, changing no file or setting. */
|
|
760
|
+
export async function rejectProposal(store: ObjectStore, id: string): Promise<string> {
|
|
761
|
+
const object = await store.get(PROPOSAL_TYPE, id);
|
|
762
|
+
if (object === undefined) throw new BotError(`there is no proposal "${id}"`);
|
|
763
|
+
const data = dataOf(object);
|
|
764
|
+
if (data.state !== "pending") {
|
|
765
|
+
return `proposal ${id} is already ${data.state}; nothing to reject`;
|
|
766
|
+
}
|
|
767
|
+
await store.put(
|
|
768
|
+
PROPOSAL_TYPE,
|
|
769
|
+
id,
|
|
770
|
+
{ ...data, state: "rejected", rejectedAt: Date.now() } as unknown as Record<string, JsonValue>,
|
|
771
|
+
"action:bot/reject",
|
|
772
|
+
);
|
|
773
|
+
return `rejected proposal ${id}`;
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
/** Every proposal waiting for a person, oldest first. */
|
|
777
|
+
export async function pendingProposals(
|
|
778
|
+
store: ObjectStore,
|
|
779
|
+
): Promise<readonly StoredObject[]> {
|
|
780
|
+
const found: StoredObject[] = [];
|
|
781
|
+
let cursor: string | undefined;
|
|
782
|
+
do {
|
|
783
|
+
const page = await store.list(PROPOSAL_TYPE, {
|
|
784
|
+
...(cursor === undefined ? {} : { cursor }),
|
|
785
|
+
});
|
|
786
|
+
for (const object of page.objects) {
|
|
787
|
+
if (object.data.state === "pending") found.push(object);
|
|
788
|
+
}
|
|
789
|
+
cursor = page.next;
|
|
790
|
+
} while (cursor !== undefined);
|
|
791
|
+
return found.sort((left, right) => {
|
|
792
|
+
const a = typeof left.data.createdAt === "number" ? left.data.createdAt : 0;
|
|
793
|
+
const b = typeof right.data.createdAt === "number" ? right.data.createdAt : 0;
|
|
794
|
+
return a - b || left.id.localeCompare(right.id);
|
|
795
|
+
});
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
/** The pending items a bot's proposals make. */
|
|
799
|
+
export async function proposalItems(
|
|
800
|
+
store: ObjectStore,
|
|
801
|
+
): Promise<readonly {
|
|
802
|
+
readonly id: string;
|
|
803
|
+
readonly prompt: string;
|
|
804
|
+
readonly object: { readonly type: string; readonly id: string };
|
|
805
|
+
}[]> {
|
|
806
|
+
return (await pendingProposals(store)).map((object) => {
|
|
807
|
+
const data = dataOf(object);
|
|
808
|
+
return {
|
|
809
|
+
id: object.id,
|
|
810
|
+
prompt: `${data.title} for bot ${data.bot} is waiting for your review`,
|
|
811
|
+
object: { type: PROPOSAL_TYPE, id: object.id },
|
|
812
|
+
};
|
|
813
|
+
});
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
/** Parses `<bot> <name> [--from <dir>]` for the `bot skill` command. */
|
|
817
|
+
export async function runSkillCommand(ctx: CommandContext, argv: readonly string[]): Promise<string> {
|
|
818
|
+
const words: string[] = [];
|
|
819
|
+
let from: string | undefined;
|
|
820
|
+
for (let at = 0; at < argv.length; at += 1) {
|
|
821
|
+
const word = argv[at];
|
|
822
|
+
if (word === "--from") {
|
|
823
|
+
at += 1;
|
|
824
|
+
const value = argv[at];
|
|
825
|
+
if (value === undefined) throw new BotError("bot skill: --from needs a directory");
|
|
826
|
+
from = value;
|
|
827
|
+
continue;
|
|
828
|
+
}
|
|
829
|
+
if (word !== undefined) words.push(word);
|
|
830
|
+
}
|
|
831
|
+
const bot = words[0];
|
|
832
|
+
const name = words[1];
|
|
833
|
+
if (bot === undefined || name === undefined || words.length > 2) {
|
|
834
|
+
throw new BotError("usage: operad bot skill <bot> <name> [--from <dir>]");
|
|
835
|
+
}
|
|
836
|
+
if (from !== undefined) {
|
|
837
|
+
return proposeSkill(ctx.store, ctx.home, bot, name, {
|
|
838
|
+
from: isAbsolute(from) ? from : resolve(ctx.cwd, from),
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
return proposeSkill(ctx.store, ctx.home, bot, name, { input: parseSkillInput(ctx) });
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
/** Parses `<bot>` and a JSON patch from stdin for the `bot setting` command. */
|
|
845
|
+
export async function runSettingCommand(ctx: CommandContext, argv: readonly string[]): Promise<string> {
|
|
846
|
+
const bot = argv[0];
|
|
847
|
+
if (bot === undefined || argv.length > 1) {
|
|
848
|
+
throw new BotError("usage: operad bot setting <bot> < changes.json");
|
|
849
|
+
}
|
|
850
|
+
const text = inputText(ctx);
|
|
851
|
+
if (text.length === 0) throw new BotError("bot setting: the settings change is empty");
|
|
852
|
+
let patch: unknown;
|
|
853
|
+
try {
|
|
854
|
+
patch = JSON.parse(text);
|
|
855
|
+
} catch (error) {
|
|
856
|
+
throw new BotError(`the settings change is not JSON: ${messageOf(error)}`);
|
|
857
|
+
}
|
|
858
|
+
return proposeSettings(ctx.store, ctx.home, bot, patch);
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
/** The actions on a proposal. */
|
|
862
|
+
export const proposalActions: readonly ActionTypeDefinition[] = [
|
|
863
|
+
{
|
|
864
|
+
name: "review",
|
|
865
|
+
on: PROPOSAL_TYPE,
|
|
866
|
+
when: (state) => state.state === "pending",
|
|
867
|
+
async run(ctx) {
|
|
868
|
+
const object = await ctx.store.get(PROPOSAL_TYPE, ctx.object.id);
|
|
869
|
+
if (object === undefined) throw new BotError(`there is no proposal "${ctx.object.id}"`);
|
|
870
|
+
return proposalReview(object);
|
|
871
|
+
},
|
|
872
|
+
},
|
|
873
|
+
{
|
|
874
|
+
name: "approve",
|
|
875
|
+
on: PROPOSAL_TYPE,
|
|
876
|
+
when: (state) => state.state === "pending",
|
|
877
|
+
async run(ctx) {
|
|
878
|
+
return applyProposal(ctx.store, ctx.home, ctx.object.id);
|
|
879
|
+
},
|
|
880
|
+
},
|
|
881
|
+
{
|
|
882
|
+
name: "reject",
|
|
883
|
+
on: PROPOSAL_TYPE,
|
|
884
|
+
when: (state) => state.state === "pending",
|
|
885
|
+
async run(ctx) {
|
|
886
|
+
return rejectProposal(ctx.store, ctx.object.id);
|
|
887
|
+
},
|
|
888
|
+
},
|
|
889
|
+
];
|
|
890
|
+
|
|
891
|
+
function row(object: StoredObject): ObjectRow {
|
|
892
|
+
const data = dataOf(object);
|
|
893
|
+
return {
|
|
894
|
+
id: object.id,
|
|
895
|
+
title: data.title,
|
|
896
|
+
state: data.state,
|
|
897
|
+
parent: `${BOT_TYPE}:${data.bot}`,
|
|
898
|
+
...(data.state === "pending" ? { mark: "proposed" as const } : {}),
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
function sections(): readonly { readonly id: string; readonly title: string }[] {
|
|
903
|
+
return [{ id: "review", title: "Review" }];
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
function load(_ctx: unknown, object: StoredObject): SectionContent {
|
|
907
|
+
return { markdown: proposalReview(object) };
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
/** How a proposal shows in a list and on its page. */
|
|
911
|
+
export const proposalViews: ObjectViews = {
|
|
912
|
+
row,
|
|
913
|
+
sections,
|
|
914
|
+
load,
|
|
915
|
+
};
|
|
916
|
+
|
|
917
|
+
export { dataOf as proposalData, mcpChangeOf };
|