pi-roundtable 0.45.1 → 0.46.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 (70) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/docs/plugins.md +32 -7
  3. package/package.json +1 -1
  4. package/src/characters/compose.ts +7 -3
  5. package/src/characters/index.ts +1 -0
  6. package/src/characters/parts-face.ts +4 -1
  7. package/src/core/agents/agent-claim.ts +2 -2
  8. package/src/core/agents/agent-group-store.ts +74 -1
  9. package/src/core/agents/agent-places.ts +32 -0
  10. package/src/core/agents/agent-ports.ts +0 -94
  11. package/src/core/agents/agent-prompt.ts +3 -1
  12. package/src/core/agents/agent-team-fixture.ts +48 -7
  13. package/src/core/agents/agent-team.ts +54 -59
  14. package/src/core/agents/agent-tools.ts +34 -166
  15. package/src/core/agents/message-target.ts +3 -2
  16. package/src/core/agents/routes.ts +2 -1
  17. package/src/core/agents/team-editing.ts +121 -150
  18. package/src/core/agents/team-helpers.ts +80 -59
  19. package/src/core/agents/team-keys.ts +16 -26
  20. package/src/core/agents/team-lifecycle.ts +155 -99
  21. package/src/core/agents/team-looks.ts +102 -0
  22. package/src/core/agents/team-options.ts +12 -11
  23. package/src/core/agents/team-place-writes.ts +193 -0
  24. package/src/core/agents/team-places.ts +30 -0
  25. package/src/core/agents/team-posts.ts +42 -73
  26. package/src/core/agents/team-selection.ts +10 -2
  27. package/src/core/agents/team-status.ts +3 -2
  28. package/src/core/agents/team-text.ts +13 -46
  29. package/src/core/agents/team-turn-types.ts +11 -16
  30. package/src/core/agents/team-turns.ts +7 -6
  31. package/src/core/builtin/agent-server-options.ts +27 -6
  32. package/src/core/builtin/agent-server.ts +65 -69
  33. package/src/core/builtin/discord.ts +58 -8
  34. package/src/core/builtin/modules.ts +2 -0
  35. package/src/core/contract/agent-channels.ts +97 -0
  36. package/src/core/contract/channels.ts +10 -4
  37. package/src/core/contract/discord-key.ts +15 -0
  38. package/src/core/contract/places.ts +8 -2
  39. package/src/core/db/legacy-channels.ts +31 -0
  40. package/src/core/discord/agent-dashboard-service.ts +55 -0
  41. package/src/core/{agents → discord}/agent-dashboard.ts +7 -2
  42. package/src/core/discord/agent-discord.ts +1 -1
  43. package/src/core/discord/agent-guild.ts +87 -0
  44. package/src/core/{agents/team-layout.ts → discord/agent-layout.ts} +9 -29
  45. package/src/core/discord/agent-places.ts +52 -33
  46. package/src/core/discord/agent-tools.ts +210 -0
  47. package/src/core/discord/connection.ts +4 -1
  48. package/src/core/discord/discord-surface.ts +9 -14
  49. package/src/core/discord/place-fake-client.ts +59 -0
  50. package/src/core/host/define-roundtable.ts +7 -5
  51. package/src/core/modules/delegation/delegator.ts +5 -0
  52. package/src/core/plugin-api/agent-ops.ts +123 -0
  53. package/src/core/plugin-api/agent-server-ids.ts +9 -0
  54. package/src/core/plugin-api/define.ts +9 -0
  55. package/src/core/plugin-api/plugin.ts +2 -0
  56. package/src/core/plugin-api/services.ts +6 -0
  57. package/src/core/registry/contributions.ts +3 -0
  58. package/src/core/routing/channel-queue.ts +28 -12
  59. package/src/core/runtime/pi-agent-runtime.ts +1 -1
  60. package/src/core/runtime/runtime-plugin.ts +1 -0
  61. package/src/core/runtime/runtime-types.ts +6 -0
  62. package/src/core/{agents/agent-team-fake-channels.ts → testing/fake-agent-channels.ts} +5 -1
  63. package/src/core/testing/fake-pager-places.ts +16 -2
  64. package/src/core/testing/modules.ts +2 -1
  65. package/src/core/testing/place-contract.ts +3 -2
  66. package/src/core/testing/team-places.ts +75 -7
  67. package/src/core/testing/test-host.ts +20 -16
  68. package/src/discord/index.ts +5 -0
  69. package/src/kit/channels.ts +1 -2
  70. package/src/kit/support.ts +9 -5
@@ -4,6 +4,8 @@ import type { ResolvedRouting } from "../config/routing.ts";
4
4
  import type { ModelRef } from "../domain/models.ts";
5
5
  import type { OwnerIdentity } from "../identity/owner-identity.ts";
6
6
  import type { ErrorReporter } from "../ops/error-reporter.ts";
7
+ import type { FormerChannelOps } from "../plugin-api/agent-ops.ts";
8
+ import type { PluginContext } from "../plugin-api/plugin.ts";
7
9
  import type { AgentSessionsSlot } from "../runtime/runtime-plugin.ts";
8
10
 
9
11
  /**
@@ -14,9 +16,16 @@ export const LOCAL_TEAM_ID = "local";
14
16
 
15
17
  export interface AgentServerOptions {
16
18
  /**
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.
19
+ * The spaces whose stored places the team lives in, by surface, such as a Discord guild: the
20
+ * rows moved from a former team id keep their places only in these, and a host with none has
21
+ * its agents in the rooms of the surfaces that host them. Each surface's place provider must be
22
+ * contributed by a plugin, or the host refuses to start.
23
+ */
24
+ placeSpaces?: readonly { surface: string; space: string }[];
25
+ /**
26
+ * @deprecated The Discord guild the team's channels live in: give it as a `placeSpaces` entry
27
+ * of the legacy channel surface, and the Discord plugin the entry channel. Without `teamId` the
28
+ * team is stored under it. Removed in 1.0.
20
29
  */
21
30
  guildId?: string;
22
31
  /**
@@ -30,11 +39,15 @@ export interface AgentServerOptions {
30
39
  * ids they carried.
31
40
  */
32
41
  formerTeamIds?: readonly string[];
33
- /** The channel the coordinator lives in; set with `guildId`, never with `coordinator`. */
42
+ /**
43
+ * @deprecated The channel the coordinator lives in, a Discord channel of `guildId`: the Discord
44
+ * plugin's `entryChannel` gives it through its place provider. Never set with `coordinator`.
45
+ * Removed in 1.0.
46
+ */
34
47
  entryChannelId?: string;
35
48
  /**
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`.
49
+ * The coordinator's name on a host where no place provider names one (Discord's entry channel);
50
+ * the first seed when absent. Refused with `entryChannelId`.
38
51
  */
39
52
  coordinator?: string;
40
53
  owner: OwnerIdentity & { id: string };
@@ -98,4 +111,12 @@ export interface AgentServerOptions {
98
111
  routing?: ResolvedRouting;
99
112
  /** The temp knights' limits; `false` leaves `helper_create` and `helper_end` out. Without it the defaults apply. */
100
113
  helpers?: ResolvedHelpers | false;
114
+ /**
115
+ * @deprecated What `AgentOps.arrange` and `AgentOps.read` run while they stay: the side of the
116
+ * surface whose own tools took their place, read at each call from the host's services.
117
+ * Without it, or when it answers undefined, the two refuse. Removed in 1.0.
118
+ */
119
+ formerChannelOps?: (
120
+ context: Pick<PluginContext, "services" | "logger">,
121
+ ) => FormerChannelOps | undefined;
101
122
  }
@@ -2,19 +2,18 @@ import { chmodSync, lstatSync, mkdirSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import type { SQL } from "bun";
4
4
  import { agentClaim } from "../agents/agent-claim.ts";
5
- import { AgentDashboard } from "../agents/agent-dashboard.ts";
6
5
  import { PgAgentStore } from "../agents/agent-store.ts";
7
- import { DiscordAgentTeam } from "../agents/agent-team.ts";
6
+ import { AgentServerTeam } from "../agents/agent-team.ts";
8
7
  import { AGENT_TOOLS } from "../agents/agent-tools.ts";
9
8
  import { FileAvatarStudio } from "../agents/avatar-studio.ts";
10
9
  import { RelevanceScorer } from "../agents/group-round.ts";
11
10
  import { modeOrigins } from "../agents/helper-modes.ts";
12
11
  import { Routes } from "../agents/routes.ts";
13
- import { discordKey } from "../agents/team-keys.ts";
14
12
  import { TeamPlaces } from "../agents/team-places.ts";
15
13
  import { ownerAttachmentDir } from "../attachments/attachment-dir.ts";
16
14
  import { ROOM_LAYOUT } from "../contract/room-layout.ts";
17
15
  import type { AgentSessions } from "../contract/runtime.ts";
16
+ import { channelKey } from "../contract/surface.ts";
18
17
  import { LEGACY_CHANNEL_SURFACE } from "../db/legacy-channels.ts";
19
18
  import { moveTeam } from "../db/team-move.ts";
20
19
  import type { ChannelKey } from "../domain/conversation.ts";
@@ -24,10 +23,15 @@ import type { SessionTool } from "../domain/sessions.ts";
24
23
  import type { Tier } from "../identity/speakers.ts";
25
24
  import { ConfirmationJudge } from "../judging/confirmation-judge.ts";
26
25
  import type { Logger } from "../kernel/log.ts";
26
+ import {
27
+ AGENT_SERVER_PLUGIN,
28
+ AGENT_TEAM_SERVICE,
29
+ } from "../plugin-api/agent-server-ids.ts";
27
30
  import type { PluginContext, RoundtablePlugin } from "../plugin-api/plugin.ts";
28
31
  import {
29
32
  AGENTS,
30
33
  BACKGROUND_TURNS,
34
+ CHANNEL_CONTEXT,
31
35
  IDENTITY,
32
36
  MODES,
33
37
  PROMPTS,
@@ -37,7 +41,6 @@ import {
37
41
  } from "../plugin-api/services.ts";
38
42
  import { splitReply } from "../presentation/reply-splitter.ts";
39
43
  import { agentPromptExtension } from "../runtime/extensions/agent-prompt.ts";
40
- import { DISCORD } from "./discord.ts";
41
44
  import { agentOnly } from "./session-tool.ts";
42
45
 
43
46
  export {
@@ -50,18 +53,14 @@ import {
50
53
  LOCAL_TEAM_ID,
51
54
  } from "./agent-server-options.ts";
52
55
 
53
- /** The name of the agent server's plugin, as `serviceStarted` events name it. */
54
- export const AGENT_SERVER_PLUGIN = "agent-server";
55
-
56
- /**
57
- * The agent server's service that starts the team and the dashboard in the background: once its
58
- * `serviceStarted` event says `ready`, the agents' channels and the dashboard are up.
59
- */
60
- export const AGENT_TEAM_SERVICE = "team";
56
+ export {
57
+ AGENT_SERVER_PLUGIN,
58
+ AGENT_TEAM_SERVICE,
59
+ } from "../plugin-api/agent-server-ids.ts";
61
60
 
62
61
  /** The agent tools and the agent's own prompt, which only agent sessions load. */
63
62
  export function agentSessionTools(
64
- team: Pick<DiscordAgentTeam, "extension" | "systemPrompt">,
63
+ team: Pick<AgentServerTeam, "extension" | "systemPrompt">,
65
64
  logger: Logger,
66
65
  ): SessionTool[] {
67
66
  return [
@@ -78,7 +77,6 @@ const AGENT_TIERS: Readonly<Record<string, Tier>> = {
78
77
  agent_list: "member",
79
78
  agent_get: "member",
80
79
  message_agent: "member",
81
- channel_read: "member",
82
80
  // A knight may make temp knights for whoever is talking to it; the limits hold the cost.
83
81
  helper_create: "member",
84
82
  helper_end: "member",
@@ -122,9 +120,22 @@ export function agentServerPlugin(
122
120
  "the agent server: entryChannelId and coordinator both name the coordinator. Set the entry channel with Discord, the coordinator without it.",
123
121
  );
124
122
  const teamId = options.teamId ?? options.guildId ?? LOCAL_TEAM_ID;
123
+ // The spaces the team's stored places live in; the deprecated `guildId` is the legacy channels' one.
124
+ const spaces = [
125
+ ...(options.placeSpaces ?? []),
126
+ ...(options.guildId === undefined ||
127
+ options.placeSpaces?.some((s) => s.surface === LEGACY_CHANNEL_SURFACE)
128
+ ? []
129
+ : [{ surface: LEGACY_CHANNEL_SURFACE, space: options.guildId }]),
130
+ ];
131
+ const legacySpace = spaces.find(
132
+ (s) => s.surface === LEGACY_CHANNEL_SURFACE,
133
+ )?.space;
125
134
  /** Set once the plugin has set up; the preflight reads it after every plugin linked. */
126
135
  let hostsRooms: (() => boolean) | undefined;
127
- let servesDiscord: (() => boolean) | undefined;
136
+ let servesSpaces:
137
+ | (() => { surface: string; space: string } | undefined)
138
+ | undefined;
128
139
  let linkRoutes: (() => void) | undefined;
129
140
  return {
130
141
  name: AGENT_SERVER_PLUGIN,
@@ -136,14 +147,14 @@ export function agentServerPlugin(
136
147
  moveTeam({
137
148
  from: options.formerTeamIds ?? [],
138
149
  to: teamId,
139
- ...(options.guildId === undefined
150
+ ...(legacySpace === undefined
140
151
  ? { clearChannels: true }
141
- : { discordGuild: options.guildId }),
142
- // The legacy channels' places follow their columns: kept in the agent guild, dropped elsewhere.
152
+ : { discordGuild: legacySpace }),
153
+ // The legacy channels' places follow their columns: kept in their space, dropped elsewhere.
143
154
  places: [
144
155
  {
145
156
  surface: LEGACY_CHANNEL_SURFACE,
146
- ...(options.guildId === undefined ? {} : { keep: options.guildId }),
157
+ ...(legacySpace === undefined ? {} : { keep: legacySpace }),
147
158
  },
148
159
  ],
149
160
  }),
@@ -159,27 +170,28 @@ export function agentServerPlugin(
159
170
  throw new ConfigError(
160
171
  "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.",
161
172
  );
162
- // Channels the team makes but no provider reads would leave its agents unanswered.
163
- if (servesDiscord && !servesDiscord())
173
+ // Places the team makes but no provider reads would leave its agents unanswered.
174
+ const unserved = servesSpaces?.();
175
+ if (unserved)
164
176
  throw new ConfigError(
165
- `the agent guild ${options.guildId} has Discord channels for the agents, but no plugin contributes the place provider of the "discord" surface, so the team cannot read them. A plugin that replaces DISCORD must contribute it with places: [discordPlaceProvider({ guild, connection, logger })] from pi-roundtable/discord.`,
177
+ unserved.surface === LEGACY_CHANNEL_SURFACE
178
+ ? `the agent guild ${unserved.space} has Discord channels for the agents, but no plugin contributes the place provider of the "${unserved.surface}" surface, so the team cannot read them. A plugin that replaces DISCORD must contribute Discord's side of the agent guild, the place provider with its tools and dashboard: spread discordAgentGuild(context, { guild, connection }) from pi-roundtable/discord into what its setup returns.`
179
+ : `the team has places in the ${unserved.surface} space ${unserved.space}, but no plugin contributes the place provider of the "${unserved.surface}" surface, so the team cannot read them. Add the plugin that brings that surface's places.`,
166
180
  );
167
181
  // The surfaces the rules name exist only once every plugin has registered its own.
168
182
  linkRoutes?.();
169
183
  },
170
184
  setup: async (context) => {
171
- // Absent on a host without Discord: then the team has no channels or dashboard.
172
- const discord = context.services.find(DISCORD);
173
185
  const schedules = context.services.get(SCHEDULES);
174
- const connection = discord?.connection;
175
186
  const { logger, providers, surfaces } = context;
176
- // The team's Discord channels, in the agent guild; a bot without one serves only the plugins.
177
- const channels =
178
- connection && options.guildId
179
- ? connection.agentChannels(options.guildId)
180
- : undefined;
181
- if (!channels) hostsRooms = () => surfaces.roomSurfaces().length > 0;
182
- else servesDiscord = () => context.places.of("discord") !== undefined;
187
+ // A host with no space for stored places has its agents in rooms only.
188
+ if (spaces.length === 0)
189
+ hostsRooms = () => surfaces.roomSurfaces().length > 0;
190
+ else
191
+ servesSpaces = () =>
192
+ spaces.find(
193
+ ({ surface }) => context.places.of(surface) === undefined,
194
+ );
183
195
  const studio = new FileAvatarStudio({
184
196
  dir: join(options.dataDir, "avatars"),
185
197
  skins: context.env.characterSkins,
@@ -245,25 +257,28 @@ export function agentServerPlugin(
245
257
  });
246
258
  // The surfaces the rules name are registered by the time every plugin has set up.
247
259
  linkRoutes = () => routes.validate({ names: surfaces.names?.() ?? [] });
248
- const built: DiscordAgentTeam = new DiscordAgentTeam({
260
+ const built: AgentServerTeam = new AgentServerTeam({
249
261
  routes,
250
262
  places,
251
263
  teamId,
252
- discordGuild: options.guildId,
253
264
  ...(options.entryChannelId !== undefined
254
- ? { entryChannelId: options.entryChannelId }
255
- : {}),
256
- // Without an entry channel the coordinator is the named agent, else the first seed.
257
- ...(options.entryChannelId === undefined
258
265
  ? {
266
+ entryChannel: channelKey(
267
+ LEGACY_CHANNEL_SURFACE,
268
+ options.entryChannelId,
269
+ ),
270
+ }
271
+ : {
272
+ // Without an entry channel a place provider names, the coordinator is the named agent, else the first seed.
259
273
  coordinator: () =>
260
274
  options.coordinator ?? context.sessions().seeds[0]?.name,
261
- }
262
- : {}),
275
+ }),
263
276
  seeds: () => context.sessions().seeds,
264
277
  promptSections: () => context.sessions().prompt,
265
278
  agentTools: context.env.agentTools,
266
279
  pluginTools: () => context.sessions().agentTools,
280
+ pluginWithheldFromHelpers: () =>
281
+ context.sessions().agentToolsWithheldFromHelpers ?? [],
267
282
  pluginSelection: () => context.sessions().agentSelection(),
268
283
  events: context.events,
269
284
  owner: options.owner,
@@ -271,7 +286,6 @@ export function agentServerPlugin(
271
286
  shellUser: options.shellUser,
272
287
  ...(options.scratchDir ? { scratchDir: options.scratchDir } : {}),
273
288
  store,
274
- ...(channels ? { channels } : {}),
275
289
  studio,
276
290
  ...(options.refreshAvatars ? { refreshAvatars: true } : {}),
277
291
  runtime: () => running,
@@ -305,18 +319,16 @@ export function agentServerPlugin(
305
319
  ...(skills ? { skills } : {}),
306
320
  modes: () => context.services.find(MODES),
307
321
  rooms: () => context.services.find(ROOM_LAYOUT),
322
+ formerChannelOps: () => options.formerChannelOps?.(context),
308
323
  ...(options.helpers !== undefined ? { helpers: options.helpers } : {}),
309
324
  principals: () => context.services.find(IDENTITY),
310
325
  logger,
311
326
  });
312
- connection?.onChannelDeleted((channelId) => {
313
- if (!built.owns(discordKey(channelId))) return;
314
- void context.queue
315
- .run(discordKey(channelId), () => built.channelDeleted(channelId))
316
- // pi-lens-ignore: no-unknown-parameters
317
- .catch((error: unknown) =>
318
- logger.error({ channelId, err: error }, "archive failed"),
319
- );
327
+ // The deprecated `AgentTeam.discordGuild`, the agent guild: kept for plugins that read it
328
+ // until 1.0, though the team itself knows no guild but through its place providers.
329
+ Object.defineProperty(built, "discordGuild", {
330
+ value: legacySpace,
331
+ enumerable: true,
320
332
  });
321
333
  const agentSessions: AgentSessions = {
322
334
  workDir: options.workDir,
@@ -345,17 +357,6 @@ export function agentServerPlugin(
345
357
  });
346
358
  const attachmentDir = (channel: ChannelKey) =>
347
359
  ownerAttachmentDir(options.dataDir, channel);
348
- // The dashboard is a Discord message; a team without Discord has none.
349
- const dashboard =
350
- connection && options.guildId
351
- ? new AgentDashboard({
352
- status: () => built.status(),
353
- board: connection.agentDashboard(options.guildId),
354
- lines: () => context.dashboard(),
355
- logger,
356
- })
357
- : undefined;
358
- if (dashboard) built.onChange(() => dashboard.changed());
359
360
  const connectErrorReporter = () =>
360
361
  options.errorReporter?.connect({
361
362
  channelOf: (name) =>
@@ -372,19 +373,14 @@ export function agentServerPlugin(
372
373
  });
373
374
  return {
374
375
  services: [
375
- ...(dashboard
376
- ? [{ name: "dashboard", stop: () => dashboard.stop() }]
377
- : []),
378
376
  {
379
377
  name: AGENT_TEAM_SERVICE,
380
378
  stop: () => built.stop(),
381
379
  busy: () => built.busy(),
382
- // The dashboard shows the team, so it starts once the team has; the error
383
- // reporter connects whether or not the team did, since it reports the failure.
380
+ // The error reporter connects whether or not the team started, since it reports the failure.
384
381
  startInBackground: async () => {
385
382
  try {
386
383
  await built.start();
387
- dashboard?.start();
388
384
  } finally {
389
385
  connectErrorReporter();
390
386
  }
@@ -410,9 +406,9 @@ export function agentServerPlugin(
410
406
  ? { attachmentDownload: options.attachmentDownload }
411
407
  : {}),
412
408
  logger,
413
- ...(discord
414
- ? { channelContext: (message) => discord.channelContext(message) }
415
- : {}),
409
+ // Read from the surface that holds the message's channel, when one reads context.
410
+ channelContext: async (message) =>
411
+ context.services.find(CHANNEL_CONTEXT)?.read(message),
416
412
  }),
417
413
  ],
418
414
  // The pictures are public on a listener only where a public address reaches it.
@@ -6,6 +6,8 @@ import type {
6
6
  ChannelContextOptions,
7
7
  } from "../contract/channel-context.ts";
8
8
  import { type ServiceKey, serviceKey } from "../contract/services.ts";
9
+ import { discordAgentGuild } from "../discord/agent-guild.ts";
10
+ import { discordChannelOps } from "../discord/agent-tools.ts";
9
11
  import { CardCopies } from "../discord/card-copies.ts";
10
12
  import { ChannelContextReader } from "../discord/channel-context.ts";
11
13
  import { CommandCollection } from "../discord/command-collection.ts";
@@ -24,8 +26,10 @@ import type { DiscordPoster } from "../discord/poster/poster.ts";
24
26
  import { restOf, restPoster } from "../discord/poster/rest-poster.ts";
25
27
  import { stopButtonModule } from "../discord/stop-button.ts";
26
28
  import type { InboundMessage } from "../domain/conversation.ts";
27
- import type { RoundtablePlugin } from "../plugin-api/plugin.ts";
28
- import { IDENTITY, THREADS } from "../plugin-api/services.ts";
29
+ import { ConfigError } from "../domain/errors.ts";
30
+ import type { FormerChannelOps } from "../plugin-api/agent-ops.ts";
31
+ import type { PluginContext, RoundtablePlugin } from "../plugin-api/plugin.ts";
32
+ import { AGENTS, IDENTITY, THREADS } from "../plugin-api/services.ts";
29
33
  import { PeerBots } from "../routing/peer-bots.ts";
30
34
  import type { DispatchThreads } from "../threads/dispatch-threads.ts";
31
35
 
@@ -63,6 +67,29 @@ export interface DiscordServices {
63
67
  export const DISCORD: ServiceKey<DiscordServices> =
64
68
  serviceKey<DiscordServices>("roundtable.discord");
65
69
 
70
+ /**
71
+ * Discord's side of the deprecated `AgentOps.arrange` and `AgentOps.read`, for the agent server:
72
+ * what the two channel tools run, over the agent guild's channels of whichever plugin provides
73
+ * `DISCORD`. Undefined on a host without one. Removed in 1.0.
74
+ */
75
+ export function discordFormerChannelOps(
76
+ guild: string,
77
+ ): (
78
+ context: Pick<PluginContext, "services" | "logger">,
79
+ ) => FormerChannelOps | undefined {
80
+ return ({ services, logger }) => {
81
+ const connection = services.find(DISCORD)?.connection;
82
+ return (
83
+ connection &&
84
+ discordChannelOps({
85
+ channels: connection.agentChannels(guild),
86
+ directory: () => services.find(AGENTS)?.directory,
87
+ logger,
88
+ })
89
+ );
90
+ };
91
+ }
92
+
66
93
  export interface DiscordOptions {
67
94
  token: string;
68
95
  /**
@@ -75,8 +102,13 @@ export interface DiscordOptions {
75
102
  dataDir: string;
76
103
  /** The name of the root slash command, without the slash. */
77
104
  rootCommand: string;
78
- /** The agent guild (`discord.guild`): when given, the plugin contributes the place provider of the agent team's channels and threads in it. */
105
+ /** The agent guild (`discord.guild`): when given, the plugin contributes Discord's side of it (`discordAgentGuild`): the place provider of the agent team's channels and threads, their tools, and the dashboard message. */
79
106
  agentGuild?: string;
107
+ /**
108
+ * The channel the coordinator lives in (`discord.entryChannel`): the agent in it is the
109
+ * coordinator. Needs `agentGuild`; the agent server's `coordinator` names it without one.
110
+ */
111
+ entryChannel?: string;
80
112
  /** Text appended as it is to the refusal a non-owner gets, such as a pointer to the commands anyone may use. */
81
113
  refusalHint?: string;
82
114
  /** The host's channel context settings; `false` turns it off. Default: on, with the defaults. */
@@ -118,6 +150,10 @@ const INTERCOM_KEEP = 300;
118
150
  * preflight, so a clash fails before any service starts.
119
151
  */
120
152
  export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
153
+ if (options.entryChannel !== undefined && options.agentGuild === undefined)
154
+ throw new ConfigError(
155
+ "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.",
156
+ );
121
157
  const collection = new CommandCollection();
122
158
  let surface: DiscordSurface | undefined;
123
159
  return {
@@ -129,7 +165,7 @@ export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
129
165
  collection.compose(ownerRootCommand(options.rootCommand)),
130
166
  );
131
167
  },
132
- setup: async ({ conversations, services, logger, events }) => {
168
+ setup: async ({ conversations, services, logger, events, dashboard }) => {
133
169
  const identity = services.find(IDENTITY);
134
170
  // A host that keeps no copy texts on disk drops what an earlier run left.
135
171
  if (options.cardCopies === false)
@@ -240,13 +276,25 @@ export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
240
276
  channelContext: (message, given) =>
241
277
  connected.channelContext(message, given),
242
278
  });
279
+ // Discord's side of the agent guild: the team's channels and threads as its places, their tools, and the dashboard message.
280
+ const agentGuild = options.agentGuild
281
+ ? discordAgentGuild(
282
+ { services, logger, dashboard },
283
+ {
284
+ guild: options.agentGuild,
285
+ connection: connected,
286
+ client: connected.client(),
287
+ ...(options.entryChannel === undefined
288
+ ? {}
289
+ : { entryChannel: options.entryChannel }),
290
+ },
291
+ )
292
+ : undefined;
243
293
  return {
244
294
  // The host starts the surface first; it registers the composed commands as it connects.
245
295
  surfaces: [connected],
246
- // The agent team's channels and threads, when there is an agent guild for them.
247
- places: options.agentGuild
248
- ? [connected.agentPlaces(options.agentGuild)]
249
- : [],
296
+ places: agentGuild?.places ?? [],
297
+ tools: agentGuild?.tools ?? [],
250
298
  // A person's Discord direct messages, through a Discord identity of theirs.
251
299
  directChannels: [
252
300
  discordDirectChannel({
@@ -256,7 +304,9 @@ export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
256
304
  ownerId: options.ownerId,
257
305
  }),
258
306
  ],
307
+ ...(agentGuild ? { events: agentGuild.events } : {}),
259
308
  services: [
309
+ ...(agentGuild?.services ?? []),
260
310
  // The copy texts of the last cards are on disk before the host exits.
261
311
  {
262
312
  name: "card-copies",
@@ -117,6 +117,7 @@ export function modulesPlugin(options: ModulesOptions): RoundtablePlugin {
117
117
  sessions,
118
118
  toolTiers,
119
119
  directChannels,
120
+ queue,
120
121
  }) => {
121
122
  const schedules = services.get(SCHEDULES);
122
123
  // Absent when a plugin list leaves the prechecks plugin out: then none can be attached.
@@ -171,6 +172,7 @@ export function modulesPlugin(options: ModulesOptions): RoundtablePlugin {
171
172
  targets: (name) => conversations.target(name),
172
173
  deliver: (job, outcome) => background.runDelegated(job, outcome),
173
174
  ...(threads ? { threads } : {}),
175
+ draining: () => queue.draining ?? queue.closed,
174
176
  logger,
175
177
  });
176
178
  services.provide(BACKGROUND_TURNS, background);
@@ -0,0 +1,97 @@
1
+ import type { IntercomCard } from "../domain/conversation.ts";
2
+ import type { InterimPosts } from "../domain/interim.ts";
3
+
4
+ /** One agent's message in a channel, posted under its name and avatar. */
5
+ export interface AgentPost {
6
+ name: string;
7
+ avatarUrl: string;
8
+ /** The turn's thinking, posted first as a quiet line. */
9
+ thinking?: string;
10
+ chunks: string[];
11
+ files?: { name: string; data: Uint8Array }[];
12
+ /** A thread of the channel to post in instead, such as a dispatch's. */
13
+ threadId?: string;
14
+ /** A message between agents, shown as a small card in place of `chunks` where the channel can. */
15
+ intercom?: IntercomCard;
16
+ }
17
+
18
+ /**
19
+ * A category's name. Agents live under `Agents` or `Agents-<suffix>`, groups under `Groups` or
20
+ * `Groups-<suffix>`, and archived ones, kept with their history, under `Archive`.
21
+ */
22
+ export type AgentCategory = string;
23
+
24
+ /** A category of the agent server and its channels, in server order. */
25
+ export interface CategoryLayout {
26
+ /** Absent for a category still to be made. */
27
+ id?: string;
28
+ name: string;
29
+ channelIds: string[];
30
+ }
31
+
32
+ /** A message of the agent server as `channel_read` returns it. */
33
+ export interface ChannelMessage {
34
+ id: string;
35
+ author: string;
36
+ at: Date;
37
+ text: string;
38
+ attachments: string[];
39
+ }
40
+
41
+ /**
42
+ * The agent guild's channels. Discord's place provider drives them to make, keep and post in the
43
+ * places of agents and groups, and Discord's tools list, arrange and read categories.
44
+ */
45
+ export interface AgentChannels {
46
+ post(channelId: string, post: AgentPost): Promise<void>;
47
+ /**
48
+ * Where a running turn posts the text it writes before its final answer, under the same name
49
+ * and avatar as `post`; absent = only the final reply is posted.
50
+ */
51
+ interim?(
52
+ channelId: string,
53
+ as: Omit<AgentPost, "thinking" | "chunks" | "files">,
54
+ ): InterimPosts;
55
+ /** Creates a text channel under the category, made when missing; returns its id. */
56
+ createChannel(
57
+ name: string,
58
+ topic: string,
59
+ category: AgentCategory,
60
+ ): Promise<string>;
61
+ /**
62
+ * Opens a thread under a channel to be a temp knight's place, with no start message; returns its
63
+ * id. Posts to that id speak through the parent channel's webhook into the thread. Absent: Discord
64
+ * makes no place for a temp knight, and making one from a Discord conversation fails.
65
+ */
66
+ createThread?(parentChannelId: string, name: string): Promise<string>;
67
+ /** Archives and locks a temp knight's thread (locked only when permitted); its history stays. */
68
+ closeThread?(threadId: string): Promise<void>;
69
+ /** Opens a temp knight's archived thread again, unlocked. */
70
+ openThread?(threadId: string): Promise<void>;
71
+ /** Moves a channel into the category when it sits elsewhere; true when it moved. */
72
+ placeIn(channelId: string, category: AgentCategory): Promise<boolean>;
73
+ /** Every category of the server in order, each with its channels in order. */
74
+ layout(): Promise<CategoryLayout[]>;
75
+ /**
76
+ * Puts the categories, and the channels in each, in this order, making categories without an
77
+ * id; then deletes the categories of `remove` that hold no channel.
78
+ */
79
+ arrange(layout: CategoryLayout[], remove: string[]): Promise<void>;
80
+ setTopic(channelId: string, topic: string): Promise<void>;
81
+ /** Deletes the assistant's webhook in the channel, when it has one; its past messages stay. */
82
+ removeWebhook(channelId: string): Promise<void>;
83
+ exists(channelId: string): Promise<boolean>;
84
+ /**
85
+ * Up to `limit` messages of a text channel or thread of the agent server, oldest first: the
86
+ * latest, or those around `around`. Other servers' channels are refused.
87
+ */
88
+ read(
89
+ channelId: string,
90
+ options: { limit: number; around?: string },
91
+ ): Promise<ChannelMessage[]>;
92
+ }
93
+
94
+ /** The dashboard channel's one pinned message, made when missing and edited in place. */
95
+ export interface DashboardBoard {
96
+ show(sections: string[]): Promise<void>;
97
+ }
@@ -429,10 +429,10 @@ export interface QueuePort {
429
429
  run<T>(channel: ChannelKey, task: () => Promise<T>): Promise<T>;
430
430
  /**
431
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.
432
+ * report: the queue task it starts runs although the host is shutting down, `closed` reads
433
+ * false there, and the drain waits for it as for any task. A queue task that task starts in
434
+ * turn is refused, and `draining` stays true. It ends when the drain does; after that the task
435
+ * is refused as any other. Absent on a host that predates it: call `task` directly then.
436
436
  */
437
437
  finishing?<T>(task: () => Promise<T>): Promise<T>;
438
438
  /** Tasks of the channel running or waiting. */
@@ -444,6 +444,12 @@ export interface QueuePort {
444
444
  * HostStoppingError, and a plugin that starts work on its own, such as a timer, starts none.
445
445
  */
446
446
  readonly closed: boolean;
447
+ /**
448
+ * Whether the host is shutting down, even inside `finishing`, which masks only `closed`: work
449
+ * that a delivery's own turn spawns, such as a transient task, starts none. Absent on a host
450
+ * that predates it: read `closed` then.
451
+ */
452
+ readonly draining?: boolean;
447
453
  /** Called whenever a channel's count of running and waiting tasks changes. */
448
454
  onChange(listener: (channel: ChannelKey) => void): void;
449
455
  }
@@ -0,0 +1,15 @@
1
+ import type { ChannelKey } from "../domain/conversation.ts";
2
+ import { channelKey, parseChannelKey } from "./surface.ts";
3
+
4
+ /** The surface of Discord's channels, whose keys are `discord:<channel id>`. */
5
+ const DISCORD_SURFACE = "discord";
6
+
7
+ /** The key of a Discord channel. */
8
+ export const discordKey = (channelId: string): ChannelKey =>
9
+ channelKey(DISCORD_SURFACE, channelId);
10
+
11
+ /** The Discord channel id of a key, or undefined when the key belongs to another surface. */
12
+ export function discordIdOf(channel: ChannelKey): string | undefined {
13
+ const { surface, id } = parseChannelKey(channel);
14
+ return surface === DISCORD_SURFACE ? id : undefined;
15
+ }
@@ -40,7 +40,7 @@ export interface PlaceSpec extends PlaceRef {
40
40
  topic: string;
41
41
  /** A temp knight's parent's place id on this surface: the place is made under it (a Discord thread). */
42
42
  parent?: string;
43
- /** The stored id of an archived or checked place, to bring back instead of making a new one. */
43
+ /** The stored id of an archived place, or of an active group's at start, to bring back and put where it belongs instead of making a new one. */
44
44
  existing?: string;
45
45
  /** The values of this provider's `createArguments` the creating tool was given, such as `category`. */
46
46
  hints?: Readonly<Record<string, string>>;
@@ -73,7 +73,13 @@ export interface PlaceProvider {
73
73
  interim?(key: ChannelKey, author: PlaceAuthor): InterimPosts | undefined;
74
74
  /** Stored: makes the place, or brings `existing` back (out of an archive, a closed thread reopened); resolves to its id. Absent = places are bound, never made. */
75
75
  ensure?(spec: PlaceSpec): Promise<string>;
76
- /** Stored: the owner was archived; the place is kept with its history where nobody answers. Resolves to a line for the archive tool's answer, or undefined. */
76
+ /**
77
+ * Stored: the owner was archived; the place is kept with its history where nobody answers.
78
+ * Resolves to the rest of the archive tool's answer after `Archived "<name>"`, which starts with
79
+ * its own separator: `; its channel <#id> is kept under Archive.`, or `, but its channel <#id>
80
+ * could not be moved (...)` for a place that could not be kept; undefined for none. Rejects only
81
+ * for a failure the answer cannot describe; the owner is archived all the same.
82
+ */
77
83
  remove?(
78
84
  id: string,
79
85
  spec: PlaceSpec & { helper: boolean },