@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/index.ts CHANGED
@@ -9,21 +9,34 @@
9
9
  * built yet, and this is the one place it goes.
10
10
  */
11
11
 
12
+ import { messageOf } from "@operad-io/engine";
12
13
  import pkg from "../package.json" with { type: "json" };
13
14
  import { mkdirSync } from "node:fs";
15
+ import { basename, isAbsolute, join, resolve } from "node:path";
14
16
  import { fileURLToPath } from "node:url";
15
- import { CHAT_TYPE, agentConditionals, type AgentChoices, chatData, createChat, sendMessage, startingEffort, startingModel, titleFromMessage } from "@operad-io/chat";
16
- import { definePlugin, isRecord, type ActionArgsSchema, type ActionTypeDefinition, type JsonValue, type ObjectRow, type ObjectStore, type ObjectViews, type PluginStepResult, type SectionContent, type StepContext, type StoredObject } from "@operad-io/engine";
17
+ import { CHAT_TYPE, MESSAGE_EVENT, levelRefusal, agentConditionals, type AgentChoices, type ScheduledChat, chatData, createChat, sendMessage, startingEffort, startingModel, titleFromMessage } from "@operad-io/chat";
18
+ import { definePlugin, isRecord, modelIds, type ActionArgSchema, type ActionArgsSchema, type ActionTypeDefinition, type HarnessCapabilities, type HarnessModelInfo, type HarnessModels, type JsonValue, type ObjectRow, type ObjectStore, type ObjectViews, type PluginStepResult, type SectionContent, type StepContext, type StoredObject } from "@operad-io/engine";
17
19
  import {
18
20
  BOT_SETTINGS,
19
21
  DEFAULT_BOT,
20
22
  BOT_TYPE,
21
23
  BotError,
24
+ botDir,
25
+ defaultBotHomeMigrated,
26
+ ensureBotMemory,
27
+ migrateDefaultBotDir,
22
28
  readBots,
23
29
  repositoryPaths,
24
30
  resolveBot,
31
+ skillName,
32
+ workingDirectory,
33
+ type BotSettings,
25
34
  type ResolvedBot,
26
35
  } from "./bot.ts";
36
+ import { MEMORY_COMMIT_STEP, memoryNotes } from "@operad-io/memory";
37
+ import { createBot, knownMcpServers, knownSkills } from "./create.ts";
38
+ import { LOGIN_EVENT, LOGIN_SOURCE, loginAction, loginFlow, loginItems, runLogin as runLoginStep } from "./login.ts";
39
+ import { chatSetupAction, runSetup, setupDevPrompt, setupPrompt, setupTitle } from "./setup.ts";
27
40
  import { ingestReports, runMcpCommand } from "./mcp-proposals.ts";
28
41
  import {
29
42
  PROPOSAL_TYPE,
@@ -31,8 +44,31 @@ import {
31
44
  proposalItems,
32
45
  proposalViews,
33
46
  runSettingCommand,
47
+ runScheduleCommand,
48
+ runSetupDev,
49
+ runSetupGit,
34
50
  runSkillCommand,
35
51
  } from "./proposals.ts";
52
+ import {
53
+ SCHEDULE_SOURCE,
54
+ scheduleActions,
55
+ scheduledChatContext,
56
+ scheduledData,
57
+ scheduledInstructionFor,
58
+ markdownCode,
59
+ markdownText,
60
+ scheduledMarkdown,
61
+ scheduledPrompts,
62
+ startScheduled,
63
+ } from "./schedule.ts";
64
+ import { followUpActions, followUpData, followUpMarkdown, followUps, runFollowUpCommand, runFollowUpsCommand } from "./follow-up.ts";
65
+ import {
66
+ TIDY_TYPE,
67
+ startTidy,
68
+ tidyActions,
69
+ tidyItems,
70
+ tidyViews,
71
+ } from "./tidy.ts";
36
72
 
37
73
  /** The step a chat calls at every reply to read its bot. */
38
74
  export const SETTINGS_STEP = "bot/settings";
@@ -43,10 +79,13 @@ function rowOf(bot: ResolvedBot): Record<string, JsonValue> {
43
79
  name: bot.name,
44
80
  cwd: bot.cwd,
45
81
  harness: bot.harness,
82
+ useOwnSettings: bot.useOwnSettings,
46
83
  model: bot.model,
47
84
  effort: bot.effort,
48
85
  skills: [...bot.skills],
49
86
  speaker: bot.speaker,
87
+ writeWiki: bot.writeWiki,
88
+ accessLevel: bot.accessLevel,
50
89
  access: bot.access,
51
90
  mcpServers: Object.keys(bot.mcpServers),
52
91
  };
@@ -55,6 +94,50 @@ function rowOf(bot: ResolvedBot): Record<string, JsonValue> {
55
94
  /** The harnesses that take MCP servers natively; any other does not mount a bot's servers. */
56
95
  export const MCP_HARNESSES: readonly string[] = ["claude", "radian"];
57
96
 
97
+ /** Moves the old default bot home once, unless the default bot names its own directory. */
98
+ async function migrateDefaultHome(
99
+ store: ObjectStore,
100
+ home: string,
101
+ written: Readonly<Record<string, BotSettings>>,
102
+ ): Promise<void> {
103
+ const settings = written[DEFAULT_BOT];
104
+ if (settings === undefined) return;
105
+ try {
106
+ if (workingDirectory(home, DEFAULT_BOT, settings) !== join(botDir(home), DEFAULT_BOT)) return;
107
+ } catch {
108
+ return;
109
+ }
110
+ if (defaultBotHomeMigrated(home)) return;
111
+ // A bot's directory may have a different name from the bot and may already be gone
112
+ // from the settings; both its stored cwd and its default path are kept in place.
113
+ const botPaths: string[] = [];
114
+ for (const [name, bot] of Object.entries(written)) {
115
+ if (name === DEFAULT_BOT) continue;
116
+ try {
117
+ botPaths.push(workingDirectory(home, name, bot));
118
+ } catch {
119
+ botPaths.push(join(botDir(home), name));
120
+ }
121
+ }
122
+ let cursor: string | undefined;
123
+ do {
124
+ const page = await store.list(BOT_TYPE, { ...(cursor === undefined ? {} : { cursor }) });
125
+ for (const object of page.objects) {
126
+ if (object.id === DEFAULT_BOT) continue;
127
+ const cwd = object.data.cwd;
128
+ botPaths.push(typeof cwd === "string" && cwd.length > 0 ? cwd : join(botDir(home), object.id));
129
+ }
130
+ cursor = page.next;
131
+ } while (cursor !== undefined);
132
+ const repositories = await repositoryPaths(store);
133
+ const grantFiles = [
134
+ join(home, "access-user.json"),
135
+ ...botPaths.map((path) => join(path, "access-user.json")),
136
+ ...repositories.map((path) => join(path, ".operad", "access-user.json")),
137
+ ];
138
+ await migrateDefaultBotDir(home, { botNames: Object.keys(written), botPaths, grantFiles });
139
+ }
140
+
58
141
  const GUARD = fileURLToPath(new URL("./guard.ts", import.meta.url));
59
142
 
60
143
  /** What a harness starts for one of a bot's servers: the guard, which starts the server itself. */
@@ -73,6 +156,7 @@ export async function syncBots(
73
156
  fallback: Readonly<Record<string, JsonValue>>,
74
157
  ): Promise<void> {
75
158
  const written = readBots(home, fallback);
159
+ await migrateDefaultHome(store, home, written);
76
160
  const repositories = await repositoryPaths(store);
77
161
  for (const [name, settings] of Object.entries(written)) {
78
162
  let data: Record<string, JsonValue>;
@@ -83,6 +167,14 @@ export async function syncBots(
83
167
  data = { name, removed: false, problem: error.message };
84
168
  }
85
169
  const current = await store.get(BOT_TYPE, name);
170
+ // A client's scheduled prompts belong to the bot object, not to config.json.
171
+ if (Array.isArray(current?.data.scheduled)) {
172
+ data.scheduled = current.data.scheduled as JsonValue[];
173
+ }
174
+ // So are its follow-ups (ADR 0030 D16).
175
+ if (Array.isArray(current?.data.followUps)) {
176
+ data.followUps = current.data.followUps as JsonValue[];
177
+ }
86
178
  if (current === undefined || JSON.stringify(current.data) !== JSON.stringify(data)) {
87
179
  await store.put(BOT_TYPE, name, data, "bot");
88
180
  }
@@ -105,8 +197,10 @@ export interface OpenChat {
105
197
  readonly home: string;
106
198
  readonly settings: Readonly<Record<string, JsonValue>>;
107
199
  readonly harnesses: readonly string[];
200
+ /** What each loaded agent can do; the level a chat starts at must be one its agent carries. */
201
+ readonly capabilities?: Readonly<Record<string, HarnessCapabilities>> | undefined;
108
202
  readonly bot: string;
109
- readonly models?: Readonly<Record<string, { readonly list: readonly string[]; readonly default: string | null }>> | undefined;
203
+ readonly models?: Readonly<Record<string, HarnessModels>> | undefined;
110
204
  readonly efforts?: Readonly<Record<string, { readonly list: readonly string[]; readonly default: string | null }>> | undefined;
111
205
  readonly harness?: string | undefined;
112
206
  readonly model?: string | undefined;
@@ -114,15 +208,37 @@ export interface OpenChat {
114
208
  readonly title?: string | undefined;
115
209
  /** The channels (`telegram:<chat>`) whose messages land in this chat. */
116
210
  readonly channels?: readonly string[] | undefined;
211
+ /** The scheduled prompt that opens the chat; absent when a person opens it. */
212
+ readonly scheduled?: ScheduledChat | undefined;
117
213
  readonly cause: string;
118
214
  }
119
215
 
216
+ /**
217
+ * The agent a chat gets when nothing names one: the first loaded agent that can
218
+ * carry the level, else the first loaded one (a refusal then names the levels).
219
+ */
220
+ export function defaultAgent(
221
+ harnesses: readonly string[],
222
+ capabilities: Readonly<Record<string, HarnessCapabilities>> | undefined,
223
+ level: string,
224
+ ): string | undefined {
225
+ if (capabilities === undefined) return harnesses[0];
226
+ return harnesses.find((name) => (capabilities[name]?.accessLevels ?? []).includes(level)) ?? harnesses[0];
227
+ }
228
+
120
229
  /** Opens a chat on a bot and returns its id. Refuses with a plain message. */
121
230
  export async function openChat(input: OpenChat): Promise<string> {
122
- const written = readBots(input.home, input.settings)[input.bot];
123
- if (written === undefined) throw new BotError(`there is no bot "${input.bot}"`);
124
- const bot = resolveBot(input.home, input.bot, written, await repositoryPaths(input.store));
125
- const harness = input.harness ?? bot.harness ?? input.harnesses[0];
231
+ const written = readBots(input.home, input.settings);
232
+ await migrateDefaultHome(input.store, input.home, written);
233
+ const settings = written[input.bot];
234
+ if (settings === undefined) throw new BotError(`there is no bot "${input.bot}"`);
235
+ const bot = resolveBot(input.home, input.bot, settings, await repositoryPaths(input.store));
236
+ // A scheduled prompt runs at full access (ADR 0030 D10); a chat a person
237
+ // opens starts at the bot's level (ADR 0026 D15). A person may still change
238
+ // the level with `/access` afterwards.
239
+ const startingLevel = input.scheduled === undefined ? bot.accessLevel : "full";
240
+ const harness =
241
+ input.harness ?? bot.harness ?? defaultAgent(input.harnesses, input.capabilities, startingLevel);
126
242
  if (harness === undefined) {
127
243
  throw new BotError("no agent is loaded; load one to chat with the bot");
128
244
  }
@@ -138,10 +254,14 @@ export async function openChat(input: OpenChat): Promise<string> {
138
254
  model = startingModel(harness, input.models?.[harness], input.model, bot.model ?? undefined);
139
255
  effort = startingEffort(harness, input.efforts?.[harness], input.effort, bot.effort ?? undefined);
140
256
  } catch (error) {
141
- throw new BotError(error instanceof Error ? error.message : String(error));
257
+ throw new BotError(messageOf(error));
142
258
  }
143
259
  const effortDefault = input.efforts?.[harness]?.default ?? undefined;
260
+ // An agent that cannot carry the level is refused here, not at the first reply.
261
+ const refusal = levelRefusal(harness, startingLevel, input.capabilities);
262
+ if (refusal !== undefined) throw new BotError(refusal);
144
263
  mkdirSync(bot.cwd, { recursive: true });
264
+ ensureBotMemory(bot.cwd, input.home);
145
265
  return createChat(
146
266
  input.store,
147
267
  {
@@ -152,9 +272,12 @@ export async function openChat(input: OpenChat): Promise<string> {
152
272
  ...(effort === undefined || effortDefault === undefined ? {} : { effortDefault }),
153
273
  cwd: bot.cwd,
154
274
  access: bot.access,
275
+ accessLevel: startingLevel,
276
+ accessDefault: startingLevel,
155
277
  skills: bot.skills,
156
278
  title: input.title ?? `Bot (${bot.name})`,
157
279
  ...(input.channels === undefined ? {} : { channels: input.channels }),
280
+ ...(input.scheduled === undefined ? {} : { scheduled: input.scheduled }),
158
281
  refresh: SETTINGS_STEP,
159
282
  },
160
283
  input.cause,
@@ -168,8 +291,11 @@ function chatArgs(
168
291
  models: readonly string[] = [],
169
292
  efforts: readonly string[] = [],
170
293
  agents: readonly AgentChoices[] = [],
294
+ info?: Readonly<Record<string, HarnessModelInfo>> | undefined,
295
+ capabilities?: Readonly<Record<string, HarnessCapabilities>> | undefined,
296
+ level = "ask",
171
297
  ): ActionArgsSchema {
172
- const first = harnesses[0];
298
+ const first = defaultAgent(harnesses, capabilities, level);
173
299
  const fallback = typeof botHarness === "string" && harnesses.includes(botHarness) ? botHarness : first;
174
300
  return {
175
301
  type: "object",
@@ -184,6 +310,7 @@ function chatArgs(
184
310
  model: {
185
311
  type: "string",
186
312
  ...(models.length === 0 ? {} : { enum: [...models] }),
313
+ ...(info === undefined ? {} : { info }),
187
314
  description:
188
315
  "The model the agent uses; one from that agent's list. The bot's model, else the agent's default, when left out. It can be changed later.",
189
316
  },
@@ -213,16 +340,180 @@ function chatArgs(
213
340
  };
214
341
  }
215
342
 
343
+ /** The skill choices: a known skill by name, or a path such as `/...`, `~/...` or `skills/...`. */
344
+ function skillItem(known: readonly { readonly name: string }[]): ActionArgSchema {
345
+ const branches: ActionArgSchema[] = [];
346
+ const names = [...new Set(known.map((skill) => skill.name))].sort();
347
+ if (names.length > 0) {
348
+ branches.push({
349
+ type: "string",
350
+ enum: names,
351
+ description: "A skill another bot already mounts, or one in ~/.agents/skills.",
352
+ });
353
+ }
354
+ branches.push({
355
+ type: "string",
356
+ pattern: "^(?:.*[/\\\\].*|~.*)$",
357
+ description: "A path to a skill, a directory of skills, or a .agents directory.",
358
+ });
359
+ return branches.length === 1 ? (branches[0] as ActionArgSchema) : { oneOf: branches };
360
+ }
361
+
362
+ /** The arguments of `bot:create`, with the choices this home knows now. */
363
+ function createArgs(
364
+ home: string | undefined,
365
+ harnesses: readonly string[],
366
+ models: readonly string[],
367
+ efforts: readonly string[],
368
+ agents: readonly AgentChoices[],
369
+ info?: Readonly<Record<string, HarnessModelInfo>> | undefined,
370
+ capabilities?: Readonly<Record<string, HarnessCapabilities>> | undefined,
371
+ ): ActionArgsSchema {
372
+ const skills = home === undefined ? [] : knownSkills(home);
373
+ const servers = home === undefined ? [] : knownMcpServers(home);
374
+ const first = defaultAgent(harnesses, capabilities, "ask");
375
+ return {
376
+ type: "object",
377
+ description: "Creates a bot with exactly the skills and MCP servers chosen for it.",
378
+ properties: {
379
+ name: {
380
+ type: "string",
381
+ description:
382
+ "The new bot's name, used for its directory under ~/.operad/bot; lowercase letters, digits, - and _.",
383
+ },
384
+ agent: {
385
+ type: "string",
386
+ ...(harnesses.length === 0 ? {} : { enum: [...harnesses] }),
387
+ ...(first === undefined ? {} : { default: first }),
388
+ description: "The agent a new chat of this bot starts with.",
389
+ },
390
+ model: {
391
+ type: "string",
392
+ ...(models.length === 0 ? {} : { enum: [...models] }),
393
+ ...(info === undefined ? {} : { info }),
394
+ description: "The model a new chat starts with; one the chosen agent lists. Left out: the agent's default.",
395
+ },
396
+ effort: {
397
+ type: "string",
398
+ ...(efforts.length === 0 ? {} : { enum: [...efforts] }),
399
+ description: "The effort a new chat starts with; one the chosen agent lists. Left out: the agent's default.",
400
+ },
401
+ speaker: {
402
+ type: "string",
403
+ minLength: 1,
404
+ description: "How this bot's chats label the model's messages; left out: the chat plugin's speaker.",
405
+ },
406
+ skills: {
407
+ type: "array",
408
+ items: skillItem(skills),
409
+ description:
410
+ "The skills exactly this bot has. A known skill is chosen by name, or a path is given; without it the bot has none. A path that is a directory of skills gives every skill inside it.",
411
+ },
412
+ mcpServers: {
413
+ type: "array",
414
+ items: { type: "string", ...(servers.length === 0 ? {} : { enum: servers.map((server) => server.key) }) },
415
+ description:
416
+ "MCP servers a person already approved on another bot, copied with their pin and digest. Without it the bot has none; a new server goes through bot mcp.",
417
+ },
418
+ },
419
+ required: ["name", "agent"],
420
+ ...(agents.length === 0 ? {} : { allOf: agentConditionals(agents) }),
421
+ additionalProperties: false,
422
+ };
423
+ }
424
+
425
+ const createAction: ActionTypeDefinition = {
426
+ name: "create",
427
+ on: BOT_TYPE,
428
+ args: createArgs(undefined, [], [], [], []),
429
+ argsFor: (_object, env) => {
430
+ const info: Record<string, HarnessModelInfo> = {};
431
+ for (const name of env.harnesses ?? []) {
432
+ for (const [id, model] of Object.entries(env.models?.[name]?.info ?? {})) info[id] = model;
433
+ }
434
+ return createArgs(
435
+ env.home,
436
+ env.harnesses ?? [],
437
+ [...new Set((env.harnesses ?? []).flatMap((name) => modelIds(env.models?.[name])))],
438
+ [...new Set((env.harnesses ?? []).flatMap((name) => env.efforts?.[name]?.list ?? []))],
439
+ (env.harnesses ?? []).map((name) => ({
440
+ name,
441
+ models: env.models?.[name],
442
+ efforts: env.efforts?.[name],
443
+ preferredModel: null,
444
+ preferredEffort: null,
445
+ })),
446
+ Object.keys(info).length === 0 ? undefined : info,
447
+ env.capabilities,
448
+ );
449
+ },
450
+ when: (state, env) => state.removed !== true && (env.harnesses ?? []).length > 0,
451
+ async why(object, env) {
452
+ if (object.data.removed === true) return `bot ${object.id} is no longer in the settings`;
453
+ if ((env.harnesses ?? []).length === 0) return "no agent is loaded; load one to create a bot";
454
+ return undefined;
455
+ },
456
+ async run(ctx, args) {
457
+ const input = args as {
458
+ readonly name?: string;
459
+ readonly agent?: string;
460
+ readonly model?: string;
461
+ readonly effort?: string;
462
+ readonly speaker?: string;
463
+ readonly skills?: readonly string[];
464
+ readonly mcpServers?: readonly string[];
465
+ };
466
+ const name = input.name ?? "";
467
+ const agent = input.agent ?? "";
468
+ if (!ctx.harnesses.includes(agent)) {
469
+ throw new BotError(
470
+ `agent "${agent}" is not loaded; the loaded ones are: ${ctx.harnesses.join(", ") || "none"}`,
471
+ );
472
+ }
473
+ try {
474
+ if (input.model !== undefined) startingModel(agent, ctx.models?.[agent], input.model);
475
+ if (input.effort !== undefined) startingEffort(agent, ctx.efforts?.[agent], input.effort);
476
+ } catch (error) {
477
+ throw new BotError(messageOf(error));
478
+ }
479
+ const created = await createBot(
480
+ ctx.home,
481
+ {
482
+ name,
483
+ agent,
484
+ ...(input.model === undefined ? {} : { model: input.model }),
485
+ ...(input.effort === undefined ? {} : { effort: input.effort }),
486
+ ...(input.speaker === undefined ? {} : { speaker: input.speaker }),
487
+ ...(input.skills === undefined ? {} : { skills: input.skills }),
488
+ ...(input.mcpServers === undefined ? {} : { mcpServers: input.mcpServers }),
489
+ },
490
+ { cwd: ctx.cwd },
491
+ );
492
+ await syncBots(ctx.store, ctx.home, ctx.settings);
493
+ const secrets =
494
+ created.secrets.length === 0
495
+ ? ""
496
+ : `; its MCP servers need ${created.secrets
497
+ .map((secret) => `${secret} (operad secret set bot ${secret})`)
498
+ .join(", ")}`;
499
+ return { text: `created bot "${name}"${secrets}`, opens: `${BOT_TYPE}:${name}` };
500
+ },
501
+ };
502
+
216
503
  const chatAction: ActionTypeDefinition = {
217
504
  name: "chat",
218
505
  on: BOT_TYPE,
219
506
  creates: "chat",
220
507
  args: chatArgs([], undefined),
221
- argsFor: (object, env) =>
222
- chatArgs(
508
+ argsFor: (object, env) => {
509
+ const info: Record<string, HarnessModelInfo> = {};
510
+ for (const name of env.harnesses ?? []) {
511
+ for (const [id, model] of Object.entries(env.models?.[name]?.info ?? {})) info[id] = model;
512
+ }
513
+ return chatArgs(
223
514
  env.harnesses ?? [],
224
515
  object.data.harness,
225
- [...new Set((env.harnesses ?? []).flatMap((name) => env.models?.[name]?.list ?? []))],
516
+ [...new Set((env.harnesses ?? []).flatMap((name) => modelIds(env.models?.[name])))],
226
517
  [...new Set((env.harnesses ?? []).flatMap((name) => env.efforts?.[name]?.list ?? []))],
227
518
  (env.harnesses ?? []).map((name) => ({
228
519
  name,
@@ -231,7 +522,11 @@ const chatAction: ActionTypeDefinition = {
231
522
  preferredModel: typeof object.data.model === "string" ? object.data.model : null,
232
523
  preferredEffort: typeof object.data.effort === "string" ? object.data.effort : null,
233
524
  })),
234
- ),
525
+ Object.keys(info).length === 0 ? undefined : info,
526
+ env.capabilities,
527
+ typeof object.data.accessLevel === "string" ? object.data.accessLevel : "ask",
528
+ );
529
+ },
235
530
  when: (state, env) => state.removed !== true && typeof state.problem !== "string" && (env.harnesses ?? []).length > 0,
236
531
  async why(object, env) {
237
532
  if (object.data.removed === true) return `bot ${object.id} is no longer in the settings`;
@@ -248,11 +543,16 @@ const chatAction: ActionTypeDefinition = {
248
543
  readonly channels?: readonly string[];
249
544
  readonly message?: string;
250
545
  };
546
+ const scheduled =
547
+ ctx.actor.via === SCHEDULE_SOURCE
548
+ ? { bot: ctx.object.id, entry: ctx.actor.id }
549
+ : undefined;
251
550
  const id = await openChat({
252
551
  store: ctx.store,
253
552
  home: ctx.home,
254
553
  settings: ctx.settings,
255
554
  harnesses: ctx.harnesses,
555
+ capabilities: ctx.capabilities,
256
556
  models: ctx.models,
257
557
  efforts: ctx.efforts,
258
558
  bot: ctx.object.id,
@@ -261,13 +561,119 @@ const chatAction: ActionTypeDefinition = {
261
561
  effort: input.effort,
262
562
  title: input.title ?? (input.message === undefined ? undefined : titleFromMessage(input.message)),
263
563
  channels: input.channels,
564
+ ...(scheduled === undefined ? {} : { scheduled }),
264
565
  cause: "action:bot/chat",
265
566
  });
266
- const sent = input.message === undefined ? undefined : await sendMessage(ctx, id, input.message);
567
+ const sent =
568
+ input.message === undefined
569
+ ? undefined
570
+ : await sendMessage(
571
+ ctx.actor.via === SCHEDULE_SOURCE ? { ...ctx, source: SCHEDULE_SOURCE } : ctx,
572
+ id,
573
+ input.message,
574
+ undefined,
575
+ [],
576
+ scheduled === undefined ? undefined : scheduledInstructionFor(ctx.object.data, scheduled.entry),
577
+ );
267
578
  return { text: `opened chat ${id}${sent === undefined ? "" : `; ${sent}`}`, opens: `chat:${id}` };
268
579
  },
269
580
  };
270
581
 
582
+ // Setup Dev (ADR 0030 D15): opens a chat on the bot whose first message shows
583
+ // the chat's title and carries the prepared prompt for one repository as a
584
+ // hidden instruction. The chat is an ordinary one; what the agent proposes is a
585
+ // pending item.
586
+ const setupDevAction: ActionTypeDefinition = {
587
+ name: "setup-dev",
588
+ on: BOT_TYPE,
589
+ creates: "chat",
590
+ args: {
591
+ type: "object",
592
+ description: "Opens a chat that has the bot's agent set up dev for a repository and propose the result.",
593
+ properties: {
594
+ path: {
595
+ type: "string",
596
+ minLength: 1,
597
+ description: "The directory of the repository or folder: any folder, with or without git, but not a subfolder of a git repository.",
598
+ },
599
+ },
600
+ required: ["path"],
601
+ },
602
+ when: (state, env) => state.removed !== true && typeof state.problem !== "string" && (env.harnesses ?? []).length > 0,
603
+ async why(object, env) {
604
+ if (object.data.removed === true) return `bot ${object.id} is no longer in the settings`;
605
+ if (typeof object.data.problem === "string") return `bot ${object.id}: ${object.data.problem}`;
606
+ if ((env.harnesses ?? []).length === 0) return `bot ${object.id}: no agent is loaded; load one to chat with it`;
607
+ return undefined;
608
+ },
609
+ async run(ctx, args) {
610
+ const repo = (args as { readonly path: string }).path.trim();
611
+ if (repo.length === 0) throw new BotError("setup-dev needs the repository's directory");
612
+ const where = isAbsolute(repo) ? repo : resolve(ctx.cwd, repo);
613
+ const title = `Setup Dev (${basename(where)})`;
614
+ const id = await openChat({
615
+ store: ctx.store,
616
+ home: ctx.home,
617
+ settings: ctx.settings,
618
+ harnesses: ctx.harnesses,
619
+ capabilities: ctx.capabilities,
620
+ models: ctx.models,
621
+ efforts: ctx.efforts,
622
+ bot: ctx.object.id,
623
+ title,
624
+ cause: "action:bot/setup-dev",
625
+ });
626
+ // The person sees the chat's title; the prompt is the agent's hidden instruction.
627
+ const sent = await sendMessage(ctx, id, title, undefined, [], await setupDevPrompt(ctx.setup, ctx.object.id, where));
628
+ return { text: `opened chat ${id}; ${sent}`, opens: `chat:${id}` };
629
+ },
630
+ };
631
+
632
+ // Setup <plugin> (ADR 0010 D7): opens a chat on the bot whose first message shows
633
+ // the chat's title and carries the plugin's guide, with what its check finds
634
+ // missing, as a hidden instruction.
635
+ const setupAction: ActionTypeDefinition = {
636
+ name: "setup",
637
+ on: BOT_TYPE,
638
+ creates: "chat",
639
+ args: {
640
+ type: "object",
641
+ description: "Opens a chat that has the bot's agent set up a plugin by its guide.",
642
+ properties: {
643
+ plugin: { type: "string", minLength: 1, description: "The plugin to set up, such as dev." },
644
+ target: {
645
+ type: "string",
646
+ description: "What the guide works on, when it needs one: for dev the repository's directory.",
647
+ },
648
+ },
649
+ required: ["plugin"],
650
+ },
651
+ when: setupDevAction.when,
652
+ why: setupDevAction.why,
653
+ async run(ctx, args) {
654
+ const given = args as { readonly plugin: string; readonly target?: string };
655
+ const plugin = given.plugin.trim();
656
+ const target = given.target?.trim() ?? "";
657
+ const where = target.length === 0 ? "" : isAbsolute(target) ? target : resolve(ctx.cwd, target);
658
+ const prompt = await setupPrompt(ctx.setup, ctx.object.id, plugin, where);
659
+ const title = `${setupTitle(plugin)}${where.length === 0 ? "" : ` (${basename(where)})`}`;
660
+ const id = await openChat({
661
+ store: ctx.store,
662
+ home: ctx.home,
663
+ settings: ctx.settings,
664
+ harnesses: ctx.harnesses,
665
+ capabilities: ctx.capabilities,
666
+ models: ctx.models,
667
+ efforts: ctx.efforts,
668
+ bot: ctx.object.id,
669
+ title,
670
+ cause: "action:bot/setup",
671
+ });
672
+ const sent = await sendMessage(ctx, id, title, undefined, [], prompt);
673
+ return { text: `opened chat ${id}; ${sent}`, opens: `chat:${id}` };
674
+ },
675
+ };
676
+
271
677
  /**
272
678
  * Step `bot/settings`: the working directory, access profile and skills of a
273
679
  * chat's bot as they are now. The `chat` reply calls it every time, so
@@ -285,12 +691,15 @@ export async function runSettings(ctx: StepContext, params: unknown): Promise<Pl
285
691
  const name = parent.slice(BOT_TYPE.length + 1);
286
692
  try {
287
693
  await ingestReports(ctx.store, ctx.home);
288
- const written = readBots(ctx.home, ctx.settings)[name];
694
+ const bots = readBots(ctx.home, ctx.settings);
695
+ await migrateDefaultHome(ctx.store, ctx.home, bots);
696
+ const written = bots[name];
289
697
  if (written === undefined) {
290
698
  return { result: "failed", data: { message: `bot "${name}" is no longer in the settings` } };
291
699
  }
292
700
  const bot = resolveBot(ctx.home, name, written, await repositoryPaths(ctx.store));
293
701
  mkdirSync(bot.cwd, { recursive: true });
702
+ ensureBotMemory(bot.cwd, ctx.home);
294
703
  // Only the servers the bot lists, and only on a harness that takes MCP servers natively.
295
704
  const mounts = MCP_HARNESSES.includes(chatData(stored.data).harness);
296
705
  const mcpServers: Record<string, JsonValue> = {};
@@ -299,38 +708,67 @@ export async function runSettings(ctx: StepContext, params: unknown): Promise<Pl
299
708
  }
300
709
  return {
301
710
  result: "done",
302
- data: { cwd: bot.cwd, access: bot.access, skills: [...bot.skills], mcpServers },
711
+ data: {
712
+ cwd: bot.cwd,
713
+ access: bot.access,
714
+ skills: [...bot.skills],
715
+ mcpServers,
716
+ useOwnSettings: bot.useOwnSettings,
717
+ // A chat that never chose a level follows the bot's setting; a scheduled chat keeps `full`.
718
+ ...(chatData(stored.data).scheduled === undefined ? { accessDefault: bot.accessLevel } : {}),
719
+ // The memory index and the person's instructions ride on the message,
720
+ // whole when this session has not seen them, under ADR 0026 D18.
721
+ notes: memoryNotes(join(bot.cwd, "memory")) as unknown as JsonValue,
722
+ // The memory plugin records what this reply wrote, once the round ends.
723
+ ...(ctx.stepLoaded !== undefined && ctx.stepLoaded(MEMORY_COMMIT_STEP) ? { after: MEMORY_COMMIT_STEP } : {}),
724
+ context: scheduledChatContext(stored.id),
725
+ },
303
726
  };
304
727
  } catch (error) {
305
- return { result: "failed", data: { message: error instanceof Error ? error.message : String(error) } };
728
+ return { result: "failed", data: { message: messageOf(error) } };
306
729
  }
307
730
  }
308
731
 
309
732
  function botMarkdown(object: StoredObject): string {
310
733
  const data = object.data;
311
734
  const lines = [`**${object.id}**`];
312
- if (typeof data.problem === "string") lines.push(`Cannot be used: ${data.problem}`);
313
- if (typeof data.cwd === "string") lines.push(`Working directory: ${data.cwd}`);
314
- if (typeof data.harness === "string") lines.push(`Default agent: ${data.harness}`);
315
- if (typeof data.speaker === "string") lines.push(`Speaker: ${data.speaker}`);
316
- const skills = Array.isArray(data.skills) ? data.skills : [];
317
- lines.push(skills.length === 0 ? "No skills." : `Skills: ${skills.join(", ")}`);
735
+ if (typeof data.problem === "string") lines.push(`Cannot be used: ${markdownText(data.problem)}`);
736
+ if (typeof data.cwd === "string") lines.push(`Working directory: ${markdownCode(data.cwd)}`);
737
+ if (typeof data.harness === "string") lines.push(`Default agent: ${markdownText(data.harness)}`);
738
+ if (typeof data.speaker === "string") lines.push(`Speaker: ${markdownText(data.speaker)}`);
739
+ const skills = Array.isArray(data.skills)
740
+ ? data.skills.filter((path): path is string => typeof path === "string")
741
+ : [];
742
+ lines.push(skills.length === 0 ? "No skills." : `Skills: ${skills.map((path) => markdownText(skillName(path))).join(", ")}`);
743
+ lines.push(data.writeWiki === true ? "Wiki: read and write." : "Wiki: read only.");
318
744
  const servers = Array.isArray(data.mcpServers) ? data.mcpServers : [];
319
745
  if (servers.length > 0) {
320
746
  lines.push(
321
- `MCP servers: ${servers.join(", ")}`,
747
+ `MCP servers: ${servers.map((name) => markdownText(String(name))).join(", ")}`,
322
748
  `They are mounted in chats on ${MCP_HARNESSES.join(" and ")}. A chat on pi does not mount them: pi takes no MCP servers yet, so it cannot use ${servers.join(", ")}.`,
323
749
  );
324
750
  }
751
+ lines.push(scheduledMarkdown(scheduledPrompts(data), Date.now()).join("\n"));
752
+ lines.push(followUpMarkdown(followUps(data)).join("\n"));
325
753
  return lines.join("\n\n");
326
754
  }
327
755
 
756
+ /** The server's IANA time zone, the one cron expressions run in; read at each call so `TZ` can be set. */
757
+ export function serverTimeZone(): string {
758
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
759
+ }
760
+
328
761
  /** How a bot shows in a list and on its page. */
329
762
  export const botViews: ObjectViews = {
330
763
  row: (object): ObjectRow => ({
331
764
  id: object.id,
332
765
  title: object.id,
333
766
  state: object.data.removed === true ? "removed" : "open",
767
+ data: {
768
+ scheduled: scheduledData(scheduledPrompts(object.data), Date.now()) as unknown as JsonValue,
769
+ timeZone: serverTimeZone(),
770
+ followUps: followUpData(followUps(object.data)) as unknown as JsonValue,
771
+ },
334
772
  }),
335
773
  sections: () => [{ id: "bot", title: "Bot" }],
336
774
  load: (_ctx, object): SectionContent => ({ markdown: botMarkdown(object) }),
@@ -344,7 +782,7 @@ export function createBotPlugin() {
344
782
  // The version comes from package.json so the two cannot drift apart.
345
783
  version: pkg.version,
346
784
  // Patch releases of chat only: a new minor may change what bot relies on.
347
- requires: { plugins: { chat: "~0.1.0" } },
785
+ requires: { plugins: { chat: "~0.3.0" } },
348
786
  settings: BOT_SETTINGS,
349
787
  // A bot page is that bot's settings page; bots live under settings, not in a tab.
350
788
  objectsUnderSettings: true,
@@ -367,9 +805,33 @@ export function createBotPlugin() {
367
805
  { name: "rejected", states: ["rejected"] },
368
806
  ],
369
807
  },
808
+ { name: TIDY_TYPE, index: ["bot", "state"] },
809
+ ],
810
+ steps: [
811
+ { name: "settings", results: ["done", "failed"], run: runSettings },
812
+ { name: "login", results: ["done", "failed"], callsNamedByData: true, timeoutSecs: 700, run: runLoginStep },
370
813
  ],
371
- steps: [{ name: "settings", results: ["done", "failed"], run: runSettings }],
372
- actions: [chatAction, ...proposalActions],
814
+ flows: [loginFlow],
815
+ // A scheduled prompt opens a chat and sends its first message from the
816
+ // bot source; that message is not a person's, so the reply is a background run.
817
+ rules: [
818
+ {
819
+ source: SCHEDULE_SOURCE,
820
+ type: MESSAGE_EVENT,
821
+ start: { flow: "chat:reply" },
822
+ object: "$event.object",
823
+ mode: "auto" as const,
824
+ },
825
+ // The person's own login on a bot; it asks through the agent's login step.
826
+ {
827
+ source: LOGIN_SOURCE,
828
+ type: LOGIN_EVENT,
829
+ start: { flow: "bot:login" },
830
+ object: "$event.object",
831
+ mode: "auto" as const,
832
+ },
833
+ ],
834
+ actions: [chatAction, setupDevAction, setupAction, chatSetupAction, createAction, loginAction, ...proposalActions, ...scheduleActions, ...followUpActions, ...tidyActions],
373
835
  commands: [
374
836
  {
375
837
  name: "skill",
@@ -386,20 +848,73 @@ export function createBotPlugin() {
386
848
  args: "<bot>",
387
849
  run: runSettingCommand,
388
850
  },
851
+ {
852
+ name: "setup-dev",
853
+ args: "<bot> <repository directory> [< dev.json]",
854
+ run: runSetupDev,
855
+ },
856
+ {
857
+ name: "setup-git",
858
+ args: "<bot> <folder> [< {gitignore, identity}]",
859
+ run: runSetupGit,
860
+ },
861
+ {
862
+ name: "setup",
863
+ args: "<bot> <plugin> [target]",
864
+ run: runSetup,
865
+ },
866
+ {
867
+ name: "schedule",
868
+ args: "<bot> add|edit|remove <name> [--words <text>] [--schedule <cron>] [--prompt <text>] [--model <model>] [--effort <effort>]",
869
+ run: runScheduleCommand,
870
+ },
871
+ {
872
+ name: "follow-up",
873
+ args: "<chat> --at <time> --do <one sentence>",
874
+ run: runFollowUpCommand,
875
+ },
876
+ {
877
+ name: "follow-ups",
878
+ args: "<chat> [--cancel <id>]",
879
+ run: runFollowUpsCommand,
880
+ },
389
881
  ],
390
882
  // A proposal waits for no run; each one is a pending item of its bot.
391
883
  standing: async (ctx) => {
392
884
  await ingestReports(ctx.store, ctx.home);
393
- return proposalItems(ctx.store);
885
+ await syncBots(ctx.store, ctx.home, ctx.settings);
886
+ return [...(await proposalItems(ctx.store)), ...(await tidyItems(ctx.store)), ...(await loginItems(ctx))];
887
+ },
888
+ // The bot is its own source for its scheduled prompts and its nightly
889
+ // memory tidy. It declares `start` while staying a domain plugin, so
890
+ // `serve` starts it like any source.
891
+ start: async (ctx) => {
892
+ await migrateDefaultHome(ctx.store, ctx.home, readBots(ctx.home, ctx.settings));
893
+ const scheduled = await startScheduled(ctx);
894
+ const tidy = await startTidy(ctx);
895
+ return {
896
+ stop: async () => {
897
+ await scheduled.stop();
898
+ await tidy.stop();
899
+ },
900
+ };
394
901
  },
395
- views: { [BOT_TYPE]: botViews, [PROPOSAL_TYPE]: proposalViews },
902
+ views: { [BOT_TYPE]: botViews, [PROPOSAL_TYPE]: proposalViews, [TIDY_TYPE]: tidyViews },
396
903
  });
397
904
  }
398
905
 
399
906
  export default createBotPlugin();
400
907
 
401
908
  export * from "./bot.ts";
909
+ export * from "./create.ts";
910
+ export * from "./login.ts";
402
911
  export * from "./proposals.ts";
912
+ export * from "./setup-dev.ts";
913
+ export * from "./setup-git.ts";
914
+ export * from "./setup.ts";
915
+ export * from "./schedule.ts";
916
+ export * from "./follow-up.ts";
917
+ export * from "./tidy.ts";
403
918
  export * from "./mcp.ts";
404
919
  export * from "./mcp-proposals.ts";
405
920
  export { runGuard, markedResult, MATERIAL_NOTE, reportPath } from "./guard.ts";