pi-roundtable 0.45.2 → 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 +30 -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
@@ -1,4 +1,6 @@
1
1
  import type { SQL } from "bun";
2
+ import { parseChannelKey } from "../contract/surface.ts";
3
+ import type { ChannelKey } from "../domain/conversation.ts";
2
4
 
3
5
  /**
4
6
  * The surface whose places `agents.channel_id` and `agent_groups.channel_id` hold: those columns
@@ -8,6 +10,35 @@ import type { SQL } from "bun";
8
10
  */
9
11
  export const LEGACY_CHANNEL_SURFACE = "discord";
10
12
 
13
+ /** The id a legacy column holds for a key of the legacy surface; undefined for a key of any other surface. */
14
+ export function legacyChannelIdOf(key: ChannelKey): string | undefined {
15
+ const { surface, id } = parseChannelKey(key);
16
+ return surface === LEGACY_CHANNEL_SURFACE ? id : undefined;
17
+ }
18
+
19
+ /**
20
+ * Sets the legacy `channel_id` of one agent or group of a team, or clears it with null; the other
21
+ * columns stay. Returns the row it wrote, as the store reads it, or none for a name the team does
22
+ * not have.
23
+ */
24
+ export function setLegacyChannel(
25
+ sql: SQL,
26
+ kind: (typeof LEGACY_CHANNEL_TABLES)[keyof typeof LEGACY_CHANNEL_TABLES],
27
+ teamId: string,
28
+ name: string,
29
+ channelId: string | null,
30
+ ): Promise<unknown[]> {
31
+ return kind === "agent"
32
+ ? sql`
33
+ UPDATE agents SET channel_id = ${channelId}, updated_at = now()
34
+ WHERE guild_id = ${teamId} AND name = ${name}
35
+ RETURNING *`
36
+ : sql`
37
+ UPDATE agent_groups SET channel_id = ${channelId}
38
+ WHERE guild_id = ${teamId} AND name = ${name}
39
+ RETURNING *`;
40
+ }
41
+
11
42
  /** The tables whose `channel_id` column is a legacy channel, and the kind of place owner each row is. */
12
43
  export const LEGACY_CHANNEL_TABLES = {
13
44
  agents: "agent",
@@ -0,0 +1,55 @@
1
+ import type { DashboardBoard } from "../contract/agent-channels.ts";
2
+ import type { Logger } from "../kernel/log.ts";
3
+ import {
4
+ AGENT_SERVER_PLUGIN,
5
+ AGENT_TEAM_SERVICE,
6
+ } from "../plugin-api/agent-server-ids.ts";
7
+ import type { Contribution } from "../plugin-api/plugin.ts";
8
+ import type { AgentTeam } from "../plugin-api/services.ts";
9
+ import { AgentDashboard } from "./agent-dashboard.ts";
10
+
11
+ export interface AgentDashboardContributionOptions {
12
+ /** The `#dashboard` message of the agent guild. */
13
+ board: DashboardBoard;
14
+ /** The agent server's team, read once its service is ready; undefined on a host whose agent server is off. */
15
+ agents: () => Pick<AgentTeam, "status" | "onChange"> | undefined;
16
+ /** The plugins' lines under the title, read at each update. */
17
+ lines: () => readonly string[];
18
+ logger: Logger;
19
+ }
20
+
21
+ /**
22
+ * The Discord plugin's dashboard: the `#dashboard` message shows the team, and starts once the
23
+ * agent server's team service is ready, since it shows what that start made. A team that fails to
24
+ * start has none. Refreshed when a turn starts or ends and when an agent or group changes.
25
+ */
26
+ export function agentDashboardContribution(
27
+ options: AgentDashboardContributionOptions,
28
+ ): Pick<Contribution, "services" | "events"> {
29
+ let dashboard: AgentDashboard | undefined;
30
+ return {
31
+ services: [{ name: "dashboard", stop: () => dashboard?.stop() }],
32
+ events: {
33
+ serviceStarted: (event) => {
34
+ if (
35
+ event.plugin !== AGENT_SERVER_PLUGIN ||
36
+ event.service !== AGENT_TEAM_SERVICE ||
37
+ event.outcome !== "ready" ||
38
+ dashboard
39
+ )
40
+ return;
41
+ const team = options.agents();
42
+ if (!team) return;
43
+ const started = new AgentDashboard({
44
+ status: () => team.status(),
45
+ board: options.board,
46
+ lines: options.lines,
47
+ logger: options.logger,
48
+ });
49
+ team.onChange(() => started.changed());
50
+ dashboard = started;
51
+ started.start();
52
+ },
53
+ },
54
+ };
55
+ }
@@ -1,9 +1,14 @@
1
+ import type { ContextUse } from "../agents/agent-ports.ts";
2
+ import type {
3
+ AgentStatus,
4
+ GroupStatus,
5
+ TeamStatus,
6
+ } from "../agents/agent-team.ts";
7
+ import type { DashboardBoard } from "../contract/agent-channels.ts";
1
8
  import { thinkingLabel } from "../domain/models.ts";
2
9
  import { messages } from "../i18n/index.ts";
3
10
  import type { Logger } from "../kernel/log.ts";
4
11
  import { zonedDate, zonedStamp } from "../kernel/time.ts";
5
- import type { ContextUse, DashboardBoard } from "./agent-ports.ts";
6
- import type { AgentStatus, GroupStatus, TeamStatus } from "./agent-team.ts";
7
12
 
8
13
  /** At most one edit this often (spec behavior 50); Discord limits message edits per channel. */
9
14
  const DASHBOARD_MIN_INTERVAL_MS = 10_000;
@@ -23,7 +23,7 @@ import type {
23
23
  CategoryLayout,
24
24
  ChannelMessage,
25
25
  DashboardBoard,
26
- } from "../agents/agent-ports.ts";
26
+ } from "../contract/agent-channels.ts";
27
27
  import { AgentError } from "../domain/errors.ts";
28
28
  import type { InterimPosts } from "../domain/interim.ts";
29
29
  import { messages } from "../i18n/index.ts";
@@ -0,0 +1,87 @@
1
+ import type { Client } from "discord.js";
2
+ import type { Contribution, PluginContext } from "../plugin-api/plugin.ts";
3
+ import { AGENTS } from "../plugin-api/services.ts";
4
+ import { agentDashboardContribution } from "./agent-dashboard-service.ts";
5
+ import { discordPlaces } from "./agent-places.ts";
6
+ import { discordAgentTools, ownerNameOf } from "./agent-tools.ts";
7
+ import type { DiscordConnection } from "./connection.ts";
8
+
9
+ export interface DiscordAgentGuildOptions {
10
+ /** The agent guild (`discord.guild`): the only server whose channels are the team's places. */
11
+ guild: string;
12
+ /**
13
+ * The Discord the host uses, as `DISCORD` provides it: the guild's channels, its `#dashboard`
14
+ * message and its deleted channels are read from it.
15
+ */
16
+ connection: Pick<
17
+ DiscordConnection,
18
+ "agentChannels" | "agentDashboard" | "onChannelDeleted"
19
+ >;
20
+ /** The discord.js client, so the team can check at start that its stored channels still exist; absent = they are taken as they are. */
21
+ client?: Client;
22
+ /**
23
+ * The channel the coordinator lives in (`discord.entryChannel`): the agent in it is the
24
+ * coordinator. Absent = the first agent the host seeds, since a host with `discord.guild`
25
+ * names no coordinator in its configuration.
26
+ */
27
+ entryChannel?: string;
28
+ }
29
+
30
+ /** Discord's side of the agent guild, as a plugin's setup returns it. */
31
+ export type DiscordAgentGuild = Required<
32
+ Pick<Contribution, "places" | "tools" | "services" | "events">
33
+ >;
34
+
35
+ /**
36
+ * Discord's side of the agent guild, for the plugin that provides `DISCORD`: the built-in Discord
37
+ * plugin contributes it, and a plugin that replaces `DISCORD` with a Discord of its own spreads it
38
+ * into what its setup returns whenever the host has `discord.guild`, since the built-in plugin is
39
+ * left out whole then.
40
+ *
41
+ * - `places`: the guild's channels as the team's places, with the keys, seats and log names they
42
+ * have always had, so no stored session, schedule or held action moves; the provider names the
43
+ * coordinator's place from `entryChannel`, and writes the categories section of `agent_list`
44
+ * with the agents' and groups' names.
45
+ * - `tools`: `channel_arrange` and `channel_read`, which an agent's turn carries.
46
+ * - `services` and `events`: the `#dashboard` message, started once the agent server's team is
47
+ * ready. A plugin with services or event handlers of its own merges them with these.
48
+ *
49
+ * It reads the team through `AGENTS` when a tool runs or the dashboard updates, never during
50
+ * setup, so the plugin may be set up before the agent server.
51
+ */
52
+ export function discordAgentGuild(
53
+ context: Pick<PluginContext, "services" | "logger" | "dashboard">,
54
+ options: DiscordAgentGuildOptions,
55
+ ): DiscordAgentGuild {
56
+ const { guild, connection } = options;
57
+ const { services, logger } = context;
58
+ const channels = connection.agentChannels(guild);
59
+ const directory = () => services.find(AGENTS)?.directory;
60
+ const dashboard = agentDashboardContribution({
61
+ board: connection.agentDashboard(guild),
62
+ agents: () => services.find(AGENTS)?.team,
63
+ lines: () => context.dashboard(),
64
+ logger,
65
+ });
66
+ return {
67
+ places: [
68
+ discordPlaces({
69
+ ...(options.client ? { client: options.client } : {}),
70
+ ...(options.entryChannel === undefined
71
+ ? {}
72
+ : { entryChannel: options.entryChannel }),
73
+ guild,
74
+ channels,
75
+ onRemoved: (listener) => connection.onChannelDeleted(listener),
76
+ nameOf: (channelId) => {
77
+ const found = directory();
78
+ return found ? ownerNameOf(found)(channelId) : undefined;
79
+ },
80
+ logger,
81
+ }),
82
+ ],
83
+ tools: discordAgentTools({ channels, directory, logger }),
84
+ services: dashboard.services ?? [],
85
+ events: dashboard.events ?? {},
86
+ };
87
+ }
@@ -1,13 +1,8 @@
1
+ import type { CategoryLayout } from "../contract/agent-channels.ts";
1
2
  import { AgentError } from "../domain/errors.ts";
2
- import { messages } from "../i18n/index.ts";
3
3
  import type { AgentDirectory } from "../plugin-api/services.ts";
4
- import type { CategoryLayout } from "./agent-ports.ts";
5
- import type { AgentGroup } from "./agent-store.ts";
6
4
 
7
- type TeamStore = Pick<
8
- AgentDirectory,
9
- "agent" | "group" | "agentByChannel" | "groupByChannel"
10
- >;
5
+ type TeamStore = Pick<AgentDirectory, "agent" | "group">;
11
6
 
12
7
  /** The two kinds of team category (spec behavior 56). */
13
8
  export type CategoryKind = "Agents" | "Groups";
@@ -36,32 +31,17 @@ export function teamCategory(
36
31
  return name;
37
32
  }
38
33
 
39
- /** A group channel's topic: who is in it and who hosts. */
40
- export function groupTopic(
41
- group: AgentGroup,
42
- store: Pick<AgentDirectory, "agent">,
43
- ): string {
44
- const shown = (name: string) => store.agent(name)?.displayName ?? name;
45
- return messages().groupTopic(
46
- group.displayName,
47
- group.members.map(shown),
48
- shown(group.host),
49
- );
50
- }
51
-
52
- /** The team categories in server order, each with its channels by agent or group name. */
53
- export function layoutText(
34
+ /**
35
+ * The team categories in server order, each with its channels by agent or group name, or as a
36
+ * mention for a channel of neither; the section `agent_list` ends with.
37
+ */
38
+ export function categoryLayoutText(
54
39
  layout: readonly CategoryLayout[],
55
- store: TeamStore,
40
+ nameOf: (channelId: string) => string | undefined,
56
41
  ): string {
57
42
  const lines = layout.flatMap((c) => {
58
43
  if (!categoryKind(c.name)) return [];
59
- const shown = c.channelIds.map(
60
- (id) =>
61
- store.agentByChannel(id)?.name ??
62
- store.groupByChannel(id)?.name ??
63
- `<#${id}>`,
64
- );
44
+ const shown = c.channelIds.map((id) => nameOf(id) ?? `<#${id}>`);
65
45
  return [`- ${c.name}: ${shown.join(", ") || "empty"}`];
66
46
  });
67
47
  return `Categories, in server order:\n${lines.join("\n") || "none"}`;
@@ -1,12 +1,16 @@
1
1
  import { type Client, DiscordAPIError } from "discord.js";
2
2
  import { Type } from "typebox";
3
- import type { AgentChannels } from "../agents/agent-ports.ts";
4
- import { categoryKind, teamCategory } from "../agents/team-layout.ts";
3
+ import type { AgentChannels } from "../contract/agent-channels.ts";
5
4
  import type { PlaceCheck, PlaceProvider } from "../contract/places.ts";
6
5
  import { channelKey, parseChannelKey } from "../contract/surface.ts";
7
6
  import { AgentError } from "../domain/errors.ts";
8
7
  import { PluginError } from "../kernel/errors.ts";
9
8
  import type { Logger } from "../kernel/log.ts";
9
+ import {
10
+ categoryKind,
11
+ categoryLayoutText,
12
+ teamCategory,
13
+ } from "./agent-layout.ts";
10
14
  import type { DiscordConnection } from "./connection.ts";
11
15
 
12
16
  const SURFACE = "discord";
@@ -14,6 +18,9 @@ const SURFACE = "discord";
14
18
  /** Discord's error code for a channel that does not exist. */
15
19
  const UNKNOWN_CHANNEL = 10003;
16
20
 
21
+ /** Discord's error code for a channel the bot may not see: one of a server it left, or a hidden one. */
22
+ const MISSING_ACCESS = 50001;
23
+
17
24
  export interface DiscordPlacesOptions {
18
25
  /** The discord.js client that can ask Discord whether a stored channel still exists; without one the provider has no `check`, and a stored channel is taken as it is. */
19
26
  client?: Client;
@@ -23,7 +30,7 @@ export interface DiscordPlacesOptions {
23
30
  /** Reports a server channel deleted, by id; as `DiscordConnection.onChannelDeleted`. */
24
31
  onRemoved(listener: (channelId: string) => void): void;
25
32
  logger: Logger;
26
- /** The channel the coordinator lives in; absent = the configured `coordinator`. */
33
+ /** The channel the coordinator lives in; absent = the agent server's `coordinator`, else the first seed. */
27
34
  entryChannel?: string;
28
35
  /** The name of the agent or group whose channel it is, for `layoutText`; a channel nobody owns shows as a mention. */
29
36
  nameOf?(channelId: string): string | undefined;
@@ -51,17 +58,22 @@ export function discordPlaces(options: DiscordPlacesOptions): PlaceProvider {
51
58
  // Fetched fresh: a cached channel says nothing of one deleted since.
52
59
  const found = await asked.channels
53
60
  .fetch(id, { force: true })
54
- .catch((error: unknown) => {
55
- // Only Discord's own "unknown" says gone. Missing Access (50001) says nothing of whose
56
- // guild the channel is in: a hidden channel of the agent guild answers it too, so it throws.
57
- if (
58
- error instanceof DiscordAPIError &&
59
- error.code === UNKNOWN_CHANNEL
60
- )
61
- return "gone" as const;
61
+ .catch(async (error: unknown) => {
62
+ if (!(error instanceof DiscordAPIError)) throw error;
63
+ if (error.code === UNKNOWN_CHANNEL) return "gone" as const;
64
+ // Missing Access says nothing of whose guild the channel is in, so the agent guild's own
65
+ // list does, which Discord gives whatever the overwrites: an id it does not hold is
66
+ // another server's (the bot left it), and one it holds is a hidden channel of its own,
67
+ // which stays a failure.
68
+ if (error.code === MISSING_ACCESS) {
69
+ const held = await (
70
+ await asked.guilds.fetch(guild)
71
+ ).channels.fetch();
72
+ if (!held.has(id)) return "foreign" as const;
73
+ }
62
74
  throw error;
63
75
  });
64
- if (found === "gone") return found;
76
+ if (found === "gone" || found === "foreign") return found;
65
77
  // A channel discord.js cannot build is none of the agent guild's; only Discord's own "unknown" says gone.
66
78
  if (found === null) return "foreign";
67
79
  return !found.isDMBased() && found.guildId === guild ? "ok" : "foreign";
@@ -113,14 +125,20 @@ export function discordPlaces(options: DiscordPlacesOptions): PlaceProvider {
113
125
  throw new AgentError("this Discord connection makes no threads");
114
126
  return channels.createThread(spec.parent, spec.displayName);
115
127
  }
116
- const under = teamCategory(
117
- spec.hints?.category,
118
- spec.kind === "agent" ? "Agents" : "Groups",
119
- );
128
+ const kind = spec.kind === "agent" ? "Agents" : "Groups";
129
+ const under = teamCategory(spec.hints?.category, kind);
120
130
  if (
121
131
  spec.existing !== undefined &&
122
132
  (await channels.exists(spec.existing))
123
133
  ) {
134
+ // A channel already under a category of its kind (`Groups-Work`) stays there unless a category is asked for.
135
+ if (spec.hints?.category === undefined) {
136
+ const { existing } = spec;
137
+ const home = (await channels.layout()).find((c) =>
138
+ c.channelIds.includes(existing),
139
+ );
140
+ if (home && categoryKind(home.name) === kind) return existing;
141
+ }
124
142
  await channels.placeIn(spec.existing, under);
125
143
  return spec.existing;
126
144
  }
@@ -154,9 +172,9 @@ export function discordPlaces(options: DiscordPlacesOptions): PlaceProvider {
154
172
  { name: spec.name, err: error },
155
173
  "archived channel not moved",
156
174
  );
157
- return `its channel ${mention(id)} could not be moved to Archive (${error instanceof Error ? error.message : String(error)}); it stays silent where it is.`;
175
+ return `, but its channel ${mention(id)} could not be moved to Archive (${error instanceof Error ? error.message : String(error)}); it stays silent where it is.`;
158
176
  }
159
- return `its channel ${mention(id)} is kept under Archive.`;
177
+ return `; its channel ${mention(id)} is kept under Archive.`;
160
178
  },
161
179
  ...(client ? { check: checkWith(client) } : {}),
162
180
  describe: (id, topic) => channels.setTopic(id, topic),
@@ -171,17 +189,8 @@ export function discordPlaces(options: DiscordPlacesOptions): PlaceProvider {
171
189
  agent: { category: category("Agents") },
172
190
  group: { category: category("Groups") },
173
191
  },
174
- layoutText: async () => {
175
- const layout = await channels.layout();
176
- const lines = layout.flatMap((c) => {
177
- if (!categoryKind(c.name)) return [];
178
- const shown = c.channelIds.map(
179
- (id) => options.nameOf?.(id) ?? mention(id),
180
- );
181
- return [`- ${c.name}: ${shown.join(", ") || "empty"}`];
182
- });
183
- return `Categories, in server order:\n${lines.join("\n") || "none"}`;
184
- },
192
+ layoutText: async () =>
193
+ categoryLayoutText(await channels.layout(), (id) => options.nameOf?.(id)),
185
194
  };
186
195
  }
187
196
 
@@ -193,13 +202,20 @@ export interface DiscordPlaceProviderOptions {
193
202
  logger: Logger;
194
203
  /** The discord.js client, so the team can check at start that its stored channels still exist; absent = they are taken as they are. */
195
204
  client?: Client;
205
+ /**
206
+ * The channel the coordinator lives in (`discord.entryChannel`): the agent in it is the
207
+ * coordinator. Absent = the first agent the host seeds, since a host with `discord.guild`
208
+ * names no coordinator in its configuration.
209
+ */
210
+ entryChannel?: string;
196
211
  }
197
212
 
198
213
  /**
199
- * Discord's place provider for a plugin that replaces `DISCORD` with a Discord of its own: the
200
- * agent guild's channels as the team's places, with the keys, seats and log names the built-in
201
- * Discord plugin gives them, so no stored session, schedule or held action moves. Contribute it
202
- * with `places` from the replacing plugin whenever the host has `discord.guild`.
214
+ * Discord's place provider alone: the agent guild's channels as the team's places, with the keys,
215
+ * seats and log names the built-in Discord plugin gives them, so no stored session, schedule or
216
+ * held action moves. A plugin that replaces `DISCORD` contributes `discordAgentGuild`, which
217
+ * holds this provider with the names of `agent_list`, the two channel tools and the dashboard;
218
+ * with the provider alone the team has none of those.
203
219
  */
204
220
  export function discordPlaceProvider(
205
221
  options: DiscordPlaceProviderOptions,
@@ -207,6 +223,9 @@ export function discordPlaceProvider(
207
223
  const { guild, connection } = options;
208
224
  return discordPlaces({
209
225
  ...(options.client ? { client: options.client } : {}),
226
+ ...(options.entryChannel === undefined
227
+ ? {}
228
+ : { entryChannel: options.entryChannel }),
210
229
  guild,
211
230
  channels: connection.agentChannels(guild),
212
231
  onRemoved: (listener) => connection.onChannelDeleted(listener),
@@ -0,0 +1,210 @@
1
+ import { Type } from "typebox";
2
+ import type {
3
+ AgentChannels,
4
+ ChannelMessage,
5
+ } from "../contract/agent-channels.ts";
6
+ import { AgentError } from "../domain/errors.ts";
7
+ import { messages } from "../i18n/index.ts";
8
+ import { ownerWords } from "../identity/owner-identity.ts";
9
+ import { THE_SPEAKER } from "../identity/speakers.ts";
10
+ import type { Logger } from "../kernel/log.ts";
11
+ import { timeZone, zonedStamp } from "../kernel/time.ts";
12
+ import type { FormerChannelOps } from "../plugin-api/agent-ops.ts";
13
+ import {
14
+ defineTool,
15
+ type ToolContribution,
16
+ ToolRefusal,
17
+ } from "../plugin-api/define.ts";
18
+ import type { AgentDirectory } from "../plugin-api/services.ts";
19
+ import {
20
+ categoryLayoutText,
21
+ planArrangement,
22
+ resolveArrangement,
23
+ } from "./agent-layout.ts";
24
+
25
+ /** The most messages `channel_read` returns. */
26
+ const READ_LIMIT = 50;
27
+
28
+ /** One message as channel_read shows it: id, local time, author, text, attachments. */
29
+ export function messageLine(message: ChannelMessage): string {
30
+ const files =
31
+ message.attachments.length > 0
32
+ ? ` [attachments: ${message.attachments.join(", ")}]`
33
+ : "";
34
+ return `[${message.id}] ${zonedStamp(message.at)} ${message.author}: ${message.text}${files}`;
35
+ }
36
+
37
+ /** A channel given as `<#id>` or its id, as its id. */
38
+ export function channelIdFromRef(channel: string): string {
39
+ const id = /^<#(\d+)>$/.exec(channel.trim())?.[1] ?? channel.trim();
40
+ if (!/^\d+$/.test(id))
41
+ throw new AgentError(
42
+ "Give the channel as <#id> or its id, as in a forwarded message.",
43
+ );
44
+ return id;
45
+ }
46
+
47
+ /** The agent or group a channel belongs to, by its name, for the category listing. */
48
+ export function ownerNameOf(
49
+ directory: Pick<AgentDirectory, "agentByChannel" | "groupByChannel">,
50
+ ): (channelId: string) => string | undefined {
51
+ return (id) =>
52
+ directory.agentByChannel(id)?.name ?? directory.groupByChannel(id)?.name;
53
+ }
54
+
55
+ export interface DiscordAgentToolsOptions {
56
+ /** The agent guild's channels, which the tools list, arrange and read. */
57
+ channels: Pick<AgentChannels, "layout" | "arrange" | "read">;
58
+ /** The team's agents and groups, read when a tool runs; undefined on a host whose agent server is off. */
59
+ directory: () =>
60
+ | Pick<
61
+ AgentDirectory,
62
+ "agent" | "group" | "agentByChannel" | "groupByChannel"
63
+ >
64
+ | undefined;
65
+ logger: Logger;
66
+ }
67
+
68
+ /** A tool that only agents' turns carry: the owner's sessions load none of it. */
69
+ function agentsOnly(tool: ToolContribution): ToolContribution {
70
+ return {
71
+ ...tool,
72
+ session: {
73
+ ...tool.session,
74
+ snapshot: () => {
75
+ // Not required at startup: the sessions the preflight builds are no agent's.
76
+ const { requiredTools: _, factory, ...rest } = tool.session.snapshot();
77
+ return {
78
+ ...rest,
79
+ factory: (session) => (session.agent ? factory(session) : null),
80
+ };
81
+ },
82
+ },
83
+ };
84
+ }
85
+
86
+ /** A refusal the model reads, where the tool's own code throws an `AgentError`. */
87
+ async function refusing<T>(run: () => Promise<T> | T): Promise<T> {
88
+ try {
89
+ return await run();
90
+ } catch (error) {
91
+ if (error instanceof AgentError) throw new ToolRefusal(error.message);
92
+ throw error;
93
+ }
94
+ }
95
+
96
+ /**
97
+ * What `channel_arrange` and `channel_read` run, and Discord's side of the deprecated
98
+ * `AgentOps.arrange` and `AgentOps.read`, which the host hands the team until 1.0. Each refuses
99
+ * with an `AgentError`.
100
+ */
101
+ export function discordChannelOps(
102
+ options: DiscordAgentToolsOptions,
103
+ ): FormerChannelOps {
104
+ const { channels, logger } = options;
105
+ const directory = () => {
106
+ const found = options.directory();
107
+ if (!found)
108
+ throw new AgentError(
109
+ "This host has no agent team, so there are no agent channels here.",
110
+ );
111
+ return found;
112
+ };
113
+ return {
114
+ arrange: async (entries) => {
115
+ const team = directory();
116
+ const listed = resolveArrangement(entries, team);
117
+ const { layout, remove } = planArrangement(
118
+ listed,
119
+ await channels.layout(),
120
+ );
121
+ await channels.arrange(layout, remove);
122
+ logger.info(
123
+ { entries: listed.map((l) => l.category), removed: remove.length },
124
+ "agent channels arranged",
125
+ );
126
+ const removed =
127
+ remove.length > 0
128
+ ? ` ${remove.length} empty team categories were deleted.`
129
+ : "";
130
+ return `Arranged the channels.${removed}\n\n${categoryLayoutText(await channels.layout(), ownerNameOf(team))}`;
131
+ },
132
+ read: async (channel, around, limit) => {
133
+ const id = channelIdFromRef(channel);
134
+ const found = await channels.read(id, {
135
+ limit: Math.min(Math.max(limit ?? 20, 1), READ_LIMIT),
136
+ ...(around ? { around } : {}),
137
+ });
138
+ return found.length > 0
139
+ ? found.map(messageLine).join("\n")
140
+ : `<#${id}> has no messages there.`;
141
+ },
142
+ };
143
+ }
144
+
145
+ /**
146
+ * The tools of the agent guild's channels: `channel_arrange` sorts agent and group channels into
147
+ * categories and `channel_read` reads a channel's messages. Agents carry them, as they carried
148
+ * them when the agent team offered them; a temp knight carries neither arrange nor creation.
149
+ */
150
+ export function discordAgentTools(
151
+ options: DiscordAgentToolsOptions,
152
+ ): ToolContribution[] {
153
+ const ops = discordChannelOps(options);
154
+ const speaker = ownerWords(THE_SPEAKER).name;
155
+ return [
156
+ defineTool({
157
+ name: "channel_arrange",
158
+ description: `Sort agent and group channels into categories and order them, when ${speaker} asks. Agents go under Agents or Agents-<suffix>, groups under Groups or Groups-<suffix>; missing categories are made. The listed categories come first in the server in list order, then every other category as it was; in each listed category the listed channels come first in order, then its other channels as they were. Agents and Groups categories left empty are deleted. Any wrong entry refuses the whole call and nothing moves. Read the current layout with agent_list first.`,
159
+ minTier: "admin",
160
+ withheldFromHelpers: true,
161
+ parameters: Type.Object({
162
+ categories: Type.Array(
163
+ Type.Object({
164
+ category: Type.String({
165
+ description:
166
+ "Agents, Groups, or either with -<suffix>, the suffix 1 to 32 characters in any language.",
167
+ }),
168
+ channels: Type.Array(Type.String(), {
169
+ minItems: 1,
170
+ description:
171
+ "Agent or group names (from agent_list), in the order they should appear.",
172
+ }),
173
+ }),
174
+ { minItems: 1, description: "Categories in server order." },
175
+ ),
176
+ }),
177
+ run: ({ categories }) =>
178
+ refusing(() =>
179
+ ops.arrange(
180
+ categories.map((entry) => ({
181
+ category: entry.category,
182
+ names: entry.channels,
183
+ })),
184
+ ),
185
+ ),
186
+ }),
187
+ defineTool({
188
+ name: "channel_read",
189
+ description: `Read messages of a text channel or thread of the agent server, oldest first, each with its id, ${messages().zoneTime(timeZone())}, author, text, and attachment names. Use it for the surroundings of a message ${speaker} forwarded to you: pass the source channel and the message id from the forwarded link. Read-only.`,
190
+ minTier: "member",
191
+ parameters: Type.Object({
192
+ channel: Type.String({
193
+ description: "The channel as <#id> or its id.",
194
+ }),
195
+ around: Type.Optional(
196
+ Type.String({
197
+ pattern: "^\\d+$",
198
+ description:
199
+ "A message id: read the messages around it instead of the latest.",
200
+ }),
201
+ ),
202
+ limit: Type.Optional(
203
+ Type.Integer({ minimum: 1, maximum: 50, description: "Default 20." }),
204
+ ),
205
+ }),
206
+ run: ({ channel, around, limit }) =>
207
+ refusing(() => ops.read(channel, around, limit)),
208
+ }),
209
+ ].map(agentsOnly);
210
+ }
@@ -1,4 +1,7 @@
1
- import type { AgentChannels, DashboardBoard } from "../agents/agent-ports.ts";
1
+ import type {
2
+ AgentChannels,
3
+ DashboardBoard,
4
+ } from "../contract/agent-channels.ts";
2
5
  import type { ChannelKey } from "../domain/conversation.ts";
3
6
  import type { OwnerOperations } from "../modules/discord-admin/discord-admin.ts";
4
7
  import type { ThreadHost } from "../threads/dispatch-threads.ts";