pi-roundtable 0.40.0 → 0.43.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.
Files changed (38) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +6 -4
  3. package/README.zh-TW.md +6 -4
  4. package/docs/plugins.md +32 -5
  5. package/package.json +2 -2
  6. package/src/core/agents/agent-claim.ts +6 -2
  7. package/src/core/agents/agent-team-fixture.ts +9 -3
  8. package/src/core/agents/agent-team.ts +7 -8
  9. package/src/core/agents/agent-tools.ts +12 -4
  10. package/src/core/agents/routes.ts +24 -7
  11. package/src/core/agents/team-options.ts +2 -0
  12. package/src/core/builtin/agent-server-options.ts +101 -0
  13. package/src/core/builtin/agent-server.ts +34 -100
  14. package/src/core/config/adapters.ts +13 -7
  15. package/src/core/config/agent-team.ts +45 -4
  16. package/src/core/config/config-schema.ts +3 -1
  17. package/src/core/config/config.ts +23 -23
  18. package/src/core/config/ops.ts +1 -1
  19. package/src/core/config/routing.ts +3 -3
  20. package/src/core/config/team.ts +30 -0
  21. package/src/core/contract/channels.ts +8 -0
  22. package/src/core/db/team-move.ts +103 -0
  23. package/src/core/host/define-roundtable.ts +15 -5
  24. package/src/core/host/drain.ts +46 -0
  25. package/src/core/host/host-registration.ts +5 -0
  26. package/src/core/host/host.ts +31 -8
  27. package/src/core/plugin-api/holds.ts +31 -0
  28. package/src/core/plugin-api/plugin.ts +6 -3
  29. package/src/core/plugin-api/services.ts +4 -5
  30. package/src/core/presentation/diagram-text.ts +17 -8
  31. package/src/core/routing/channel-queue.ts +36 -3
  32. package/src/core/runtime/extensions/yolo.ts +3 -0
  33. package/src/core/runtime/mcp.ts +10 -0
  34. package/src/core/testing/partial.ts +8 -0
  35. package/src/kit/holds.ts +1 -0
  36. package/src/kit/index.ts +6 -1
  37. package/src/kit/worker.ts +1 -1
  38. package/src/testing.ts +4 -4
@@ -1,6 +1,5 @@
1
1
  import { chmodSync, lstatSync, mkdirSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import type { ModelRuntime } from "@earendil-works/pi-coding-agent";
4
3
  import type { SQL } from "bun";
5
4
  import { agentClaim } from "../agents/agent-claim.ts";
6
5
  import { AgentDashboard } from "../agents/agent-dashboard.ts";
@@ -13,23 +12,16 @@ import { modeOrigins } from "../agents/helper-modes.ts";
13
12
  import { Routes } from "../agents/routes.ts";
14
13
  import { agentOfChannel, discordKey } from "../agents/team-keys.ts";
15
14
  import { ownerAttachmentDir } from "../attachments/attachment-dir.ts";
16
- import type { ResolvedHelpers } from "../config/helpers.ts";
17
- import type { ResolvedRouting } from "../config/routing.ts";
18
15
  import { ROOM_LAYOUT } from "../contract/room-layout.ts";
19
16
  import type { AgentSessions } from "../contract/runtime.ts";
17
+ import { moveTeam } from "../db/team-move.ts";
20
18
  import type { ChannelKey } from "../domain/conversation.ts";
21
19
  import { ConfigError } from "../domain/errors.ts";
22
- import {
23
- AUTO_THINKING,
24
- formatModelRef,
25
- type ModelRef,
26
- } from "../domain/models.ts";
20
+ import { AUTO_THINKING, formatModelRef } from "../domain/models.ts";
27
21
  import type { SessionTool } from "../domain/sessions.ts";
28
- import type { OwnerIdentity } from "../identity/owner-identity.ts";
29
22
  import type { Tier } from "../identity/speakers.ts";
30
23
  import { ConfirmationJudge } from "../judging/confirmation-judge.ts";
31
24
  import type { Logger } from "../kernel/log.ts";
32
- import type { ErrorReporter } from "../ops/error-reporter.ts";
33
25
  import type { PluginContext, RoundtablePlugin } from "../plugin-api/plugin.ts";
34
26
  import {
35
27
  AGENTS,
@@ -43,92 +35,18 @@ import {
43
35
  } from "../plugin-api/services.ts";
44
36
  import { splitReply } from "../presentation/reply-splitter.ts";
45
37
  import { agentPromptExtension } from "../runtime/extensions/agent-prompt.ts";
46
- import type { AgentSessionsSlot } from "../runtime/runtime-plugin.ts";
47
38
  import { DISCORD } from "./discord.ts";
48
39
  import { agentOnly } from "./session-tool.ts";
49
40
 
50
- /**
51
- * The id of the team on a host without Discord, in place of the Discord guild: the rows the team
52
- * keeps are stored under it, as under the guild's id on a host with Discord.
53
- */
54
- export const LOCAL_TEAM_ID = "local";
41
+ export {
42
+ type AgentServerOptions,
43
+ LOCAL_TEAM_ID,
44
+ } from "./agent-server-options.ts";
55
45
 
56
- export interface AgentServerOptions {
57
- /**
58
- * The Discord guild the team lives in. Absent on a host without Discord: the team is then
59
- * `LOCAL_TEAM_ID`, it has no channels, and its agents live in the rooms of the surfaces that
60
- * host them.
61
- */
62
- guildId?: string;
63
- /** The channel the coordinator lives in; set with `guildId`, never with `coordinator`. */
64
- entryChannelId?: string;
65
- /**
66
- * The coordinator's name on a host without Discord, where no entry channel names it; the first
67
- * seed when absent. Refused with `entryChannelId`.
68
- */
69
- coordinator?: string;
70
- owner: OwnerIdentity & { id: string };
71
- /** The assistant's display name, as the confirmation judge names it. */
72
- assistant: string;
73
- /** Shared with the rest of the host, so logins refresh in one place; lists the models an agent may run. */
74
- modelRuntime: ModelRuntime;
75
- dataDir: string;
76
- /** The model of agents and of the assistant. */
77
- model: ModelRef;
78
- /** How sure the confirmation judge must be before its answer is used. */
79
- judgeThreshold: number;
80
- /** Where the agent server hands the runtime plugin its per-agent settings. */
81
- agents?: AgentSessionsSlot;
82
- /** The shell's shared working directory. */
83
- workDir: string;
84
- /**
85
- * The agents' scratch dir, created with mode 0700 when the agent server starts: their shell's
86
- * TMPDIR, where writes and removals run without a hold.
87
- */
88
- scratchDir?: string;
89
- /** The host account the agents' shell and file tools run as. */
90
- shellUser: string;
91
- /**
92
- * Whose turns in the agents' channels load memory: `"everyone"` (the default) or `"owners"`;
93
- * see `AgentSessions.memory`.
94
- */
95
- memory?: "everyone" | "owners";
96
- /**
97
- * Who the agents answer in their channels and groups' channels: `"everyone"` (the default) or
98
- * `"owners"`, which leaves a speaker below the owner tier unanswered.
99
- */
100
- speakers?: "everyone" | "owners";
101
- /**
102
- * Limits of the downloads of a message's files (`discord.attachmentDownload`): `deadlineMs`
103
- * for all of a message's files together (default 60 s), `idleMs` for one file to send no byte
104
- * (default 10 s).
105
- */
106
- attachmentDownload?: { deadlineMs?: number; idleMs?: number };
107
- /** The prompt every agent starts with, and the one for speakers other than the owner. */
108
- prompts: { shared: string; guest?: string };
109
- /** The listener the avatar pictures are served on; none mounts no route, and a surface serves them through `AGENTS.avatars.serve`. */
110
- avatarListener?: string;
111
- /**
112
- * The origin the agents' pictures are served from. Without one a picture's URL is
113
- * `/avatars/<hash>.png`, which the surface that serves the pictures resolves against its origin.
114
- */
115
- avatarUrl?: string;
116
- /**
117
- * Render every agent's picture again at start (`characters.refreshAvatars`) and set it where
118
- * its hash differs from the stored one; default false.
119
- */
120
- refreshAvatars?: boolean;
121
- /** The assistant's neutral avatar: the style reference and the picture of an agent without one. */
122
- avatarReference: string;
123
- /** The picture used instead when `avatarReference` cannot be read as one; the failure is logged. */
124
- avatarNeutral?: string;
125
- /** Reports the process's own errors to an agent; without one nothing is reported. */
126
- errorReporter?: ErrorReporter;
127
- /** The checked `routing` block: where work no person started lands. Without it every place is what it was before `routing`. */
128
- routing?: ResolvedRouting;
129
- /** The temp knights' limits; `false` leaves `helper_create` and `helper_end` out. Without it the defaults apply. */
130
- helpers?: ResolvedHelpers | false;
131
- }
46
+ import {
47
+ type AgentServerOptions,
48
+ LOCAL_TEAM_ID,
49
+ } from "./agent-server-options.ts";
132
50
 
133
51
  /** The name of the agent server's plugin, as `serviceStarted` events name it. */
134
52
  export const AGENT_SERVER_PLUGIN = "agent-server";
@@ -201,7 +119,7 @@ export function agentServerPlugin(
201
119
  throw new ConfigError(
202
120
  "the agent server: entryChannelId and coordinator both name the coordinator. Set the entry channel with Discord, the coordinator without it.",
203
121
  );
204
- const teamId = options.guildId ?? LOCAL_TEAM_ID;
122
+ const teamId = options.teamId ?? options.guildId ?? LOCAL_TEAM_ID;
205
123
  /** Set once the plugin has set up; the preflight reads it after every plugin linked. */
206
124
  let hostsRooms: (() => boolean) | undefined;
207
125
  let linkRoutes: (() => void) | undefined;
@@ -209,7 +127,17 @@ export function agentServerPlugin(
209
127
  name: AGENT_SERVER_PLUGIN,
210
128
  // The agent server's own tables; the host runs them before any setup, in this order. The
211
129
  // held actions' table is the runtime plugin's.
212
- migrations: PgAgentStore.migrations(teamId),
130
+ migrations: [
131
+ ...PgAgentStore.migrations(teamId),
132
+ // After the agents' tables, and the prompts', skills' and conversations' before it.
133
+ moveTeam({
134
+ from: options.formerTeamIds ?? [],
135
+ to: teamId,
136
+ ...(options.guildId === undefined
137
+ ? { clearChannels: true }
138
+ : { discordGuild: options.guildId }),
139
+ }),
140
+ ],
213
141
  provides: [AGENTS],
214
142
  requires: [RUNTIME],
215
143
  // A team with no Discord channels is reached through rooms only; without a surface that
@@ -217,7 +145,7 @@ export function agentServerPlugin(
217
145
  preflight: () => {
218
146
  if (hostsRooms && !hostsRooms())
219
147
  throw new ConfigError(
220
- "the agents need a surface that hosts their rooms, such as pi-roundtable-web, and none is installed. Without Discord channels there is nowhere to talk to them; add a plugin whose chat surface declares agentRooms: true, or configure discord.",
148
+ "the agents need a surface that hosts their rooms, such as pi-roundtable-web, and none is installed. Without Discord channels there is nowhere to talk to them; add a plugin whose chat surface declares agentRooms: true, or configure discord with its guild.",
221
149
  );
222
150
  // The surfaces the rules name exist only once every plugin has registered its own.
223
151
  linkRoutes?.();
@@ -228,7 +156,12 @@ export function agentServerPlugin(
228
156
  const schedules = context.services.get(SCHEDULES);
229
157
  const connection = discord?.connection;
230
158
  const { logger, providers, surfaces } = context;
231
- if (!connection) hostsRooms = () => surfaces.roomSurfaces().length > 0;
159
+ // The team's Discord channels, in the agent guild; a bot without one serves only the plugins.
160
+ const channels =
161
+ connection && options.guildId
162
+ ? connection.agentChannels(options.guildId)
163
+ : undefined;
164
+ if (!channels) hostsRooms = () => surfaces.roomSurfaces().length > 0;
232
165
  const studio = new FileAvatarStudio({
233
166
  dir: join(options.dataDir, "avatars"),
234
167
  skins: context.env.characterSkins,
@@ -287,17 +220,19 @@ export function agentServerPlugin(
287
220
  store,
288
221
  roomSurfaces: () => surfaces.roomSurfaces(),
289
222
  latest: (agent) => store.conversations.latest(agent),
223
+ discordChannels: channels !== undefined,
290
224
  logger,
291
225
  });
292
226
  // The surfaces the rules name are registered by the time every plugin has set up.
293
227
  linkRoutes = () =>
294
228
  routes.validate({
295
229
  names: surfaces.names?.() ?? [],
296
- discordChannels: connection !== undefined,
230
+ discordChannels: channels !== undefined,
297
231
  });
298
232
  const built: DiscordAgentTeam = new DiscordAgentTeam({
299
233
  routes,
300
234
  guildId: teamId,
235
+ discordGuild: options.guildId,
301
236
  ...(options.entryChannelId !== undefined
302
237
  ? { entryChannelId: options.entryChannelId }
303
238
  : {}),
@@ -319,9 +254,7 @@ export function agentServerPlugin(
319
254
  shellUser: options.shellUser,
320
255
  ...(options.scratchDir ? { scratchDir: options.scratchDir } : {}),
321
256
  store,
322
- ...(connection && options.guildId
323
- ? { channels: connection.agentChannels(options.guildId) }
324
- : {}),
257
+ ...(channels ? { channels } : {}),
325
258
  studio,
326
259
  ...(options.refreshAvatars ? { refreshAvatars: true } : {}),
327
260
  runtime: () => running,
@@ -444,6 +377,7 @@ export function agentServerPlugin(
444
377
  channels: [
445
378
  agentClaim({
446
379
  owner: options.owner,
380
+ discordGuild: options.guildId,
447
381
  ...(options.speakers ? { speakers: options.speakers } : {}),
448
382
  team: built,
449
383
  runtime: running,
@@ -17,9 +17,14 @@ import {
17
17
  export interface DiscordConfig {
18
18
  /** The bot token; keep it in `.env`, not in this file. */
19
19
  token: string;
20
- /** The agent server's guild id. */
21
- guild: string;
22
- /** The channel the coordinator lives in. Required unless the configuration says `agentServer: false`, which has no coordinator. */
20
+ /**
21
+ * The agent server's guild id: the agents' channels, categories, `#dashboard` and threads live
22
+ * there. Left out, the bot serves only the plugins' claims and commands in the guilds it is in,
23
+ * and the agent team lives in the app's rooms as on a host without Discord: `agents` is then
24
+ * required, `coordinator` names the coordinator, and `entryChannel` is refused.
25
+ */
26
+ guild?: string;
27
+ /** The channel the coordinator lives in. Required with `guild`, unless the configuration says `agentServer: false`, which has no coordinator. */
23
28
  entryChannel?: string;
24
29
  /** The root slash command, without the slash; default the lowercase assistant name. */
25
30
  rootCommand?: string;
@@ -108,8 +113,9 @@ export interface DiscordConfig {
108
113
  /** The Discord settings with every default filled in. */
109
114
  export interface ResolvedDiscord {
110
115
  token: string;
111
- guild: string;
112
- /** Undefined only with `agentServer: false`. */
116
+ /** Undefined when the agent team lives in the app's rooms. */
117
+ guild?: string;
118
+ /** Undefined with `agentServer: false` or without `guild`. */
113
119
  entryChannel?: string;
114
120
  rootCommand: string;
115
121
  admin: boolean;
@@ -136,7 +142,7 @@ export function resolvedDiscord(
136
142
  ): ResolvedDiscord {
137
143
  return {
138
144
  token: discord.token,
139
- guild: discord.guild,
145
+ ...(discord.guild === undefined ? {} : { guild: discord.guild }),
140
146
  ...(discord.entryChannel === undefined
141
147
  ? {}
142
148
  : { entryChannel: discord.entryChannel }),
@@ -194,7 +200,7 @@ const channelContextShape = shape({
194
200
  /** The Discord settings, at the top level or in a Discord adapter. */
195
201
  export const discordShape = shape({
196
202
  token: text,
197
- guild: text,
203
+ guild: optional(text),
198
204
  entryChannel: optional(text),
199
205
  rootCommand: optional(text),
200
206
  admin: optional(bool),
@@ -8,8 +8,8 @@ interface AgentTeamKeys {
8
8
  }
9
9
 
10
10
  /**
11
- * Refuses what the agent team needs and a host without Discord lacks, naming the key; and the
12
- * coordinator, which only a host without Discord names: with Discord it is the entry channel's agent.
11
+ * Refuses what the agent team needs and a team without Discord channels lacks, naming the key; and
12
+ * the coordinator, which only such a team names: in the agent guild it is the entry channel's agent.
13
13
  */
14
14
  export function checkAgentTeamKeys(
15
15
  config: AgentTeamKeys,
@@ -19,7 +19,7 @@ export function checkAgentTeamKeys(
19
19
  if (config.coordinator !== undefined) {
20
20
  if (withDiscord)
21
21
  throw new ConfigError(
22
- "config coordinator: the entry channel's agent is the coordinator with discord. Remove coordinator, or move the agent to discord.entryChannel.",
22
+ "config coordinator: the entry channel's agent is the coordinator with discord.guild. Remove coordinator, or move the agent to discord.entryChannel.",
23
23
  );
24
24
  if (seeds.length === 0)
25
25
  throw new ConfigError(
@@ -34,7 +34,7 @@ export function checkAgentTeamKeys(
34
34
  const placed = seeds.findIndex((seed) => seed.channelId !== undefined);
35
35
  if (placed >= 0)
36
36
  throw new ConfigError(
37
- `config agents[${placed}].channelId: a Discord channel, and Discord is not configured. Remove channelId, or configure discord.`,
37
+ `config agents[${placed}].channelId: a Discord channel, and the agents have none (no discord, or no discord.guild). Remove channelId, or configure discord with its guild.`,
38
38
  );
39
39
  if (config.skills && seeds.length === 0)
40
40
  throw new ConfigError(
@@ -42,6 +42,47 @@ export function checkAgentTeamKeys(
42
42
  );
43
43
  }
44
44
 
45
+ /** The keys of the configuration that say whether the agents have Discord channels. */
46
+ interface AgentGuildKeys {
47
+ discord?: { guild?: string; entryChannel?: string };
48
+ http?: { publicUrl?: string };
49
+ agents?: readonly unknown[];
50
+ }
51
+
52
+ /**
53
+ * Whether the agent team lives in the Discord guild `discord.guild` names; refuses what that
54
+ * guild needs and lacks, and an entry channel without it. Without `discord.guild` the bot still
55
+ * serves the plugins, and the team lives in the app's rooms, as on a host without Discord.
56
+ */
57
+ export function checkAgentGuild(
58
+ config: AgentGuildKeys,
59
+ agentServer: boolean,
60
+ ): boolean {
61
+ const { discord } = config;
62
+ if (!discord) return false;
63
+ if (discord.guild === undefined) {
64
+ if (discord.entryChannel !== undefined)
65
+ throw new ConfigError(
66
+ "config discord.entryChannel: the coordinator's channel is in the agent guild, and discord.guild is left out, so the agents live in the app's rooms. Remove entryChannel and name the coordinator with coordinator, or add discord.guild.",
67
+ );
68
+ if (agentServer && (config.agents?.length ?? 0) === 0)
69
+ throw new ConfigError(
70
+ "config discord.guild: left out, so the agents live in the app's rooms, and agents configures none. Add agents, add discord.guild for an agent server in Discord, or set agentServer: false for a host without agents.",
71
+ );
72
+ return false;
73
+ }
74
+ if (!agentServer) return true;
75
+ if (!discord.entryChannel)
76
+ throw new ConfigError(
77
+ "config discord.entryChannel: required, expected the id of the channel the coordinator lives in. Add it to roundtable.config.ts, leave out discord.guild for agents that live in the app, or set agentServer: false for a host without agents.",
78
+ );
79
+ if (!config.http?.publicUrl)
80
+ throw new ConfigError(
81
+ "config http.publicUrl: required with discord, expected the public address that reaches the bot; Discord fetches the agents' avatars from it. Add it to roundtable.config.ts.",
82
+ );
83
+ return true;
84
+ }
85
+
45
86
  /** The keys of the configuration, as written, that only the agent server uses. */
46
87
  interface AgentOnlyKeys {
47
88
  agents?: readonly unknown[];
@@ -28,6 +28,7 @@ import {
28
28
  text,
29
29
  } from "./schema.ts";
30
30
  import { skillsField } from "./skills-config.ts";
31
+ import { teamField } from "./team.ts";
31
32
 
32
33
  /** The shape `roundtable.config.ts` is checked against: every key, its type and its bounds. */
33
34
  const tierMembers = shape({
@@ -132,6 +133,7 @@ export const configSchema = shape({
132
133
  ),
133
134
  ),
134
135
  coordinator: optional(text),
136
+ team: teamField,
135
137
  characters: optional(
136
138
  shape({ skins: optional(skinTones), refreshAvatars: optional(bool) }),
137
139
  ),
@@ -155,7 +157,7 @@ export const configSchema = shape({
155
157
  ops: optional(shape({ agent: optional(text), conversation: optional(text) })),
156
158
  routing: routingShape,
157
159
  helpers: optional(helpersField),
158
- drainSeconds: optional(integer(1, 3_600)),
160
+ drainSeconds: optional(integer(1, 14_400)),
159
161
  ...limitsShape,
160
162
  interimText: optional(oneOf<InterimTextMode>("on", "off")),
161
163
  interimPrimaryChars: optional(integer(1, 100_000)),
@@ -26,7 +26,11 @@ import {
26
26
  type ResolvedDiscord,
27
27
  resolvedDiscord,
28
28
  } from "./adapters.ts";
29
- import { checkAgentServerOff, checkAgentTeamKeys } from "./agent-team.ts";
29
+ import {
30
+ checkAgentGuild,
31
+ checkAgentServerOff,
32
+ checkAgentTeamKeys,
33
+ } from "./agent-team.ts";
30
34
  import type { AttachmentsConfig } from "./attachments.ts";
31
35
  import { configSchema, DRAIN_LIMIT_MS } from "./config-schema.ts";
32
36
  import type { ConversationsConfig } from "./conversations.ts";
@@ -44,6 +48,7 @@ import {
44
48
  routingOf,
45
49
  } from "./routing.ts";
46
50
  import type { SkillsConfig } from "./skills-config.ts";
51
+ import { type ResolvedTeam, type TeamConfig, teamOf } from "./team.ts";
47
52
 
48
53
  export type { DiscordConfig };
49
54
 
@@ -164,15 +169,17 @@ export interface RoundtableConfig extends LimitsConfig, ShellEnvConfig {
164
169
  prompts?: { shared: string; guest?: string };
165
170
  /**
166
171
  * The first team, created once; an agent already stored is never overwritten. Without `discord`
167
- * the team lives in the rooms of a surface that hosts them, so a seed has no `channelId`.
172
+ * or `discord.guild` the team lives in the rooms of a surface that hosts them: a seed has no `channelId`.
168
173
  */
169
174
  agents?: AgentSeed[];
170
175
  /**
171
- * Without `discord`, the name of the agent that coordinates the team: the one the owner's
172
- * general requests come to, which cannot be archived. It must be one of `agents`; default the
173
- * first. With `discord` the agent in `discord.entryChannel` is the coordinator, and this key is refused.
176
+ * Without `discord` or `discord.guild`, the name of the agent that coordinates the team: the one
177
+ * the owner's general requests come to, which cannot be archived. It must be one of `agents`; default
178
+ * the first. With `discord.guild` the agent in `discord.entryChannel` is the coordinator, and this key is refused.
174
179
  */
175
180
  coordinator?: string;
181
+ /** Where the team's rows are stored, and the ids they moved from; see `TeamConfig`. */
182
+ team?: TeamConfig;
176
183
  /**
177
184
  * How the agents' characters are drawn, everywhere the host draws them: the web console, its
178
185
  * round table and the agents' pictures on Discord. `skins` is exactly six `#rrggbb` skin tones
@@ -318,8 +325,9 @@ export interface ResolvedConfig extends ResolvedLimits {
318
325
  toolTiers: Record<string, Tier>;
319
326
  prompts: { shared?: string; guest?: string };
320
327
  agents: AgentSeed[];
321
- /** The coordinator's name; set only without `discord` and with `agents`: the configured one, else the first seed. */
328
+ /** The coordinator's name; set only without `discord.guild` and with `agents`: the configured one, else the first seed. */
322
329
  coordinator?: string;
330
+ team: ResolvedTeam;
323
331
  /** How the agents' characters are drawn: the six skin tones, the package's own unless `characters.skins` is set. */
324
332
  characters: { skins: readonly Hex[]; refreshAvatars: boolean };
325
333
  /** Undefined when no `http` is configured, and the host opens no `public` listener. */
@@ -376,26 +384,18 @@ export function resolveConfig(input: unknown): ResolvedConfig {
376
384
  const { discord, http } = config;
377
385
  const agentServer = config.agentServer !== false;
378
386
  if (!agentServer) checkAgentServerOff(config);
379
- if (discord && agentServer && !discord.entryChannel)
380
- throw new ConfigError(
381
- "config discord.entryChannel: required, expected the id of the channel the coordinator lives in. Add it to roundtable.config.ts, or set agentServer: false for a host without agents.",
382
- );
383
- if (discord && agentServer && !http?.publicUrl)
384
- throw new ConfigError(
385
- "config http.publicUrl: required with discord, expected the public address that reaches the bot; Discord fetches the agents' avatars from it. Add it to roundtable.config.ts.",
386
- );
387
- checkAgentTeamKeys(config, discord !== undefined);
387
+ // Whether the agents have Discord channels: with `discord.guild`, else they live in the app's rooms.
388
+ const agentGuild = checkAgentGuild(config, agentServer);
389
+ checkAgentTeamKeys(config, agentGuild);
388
390
  const slug =
389
391
  discord?.rootCommand ?? name.toLowerCase().replace(/[^a-z0-9-]+/g, "-");
390
392
  const routing = routingOf(config.routing, {
391
- withDiscord: discord !== undefined,
393
+ withDiscord: agentGuild,
392
394
  agentServer:
393
- agentServer &&
394
- (discord !== undefined || (config.agents?.length ?? 0) > 0),
395
+ agentServer && (agentGuild || (config.agents?.length ?? 0) > 0),
395
396
  topLevelOps: config.ops !== undefined,
396
397
  });
397
- const ops =
398
- opsOf(config.ops, discord !== undefined) ?? opsOfPlace(routing?.places.ops);
398
+ const ops = opsOf(config.ops, agentGuild) ?? opsOfPlace(routing?.places.ops);
399
399
  const access = accessOf(config, discord !== undefined);
400
400
  const { primaryOwner } = access;
401
401
  return {
@@ -452,15 +452,15 @@ export function resolveConfig(input: unknown): ResolvedConfig {
452
452
  prompts: config.prompts ?? {},
453
453
  agents: config.agents ?? [],
454
454
  agentServer:
455
- agentServer &&
456
- (discord !== undefined || (config.agents?.length ?? 0) > 0),
455
+ agentServer && (agentGuild || (config.agents?.length ?? 0) > 0),
457
456
  agentTools:
458
457
  typeof config.agentServer === "object"
459
458
  ? config.agentServer.tools
460
459
  : "full",
461
- ...(!discord && config.agents?.[0]
460
+ ...(!agentGuild && config.agents?.[0]
462
461
  ? { coordinator: config.coordinator ?? config.agents[0].name }
463
462
  : {}),
463
+ team: teamOf(config.team),
464
464
  characters: {
465
465
  skins: skinsOf(config.characters?.skins),
466
466
  refreshAvatars: config.characters?.refreshAvatars ?? false,
@@ -18,7 +18,7 @@ export function opsOf(
18
18
  if (agent !== undefined) {
19
19
  if (!withDiscord)
20
20
  throw new ConfigError(
21
- 'config ops.agent: the agents live in Discord, which is not configured. Report to a conversation a plugin\'s chat surface serves instead, with ops: { conversation: "<surface>:<id>" }; the web chat takes no error reports.',
21
+ 'config ops.agent: the agents live in Discord, which is not configured or has no discord.guild. Report to a conversation a plugin\'s chat surface serves instead, with ops: { conversation: "<surface>:<id>" }; the web chat takes no error reports.',
22
22
  );
23
23
  return { agent };
24
24
  }
@@ -167,7 +167,7 @@ export interface ResolvedRouting {
167
167
 
168
168
  /** What the rest of the configuration says that the block is checked against. */
169
169
  export interface RoutingContext {
170
- /** Whether Discord is configured, so agents have Discord channels. */
170
+ /** Whether the agents have Discord channels: Discord is configured with `discord.guild`. */
171
171
  withDiscord: boolean;
172
172
  /** Whether the agent server runs: only then do agents and their places exist. */
173
173
  agentServer: boolean;
@@ -261,8 +261,8 @@ export function routingOf(
261
261
  if (named[0] || surfaces.discord)
262
262
  throw refuse(
263
263
  named[0] ?? "routing.surfaces.discord",
264
- "names the discord surface, and Discord is not configured",
265
- "Name a surface that hosts rooms instead, or configure discord",
264
+ "names the discord surface, and Discord is not configured or has no discord.guild, so the agents have no Discord channels",
265
+ "Name a surface that hosts rooms instead, or configure discord with its guild",
266
266
  );
267
267
  }
268
268
  return {
@@ -0,0 +1,30 @@
1
+ import { list, optional, shape, text } from "./schema.ts";
2
+
3
+ /**
4
+ * The team's identity in the database, independent of any Discord guild. `id` is what the rows the
5
+ * team keeps (agents, groups, skills, prompts, presets) are stored under; default the id of
6
+ * `discord.guild`, else `"local"`. `formerIds` are the ids the team was stored under before, such
7
+ * as a guild it left: their rows move to `id` at every boot (a row the team already holds stays),
8
+ * and without Discord channels lose the channel ids they carried.
9
+ */
10
+ export interface TeamConfig {
11
+ id?: string;
12
+ formerIds?: string[];
13
+ }
14
+
15
+ /** What the host reads: `id` is left out when the Discord guild or the local team gives it. */
16
+ export interface ResolvedTeam {
17
+ id?: string;
18
+ formerIds: readonly string[];
19
+ }
20
+
21
+ export const teamField = optional(
22
+ shape({ id: optional(text), formerIds: optional(list(text)) }),
23
+ );
24
+
25
+ export function teamOf(team: TeamConfig | undefined): ResolvedTeam {
26
+ return {
27
+ ...(team?.id === undefined ? {} : { id: team.id }),
28
+ formerIds: team?.formerIds ?? [],
29
+ };
30
+ }
@@ -427,6 +427,14 @@ export type MessageObserver = (
427
427
  /** The host's channel queue, as plugins use it. */
428
428
  export interface QueuePort {
429
429
  run<T>(channel: ChannelKey, task: () => Promise<T>): Promise<T>;
430
+ /**
431
+ * Runs `task` as the delivery of work the shutdown drain waits for, such as a coding worker's
432
+ * report: a queue task it starts, and what that task awaits, is admitted although the host is
433
+ * shutting down, `closed` reads false there, and the drain waits for it as for any task. It
434
+ * ends when the drain does; after that the task is refused as any other. Absent on a host that
435
+ * predates it: call `task` directly then.
436
+ */
437
+ finishing?<T>(task: () => Promise<T>): Promise<T>;
430
438
  /** Tasks of the channel running or waiting. */
431
439
  size(channel: ChannelKey): number;
432
440
  /** Channels with a task running or waiting. */
@@ -0,0 +1,103 @@
1
+ import type { Migration } from "./migrations.ts";
2
+
3
+ export interface TeamMoveOptions {
4
+ /** The ids the team was stored under before, such as a Discord guild it no longer lives in. */
5
+ from: readonly string[];
6
+ /** The team's id now. */
7
+ to: string;
8
+ /**
9
+ * The Discord guild the team's channels live in. The channel ids of the rows moved from any other
10
+ * former id are cleared: they name channels of a guild the team left, so start creates new ones.
11
+ */
12
+ discordGuild?: string;
13
+ /**
14
+ * The team has no Discord channels: the channel ids of the rows it moves, and of the rows it
15
+ * already holds, are cleared. Default false.
16
+ */
17
+ clearChannels?: boolean;
18
+ }
19
+
20
+ /** The tables whose rows hold a Discord channel id. */
21
+ const CHANNEL_TABLES = new Set(["agents", "agent_groups"]);
22
+
23
+ /**
24
+ * Moves a former team's rows to the team id: every row of a table with a `guild_id` column whose id
25
+ * is one of `from`, in the tables the host's plugins keep (agents, groups, skills, prompts, presets,
26
+ * outbox, conversations). Rows of other guilds stay, such as the `discord_*` grants and audit of the
27
+ * guilds a bot still serves. A row whose key the team already holds stays where it is (a warning
28
+ * names it), so a second boot changes nothing; of two former ids holding one key, the one listed
29
+ * first moves.
30
+ *
31
+ * It runs at every boot, after the migrations that create the tables and before any setup, so the
32
+ * team's seeds find their agents already moved.
33
+ */
34
+ export function moveTeam(options: TeamMoveOptions): Migration {
35
+ const from = [...new Set(options.from)].filter((id) => id !== options.to);
36
+ return {
37
+ name: "team-move",
38
+ runs: "every-boot",
39
+ up: (sql) =>
40
+ sql.begin(async (tx) => {
41
+ if (from.length === 0 && !options.clearChannels) return;
42
+ const tables: { table: string; key: string[] | null }[] = await tx`
43
+ SELECT c.table_name AS table,
44
+ (SELECT array_agg(a.attname::text ORDER BY a.attnum)
45
+ FROM pg_constraint p
46
+ JOIN pg_attribute a
47
+ ON a.attrelid = p.conrelid AND a.attnum = ANY (p.conkey)
48
+ WHERE p.conrelid = format('%I', c.table_name)::regclass
49
+ AND p.contype = 'p' AND a.attname <> 'guild_id') AS key
50
+ FROM information_schema.columns c
51
+ JOIN information_schema.tables t
52
+ ON t.table_schema = c.table_schema AND t.table_name = c.table_name
53
+ WHERE c.table_schema = current_schema() AND c.column_name = 'guild_id'
54
+ AND t.table_type = 'BASE TABLE' AND c.table_name NOT LIKE 'discord\\_%'
55
+ ORDER BY c.table_name`;
56
+ for (const { table, key } of tables) {
57
+ const channels = CHANNEL_TABLES.has(table);
58
+ if (options.clearChannels && channels)
59
+ await tx.unsafe(
60
+ `UPDATE "${table}" SET channel_id = NULL WHERE guild_id = $1 AND channel_id IS NOT NULL`,
61
+ [options.to],
62
+ );
63
+ const match = (key ?? [])
64
+ .map((column) => `l."${column}" = t."${column}"`)
65
+ .join(" AND ");
66
+ // One former id at a time, in the listed order: the first to hold a key wins, and the
67
+ // later ones find it taken.
68
+ for (const id of from) {
69
+ const taken = match
70
+ ? ` AND NOT EXISTS (SELECT 1 FROM "${table}" l WHERE l.guild_id = $1 AND ${match})`
71
+ : "";
72
+ const clear =
73
+ channels &&
74
+ (options.clearChannels ||
75
+ (options.discordGuild !== undefined &&
76
+ id !== options.discordGuild))
77
+ ? ", channel_id = NULL"
78
+ : "";
79
+ await tx.unsafe(
80
+ `UPDATE "${table}" t SET guild_id = $1${clear} WHERE t.guild_id = $2${taken}`,
81
+ [options.to, id],
82
+ );
83
+ }
84
+ if (!match || from.length === 0) continue;
85
+ const kept: Record<string, unknown>[] = await tx.unsafe(
86
+ `SELECT t.guild_id, ${key?.map((column) => `t."${column}"`).join(", ")} FROM "${table}" t
87
+ WHERE t.guild_id = ANY ($2::text[])
88
+ AND EXISTS (SELECT 1 FROM "${table}" l WHERE l.guild_id = $1 AND ${match})`,
89
+ [options.to, from],
90
+ );
91
+ if (kept.length > 0)
92
+ console.warn(
93
+ `team-move: ${kept.length} row(s) of "${table}" stay under their former id, because team "${options.to}" already holds the same key: ${kept
94
+ .map(
95
+ ({ guild_id, ...rest }) =>
96
+ `${guild_id}/${Object.values(rest).join("/")}`,
97
+ )
98
+ .join(", ")}`,
99
+ );
100
+ }
101
+ }),
102
+ };
103
+ }