pi-roundtable 0.45.2 → 0.47.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 (79) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/docs/plugins.md +33 -8
  3. package/package.json +2 -2
  4. package/src/characters/catalog.ts +1 -0
  5. package/src/characters/characters.css +2 -1
  6. package/src/characters/compose.ts +7 -3
  7. package/src/characters/css.ts +2 -1
  8. package/src/characters/index.ts +1 -0
  9. package/src/characters/parts-face.ts +14 -1
  10. package/src/core/agents/agent-claim.ts +2 -2
  11. package/src/core/agents/agent-group-store.ts +74 -1
  12. package/src/core/agents/agent-places.ts +32 -0
  13. package/src/core/agents/agent-ports.ts +0 -94
  14. package/src/core/agents/agent-prompt.ts +3 -1
  15. package/src/core/agents/agent-team-fixture.ts +74 -14
  16. package/src/core/agents/agent-team.ts +50 -59
  17. package/src/core/agents/agent-tools.ts +34 -166
  18. package/src/core/agents/message-target.ts +3 -2
  19. package/src/core/agents/routes.ts +2 -1
  20. package/src/core/agents/team-editing.ts +121 -150
  21. package/src/core/agents/team-helpers.ts +80 -59
  22. package/src/core/agents/team-keys.ts +16 -26
  23. package/src/core/agents/team-lifecycle.ts +155 -99
  24. package/src/core/agents/team-looks.ts +102 -0
  25. package/src/core/agents/team-options.ts +12 -11
  26. package/src/core/agents/team-place-writes.ts +215 -0
  27. package/src/core/agents/team-places.ts +30 -0
  28. package/src/core/agents/team-posts.ts +42 -73
  29. package/src/core/agents/team-selection.ts +10 -2
  30. package/src/core/agents/team-status.ts +3 -2
  31. package/src/core/agents/team-text.ts +14 -43
  32. package/src/core/agents/team-turn-types.ts +11 -16
  33. package/src/core/agents/team-turns.ts +7 -6
  34. package/src/core/builtin/agent-server-options.ts +27 -6
  35. package/src/core/builtin/agent-server.ts +69 -72
  36. package/src/core/builtin/discord.ts +60 -8
  37. package/src/core/builtin/modules.ts +2 -0
  38. package/src/core/config/agent-team.ts +5 -3
  39. package/src/core/contract/agent-channels.ts +105 -0
  40. package/src/core/contract/channels.ts +10 -4
  41. package/src/core/contract/discord-key.ts +15 -0
  42. package/src/core/contract/places.ts +28 -3
  43. package/src/core/db/legacy-channels.ts +31 -0
  44. package/src/core/db/team-move.ts +2 -2
  45. package/src/core/discord/agent-dashboard-service.ts +55 -0
  46. package/src/core/{agents → discord}/agent-dashboard.ts +28 -4
  47. package/src/core/discord/agent-discord.ts +1 -1
  48. package/src/core/discord/agent-guild.ts +141 -0
  49. package/src/core/{agents/team-layout.ts → discord/agent-layout.ts} +15 -31
  50. package/src/core/discord/agent-places.ts +52 -33
  51. package/src/core/discord/agent-tools.ts +237 -0
  52. package/src/core/discord/channel-operations.ts +2 -0
  53. package/src/core/discord/connection.ts +4 -1
  54. package/src/core/discord/discord-surface.ts +9 -14
  55. package/src/core/discord/place-fake-client.ts +59 -0
  56. package/src/core/host/define-roundtable.ts +7 -5
  57. package/src/core/modules/delegation/delegator.ts +5 -0
  58. package/src/core/plugin-api/agent-ops.ts +119 -0
  59. package/src/core/plugin-api/agent-server-ids.ts +9 -0
  60. package/src/core/plugin-api/define.ts +9 -0
  61. package/src/core/plugin-api/plugin.ts +2 -0
  62. package/src/core/plugin-api/services.ts +6 -0
  63. package/src/core/registry/contributions.ts +3 -0
  64. package/src/core/registry/places.ts +31 -1
  65. package/src/core/routing/channel-queue.ts +28 -12
  66. package/src/core/runtime/pi-agent-runtime.ts +1 -1
  67. package/src/core/runtime/runtime-plugin.ts +1 -0
  68. package/src/core/runtime/runtime-types.ts +6 -0
  69. package/src/core/{agents/agent-team-fake-channels.ts → testing/fake-agent-channels.ts} +5 -1
  70. package/src/core/testing/fake-pager-places.ts +16 -2
  71. package/src/core/testing/modules.ts +2 -1
  72. package/src/core/testing/place-contract.ts +3 -2
  73. package/src/core/testing/team-places.ts +73 -7
  74. package/src/core/testing/test-host.ts +20 -16
  75. package/src/discord/index.ts +5 -0
  76. package/src/kit/channels.ts +1 -2
  77. package/src/kit/support.ts +25 -7
  78. package/templates/adapters/web/package.json.tmpl +1 -1
  79. package/templates/package.json.tmpl +1 -1
@@ -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>>;
@@ -49,9 +49,28 @@ export interface PlaceSpec extends PlaceRef {
49
49
  /** What `check` finds of a stored place at start. */
50
50
  export type PlaceCheck = "ok" | "gone" | "foreign";
51
51
 
52
- /** An argument a provider adds to a creation tool: a Typebox schema, with its description in the schema. */
52
+ /**
53
+ * An argument a provider adds to a creation tool: a Typebox schema, with its description in the
54
+ * schema. Only a string value the model gives reaches `ensure` (as `hints`), so give a string schema.
55
+ */
53
56
  export type ToolArgument = TSchema;
54
57
 
58
+ /** The arguments `agent_create` and `group_create` take of their own, which no provider's `createArguments` may reuse. */
59
+ export const CREATION_TOOL_ARGUMENTS = {
60
+ agent: [
61
+ "name",
62
+ "display_name",
63
+ "prompt",
64
+ "class",
65
+ "color",
66
+ "task",
67
+ "group",
68
+ "long_running",
69
+ "skills",
70
+ ],
71
+ group: ["name", "display_name", "members", "host", "group"],
72
+ } as const;
73
+
55
74
  /**
56
75
  * What a chat surface holds of the team's places: where an agent or group is spoken to on it.
57
76
  * The members a minimal provider needs are `surface`, `storage`, `key`, `placeOf` and `post`; the
@@ -73,7 +92,13 @@ export interface PlaceProvider {
73
92
  interim?(key: ChannelKey, author: PlaceAuthor): InterimPosts | undefined;
74
93
  /** 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
94
  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. */
95
+ /**
96
+ * Stored: the owner was archived; the place is kept with its history where nobody answers.
97
+ * Resolves to the rest of the archive tool's answer after `Archived "<name>"`, which starts with
98
+ * its own separator: `; its channel <#id> is kept under Archive.`, or `, but its channel <#id>
99
+ * could not be moved (...)` for a place that could not be kept; undefined for none. Rejects only
100
+ * for a failure the answer cannot describe; the owner is archived all the same.
101
+ */
77
102
  remove?(
78
103
  id: string,
79
104
  spec: PlaceSpec & { helper: boolean },
@@ -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",
@@ -20,7 +20,7 @@ export interface TeamMoveOptions {
20
20
  * The surfaces whose stored places name something of the space the team lived in, such as the
21
21
  * channels of a Discord guild. A place row moved from a former id other than `keep` is dropped, as
22
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.
23
+ * is dropped. With `clearChannels` the team's own rows of the surfaces without `keep` go too.
24
24
  */
25
25
  places?: readonly { surface: string; keep?: string }[];
26
26
  }
@@ -75,7 +75,7 @@ export function moveTeam(options: TeamMoveOptions): Migration {
75
75
  );
76
76
  if (table === PLACES_TABLE)
77
77
  for (const { surface, keep } of options.places ?? []) {
78
- if (options.clearChannels)
78
+ if (options.clearChannels && keep === undefined)
79
79
  await tx.unsafe(
80
80
  `DELETE FROM "${table}" WHERE ${scope} = $1 AND surface = $2`,
81
81
  [options.to, surface],
@@ -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,15 @@
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";
8
+ import { discordIdOf } from "../contract/discord-key.ts";
1
9
  import { thinkingLabel } from "../domain/models.ts";
2
10
  import { messages } from "../i18n/index.ts";
3
11
  import type { Logger } from "../kernel/log.ts";
4
12
  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
13
 
8
14
  /** At most one edit this often (spec behavior 50); Discord limits message edits per channel. */
9
15
  const DASHBOARD_MIN_INTERVAL_MS = 10_000;
@@ -12,6 +18,22 @@ const DASHBOARD_REFRESH_MS = 5 * 60_000;
12
18
  /** Components V2 allows 4000 characters of text per message. */
13
19
  const TEXT_BUDGET = 3_800;
14
20
 
21
+ /**
22
+ * The Discord channel a status names, from its places; the deprecated `channelId` answers only for
23
+ * a status written before places were providers, which has none.
24
+ */
25
+ function discordChannelOf(status: {
26
+ places?: AgentStatus["places"];
27
+ channelId?: string;
28
+ }): string | undefined {
29
+ if (!status.places) return status.channelId;
30
+ for (const place of status.places) {
31
+ const id = discordIdOf(place.key);
32
+ if (id !== undefined) return id;
33
+ }
34
+ return undefined;
35
+ }
36
+
15
37
  /** Configured local time, with the month and day when it is not today's. */
16
38
  function when(at: Date, now: Date): string {
17
39
  const date = zonedDate(at);
@@ -45,7 +67,8 @@ function agentBlock(
45
67
  now: Date,
46
68
  helpers: readonly AgentStatus[],
47
69
  ): string {
48
- const channel = agent.channelId ? ` <#${agent.channelId}>` : "";
70
+ const channelId = discordChannelOf(agent);
71
+ const channel = channelId ? ` <#${channelId}>` : "";
49
72
  const text = messages();
50
73
  const last = agent.lastActive
51
74
  ? text.dashLastActive(when(agent.lastActive, now))
@@ -69,12 +92,13 @@ function agentBlock(
69
92
 
70
93
  function groupBlock(group: GroupStatus, now: Date): string {
71
94
  const text = messages();
95
+ const channelId = discordChannelOf(group);
72
96
  const state = group.busy > 0 ? text.dashGroupBusy(group.busy) : text.dashIdle;
73
97
  const last = group.lastActive
74
98
  ? text.dashLastActive(when(group.lastActive, now))
75
99
  : text.dashNotActive;
76
100
  return [
77
- `**${group.displayName}**${group.channelId ? ` <#${group.channelId}>` : ""}`,
101
+ `**${group.displayName}**${channelId ? ` <#${channelId}>` : ""}`,
78
102
  text.dashGroupMembers(group.members, group.host),
79
103
  state,
80
104
  `-# ${last}`,
@@ -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,141 @@
1
+ import type { Client } from "discord.js";
2
+ import type {
3
+ Contribution,
4
+ EventHandlers,
5
+ PluginContext,
6
+ } from "../plugin-api/plugin.ts";
7
+ import { AGENTS } from "../plugin-api/services.ts";
8
+ import { agentDashboardContribution } from "./agent-dashboard-service.ts";
9
+ import { discordPlaces } from "./agent-places.ts";
10
+ import { discordAgentTools, discordTeamReads } from "./agent-tools.ts";
11
+ import type { DiscordConnection } from "./connection.ts";
12
+
13
+ export interface DiscordAgentGuildOptions {
14
+ /** The agent guild (`discord.guild`): the only server whose channels are the team's places. */
15
+ guild: string;
16
+ /**
17
+ * The Discord the host uses, as `DISCORD` provides it: the guild's channels, its `#dashboard`
18
+ * message and its deleted channels are read from it.
19
+ */
20
+ connection: Pick<
21
+ DiscordConnection,
22
+ "agentChannels" | "agentDashboard" | "onChannelDeleted"
23
+ >;
24
+ /** The discord.js client, so the team can check at start that its stored channels still exist; absent = they are taken as they are. */
25
+ client?: Client;
26
+ /**
27
+ * The channel the coordinator lives in (`discord.entryChannel`): the agent in it is the
28
+ * coordinator. Absent = the first agent the host seeds, since a host with `discord.guild`
29
+ * names no coordinator in its configuration.
30
+ */
31
+ entryChannel?: string;
32
+ /**
33
+ * The services and event handlers the plugin contributes itself. Spreading the result puts
34
+ * `services` and `events` in place of the plugin's own, so give them here: the services follow
35
+ * the dashboard's, and a handler of an event the dashboard also hears runs after it, and runs
36
+ * even when the dashboard's throws.
37
+ */
38
+ own?: Pick<Contribution, "services" | "events">;
39
+ }
40
+
41
+ /** Discord's side of the agent guild, as a plugin's setup returns it. */
42
+ export type DiscordAgentGuild = Required<
43
+ Pick<Contribution, "places" | "tools" | "services" | "events">
44
+ >;
45
+
46
+ /**
47
+ * Discord's side of the agent guild, for the plugin that provides `DISCORD`: the built-in Discord
48
+ * plugin contributes it, and a plugin that replaces `DISCORD` with a Discord of its own spreads it
49
+ * into what its setup returns whenever the host has `discord.guild`, since the built-in plugin is
50
+ * left out whole then.
51
+ *
52
+ * - `places`: the guild's channels as the team's places, with the keys, seats and log names they
53
+ * have always had, so no stored session, schedule or held action moves; the provider names the
54
+ * coordinator's place from `entryChannel`, and writes the categories section of `agent_list`
55
+ * with the agents' and groups' names.
56
+ * - `tools`: `channel_arrange` and `channel_read`, which an agent's turn carries.
57
+ * - `services` and `events`: the `#dashboard` message, started once the agent server's team is
58
+ * ready. A plugin with services or event handlers of its own gives them as `own`, and the result
59
+ * merges them with these.
60
+ *
61
+ * It reads the team through `AGENTS` when a tool runs or the dashboard updates, never during
62
+ * setup, so the plugin may be set up before the agent server.
63
+ */
64
+ export function discordAgentGuild(
65
+ context: Pick<PluginContext, "services" | "logger" | "dashboard">,
66
+ options: DiscordAgentGuildOptions,
67
+ ): DiscordAgentGuild {
68
+ const { guild, connection } = options;
69
+ const { services, logger } = context;
70
+ const channels = connection.agentChannels(guild);
71
+ const directory = () => {
72
+ const server = services.find(AGENTS);
73
+ return server && discordTeamReads(server);
74
+ };
75
+ const dashboard = agentDashboardContribution({
76
+ board: connection.agentDashboard(guild),
77
+ agents: () => services.find(AGENTS)?.team,
78
+ lines: () => context.dashboard(),
79
+ logger,
80
+ });
81
+ return {
82
+ places: [
83
+ discordPlaces({
84
+ ...(options.client ? { client: options.client } : {}),
85
+ ...(options.entryChannel === undefined
86
+ ? {}
87
+ : { entryChannel: options.entryChannel }),
88
+ guild,
89
+ channels,
90
+ onRemoved: (listener) => connection.onChannelDeleted(listener),
91
+ nameOf: (channelId) => directory()?.ownerOf(channelId),
92
+ logger,
93
+ }),
94
+ ],
95
+ tools: discordAgentTools({ channels, directory, logger }),
96
+ services: [...(dashboard.services ?? []), ...(options.own?.services ?? [])],
97
+ events: mergedEvents(
98
+ dashboard.events ?? {},
99
+ options.own?.events ?? {},
100
+ logger,
101
+ ),
102
+ };
103
+ }
104
+
105
+ /**
106
+ * Handlers of both sets under one event name each: those of an event both hear run in order, each
107
+ * even when one before it throws. The first error is the one raised, as the bus logs it; the later
108
+ * ones are logged here, or they would be lost.
109
+ */
110
+ function mergedEvents(
111
+ first: EventHandlers,
112
+ second: EventHandlers,
113
+ logger: Pick<PluginContext["logger"], "error">,
114
+ ): EventHandlers {
115
+ const merged: Record<string, (...args: unknown[]) => Promise<void>> = {};
116
+ const names = new Set([...Object.keys(first), ...Object.keys(second)]);
117
+ for (const name of names) {
118
+ const handlers = [first, second].flatMap((set) => {
119
+ const handler = (set as Record<string, unknown>)[name] as
120
+ | ((...args: unknown[]) => Promise<void> | void)
121
+ | undefined;
122
+ return handler ? [{ set, handler }] : [];
123
+ });
124
+ merged[name] = async (...args) => {
125
+ const failures: unknown[] = [];
126
+ for (const { set, handler } of handlers)
127
+ try {
128
+ await handler.apply(set, args);
129
+ } catch (error) {
130
+ failures.push(error);
131
+ }
132
+ for (const error of failures.slice(1))
133
+ logger.error(
134
+ { err: error, event: name },
135
+ "a later handler of the event failed",
136
+ );
137
+ if (failures.length > 0) throw failures[0];
138
+ };
139
+ }
140
+ return merged as EventHandlers;
141
+ }
@@ -1,13 +1,11 @@
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"> & {
6
+ /** The Discord channel of an agent or group; undefined when it has none. */
7
+ channelOf(name: string): string | undefined;
8
+ };
11
9
 
12
10
  /** The two kinds of team category (spec behavior 56). */
13
11
  export type CategoryKind = "Agents" | "Groups";
@@ -36,32 +34,17 @@ export function teamCategory(
36
34
  return name;
37
35
  }
38
36
 
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(
37
+ /**
38
+ * The team categories in server order, each with its channels by agent or group name, or as a
39
+ * mention for a channel of neither; the section `agent_list` ends with.
40
+ */
41
+ export function categoryLayoutText(
54
42
  layout: readonly CategoryLayout[],
55
- store: TeamStore,
43
+ nameOf: (channelId: string) => string | undefined,
56
44
  ): string {
57
45
  const lines = layout.flatMap((c) => {
58
46
  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
- );
47
+ const shown = c.channelIds.map((id) => nameOf(id) ?? `<#${id}>`);
65
48
  return [`- ${c.name}: ${shown.join(", ") || "empty"}`];
66
49
  });
67
50
  return `Categories, in server order:\n${lines.join("\n") || "none"}`;
@@ -95,8 +78,9 @@ export function resolveArrangement(
95
78
  if (target.status !== "active")
96
79
  throw new AgentError(`"${name}" is archived.`);
97
80
  teamCategory(category, agent ? "Agents" : "Groups");
98
- if (!target.channelId) throw new AgentError(`${name} has no channel.`);
99
- return target.channelId;
81
+ const channelId = store.channelOf(name);
82
+ if (!channelId) throw new AgentError(`${name} has no channel.`);
83
+ return channelId;
100
84
  });
101
85
  return { category, channelIds };
102
86
  });
@@ -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),