pi-roundtable 0.42.0 → 0.44.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 (41) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +1 -0
  3. package/README.zh-TW.md +1 -0
  4. package/docs/plugins.md +3 -1
  5. package/package.json +3 -1
  6. package/src/characters/catalog.ts +7 -750
  7. package/src/characters/class-data.ts +56 -0
  8. package/src/characters/classes-a.ts +235 -0
  9. package/src/characters/classes-b.ts +242 -0
  10. package/src/characters/classes-c.ts +241 -0
  11. package/src/core/agents/agent-claim.ts +6 -2
  12. package/src/core/agents/agent-group-store.ts +176 -0
  13. package/src/core/agents/agent-places.ts +197 -0
  14. package/src/core/agents/agent-schema.ts +37 -3
  15. package/src/core/agents/agent-statements.ts +14 -12
  16. package/src/core/agents/agent-store.ts +81 -211
  17. package/src/core/agents/agent-team-fixture.ts +9 -3
  18. package/src/core/agents/agent-team.ts +6 -8
  19. package/src/core/agents/routes.ts +24 -7
  20. package/src/core/agents/team-options.ts +2 -0
  21. package/src/core/builtin/agent-server-options.ts +101 -0
  22. package/src/core/builtin/agent-server.ts +35 -94
  23. package/src/core/config/config-schema.ts +3 -1
  24. package/src/core/config/config.ts +5 -0
  25. package/src/core/config/team.ts +30 -0
  26. package/src/core/contract/channels.ts +8 -0
  27. package/src/core/db/legacy-channels.ts +92 -0
  28. package/src/core/db/team-move.ts +138 -0
  29. package/src/core/host/define-roundtable.ts +10 -2
  30. package/src/core/host/drain.ts +46 -0
  31. package/src/core/host/host.ts +25 -8
  32. package/src/core/plugin-api/plugin.ts +6 -3
  33. package/src/core/plugin-api/services.ts +4 -5
  34. package/src/core/presentation/diagram-text.ts +17 -8
  35. package/src/core/routing/channel-queue.ts +36 -3
  36. package/src/core/testing/fake-discord.ts +67 -0
  37. package/src/core/testing/partial.ts +8 -0
  38. package/src/core/testing/plugin-stand-ins.ts +95 -0
  39. package/src/core/testing/service-pair.ts +18 -0
  40. package/src/core/testing/test-plugin-types.ts +110 -0
  41. package/src/testing.ts +36 -276
@@ -0,0 +1,101 @@
1
+ import type { ModelRuntime } from "@earendil-works/pi-coding-agent";
2
+ import type { ResolvedHelpers } from "../config/helpers.ts";
3
+ import type { ResolvedRouting } from "../config/routing.ts";
4
+ import type { ModelRef } from "../domain/models.ts";
5
+ import type { OwnerIdentity } from "../identity/owner-identity.ts";
6
+ import type { ErrorReporter } from "../ops/error-reporter.ts";
7
+ import type { AgentSessionsSlot } from "../runtime/runtime-plugin.ts";
8
+
9
+ /**
10
+ * The id of a team that has no id of its own and no Discord guild: the rows the team keeps are
11
+ * stored under it.
12
+ */
13
+ export const LOCAL_TEAM_ID = "local";
14
+
15
+ export interface AgentServerOptions {
16
+ /**
17
+ * The Discord guild the team's channels live in. Absent on a host without Discord, or whose bot
18
+ * has no agent guild: the team has no channels, and its agents live in the rooms of the
19
+ * surfaces that host them. Without `teamId` the team is stored under the guild's id.
20
+ */
21
+ guildId?: string;
22
+ /**
23
+ * The id the team's rows are stored under, independent of the guild; default `guildId`, else
24
+ * `LOCAL_TEAM_ID`.
25
+ */
26
+ teamId?: string;
27
+ /**
28
+ * The ids the team was stored under before, such as a guild it no longer lives in: their rows
29
+ * move to `teamId` at every boot (`moveTeam`), and, without Discord channels, lose the channel
30
+ * ids they carried.
31
+ */
32
+ formerTeamIds?: readonly string[];
33
+ /** The channel the coordinator lives in; set with `guildId`, never with `coordinator`. */
34
+ entryChannelId?: string;
35
+ /**
36
+ * The coordinator's name on a host without Discord, where no entry channel names it; the first
37
+ * seed when absent. Refused with `entryChannelId`.
38
+ */
39
+ coordinator?: string;
40
+ owner: OwnerIdentity & { id: string };
41
+ /** The assistant's display name, as the confirmation judge names it. */
42
+ assistant: string;
43
+ /** Shared with the rest of the host, so logins refresh in one place; lists the models an agent may run. */
44
+ modelRuntime: ModelRuntime;
45
+ dataDir: string;
46
+ /** The model of agents and of the assistant. */
47
+ model: ModelRef;
48
+ /** How sure the confirmation judge must be before its answer is used. */
49
+ judgeThreshold: number;
50
+ /** Where the agent server hands the runtime plugin its per-agent settings. */
51
+ agents?: AgentSessionsSlot;
52
+ /** The shell's shared working directory. */
53
+ workDir: string;
54
+ /**
55
+ * The agents' scratch dir, created with mode 0700 when the agent server starts: their shell's
56
+ * TMPDIR, where writes and removals run without a hold.
57
+ */
58
+ scratchDir?: string;
59
+ /** The host account the agents' shell and file tools run as. */
60
+ shellUser: string;
61
+ /**
62
+ * Whose turns in the agents' channels load memory: `"everyone"` (the default) or `"owners"`;
63
+ * see `AgentSessions.memory`.
64
+ */
65
+ memory?: "everyone" | "owners";
66
+ /**
67
+ * Who the agents answer in their channels and groups' channels: `"everyone"` (the default) or
68
+ * `"owners"`, which leaves a speaker below the owner tier unanswered.
69
+ */
70
+ speakers?: "everyone" | "owners";
71
+ /**
72
+ * Limits of the downloads of a message's files (`discord.attachmentDownload`): `deadlineMs`
73
+ * for all of a message's files together (default 60 s), `idleMs` for one file to send no byte
74
+ * (default 10 s).
75
+ */
76
+ attachmentDownload?: { deadlineMs?: number; idleMs?: number };
77
+ /** The prompt every agent starts with, and the one for speakers other than the owner. */
78
+ prompts: { shared: string; guest?: string };
79
+ /** The listener the avatar pictures are served on; none mounts no route, and a surface serves them through `AGENTS.avatars.serve`. */
80
+ avatarListener?: string;
81
+ /**
82
+ * The origin the agents' pictures are served from. Without one a picture's URL is
83
+ * `/avatars/<hash>.png`, which the surface that serves the pictures resolves against its origin.
84
+ */
85
+ avatarUrl?: string;
86
+ /**
87
+ * Render every agent's picture again at start (`characters.refreshAvatars`) and set it where
88
+ * its hash differs from the stored one; default false.
89
+ */
90
+ refreshAvatars?: boolean;
91
+ /** The assistant's neutral avatar: the style reference and the picture of an agent without one. */
92
+ avatarReference: string;
93
+ /** The picture used instead when `avatarReference` cannot be read as one; the failure is logged. */
94
+ avatarNeutral?: string;
95
+ /** Reports the process's own errors to an agent; without one nothing is reported. */
96
+ errorReporter?: ErrorReporter;
97
+ /** The checked `routing` block: where work no person started lands. Without it every place is what it was before `routing`. */
98
+ routing?: ResolvedRouting;
99
+ /** The temp knights' limits; `false` leaves `helper_create` and `helper_end` out. Without it the defaults apply. */
100
+ helpers?: ResolvedHelpers | false;
101
+ }
@@ -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,17 @@ 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 { LEGACY_CHANNEL_SURFACE } from "../db/legacy-channels.ts";
18
+ import { moveTeam } from "../db/team-move.ts";
20
19
  import type { ChannelKey } from "../domain/conversation.ts";
21
20
  import { ConfigError } from "../domain/errors.ts";
22
- import {
23
- AUTO_THINKING,
24
- formatModelRef,
25
- type ModelRef,
26
- } from "../domain/models.ts";
21
+ import { AUTO_THINKING, formatModelRef } from "../domain/models.ts";
27
22
  import type { SessionTool } from "../domain/sessions.ts";
28
- import type { OwnerIdentity } from "../identity/owner-identity.ts";
29
23
  import type { Tier } from "../identity/speakers.ts";
30
24
  import { ConfirmationJudge } from "../judging/confirmation-judge.ts";
31
25
  import type { Logger } from "../kernel/log.ts";
32
- import type { ErrorReporter } from "../ops/error-reporter.ts";
33
26
  import type { PluginContext, RoundtablePlugin } from "../plugin-api/plugin.ts";
34
27
  import {
35
28
  AGENTS,
@@ -43,92 +36,18 @@ import {
43
36
  } from "../plugin-api/services.ts";
44
37
  import { splitReply } from "../presentation/reply-splitter.ts";
45
38
  import { agentPromptExtension } from "../runtime/extensions/agent-prompt.ts";
46
- import type { AgentSessionsSlot } from "../runtime/runtime-plugin.ts";
47
39
  import { DISCORD } from "./discord.ts";
48
40
  import { agentOnly } from "./session-tool.ts";
49
41
 
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";
42
+ export {
43
+ type AgentServerOptions,
44
+ LOCAL_TEAM_ID,
45
+ } from "./agent-server-options.ts";
55
46
 
56
- export interface AgentServerOptions {
57
- /**
58
- * The Discord guild the team lives in. Absent on a host without Discord, or whose bot has no
59
- * agent guild: the team is then `LOCAL_TEAM_ID`, it has no channels, and its agents live in the
60
- * rooms of the surfaces that 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
- }
47
+ import {
48
+ type AgentServerOptions,
49
+ LOCAL_TEAM_ID,
50
+ } from "./agent-server-options.ts";
132
51
 
133
52
  /** The name of the agent server's plugin, as `serviceStarted` events name it. */
134
53
  export const AGENT_SERVER_PLUGIN = "agent-server";
@@ -201,7 +120,7 @@ export function agentServerPlugin(
201
120
  throw new ConfigError(
202
121
  "the agent server: entryChannelId and coordinator both name the coordinator. Set the entry channel with Discord, the coordinator without it.",
203
122
  );
204
- const teamId = options.guildId ?? LOCAL_TEAM_ID;
123
+ const teamId = options.teamId ?? options.guildId ?? LOCAL_TEAM_ID;
205
124
  /** Set once the plugin has set up; the preflight reads it after every plugin linked. */
206
125
  let hostsRooms: (() => boolean) | undefined;
207
126
  let linkRoutes: (() => void) | undefined;
@@ -209,7 +128,26 @@ export function agentServerPlugin(
209
128
  name: AGENT_SERVER_PLUGIN,
210
129
  // The agent server's own tables; the host runs them before any setup, in this order. The
211
130
  // held actions' table is the runtime plugin's.
212
- migrations: PgAgentStore.migrations(teamId),
131
+ migrations: [
132
+ ...PgAgentStore.migrations(teamId),
133
+ // After the agents' tables, and the prompts', skills' and conversations' before it.
134
+ moveTeam({
135
+ from: options.formerTeamIds ?? [],
136
+ to: teamId,
137
+ ...(options.guildId === undefined
138
+ ? { clearChannels: true }
139
+ : { discordGuild: options.guildId }),
140
+ // The legacy channels' places follow their columns: kept in the agent guild, dropped elsewhere.
141
+ places: [
142
+ {
143
+ surface: LEGACY_CHANNEL_SURFACE,
144
+ ...(options.guildId === undefined ? {} : { keep: options.guildId }),
145
+ },
146
+ ],
147
+ }),
148
+ // After the move, so the rows it brought in with their channel ids get their places at this boot.
149
+ PgAgentStore.placesConvergence(teamId),
150
+ ],
213
151
  provides: [AGENTS],
214
152
  requires: [RUNTIME],
215
153
  // A team with no Discord channels is reached through rooms only; without a surface that
@@ -292,6 +230,7 @@ export function agentServerPlugin(
292
230
  store,
293
231
  roomSurfaces: () => surfaces.roomSurfaces(),
294
232
  latest: (agent) => store.conversations.latest(agent),
233
+ discordChannels: channels !== undefined,
295
234
  logger,
296
235
  });
297
236
  // The surfaces the rules name are registered by the time every plugin has set up.
@@ -303,6 +242,7 @@ export function agentServerPlugin(
303
242
  const built: DiscordAgentTeam = new DiscordAgentTeam({
304
243
  routes,
305
244
  guildId: teamId,
245
+ discordGuild: options.guildId,
306
246
  ...(options.entryChannelId !== undefined
307
247
  ? { entryChannelId: options.entryChannelId }
308
248
  : {}),
@@ -447,6 +387,7 @@ export function agentServerPlugin(
447
387
  channels: [
448
388
  agentClaim({
449
389
  owner: options.owner,
390
+ discordGuild: options.guildId,
450
391
  ...(options.speakers ? { speakers: options.speakers } : {}),
451
392
  team: built,
452
393
  runtime: running,
@@ -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)),
@@ -48,6 +48,7 @@ import {
48
48
  routingOf,
49
49
  } from "./routing.ts";
50
50
  import type { SkillsConfig } from "./skills-config.ts";
51
+ import { type ResolvedTeam, type TeamConfig, teamOf } from "./team.ts";
51
52
 
52
53
  export type { DiscordConfig };
53
54
 
@@ -177,6 +178,8 @@ export interface RoundtableConfig extends LimitsConfig, ShellEnvConfig {
177
178
  * the first. With `discord.guild` the agent in `discord.entryChannel` is the coordinator, and this key is refused.
178
179
  */
179
180
  coordinator?: string;
181
+ /** Where the team's rows are stored, and the ids they moved from; see `TeamConfig`. */
182
+ team?: TeamConfig;
180
183
  /**
181
184
  * How the agents' characters are drawn, everywhere the host draws them: the web console, its
182
185
  * round table and the agents' pictures on Discord. `skins` is exactly six `#rrggbb` skin tones
@@ -324,6 +327,7 @@ export interface ResolvedConfig extends ResolvedLimits {
324
327
  agents: AgentSeed[];
325
328
  /** The coordinator's name; set only without `discord.guild` and with `agents`: the configured one, else the first seed. */
326
329
  coordinator?: string;
330
+ team: ResolvedTeam;
327
331
  /** How the agents' characters are drawn: the six skin tones, the package's own unless `characters.skins` is set. */
328
332
  characters: { skins: readonly Hex[]; refreshAvatars: boolean };
329
333
  /** Undefined when no `http` is configured, and the host opens no `public` listener. */
@@ -456,6 +460,7 @@ export function resolveConfig(input: unknown): ResolvedConfig {
456
460
  ...(!agentGuild && config.agents?.[0]
457
461
  ? { coordinator: config.coordinator ?? config.agents[0].name }
458
462
  : {}),
463
+ team: teamOf(config.team),
459
464
  characters: {
460
465
  skins: skinsOf(config.characters?.skins),
461
466
  refreshAvatars: config.characters?.refreshAvatars ?? false,
@@ -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,92 @@
1
+ import type { SQL } from "bun";
2
+
3
+ /**
4
+ * The surface whose places `agents.channel_id` and `agent_groups.channel_id` hold: those columns
5
+ * always kept a Discord channel or thread id. Named here once, outside the team directories, so the
6
+ * team code stays free of it. Until 1.0 the store writes the columns and the `agent_places` rows of
7
+ * this surface together, and every boot makes the rows equal the columns again.
8
+ */
9
+ export const LEGACY_CHANNEL_SURFACE = "discord";
10
+
11
+ /** The tables whose `channel_id` column is a legacy channel, and the kind of place owner each row is. */
12
+ export const LEGACY_CHANNEL_TABLES = {
13
+ agents: "agent",
14
+ agent_groups: "group",
15
+ } as const;
16
+
17
+ /** Serializes concurrent boots of the convergence; the key of the ledger's lock for this id. */
18
+ const LOCK = "pi-roundtable:migration:agent-server/agent-places-from-channels";
19
+
20
+ interface WantedPlace {
21
+ kind: string;
22
+ name: string;
23
+ external_id: string;
24
+ }
25
+
26
+ /**
27
+ * The warning for an owner whose channel id another owner of its team holds already: a place id
28
+ * belongs to one owner, so no place row is made for the second, and its column stays as it is.
29
+ */
30
+ export function warnSharedChannel(
31
+ team: string,
32
+ owner: { kind: string; name: string },
33
+ channelId: string,
34
+ holder: { kind: string; name: string } | undefined,
35
+ ): void {
36
+ console.warn(
37
+ `agent-places: ${owner.kind} "${owner.name}" of team "${team}" holds channel ${channelId}, which ${holder?.kind} "${holder?.name}" holds already; no place row is made for it`,
38
+ );
39
+ }
40
+
41
+ /**
42
+ * Makes the legacy-surface rows of `agent_places` of one team equal the legacy columns of that
43
+ * team: inserts each non-null `channel_id` as `(team, kind, name, surface, channel_id)`, and
44
+ * deletes a row whose column is now null or different, as after a rollback to a build that wrote
45
+ * only the columns. It reads and writes the rows of `teamId` only, so hosts of several teams over
46
+ * one database never delete each other's rows, and a record that stays under a former id, which
47
+ * `moveTeam` could not move, gets no row. Idempotent, in one transaction under an advisory lock. A
48
+ * channel id that two owners of the team hold stays with the owner that has the row already, or
49
+ * else with the first by kind then name, and the other is skipped with a warning naming both.
50
+ */
51
+ export function convergeLegacyChannelPlaces(
52
+ teamId: string,
53
+ ): (sql: SQL) => Promise<void> {
54
+ const wanted = Object.entries(LEGACY_CHANNEL_TABLES)
55
+ .map(
56
+ ([table, kind]) =>
57
+ `SELECT '${kind}' AS kind, name, channel_id AS external_id FROM ${table} WHERE guild_id = $2 AND channel_id IS NOT NULL`,
58
+ )
59
+ .join(" UNION ALL ");
60
+ return (sql) =>
61
+ sql.begin(async (tx) => {
62
+ await tx`SELECT pg_advisory_xact_lock(hashtextextended(${LOCK}, 0))`;
63
+ await tx.unsafe(
64
+ `DELETE FROM agent_places p
65
+ WHERE p.surface = $1 AND p.team_id = $2 AND NOT EXISTS (
66
+ SELECT 1 FROM (${wanted}) w
67
+ WHERE w.kind = p.kind AND w.name = p.name AND w.external_id = p.external_id)`,
68
+ [LEGACY_CHANNEL_SURFACE, teamId],
69
+ );
70
+ const missing: WantedPlace[] = await tx.unsafe(
71
+ `SELECT w.kind, w.name, w.external_id FROM (${wanted}) w
72
+ WHERE NOT EXISTS (
73
+ SELECT 1 FROM agent_places p
74
+ WHERE p.surface = $1 AND p.team_id = $2 AND p.kind = w.kind AND p.name = w.name)
75
+ ORDER BY w.kind, w.name`,
76
+ [LEGACY_CHANNEL_SURFACE, teamId],
77
+ );
78
+ for (const place of missing) {
79
+ const inserted = await tx`
80
+ INSERT INTO agent_places (team_id, kind, name, surface, external_id)
81
+ VALUES (${teamId}, ${place.kind}, ${place.name}, ${LEGACY_CHANNEL_SURFACE}, ${place.external_id})
82
+ ON CONFLICT DO NOTHING
83
+ RETURNING 1`;
84
+ if (inserted.length > 0) continue;
85
+ const [holder]: { kind: string; name: string }[] = await tx`
86
+ SELECT kind, name FROM agent_places
87
+ WHERE team_id = ${teamId} AND surface = ${LEGACY_CHANNEL_SURFACE}
88
+ AND external_id = ${place.external_id}`;
89
+ warnSharedChannel(teamId, place, place.external_id, holder);
90
+ }
91
+ });
92
+ }
@@ -0,0 +1,138 @@
1
+ import { LEGACY_CHANNEL_TABLES } from "./legacy-channels.ts";
2
+ import type { Migration } from "./migrations.ts";
3
+
4
+ export interface TeamMoveOptions {
5
+ /** The ids the team was stored under before, such as a Discord guild it no longer lives in. */
6
+ from: readonly string[];
7
+ /** The team's id now. */
8
+ to: string;
9
+ /**
10
+ * The Discord guild the team's channels live in. The channel ids of the rows moved from any other
11
+ * former id are cleared: they name channels of a guild the team left, so start creates new ones.
12
+ */
13
+ discordGuild?: string;
14
+ /**
15
+ * The team has no Discord channels: the channel ids of the rows it moves, and of the rows it
16
+ * already holds, are cleared. Default false.
17
+ */
18
+ clearChannels?: boolean;
19
+ /**
20
+ * The surfaces whose stored places name something of the space the team lived in, such as the
21
+ * channels of a Discord guild. A place row moved from a former id other than `keep` is dropped, as
22
+ * the legacy channel ids are cleared, so start makes new places; without `keep` every moved row
23
+ * is dropped. With `clearChannels` the team's own rows of these surfaces go too.
24
+ */
25
+ places?: readonly { surface: string; keep?: string }[];
26
+ }
27
+
28
+ /** The tables whose rows hold a legacy channel id. */
29
+ const CHANNEL_TABLES = new Set(Object.keys(LEGACY_CHANNEL_TABLES));
30
+
31
+ /** The table of stored places: its second unique key is a place id, which no two owners of a team share. */
32
+ const PLACES_TABLE = "agent_places";
33
+
34
+ /**
35
+ * Moves a former team's rows to the team id: every row of a table with a `guild_id` (or, for places, `team_id`) column whose id
36
+ * is one of `from`, in the tables the host's plugins keep (agents, groups, skills, prompts, presets,
37
+ * outbox, conversations, places). Rows of other guilds stay, such as the `discord_*` grants and audit of the
38
+ * guilds a bot still serves. A row whose key, or for places whose id, the team already holds stays where it is (a warning
39
+ * names it), so a second boot changes nothing; of two former ids holding one key, the one listed
40
+ * first moves.
41
+ *
42
+ * It runs at every boot, after the migrations that create the tables and before any setup, so the
43
+ * team's seeds find their agents already moved.
44
+ */
45
+ export function moveTeam(options: TeamMoveOptions): Migration {
46
+ const from = [...new Set(options.from)].filter((id) => id !== options.to);
47
+ return {
48
+ name: "team-move",
49
+ runs: "every-boot",
50
+ up: (sql) =>
51
+ sql.begin(async (tx) => {
52
+ if (from.length === 0 && !options.clearChannels) return;
53
+ const tables: { table: string; scope: string; key: string[] | null }[] =
54
+ await tx`
55
+ SELECT c.table_name AS table, c.column_name AS scope,
56
+ (SELECT array_agg(a.attname::text ORDER BY a.attnum)
57
+ FROM pg_constraint p
58
+ JOIN pg_attribute a
59
+ ON a.attrelid = p.conrelid AND a.attnum = ANY (p.conkey)
60
+ WHERE p.conrelid = format('%I', c.table_name)::regclass
61
+ AND p.contype = 'p' AND a.attname <> c.column_name) AS key
62
+ FROM information_schema.columns c
63
+ JOIN information_schema.tables t
64
+ ON t.table_schema = c.table_schema AND t.table_name = c.table_name
65
+ WHERE c.table_schema = current_schema()
66
+ AND c.column_name IN ('guild_id', 'team_id')
67
+ AND t.table_type = 'BASE TABLE' AND c.table_name NOT LIKE 'discord\\_%'
68
+ ORDER BY c.table_name`;
69
+ for (const { table, scope, key } of tables) {
70
+ const channels = CHANNEL_TABLES.has(table);
71
+ if (options.clearChannels && channels)
72
+ await tx.unsafe(
73
+ `UPDATE "${table}" SET channel_id = NULL WHERE ${scope} = $1 AND channel_id IS NOT NULL`,
74
+ [options.to],
75
+ );
76
+ if (table === PLACES_TABLE)
77
+ for (const { surface, keep } of options.places ?? []) {
78
+ if (options.clearChannels)
79
+ await tx.unsafe(
80
+ `DELETE FROM "${table}" WHERE ${scope} = $1 AND surface = $2`,
81
+ [options.to, surface],
82
+ );
83
+ // The places of a former id whose space is not the team's now name nothing it can reach.
84
+ await tx.unsafe(
85
+ `DELETE FROM "${table}" WHERE ${scope} = ANY ($1::text[]) AND surface = $2 AND ${scope} IS DISTINCT FROM $3::text`,
86
+ [from, surface, keep ?? null],
87
+ );
88
+ }
89
+ const match = (key ?? [])
90
+ .map((column) => `l."${column}" = t."${column}"`)
91
+ .join(" AND ");
92
+ // One former id at a time, in the listed order: the first to hold a key wins, and the
93
+ // later ones find it taken.
94
+ for (const id of from) {
95
+ const same =
96
+ table === PLACES_TABLE
97
+ ? ` AND NOT EXISTS (SELECT 1 FROM "${table}" l WHERE l.${scope} = $1 AND l.surface = t.surface AND l.external_id = t.external_id)`
98
+ : "";
99
+ const taken = match
100
+ ? ` AND NOT EXISTS (SELECT 1 FROM "${table}" l WHERE l.${scope} = $1 AND ${match})${same}`
101
+ : same;
102
+ const clear =
103
+ channels &&
104
+ (options.clearChannels ||
105
+ (options.discordGuild !== undefined &&
106
+ id !== options.discordGuild))
107
+ ? ", channel_id = NULL"
108
+ : "";
109
+ await tx.unsafe(
110
+ `UPDATE "${table}" t SET ${scope} = $1${clear} WHERE t.${scope} = $2${taken}`,
111
+ [options.to, id],
112
+ );
113
+ }
114
+ if (!match || from.length === 0) continue;
115
+ // A place also stays when the team holds its id on the surface, which the key does not show.
116
+ const sameId =
117
+ table === PLACES_TABLE
118
+ ? ` OR EXISTS (SELECT 1 FROM "${table}" l WHERE l.${scope} = $1 AND l.surface = t.surface AND l.external_id = t.external_id)`
119
+ : "";
120
+ const kept: Record<string, unknown>[] = await tx.unsafe(
121
+ `SELECT t.${scope} AS moved_from, ${key?.map((column) => `t."${column}"`).join(", ")} FROM "${table}" t
122
+ WHERE t.${scope} = ANY ($2::text[])
123
+ AND (EXISTS (SELECT 1 FROM "${table}" l WHERE l.${scope} = $1 AND ${match})${sameId})`,
124
+ [options.to, from],
125
+ );
126
+ if (kept.length > 0)
127
+ console.warn(
128
+ `team-move: ${kept.length} row(s) of "${table}" stay under their former id, because team "${options.to}" already holds the same ${sameId ? "key or place id" : "key"}: ${kept
129
+ .map(
130
+ ({ moved_from, ...rest }) =>
131
+ `${moved_from}/${Object.values(rest).join("/")}`,
132
+ )
133
+ .join(", ")}`,
134
+ );
135
+ }
136
+ }),
137
+ };
138
+ }
@@ -173,6 +173,11 @@ function discordAssembly(
173
173
  };
174
174
  }
175
175
 
176
+ /** The id the team's rows are stored under: the configured one, else the agent guild's, else `local`. */
177
+ function teamIdOf(config: ResolvedConfig): string {
178
+ return config.team.id ?? config.discord?.guild ?? LOCAL_TEAM_ID;
179
+ }
180
+
176
181
  /**
177
182
  * The agent server and what only it uses, each in its place in the plugin list: the skills addon
178
183
  * and the seed agents. Its team lives in the Discord guild `discord.guild` names when there is one,
@@ -195,6 +200,7 @@ function agentAssembly(
195
200
  ): AgentAssembly {
196
201
  const { name, discord } = config;
197
202
  const owner = discordOwnerOf(config);
203
+ const teamId = teamIdOf(config);
198
204
  const sharedPrompt = config.prompts.shared
199
205
  ? readPrompt(config.prompts.shared, "prompts.shared")
200
206
  : readPrompt(join(ASSETS, "prompts", "shared.md"), "prompts.shared");
@@ -206,7 +212,7 @@ function agentAssembly(
206
212
  skills: config.skills
207
213
  ? [
208
214
  skillsPlugin({
209
- guildId: discord?.guild ?? LOCAL_TEAM_ID,
215
+ guildId: teamId,
210
216
  reposDir: config.skills.reposDir ?? join(config.dataDir, "repos"),
211
217
  writtenDir: join(config.dataDir, "skills"),
212
218
  builtinDir: config.skills.builtinDir ?? join(ASSETS, "skills"),
@@ -215,6 +221,8 @@ function agentAssembly(
215
221
  ]
216
222
  : [],
217
223
  agentServer: agentServerPlugin({
224
+ teamId,
225
+ formerTeamIds: config.team.formerIds,
218
226
  // Without the agent guild the team lives in the app's rooms, as on a host without Discord.
219
227
  ...(discord?.guild
220
228
  ? {
@@ -358,7 +366,7 @@ export async function defineRoundtable(
358
366
  scheduleStorePlugin(),
359
367
  precheckPlugin(),
360
368
  // Before the agent server and the operator's plugins, which register the texts the owner edits.
361
- promptsPlugin({ guildId: discord?.guild ?? LOCAL_TEAM_ID }),
369
+ promptsPlugin({ guildId: teamIdOf(config) }),
362
370
  // Before Discord, whose services hand out its instance, and the modules and agent server that use it.
363
371
  threadsPlugin({ dataDir: config.dataDir }),
364
372
  channelContextPlugin(),