@operad-io/bot 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/proposals.ts CHANGED
@@ -16,14 +16,13 @@ import {
16
16
  rmSync,
17
17
  writeFileSync,
18
18
  } from "node:fs";
19
- import { homedir } from "node:os";
20
19
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
21
20
  import {
22
21
  configPath,
22
+ isMissingFile,
23
23
  isRecord,
24
24
  messageOf,
25
25
  prepareSettings,
26
- writeFileAtomic,
27
26
  type ActionTypeDefinition,
28
27
  type CommandContext,
29
28
  type JsonValue,
@@ -33,17 +32,29 @@ import {
33
32
  type SectionContent,
34
33
  type StoredObject,
35
34
  } from "@operad-io/engine";
36
- import { withLockFile } from "@operad-io/engine/platform";
35
+ import { withLockFile, writeFileAtomic } from "@operad-io/engine/platform";
37
36
  import {
38
37
  BOT_SETTINGS,
39
38
  BOT_TYPE,
40
39
  BotError,
40
+ listedSkills,
41
41
  readBots,
42
- resolveBot,
42
+ workingDirectory,
43
43
  type BotSettings,
44
44
  type McpServerSettings,
45
45
  } from "./bot.ts";
46
+ import { applyDev, devChangeOf, devReview, runSetupDevCommand, type DevChange, type PipedInput } from "./setup-dev.ts";
47
+ import { applyGit, gitChangeOf, gitPrompt, gitReview, runSetupGitCommand, SETUP_GIT_TITLE, type GitChange } from "./setup-git.ts";
46
48
  import { commandLine, compareTools, differenceLines, secretName, storedTools } from "./mcp.ts";
49
+ import {
50
+ applyScheduleChange,
51
+ checkPromptName,
52
+ checkSchedule,
53
+ scheduleChangeOf,
54
+ scheduledPrompts,
55
+ type ScheduleChange,
56
+ type ScheduledPrompt,
57
+ } from "./schedule.ts";
47
58
 
48
59
  /** The object type of a proposal. It is internal: a person sees its pending item. */
49
60
  export const PROPOSAL_TYPE = "bot-proposal";
@@ -78,7 +89,7 @@ export interface SettingsChange {
78
89
  export interface ProposalData {
79
90
  readonly [key: string]: unknown;
80
91
  readonly bot: string;
81
- readonly kind: "skill" | "settings" | "mcp";
92
+ readonly kind: "skill" | "settings" | "mcp" | "schedule" | "dev" | "git";
82
93
  readonly title: string;
83
94
  readonly state: ProposalState;
84
95
  readonly createdAt: number;
@@ -89,6 +100,9 @@ export interface ProposalData {
89
100
  } | undefined;
90
101
  readonly settings?: SettingsChange | undefined;
91
102
  readonly mcp?: McpChange | undefined;
103
+ readonly schedule?: ScheduleChange | undefined;
104
+ readonly dev?: DevChange | undefined;
105
+ readonly git?: GitChange | undefined;
92
106
  }
93
107
 
94
108
  /** A local MCP server a proposal registers, upgrades or lets through after a change of its tools. */
@@ -106,7 +120,12 @@ function dataOf(object: StoredObject): ProposalData {
106
120
  const data = object.data;
107
121
  if (
108
122
  typeof data.bot !== "string" ||
109
- (data.kind !== "skill" && data.kind !== "settings" && data.kind !== "mcp") ||
123
+ (data.kind !== "skill" &&
124
+ data.kind !== "settings" &&
125
+ data.kind !== "mcp" &&
126
+ data.kind !== "schedule" &&
127
+ data.kind !== "dev" &&
128
+ data.kind !== "git") ||
110
129
  typeof data.title !== "string" ||
111
130
  (data.state !== "pending" && data.state !== "applied" && data.state !== "rejected") ||
112
131
  typeof data.createdAt !== "number"
@@ -151,12 +170,6 @@ function fileOf(files: readonly SkillFile[], path: string): SkillFile | undefine
151
170
  return files.find((file) => file.path === path);
152
171
  }
153
172
 
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
173
  /** The skill directory a bot already mounts under this name, if any. */
161
174
  function existingSkillPath(
162
175
  home: string,
@@ -165,37 +178,37 @@ function existingSkillPath(
165
178
  ): string | undefined {
166
179
  const written = readBots(home)[bot];
167
180
  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);
181
+ for (const path of mountedSkills(home, bot, written)) {
171
182
  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;
183
+ let marker: string | undefined;
184
+ try {
185
+ marker = /^name:\s*(\S+)/m.exec(readFileSync(join(path, "SKILL.md"), "utf8"))?.[1];
186
+ } catch {
187
+ // A listed skill that vanished is skipped, like one that was never there.
188
+ continue;
189
+ }
175
190
  if (expected === name || marker === name) return path;
176
191
  }
177
192
  return undefined;
178
193
  }
179
194
 
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;
195
+ /** The skills a bot's written paths mount now; a path with nothing to mount is skipped. */
196
+ function mountedSkills(home: string, bot: string, settings: BotSettings): string[] {
197
+ const cwd = workingDirectory(home, bot, settings);
198
+ const found: string[] = [];
199
+ for (const listed of settings.skills ?? []) {
200
+ for (const path of listedSkills(listed, cwd).directories) {
201
+ if (!found.includes(resolve(path))) found.push(resolve(path));
202
+ }
190
203
  }
204
+ return found;
191
205
  }
192
206
 
193
207
  /** The directory a new skill of this bot goes into. */
194
208
  export function newSkillPath(home: string, bot: string): string {
195
209
  const written = readBots(home)[bot];
196
210
  if (written === undefined) throw new BotError(`there is no bot "${bot}"`);
197
- const cwd = resolveBotFromSettings(home, bot, written).cwd;
198
- return join(cwd, "skills");
211
+ return join(workingDirectory(home, bot, written), "skills");
199
212
  }
200
213
 
201
214
  function pathInside(path: string, directory: string): boolean {
@@ -482,9 +495,70 @@ function mcpReview(bot: string, change: McpChange): string {
482
495
  return out.join("\n");
483
496
  }
484
497
 
498
+ function scheduleLines(entry: ScheduledPrompt, words: string | undefined): string[] {
499
+ const spoken = words === undefined || words.trim().length === 0 ? undefined : words.trim();
500
+ return [
501
+ `- Name: ${entry.name}`,
502
+ `- Schedule: ${spoken === undefined ? `\`${entry.schedule}\`` : `${spoken} (\`${entry.schedule}\`)`}`,
503
+ `- Model: ${entry.model ?? "the bot's model"}`,
504
+ `- Effort: ${entry.effort ?? "the bot's effort"}`,
505
+ ...(entry.paused ? ["- Paused: yes"] : []),
506
+ ];
507
+ }
508
+
509
+ function schedulePromptLines(entry: ScheduledPrompt): string[] {
510
+ return [
511
+ "",
512
+ "### Prompt",
513
+ "",
514
+ "```",
515
+ ...entry.prompt.replaceAll("\r\n", "\n").split("\n"),
516
+ "```",
517
+ ];
518
+ }
519
+
520
+ /** What a person reads before a scheduled prompt is added, changed or removed. */
521
+ function scheduleReview(bot: string, change: ScheduleChange): string {
522
+ const name = (change.after ?? change.before)?.name ?? "?";
523
+ const action =
524
+ change.action === "add" ? "adds" : change.action === "edit" ? "changes" : "removes";
525
+ const out = [
526
+ `## Scheduled prompt ${name} for bot ${bot}`,
527
+ "",
528
+ `This proposal ${action} a scheduled prompt on bot ${bot}. Approve applies it; reject leaves the bot as it is.`,
529
+ ];
530
+ if (change.before !== null) {
531
+ out.push(
532
+ "",
533
+ "### Before",
534
+ "",
535
+ ...scheduleLines(change.before, change.action === "remove" ? change.words : undefined),
536
+ ...schedulePromptLines(change.before),
537
+ );
538
+ }
539
+ if (change.after !== null) {
540
+ out.push("", "### After", "", ...scheduleLines(change.after, change.words), ...schedulePromptLines(change.after));
541
+ }
542
+ return out.join("\n");
543
+ }
544
+
485
545
  /** The review a person reads for a proposal. */
486
546
  export function proposalReview(object: StoredObject): string {
487
547
  const data = dataOf(object);
548
+ if (data.kind === "dev") {
549
+ const change = devChangeOf(data.dev);
550
+ return change === undefined ? "No repository is recorded for this proposal." : devReview(data.bot, change);
551
+ }
552
+ if (data.kind === "git") {
553
+ const change = gitChangeOf(data.git);
554
+ return change === undefined ? "No folder is recorded for this proposal." : gitReview(data.bot, change);
555
+ }
556
+ if (data.kind === "schedule") {
557
+ const change = scheduleChangeOf(data.schedule);
558
+ return change === undefined
559
+ ? "No scheduled prompt is recorded for this proposal."
560
+ : scheduleReview(data.bot, change);
561
+ }
488
562
  if (data.kind === "mcp") {
489
563
  const change = mcpChangeOf(data.mcp);
490
564
  return change === undefined ? "No MCP server is recorded for this proposal." : mcpReview(data.bot, change);
@@ -536,25 +610,10 @@ export function proposalReview(object: StoredObject): string {
536
610
  return out.join("\n");
537
611
  }
538
612
 
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(
613
+ /** Reads, changes and writes the `bots` map under one lock, keeping the rest of config.json. */
614
+ async function changeBotsFile(
556
615
  home: string,
557
- bots: Readonly<Record<string, unknown>>,
616
+ change: (bots: Record<string, unknown>) => Record<string, unknown>,
558
617
  ): Promise<void> {
559
618
  const file = configPath(home);
560
619
  await withLockFile(`${file}.lock`, async () => {
@@ -564,7 +623,7 @@ async function writeBotsFile(
564
623
  if (!isRecord(raw)) throw new BotError(`${file}: must be a JSON object`);
565
624
  parsed = { ...raw };
566
625
  } catch (error) {
567
- if (!(isRecord(error) && error.code === "ENOENT")) {
626
+ if (!isMissingFile(error)) {
568
627
  if (error instanceof BotError) throw error;
569
628
  throw new BotError(`${file}: cannot read the bot settings: ${messageOf(error)}`);
570
629
  }
@@ -578,12 +637,21 @@ async function writeBotsFile(
578
637
  ? { ...current }
579
638
  : {};
580
639
  const settings = isRecord(entry.settings) ? entry.settings : {};
581
- plugins.bot = { ...entry, settings: { ...settings, bots } };
640
+ const bots = isRecord(settings.bots) ? { ...settings.bots } : {};
641
+ plugins.bot = { ...entry, settings: { ...settings, bots: change(bots) } };
582
642
  parsed.plugins = plugins;
583
643
  await writeFileAtomic(file, `${JSON.stringify(parsed, null, 2)}\n`);
584
644
  });
585
645
  }
586
646
 
647
+ /** Changes the `bots` map under the config lock, so two writers do not drop each other's change. */
648
+ export async function updateBotsFile(
649
+ home: string,
650
+ change: (bots: Record<string, unknown>) => Record<string, unknown>,
651
+ ): Promise<void> {
652
+ await changeBotsFile(home, change);
653
+ }
654
+
587
655
  export function validateBots(bots: Readonly<Record<string, unknown>>): void {
588
656
  prepareSettings(BOT_SETTINGS, { bots }, "bot");
589
657
  for (const name of Object.keys(bots)) validateName(name, "bot");
@@ -662,6 +730,126 @@ export async function proposeSettings(
662
730
  return `proposed settings for bot ${bot}; review it in pending`;
663
731
  }
664
732
 
733
+ /** What the chat's `bot schedule` command is asked to propose. */
734
+ export interface ScheduleProposalInput {
735
+ readonly action: "add" | "edit" | "remove";
736
+ readonly name: string;
737
+ readonly words?: string | undefined;
738
+ readonly schedule?: string | undefined;
739
+ readonly prompt?: string | undefined;
740
+ readonly model?: string | undefined;
741
+ readonly effort?: string | undefined;
742
+ }
743
+
744
+ function optionalText(value: string | undefined): string | undefined {
745
+ return value !== undefined && value.trim().length > 0 ? value : undefined;
746
+ }
747
+
748
+ /**
749
+ * Proposes adding, changing or removing one of a bot's scheduled prompts. The
750
+ * owner's direct actions apply at once; this path is the one a chat's agent
751
+ * uses, so nothing fires until a person approves the proposal.
752
+ */
753
+ export async function proposeSchedule(
754
+ store: ObjectStore,
755
+ home: string,
756
+ bot: string,
757
+ input: ScheduleProposalInput,
758
+ ): Promise<string> {
759
+ if (readBots(home)[bot] === undefined) throw new BotError(`there is no bot "${bot}"`);
760
+ const object = await store.get(BOT_TYPE, bot);
761
+ if (object === undefined) throw new BotError(`there is no bot "${bot}"`);
762
+ const name = checkPromptName(input.name);
763
+ const current = scheduledPrompts(object.data).find((entry) => entry.name === name);
764
+ if (input.action === "add" && current !== undefined) {
765
+ throw new BotError(`bot ${bot} already has a scheduled prompt "${name}"`);
766
+ }
767
+ if (input.action !== "add" && current === undefined) {
768
+ throw new BotError(`bot ${bot} has no scheduled prompt "${name}"`);
769
+ }
770
+ if (
771
+ input.action === "remove" &&
772
+ (input.schedule !== undefined ||
773
+ input.prompt !== undefined ||
774
+ input.model !== undefined ||
775
+ input.effort !== undefined)
776
+ ) {
777
+ throw new BotError(
778
+ "removing a scheduled prompt takes only its name and, optionally, the schedule in words",
779
+ );
780
+ }
781
+ const words = optionalText(input.words);
782
+ if (words === undefined) {
783
+ throw new BotError(
784
+ "give the schedule in words with --words, so the review shows both it and the cron expression",
785
+ );
786
+ }
787
+ let after: ScheduledPrompt | null = null;
788
+ if (input.action === "add") {
789
+ if (input.schedule === undefined) {
790
+ throw new BotError("adding a scheduled prompt needs --schedule, a five-field cron expression");
791
+ }
792
+ const prompt = input.prompt === undefined ? "" : input.prompt.trim();
793
+ if (prompt.length === 0) throw new BotError("a scheduled prompt needs a prompt");
794
+ const model = optionalText(input.model);
795
+ const effort = optionalText(input.effort);
796
+ after = {
797
+ name,
798
+ schedule: checkSchedule(input.schedule),
799
+ prompt,
800
+ ...(model === undefined ? {} : { model }),
801
+ ...(effort === undefined ? {} : { effort }),
802
+ paused: false,
803
+ };
804
+ } else if (input.action === "edit" && current !== undefined) {
805
+ if (
806
+ input.schedule === undefined &&
807
+ input.prompt === undefined &&
808
+ input.model === undefined &&
809
+ input.effort === undefined
810
+ ) {
811
+ throw new BotError(
812
+ "editing a scheduled prompt needs a field to change: --schedule, --prompt, --model or --effort",
813
+ );
814
+ }
815
+ const schedule = input.schedule === undefined ? current.schedule : checkSchedule(input.schedule);
816
+ const prompt = input.prompt === undefined ? current.prompt : input.prompt.trim();
817
+ if (prompt.length === 0) throw new BotError("a scheduled prompt needs a prompt");
818
+ const model = input.model === undefined ? current.model : optionalText(input.model);
819
+ const effort = input.effort === undefined ? current.effort : optionalText(input.effort);
820
+ after = {
821
+ name,
822
+ schedule,
823
+ prompt,
824
+ ...(model === undefined ? {} : { model }),
825
+ ...(effort === undefined ? {} : { effort }),
826
+ paused: current.paused,
827
+ ...(schedule === current.schedule
828
+ ? current.last === undefined
829
+ ? {}
830
+ : { last: current.last }
831
+ : {}),
832
+ };
833
+ }
834
+ const change: ScheduleChange = {
835
+ action: input.action,
836
+ words: words.trim(),
837
+ before: current ?? null,
838
+ after,
839
+ };
840
+ const data: ProposalData = {
841
+ bot,
842
+ kind: "schedule",
843
+ title: `Scheduled prompt ${name}`,
844
+ state: "pending",
845
+ createdAt: Date.now(),
846
+ schedule: change,
847
+ };
848
+ const id = `p-${randomUUID()}`;
849
+ await store.put(PROPOSAL_TYPE, id, data as unknown as Record<string, JsonValue>, "command:bot/schedule");
850
+ return `proposed scheduled prompt "${name}" for bot ${bot}; review it in pending`;
851
+ }
852
+
665
853
  function skillData(value: unknown): ProposalData["skill"] | undefined {
666
854
  if (!isRecord(value) || typeof value.name !== "string") return undefined;
667
855
  const before = value.before === null ? null : snapshotOf(value.before) ?? null;
@@ -691,34 +879,42 @@ function applySkill(skill: NonNullable<ProposalData["skill"]>): void {
691
879
  }
692
880
 
693
881
  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);
882
+ await updateBotsFile(home, (bots) => {
883
+ const next = { ...bots, [bot]: after };
884
+ validateBots(next);
885
+ return next;
886
+ });
697
887
  }
698
888
 
699
889
  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);
890
+ await updateBotsFile(home, (bots) => {
891
+ const raw = isRecord(bots[bot]) ? bots[bot] : {};
892
+ const servers = isRecord(raw.mcpServers) ? raw.mcpServers : {};
893
+ const next = {
894
+ ...bots,
895
+ [bot]: { ...raw, mcpServers: { ...servers, [change.server]: change.after } },
896
+ };
897
+ validateBots(next);
898
+ return next;
899
+ });
706
900
  }
707
901
 
708
902
  async function ensureSkillListed(home: string, bot: string, path: string): Promise<void> {
709
903
  const written = readBots(home)[bot];
710
904
  if (written === undefined) throw new BotError(`there is no bot "${bot}"`);
711
- if (resolveBot(home, bot, written).skills.some((item) => resolve(item) === resolve(path))) {
905
+ if (mountedSkills(home, bot, written).some((item) => resolve(item) === resolve(path))) {
712
906
  return;
713
907
  }
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);
908
+ await updateBotsFile(home, (bots) => {
909
+ const raw = isRecord(bots[bot]) ? bots[bot] : {};
910
+ const skills = Array.isArray(raw.skills)
911
+ ? raw.skills.filter((item): item is string => typeof item === "string")
912
+ : [];
913
+ if (skills.some((item) => resolve(item) === resolve(path))) return bots;
914
+ const next = { ...bots, [bot]: { ...raw, skills: [...skills, path] } };
915
+ validateBots(next);
916
+ return next;
917
+ });
722
918
  }
723
919
 
724
920
  /** Applies a pending proposal. A proposal already decided is left as it is. */
@@ -734,7 +930,19 @@ export async function applyProposal(
734
930
  return `proposal ${id} is already ${data.state}; nothing to apply`;
735
931
  }
736
932
  const skill = skillData(data.skill);
737
- if (data.kind === "mcp") {
933
+ if (data.kind === "dev") {
934
+ const change = devChangeOf(data.dev);
935
+ if (change === undefined) throw new BotError(`proposal ${id} has no repository to set up`);
936
+ await applyDev(home, change);
937
+ } else if (data.kind === "git") {
938
+ const change = gitChangeOf(data.git);
939
+ if (change === undefined) throw new BotError(`proposal ${id} has no folder to set up git in`);
940
+ applyGit(home, change);
941
+ } else if (data.kind === "schedule") {
942
+ const change = scheduleChangeOf(data.schedule);
943
+ if (change === undefined) throw new BotError(`proposal ${id} has no scheduled prompt to apply`);
944
+ await applyScheduleChange(store, data.bot, change);
945
+ } else if (data.kind === "mcp") {
738
946
  const change = mcpChangeOf(data.mcp);
739
947
  if (change === undefined) throw new BotError(`proposal ${id} has no MCP server to apply`);
740
948
  await applyMcp(home, data.bot, change);
@@ -807,7 +1015,7 @@ export async function proposalItems(
807
1015
  const data = dataOf(object);
808
1016
  return {
809
1017
  id: object.id,
810
- prompt: `${data.title} for bot ${data.bot} is waiting for your review`,
1018
+ prompt: data.kind === "git" ? gitPrompt(data.bot, gitChangeOf(data.git)) : data.kind === "dev" ? `${data.title} (proposed by bot ${data.bot}) is waiting for your review` : `${data.title} for bot ${data.bot} is waiting for your review`,
811
1019
  object: { type: PROPOSAL_TYPE, id: object.id },
812
1020
  };
813
1021
  });
@@ -858,32 +1066,137 @@ export async function runSettingCommand(ctx: CommandContext, argv: readonly stri
858
1066
  return proposeSettings(ctx.store, ctx.home, bot, patch);
859
1067
  }
860
1068
 
861
- /** The actions on a proposal. */
1069
+ /** The `bot setup-dev` command: the steps for the agent, or with `dev.json` on stdin the proposal (ADR 0030 D15). */
1070
+ export async function runSetupDev(ctx: CommandContext, argv: readonly string[], piped?: PipedInput): Promise<string> {
1071
+ return runSetupDevCommand(ctx, argv, async (bot, change) => {
1072
+ const data: ProposalData = {
1073
+ bot,
1074
+ kind: "dev",
1075
+ title: `Setup Dev: ${basename(change.repo)}`,
1076
+ state: "pending",
1077
+ createdAt: Date.now(),
1078
+ dev: change,
1079
+ };
1080
+ const id = `p-${randomUUID()}`;
1081
+ await ctx.store.put(PROPOSAL_TYPE, id, data as unknown as Record<string, JsonValue>, "command:bot/setup-dev");
1082
+ return `proposed Setup Dev for ${change.repo}; review it in pending`;
1083
+ }, piped);
1084
+ }
1085
+
1086
+ /** The `bot setup-git` command: the steps for the agent, or with the `.gitignore` and identity on stdin the "Set up git here" proposal (ADR 0039 D8). */
1087
+ export async function runSetupGit(ctx: CommandContext, argv: readonly string[], piped?: PipedInput): Promise<string> {
1088
+ return runSetupGitCommand(
1089
+ ctx,
1090
+ argv,
1091
+ async (bot, change) => {
1092
+ const data: ProposalData = {
1093
+ bot,
1094
+ kind: "git",
1095
+ title: SETUP_GIT_TITLE,
1096
+ state: "pending",
1097
+ createdAt: Date.now(),
1098
+ git: change,
1099
+ };
1100
+ const id = `p-${randomUUID()}`;
1101
+ await ctx.store.put(PROPOSAL_TYPE, id, data as unknown as Record<string, JsonValue>, "command:bot/setup-git");
1102
+ return `proposed ${SETUP_GIT_TITLE} for ${change.repo}; review it in pending`;
1103
+ },
1104
+ piped,
1105
+ );
1106
+ }
1107
+
1108
+ /** The usage line shared by the parser's refusals. */
1109
+ const SCHEDULE_USAGE =
1110
+ "usage: operad bot schedule <bot> add|edit|remove <name> [--words <text>] [--schedule <cron>] [--prompt <text>] [--model <model>] [--effort <effort>]";
1111
+
1112
+ /** Parses the `bot schedule` command: what the chat's agent calls to propose an entry. */
1113
+ export async function runScheduleCommand(
1114
+ ctx: CommandContext,
1115
+ argv: readonly string[],
1116
+ ): Promise<string> {
1117
+ const positional: string[] = [];
1118
+ let words: string | undefined;
1119
+ let schedule: string | undefined;
1120
+ let prompt: string | undefined;
1121
+ let model: string | undefined;
1122
+ let effort: string | undefined;
1123
+ for (let at = 0; at < argv.length; at += 1) {
1124
+ const word = argv[at];
1125
+ if (word === undefined) continue;
1126
+ if (
1127
+ word === "--words" ||
1128
+ word === "--schedule" ||
1129
+ word === "--prompt" ||
1130
+ word === "--model" ||
1131
+ word === "--effort"
1132
+ ) {
1133
+ const value = argv[at + 1];
1134
+ if (value === undefined) throw new BotError(`bot schedule: ${word} needs a value`);
1135
+ if (word === "--words") words = value;
1136
+ else if (word === "--schedule") schedule = value;
1137
+ else if (word === "--prompt") prompt = value;
1138
+ else if (word === "--model") model = value;
1139
+ else effort = value;
1140
+ at += 1;
1141
+ continue;
1142
+ }
1143
+ if (word.startsWith("--")) {
1144
+ throw new BotError(`bot schedule: there is no option ${word}; ${SCHEDULE_USAGE}`);
1145
+ }
1146
+ positional.push(word);
1147
+ }
1148
+ const bot = positional[0];
1149
+ const action = positional[1];
1150
+ const name = positional[2];
1151
+ if (
1152
+ bot === undefined ||
1153
+ name === undefined ||
1154
+ positional.length > 3 ||
1155
+ (action !== "add" && action !== "edit" && action !== "remove")
1156
+ ) {
1157
+ throw new BotError(SCHEDULE_USAGE);
1158
+ }
1159
+ return proposeSchedule(ctx.store, ctx.home, bot, {
1160
+ action,
1161
+ name,
1162
+ words,
1163
+ schedule,
1164
+ prompt,
1165
+ model,
1166
+ effort,
1167
+ });
1168
+ }
1169
+
1170
+ /**
1171
+ * The actions on a proposal. Approve comes first, so it is the main button of a
1172
+ * client; review is last because a proposal's Review section already shows what
1173
+ * it returns, and it stays for the command line and MCP.
1174
+ */
862
1175
  export const proposalActions: readonly ActionTypeDefinition[] = [
863
1176
  {
864
- name: "review",
1177
+ name: "approve",
865
1178
  on: PROPOSAL_TYPE,
866
1179
  when: (state) => state.state === "pending",
867
1180
  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);
1181
+ return applyProposal(ctx.store, ctx.home, ctx.object.id);
871
1182
  },
872
1183
  },
873
1184
  {
874
- name: "approve",
1185
+ name: "reject",
875
1186
  on: PROPOSAL_TYPE,
876
1187
  when: (state) => state.state === "pending",
877
1188
  async run(ctx) {
878
- return applyProposal(ctx.store, ctx.home, ctx.object.id);
1189
+ return rejectProposal(ctx.store, ctx.object.id);
879
1190
  },
880
1191
  },
881
1192
  {
882
- name: "reject",
1193
+ name: "review",
883
1194
  on: PROPOSAL_TYPE,
884
1195
  when: (state) => state.state === "pending",
885
1196
  async run(ctx) {
886
- return rejectProposal(ctx.store, ctx.object.id);
1197
+ const object = await ctx.store.get(PROPOSAL_TYPE, ctx.object.id);
1198
+ if (object === undefined) throw new BotError(`there is no proposal "${ctx.object.id}"`);
1199
+ return proposalReview(object);
887
1200
  },
888
1201
  },
889
1202
  ];