pi-roundtable 0.44.1 → 0.45.1

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 (51) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/docs/plugins.md +36 -2
  3. package/package.json +2 -2
  4. package/src/core/agents/agent-claim.ts +15 -21
  5. package/src/core/agents/agent-messages.ts +10 -10
  6. package/src/core/agents/agent-prompt.ts +7 -8
  7. package/src/core/agents/agent-rules.ts +9 -2
  8. package/src/core/agents/agent-store.ts +16 -0
  9. package/src/core/agents/agent-team-fake-channels.ts +105 -0
  10. package/src/core/agents/agent-team-fixture.ts +30 -105
  11. package/src/core/agents/agent-team.ts +20 -21
  12. package/src/core/agents/group-turns.ts +8 -15
  13. package/src/core/agents/helper-modes.ts +7 -13
  14. package/src/core/agents/helper-work.ts +7 -6
  15. package/src/core/agents/message-target.ts +24 -12
  16. package/src/core/agents/room-progress.ts +8 -6
  17. package/src/core/agents/routes.ts +24 -47
  18. package/src/core/agents/team-editing.ts +5 -8
  19. package/src/core/agents/team-keys.ts +5 -190
  20. package/src/core/agents/team-lifecycle.ts +23 -39
  21. package/src/core/agents/team-options.ts +1 -1
  22. package/src/core/agents/team-places.ts +335 -0
  23. package/src/core/agents/team-posts.ts +157 -0
  24. package/src/core/agents/team-prompt.ts +3 -3
  25. package/src/core/agents/team-status.ts +18 -10
  26. package/src/core/agents/team-turn-types.ts +5 -8
  27. package/src/core/agents/team-turns.ts +26 -169
  28. package/src/core/builtin/agent-server-test-kit.ts +29 -0
  29. package/src/core/builtin/agent-server.ts +19 -12
  30. package/src/core/builtin/discord.ts +6 -0
  31. package/src/core/contract/places.ts +141 -0
  32. package/src/core/discord/agent-places.ts +215 -0
  33. package/src/core/discord/discord-surface.ts +13 -0
  34. package/src/core/host/define-roundtable.ts +1 -0
  35. package/src/core/plugin-api/agent-assets.ts +36 -0
  36. package/src/core/plugin-api/plugin-context.ts +30 -0
  37. package/src/core/plugin-api/plugin.ts +10 -28
  38. package/src/core/plugin-api/services.ts +20 -39
  39. package/src/core/registry/claims.ts +120 -0
  40. package/src/core/registry/contributions.ts +36 -118
  41. package/src/core/registry/place-port.ts +94 -0
  42. package/src/core/registry/places.ts +43 -0
  43. package/src/core/testing/fake-pager-places.ts +120 -0
  44. package/src/core/testing/fake-room-surface.ts +60 -0
  45. package/src/core/testing/modules.ts +5 -5
  46. package/src/core/testing/place-contract.ts +481 -0
  47. package/src/core/testing/team-places.ts +121 -0
  48. package/src/core/testing/test-host.ts +36 -10
  49. package/src/discord/index.ts +2 -0
  50. package/src/index.ts +12 -0
  51. package/src/testing.ts +15 -3
@@ -1,21 +1,13 @@
1
- import { channelKey, parseChannelKey } from "../contract/surface.ts";
2
1
  import type { TurnAttachments } from "../domain/attachment.ts";
3
- import { supportOf } from "../domain/block-support.ts";
4
2
  import type {
5
3
  ChannelKey,
6
- IntercomCard,
7
4
  PendingConfirmation,
8
- PostAuthor,
9
- ReplyFile,
10
5
  TurnResult,
11
6
  } from "../domain/conversation.ts";
12
7
  import { AgentError } from "../domain/errors.ts";
13
- import type { InterimPosts } from "../domain/interim.ts";
14
8
  import type { AgentTurnScope } from "../domain/ports.ts";
15
- import type { TurnProgress } from "../domain/progress.ts";
16
9
  import type { Speaker } from "../identity/speakers.ts";
17
10
  import { isQuiet, replyBody } from "../presentation/reply-body.ts";
18
- import { chunksFor } from "../presentation/reply-chunks.ts";
19
11
  import { endOf, settleTurn } from "../routing/settle-turn.ts";
20
12
  import { toolTiers } from "../runtime/tool-tiers.ts";
21
13
  import { withReplyFiles } from "../shared/reply-files.ts";
@@ -26,16 +18,8 @@ import { HelperWork } from "./helper-work.ts";
26
18
  import { roomProgress } from "./room-progress.ts";
27
19
  import { type Routes, routesOf } from "./routes.ts";
28
20
  import { mayApprove } from "./team-approval.ts";
29
- import {
30
- agentOfChannel,
31
- channelIdOf,
32
- channelOwner,
33
- coordinatorOf,
34
- discordIdOf,
35
- discordKey,
36
- groupSeatChannel,
37
- scopeOf,
38
- } from "./team-keys.ts";
21
+ import { coordinatorOf, discordKey } from "./team-keys.ts";
22
+ import { TeamPosts } from "./team-posts.ts";
39
23
  import {
40
24
  type Chain,
41
25
  MAX_CHAIN_MESSAGES,
@@ -65,17 +49,19 @@ export class TeamTurns {
65
49
  /** When each agent or group (by `group:<name>`) last started or ended a turn. */
66
50
  readonly #lastActive = new Map<string, Date>();
67
51
 
52
+ readonly #posts: TeamPosts;
68
53
  readonly #messages: AgentMessages;
69
54
  readonly #groups: GroupTurns;
70
55
 
71
56
  constructor(options: TeamTurnsOptions) {
72
57
  this.#options = options;
73
58
  this.routes = routesOf(options);
59
+ this.#posts = new TeamPosts(options);
74
60
  this.helpers = new HelperWork({
75
61
  store: options.store,
62
+ places: options.places,
76
63
  queue: options.queue,
77
64
  runtime: options.runtime,
78
- roomSurfaces: () => options.surfaces?.roomSurfaces() ?? [],
79
65
  changed: () => options.changed(),
80
66
  logger: options.logger,
81
67
  });
@@ -86,11 +72,11 @@ export class TeamTurns {
86
72
  chains: this.#chains,
87
73
  turn: (agent, scope, postTo, text, chain, extra) =>
88
74
  this.#turn(agent, scope, postTo, text, chain, extra),
89
- post: (channel, as, body) => this.#post(channel, as, body),
75
+ post: (channel, as, body) => this.#posts.post(channel, as, body),
90
76
  current: (agent) => this.#current(agent),
91
77
  mayApprove: (speaker, pending) => this.#mayApprove(speaker, pending),
92
78
  turnChannel: (scope) => this.turnChannel(scope),
93
- chunks: (channel, text) => this.#chunks(channel, text),
79
+ chunks: (channel, text) => this.#posts.chunks(channel, text),
94
80
  };
95
81
  this.#messages = new AgentMessages(host);
96
82
  this.#groups = new GroupTurns(host);
@@ -126,7 +112,7 @@ export class TeamTurns {
126
112
  attachments: TurnAttachments,
127
113
  ): Promise<TurnResult> {
128
114
  const agent = this.#agentOf(channel);
129
- const scope = scopeOf(agent, channel);
115
+ const scope = this.#options.places.scopeOf(agent, channel);
130
116
  const pending = await this.#options.runtime().heldActions(scope.session);
131
117
  const confirmed =
132
118
  pending !== undefined &&
@@ -159,7 +145,7 @@ export class TeamTurns {
159
145
  const agent = this.#agentOf(channel);
160
146
  return this.#turn(
161
147
  agent,
162
- scopeOf(agent, channel),
148
+ this.#options.places.scopeOf(agent, channel),
163
149
  channel,
164
150
  text,
165
151
  { messages: 0, speaker },
@@ -174,18 +160,9 @@ export class TeamTurns {
174
160
  return mayApprove(this.#options.toolTiers ?? toolTiers(), speaker, pending);
175
161
  }
176
162
 
177
- /** The surfaces that host rooms; none for a team without a surface port. */
178
- #rooms(channel: ChannelKey): readonly string[] {
179
- // Only a room key needs the list, which a surface port gives once the hosts are linked.
180
- return discordIdOf(channel) === undefined
181
- ? (this.#options.surfaces?.roomSurfaces() ?? [])
182
- : [];
183
- }
184
-
185
- /** The agent whose channel or room it is. */
163
+ /** The agent whose place it is. */
186
164
  #agentOf(channel: ChannelKey): Agent {
187
- const { store, surfaces } = this.#options;
188
- const agent = agentOfChannel(store, surfaces, channel);
165
+ const agent = this.#options.places.agentOf(channel);
189
166
  if (agent?.status !== "active")
190
167
  throw new AgentError(`no agent owns ${channel}`);
191
168
  return agent;
@@ -224,13 +201,13 @@ export class TeamTurns {
224
201
  ...(scope.group ? { group: scope.group } : {}),
225
202
  };
226
203
  this.#options.events?.turnStarted(turn);
227
- const interim = this.#interim(postTo, agent);
204
+ const interim = this.#posts.interim(postTo, agent);
228
205
  const progress = roomProgress(this.#options, postTo);
229
206
  let result: TurnResult;
230
207
  try {
231
208
  result = await settleTurn(
232
209
  () =>
233
- withReplyFiles(this.#carriesFiles(postTo), () =>
210
+ withReplyFiles(this.#posts.carriesFiles(postTo), () =>
234
211
  this.#options.runtime().runTurn({
235
212
  channel: postTo,
236
213
  selection: this.#options.selection(scope),
@@ -269,8 +246,8 @@ export class TeamTurns {
269
246
  "unattended turn had nothing to say; nothing posted",
270
247
  );
271
248
  else {
272
- const body = replyBody(result, this.#support(postTo));
273
- await this.#post(postTo, this.#current(agent), body);
249
+ const body = replyBody(result, this.#posts.support(postTo));
250
+ await this.#posts.post(postTo, this.#current(agent), body);
274
251
  }
275
252
  } catch (error) {
276
253
  logger.error({ agent: agent.name, err: error }, "agent reply not posted");
@@ -280,17 +257,6 @@ export class TeamTurns {
280
257
  return result;
281
258
  }
282
259
 
283
- /**
284
- * Whether a reply in the channel may carry files: Discord's webhook posts do; a room only when
285
- * its surface declares `supportsFiles`, since a reply with files that surface refuses is lost whole.
286
- */
287
- #carriesFiles(channel: ChannelKey): boolean {
288
- return (
289
- discordIdOf(channel) !== undefined ||
290
- this.#options.surfaces?.of(channel)?.supportsFiles === true
291
- );
292
- }
293
-
294
260
  #active(agent: string, group: string | undefined): void {
295
261
  const now = new Date();
296
262
  this.#lastActive.set(agent, now);
@@ -303,120 +269,6 @@ export class TeamTurns {
303
269
  return this.#options.store.agent(agent.name) ?? agent;
304
270
  }
305
271
 
306
- /** What the surface that serves the channel does there (see `supportOf`). */
307
- #support(channel: ChannelKey) {
308
- return supportOf(
309
- this.#options.surfaces?.of(channel),
310
- channel,
311
- this.#options.surfaces?.lang,
312
- );
313
- }
314
-
315
- /** The messages that carry an agent's text to the channel, cut for the surface that serves it. */
316
- #chunks(channel: ChannelKey, text: string): string[] {
317
- return chunksFor(this.#support(channel), text);
318
- }
319
-
320
- /**
321
- * The turn's interim posts under the agent's name, read as each goes out so a name changed
322
- * during the turn shows; none in a channel no agent or group owns any more.
323
- */
324
- #interim(channel: ChannelKey, agent: Agent): InterimPosts | undefined {
325
- const { store, channels, studio, surfaces } = this.#options;
326
- if (discordIdOf(channel) === undefined) {
327
- // A room's interim posts are its surface's, under the agent as author.
328
- const first = surfaces?.interim(channel, this.#author(agent));
329
- if (!surfaces || !first) return undefined;
330
- return {
331
- ...(first.tools === false ? { tools: false } : {}),
332
- // The poster cuts text for the surface the posts go to.
333
- ...(first.blocks ? { blocks: first.blocks } : {}),
334
- ...(first.blockText ? { blockText: first.blockText } : {}),
335
- post: async (text) => {
336
- if (!channelOwner(store, channel, this.#rooms(channel)))
337
- throw new AgentError(`${channel} is archived`);
338
- const posts = surfaces.interim(
339
- channel,
340
- this.#author(this.#current(agent)),
341
- );
342
- if (!posts) throw new AgentError(`${channel} shows no interim posts`);
343
- return posts.post(text);
344
- },
345
- };
346
- }
347
- if (!channels?.interim) return undefined;
348
- const interim = channels.interim.bind(channels);
349
- return {
350
- post: async (text) => {
351
- if (!channelOwner(store, channel))
352
- throw new AgentError(`${channel} is archived`);
353
- const as = this.#current(agent);
354
- return interim(channelIdOf(channel), {
355
- name: as.displayName,
356
- avatarUrl: studio.url(as.avatarHash),
357
- }).post(text);
358
- },
359
- };
360
- }
361
-
362
- /**
363
- * Posts under the agent's name. A channel no agent or group owns any more, archived while a
364
- * turn ran, gets nothing, so its webhook is not made again.
365
- */
366
- async #post(
367
- channel: ChannelKey,
368
- as: Agent,
369
- body: {
370
- thinking?: string;
371
- chunks: string[];
372
- files?: ReplyFile[];
373
- threadId?: string;
374
- failed?: true;
375
- intercom?: IntercomCard;
376
- },
377
- ): Promise<void> {
378
- const { store, channels, studio, surfaces, logger } = this.#options;
379
- if (!channelOwner(store, channel, this.#rooms(channel))) {
380
- logger.info(
381
- { channel, agent: as.name },
382
- "post to an archived channel dropped",
383
- );
384
- return;
385
- }
386
- // Discord ignores `failed`.
387
- const { failed, ...rest } = body;
388
- if (discordIdOf(channel) === undefined) {
389
- if (!surfaces)
390
- throw new AgentError(`no surface serves the room ${channel}`);
391
- const { thinking, chunks, files, threadId, intercom } = rest;
392
- // A thread of the room's surface is a channel of that surface, and speaks there.
393
- return surfaces.sendReply(
394
- threadId === undefined
395
- ? channel
396
- : channelKey(parseChannelKey(channel).surface, threadId),
397
- {
398
- ...(thinking ? { thinking } : {}),
399
- chunks,
400
- ...(files?.length ? { files } : {}),
401
- author: this.#author(as),
402
- ...(failed ? { failed } : {}),
403
- ...(intercom ? { intercom } : {}),
404
- },
405
- );
406
- }
407
- if (!channels) throw new AgentError(`no Discord channels serve ${channel}`);
408
- return channels.post(channelIdOf(channel), {
409
- name: as.displayName,
410
- avatarUrl: studio.url(as.avatarHash),
411
- ...rest,
412
- });
413
- }
414
-
415
- /** Who speaks for the agent on a surface that shows authors. */
416
- #author(agent: Agent): PostAuthor {
417
- return { name: agent.displayName, agent: agent.name };
418
- }
419
-
420
272
  /**
421
273
  * Posts text under the caller's name in the channel of its turn: the group's in a group
422
274
  * round, otherwise its own, as a change report is.
@@ -424,8 +276,8 @@ export class TeamTurns {
424
276
  async postAs(caller: AgentTurnScope, text: string): Promise<void> {
425
277
  const agent = this.#options.store.activeAgent(caller.name);
426
278
  const channel = this.turnChannel(caller);
427
- const chunks = this.#chunks(channel, text);
428
- await this.#post(channel, this.#current(agent), { chunks });
279
+ const chunks = this.#posts.chunks(channel, text);
280
+ await this.#posts.post(channel, this.#current(agent), { chunks });
429
281
  }
430
282
 
431
283
  /** The channel the scope's turns run in: the group's in a group round, otherwise its own. */
@@ -435,7 +287,10 @@ export class TeamTurns {
435
287
  : undefined;
436
288
  if (!group) return scope.home;
437
289
  // A seat of a room's group runs in that room; its running turn knows which.
438
- return this.#posting.get(scope.session) ?? groupSeatChannel(group, scope);
290
+ return (
291
+ this.#posting.get(scope.session) ??
292
+ this.#options.places.seatChannel(group, scope)
293
+ );
439
294
  }
440
295
 
441
296
  /**
@@ -443,8 +298,8 @@ export class TeamTurns {
443
298
  * its name: the entry channel, or, without Discord, its room on the first surface that hosts rooms.
444
299
  */
445
300
  async announce(text: string): Promise<void> {
446
- const { store, entryChannelId } = this.#options;
447
- const coordinator = coordinatorOf(store, this.#options);
301
+ const { store, places, entryChannelId } = this.#options;
302
+ const coordinator = coordinatorOf(store, places, this.#options);
448
303
  if (!coordinator)
449
304
  throw new AgentError(
450
305
  entryChannelId === undefined
@@ -457,7 +312,9 @@ export class TeamTurns {
457
312
  : this.routes.primary(coordinator.name);
458
313
  if (!home)
459
314
  throw new AgentError(`${coordinator.name} has no room to post in`);
460
- await this.#post(home, coordinator, { chunks: this.#chunks(home, text) });
315
+ await this.#posts.post(home, coordinator, {
316
+ chunks: this.#posts.chunks(home, text),
317
+ });
461
318
  }
462
319
 
463
320
  message(...args: Parameters<AgentMessages["message"]>): string {
@@ -0,0 +1,29 @@
1
+ import type { PlaceProvider } from "../contract/places.ts";
2
+ import type { ChatSurface } from "../contract/surface.ts";
3
+ import type { RoundtablePlugin } from "../plugin-api/plugin.ts";
4
+
5
+ /** The surfaces and place providers the host would link: a stand-in surface for each provider and a room surface for each of `rooms`. */
6
+ export function placesPlugin(
7
+ rooms: readonly string[],
8
+ providers: readonly PlaceProvider[],
9
+ ): RoundtablePlugin[] {
10
+ if (rooms.length + providers.length === 0) return [];
11
+ const surface = (name: string, agentRooms: boolean): ChatSurface => ({
12
+ surface: name,
13
+ start: async () => undefined,
14
+ sendReply: async () => undefined,
15
+ ...(agentRooms ? { agentRooms: true } : {}),
16
+ });
17
+ return [
18
+ {
19
+ name: "places-fixture",
20
+ setup: () => ({
21
+ surfaces: [
22
+ ...providers.map((p) => surface(p.surface, false)),
23
+ ...rooms.map((room) => surface(room, true)),
24
+ ],
25
+ places: [...providers],
26
+ }),
27
+ },
28
+ ];
29
+ }
@@ -10,7 +10,8 @@ import { FileAvatarStudio } from "../agents/avatar-studio.ts";
10
10
  import { RelevanceScorer } from "../agents/group-round.ts";
11
11
  import { modeOrigins } from "../agents/helper-modes.ts";
12
12
  import { Routes } from "../agents/routes.ts";
13
- import { agentOfChannel, discordKey } from "../agents/team-keys.ts";
13
+ import { discordKey } from "../agents/team-keys.ts";
14
+ import { TeamPlaces } from "../agents/team-places.ts";
14
15
  import { ownerAttachmentDir } from "../attachments/attachment-dir.ts";
15
16
  import { ROOM_LAYOUT } from "../contract/room-layout.ts";
16
17
  import type { AgentSessions } from "../contract/runtime.ts";
@@ -123,6 +124,7 @@ export function agentServerPlugin(
123
124
  const teamId = options.teamId ?? options.guildId ?? LOCAL_TEAM_ID;
124
125
  /** Set once the plugin has set up; the preflight reads it after every plugin linked. */
125
126
  let hostsRooms: (() => boolean) | undefined;
127
+ let servesDiscord: (() => boolean) | undefined;
126
128
  let linkRoutes: (() => void) | undefined;
127
129
  return {
128
130
  name: AGENT_SERVER_PLUGIN,
@@ -157,6 +159,11 @@ export function agentServerPlugin(
157
159
  throw new ConfigError(
158
160
  "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.",
159
161
  );
162
+ // Channels the team makes but no provider reads would leave its agents unanswered.
163
+ if (servesDiscord && !servesDiscord())
164
+ 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.`,
166
+ );
160
167
  // The surfaces the rules name exist only once every plugin has registered its own.
161
168
  linkRoutes?.();
162
169
  },
@@ -172,6 +179,7 @@ export function agentServerPlugin(
172
179
  ? connection.agentChannels(options.guildId)
173
180
  : undefined;
174
181
  if (!channels) hostsRooms = () => surfaces.roomSurfaces().length > 0;
182
+ else servesDiscord = () => context.places.of("discord") !== undefined;
175
183
  const studio = new FileAvatarStudio({
176
184
  dir: join(options.dataDir, "avatars"),
177
185
  skins: context.env.characterSkins,
@@ -195,7 +203,10 @@ export function agentServerPlugin(
195
203
  const skills = context.services.find(SKILLS);
196
204
  const { agents: store } = await openStores(context, teamId);
197
205
  // A temp knight's conversations follow the modes of the one that made it.
198
- context.services.find(MODES)?.trackOrigins(modeOrigins(store, surfaces));
206
+ // Where the agents are, through the place providers the host links once every plugin is set up.
207
+ const places = new TeamPlaces(store, store.places, context.places);
208
+ store.readPlacesWith(places);
209
+ context.services.find(MODES)?.trackOrigins(modeOrigins(store, places));
199
210
  const running = context.services.get(RUNTIME);
200
211
  const judge = providers.judge;
201
212
  const confirmations = new ConfirmationJudge({
@@ -228,20 +239,16 @@ export function agentServerPlugin(
228
239
  const routes = new Routes({
229
240
  routing: options.routing,
230
241
  store,
231
- roomSurfaces: () => surfaces.roomSurfaces(),
242
+ places,
232
243
  latest: (agent) => store.conversations.latest(agent),
233
- discordChannels: channels !== undefined,
234
244
  logger,
235
245
  });
236
246
  // The surfaces the rules name are registered by the time every plugin has set up.
237
- linkRoutes = () =>
238
- routes.validate({
239
- names: surfaces.names?.() ?? [],
240
- discordChannels: channels !== undefined,
241
- });
247
+ linkRoutes = () => routes.validate({ names: surfaces.names?.() ?? [] });
242
248
  const built: DiscordAgentTeam = new DiscordAgentTeam({
243
249
  routes,
244
- guildId: teamId,
250
+ places,
251
+ teamId,
245
252
  discordGuild: options.guildId,
246
253
  ...(options.entryChannelId !== undefined
247
254
  ? { entryChannelId: options.entryChannelId }
@@ -387,13 +394,13 @@ export function agentServerPlugin(
387
394
  channels: [
388
395
  agentClaim({
389
396
  owner: options.owner,
390
- discordGuild: options.guildId,
397
+ spaceOf: (channel) => places.spaceOf(channel),
391
398
  ...(options.speakers ? { speakers: options.speakers } : {}),
392
399
  team: built,
393
400
  runtime: running,
394
401
  surface: context.surfaces,
395
402
  integrationChannel: (origin) => {
396
- const agent = agentOfChannel(store, surfaces, origin);
403
+ const agent = places.agentOf(origin);
397
404
  return agent
398
405
  ? routes.of(agent.name, "integration", origin)
399
406
  : origin;
@@ -75,6 +75,8 @@ export interface DiscordOptions {
75
75
  dataDir: string;
76
76
  /** The name of the root slash command, without the slash. */
77
77
  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. */
79
+ agentGuild?: string;
78
80
  /** Text appended as it is to the refusal a non-owner gets, such as a pointer to the commands anyone may use. */
79
81
  refusalHint?: string;
80
82
  /** The host's channel context settings; `false` turns it off. Default: on, with the defaults. */
@@ -241,6 +243,10 @@ export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
241
243
  return {
242
244
  // The host starts the surface first; it registers the composed commands as it connects.
243
245
  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
+ : [],
244
250
  // A person's Discord direct messages, through a Discord identity of theirs.
245
251
  directChannels: [
246
252
  discordDirectChannel({
@@ -0,0 +1,141 @@
1
+ import type { TSchema } from "typebox";
2
+ import type {
3
+ IntercomCard,
4
+ PostAuthor,
5
+ ReplyFile,
6
+ } from "../domain/conversation.ts";
7
+ import type { InterimPosts } from "../domain/interim.ts";
8
+ import type { ChannelKey } from "../domain/sessions.ts";
9
+ import { channelKey, parseChannelKey } from "./surface.ts";
10
+
11
+ /** What a place belongs to. */
12
+ export type PlaceKind = "agent" | "group";
13
+
14
+ export interface PlaceRef {
15
+ kind: PlaceKind;
16
+ name: string;
17
+ }
18
+
19
+ /** Who speaks in a post: the agent's name and look. */
20
+ export interface PlaceAuthor extends PostAuthor {
21
+ avatarUrl: string;
22
+ }
23
+
24
+ /** One agent post in a place; what a Discord channel post and a room's `OutboundReply` carry. */
25
+ export interface PlacePost {
26
+ author: PlaceAuthor;
27
+ thinking?: string;
28
+ chunks: string[];
29
+ files?: ReplyFile[];
30
+ /** A thread of the place to post in instead, such as a dispatch's. */
31
+ thread?: string;
32
+ intercom?: IntercomCard;
33
+ failed?: true;
34
+ }
35
+
36
+ /** What `ensure` makes or brings back a place for. */
37
+ export interface PlaceSpec extends PlaceRef {
38
+ displayName: string;
39
+ /** An agent's display name; a group's members and host on one line. */
40
+ topic: string;
41
+ /** A temp knight's parent's place id on this surface: the place is made under it (a Discord thread). */
42
+ parent?: string;
43
+ /** The stored id of an archived or checked place, to bring back instead of making a new one. */
44
+ existing?: string;
45
+ /** The values of this provider's `createArguments` the creating tool was given, such as `category`. */
46
+ hints?: Readonly<Record<string, string>>;
47
+ }
48
+
49
+ /** What `check` finds of a stored place at start. */
50
+ export type PlaceCheck = "ok" | "gone" | "foreign";
51
+
52
+ /** An argument a provider adds to a creation tool: a Typebox schema, with its description in the schema. */
53
+ export type ToolArgument = TSchema;
54
+
55
+ /**
56
+ * What a chat surface holds of the team's places: where an agent or group is spoken to on it.
57
+ * The members a minimal provider needs are `surface`, `storage`, `key`, `placeOf` and `post`; the
58
+ * rest are optional capabilities. A plugin contributes providers with `places`; a surface that
59
+ * hosts agent rooms (`agentRooms: true`) and has no provider gets a derived one from the host.
60
+ */
61
+ export interface PlaceProvider {
62
+ /** The surface whose keys this provider's places have; one provider per surface. */
63
+ readonly surface: string;
64
+ /** `derived`: the place exists with the name and nothing is stored. `stored`: the place has an id of the surface's own, which the team keeps. */
65
+ readonly storage: "derived" | "stored";
66
+ /** The key of a place: from the name when derived, from `id` when stored (which a stored provider requires). */
67
+ key(ref: PlaceRef, id?: string): ChannelKey;
68
+ /** Which place a key of this surface is: the ref of a derived one, the id of a stored one; undefined for a key that is none of this provider's. */
69
+ placeOf(key: ChannelKey): PlaceRef | { id: string } | undefined;
70
+ /** Posts under the author's name and look. */
71
+ post(key: ChannelKey, post: PlacePost): Promise<void>;
72
+ /** The running turn's interim posts under the author; absent = final replies only. */
73
+ interim?(key: ChannelKey, author: PlaceAuthor): InterimPosts | undefined;
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
+ 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. */
77
+ remove?(
78
+ id: string,
79
+ spec: PlaceSpec & { helper: boolean },
80
+ ): Promise<string | undefined>;
81
+ /** Stored, at start: `gone` archives the owner as a deletion would; `foreign` (the id is no place of this provider's space, such as a channel of a guild the team left) drops the row, and `ensure` makes a new one. */
82
+ check?(id: string): Promise<PlaceCheck>;
83
+ /** Writes a group's topic; never awaited by a turn. */
84
+ describe?(id: string, topic: string): Promise<void>;
85
+ /** Reports a place deleted on the surface; its owner is archived. Register during setup. */
86
+ onRemoved?(listener: (id: string) => void): void;
87
+ /** The space (a Discord guild) whose every channel belongs to the team: unaddressed ones are the owner's notes and go unanswered. */
88
+ readonly space?: string;
89
+ /** How the model names a place in text, such as `<#id>`; default the key. */
90
+ mention?(key: ChannelKey): string;
91
+ /** The conversation keys of a stored group's seats and log, for a provider that must keep forms already in use. Default `agentgroup:<surface>.<id>.<agent>` and `<group>@<surface>`. */
92
+ conversations?: {
93
+ seat(groupId: string, agent: string): ChannelKey;
94
+ log(group: string): string;
95
+ };
96
+ /** The id of the place whose agent is the coordinator, such as Discord's entry channel; absent = the configured `coordinator`. */
97
+ readonly coordinatorPlace?: string;
98
+ /** Arguments this provider adds to `agent_create` and `group_create`; their values reach `ensure` as `hints`. */
99
+ createArguments?: {
100
+ agent?: Readonly<Record<string, ToolArgument>>;
101
+ group?: Readonly<Record<string, ToolArgument>>;
102
+ };
103
+ /** A section of `agent_list` after the team, such as Discord's categories in server order. */
104
+ layoutText?(): Promise<string | undefined>;
105
+ }
106
+
107
+ /**
108
+ * Every place provider of the host, chosen by a surface or a channel key. Calls during setup
109
+ * throw NotLinkedError, because the providers are collected once every plugin is set up.
110
+ */
111
+ export interface PlacePort {
112
+ /** The provider of a surface by name, or of a channel key by its prefix; undefined when none serves it. */
113
+ of(surfaceOrKey: string): PlaceProvider | undefined;
114
+ /** The stored providers, in contribution order. */
115
+ stored(): readonly PlaceProvider[];
116
+ /** Every provider in the order "auto" prefers: the stored ones in contribution order, then the derived ones in surface order. */
117
+ all(): readonly PlaceProvider[];
118
+ }
119
+
120
+ const ROOM_ID = /^(agent|group)\.([a-z0-9-]{1,32})$/;
121
+
122
+ /** The key of an agent's or group's room on a surface: `<surface>:agent.<name>` or `<surface>:group.<name>`. */
123
+ export const roomKey = (surface: string, ref: PlaceRef): ChannelKey =>
124
+ channelKey(surface, `${ref.kind}.${ref.name}`);
125
+
126
+ /**
127
+ * Which agent's or group's room a key of `surface` is, when its id has the exact shape of a room;
128
+ * undefined for any other key, so no other key is ever taken for one.
129
+ */
130
+ export function roomRef(
131
+ key: ChannelKey,
132
+ surface: string,
133
+ ): PlaceRef | undefined {
134
+ const at = typeof key === "string" ? key.indexOf(":") : -1;
135
+ if (at <= 0) return undefined;
136
+ const parsed = parseChannelKey(key);
137
+ if (parsed.surface !== surface) return undefined;
138
+ const match = ROOM_ID.exec(parsed.id);
139
+ if (!match) return undefined;
140
+ return { kind: match[1] as PlaceKind, name: match[2] as string };
141
+ }