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
@@ -1,8 +1,5 @@
1
1
  import {
2
- CharacterError,
3
2
  type CharacterInput,
4
- type CharacterSpec,
5
- resolveCharacter,
6
3
  suggestCharacter,
7
4
  } from "../../characters/index.ts";
8
5
  import { parseChannelKey } from "../contract/surface.ts";
@@ -11,27 +8,41 @@ import type { AgentTurnScope } from "../domain/ports.ts";
11
8
  import { SYSTEM_PRINCIPAL } from "../identity/principal-store.ts";
12
9
  import { addressee, type Speaker } from "../identity/speakers.ts";
13
10
  import type { ConversationModes } from "../modes/conversation-modes.ts";
14
- import type { AgentChange } from "../plugin-api/services.ts";
11
+ import type { AgentChange, NewAgent } from "../plugin-api/services.ts";
15
12
  import { openingTaskText } from "./agent-prompt.ts";
16
- import { characterOf, overBase } from "./agent-rules.ts";
17
13
  import { modelSetting, thinkingSetting } from "./agent-settings.ts";
18
14
  import type { Agent } from "./agent-store.ts";
19
- import type { AvatarMode } from "./agent-tools.ts";
20
15
  import { createHelper } from "./helper-create.ts";
21
16
  import { routesOf } from "./routes.ts";
22
- import { groupTopic, teamCategory } from "./team-layout.ts";
17
+ import { resolveLook } from "./team-looks.ts";
23
18
  import type { TeamContext } from "./team-options.ts";
19
+ import { type PlaceWish, TeamPlaceWrites } from "./team-place-writes.ts";
20
+ import { groupTopic } from "./team-text.ts";
24
21
 
25
- /** Said when an avatar is to be redrawn on a host without an image provider. */
26
- const NO_IMAGE_PROVIDER =
27
- "No image provider is configured, so avatars cannot be redrawn; the current picture stays. A plugin fills the images slot to draw them.";
22
+ /**
23
+ * What the creating tools and the team's callers give a provider's own arguments: `hints`, with
24
+ * the string fields left over from the known ones, which are the arguments a provider added before
25
+ * `hints` existed (the deprecated `NewAgent.category`). Undefined when there are none.
26
+ */
27
+ function providerHints(
28
+ extras: object,
29
+ hints: Readonly<Record<string, string>> | undefined,
30
+ ): Readonly<Record<string, string>> | undefined {
31
+ const legacy = Object.entries(extras).filter(
32
+ (entry): entry is [string, string] => typeof entry[1] === "string",
33
+ );
34
+ const all = { ...Object.fromEntries(legacy), ...hints };
35
+ return Object.keys(all).length > 0 ? all : undefined;
36
+ }
28
37
 
29
38
  /** Creating and changing agents, their avatars, and groups. */
30
39
  export class TeamEditing {
31
40
  readonly #ctx: TeamContext;
41
+ readonly #places: TeamPlaceWrites;
32
42
 
33
43
  constructor(ctx: TeamContext) {
34
44
  this.#ctx = ctx;
45
+ this.#places = new TeamPlaceWrites(ctx);
35
46
  }
36
47
 
37
48
  /**
@@ -96,7 +107,8 @@ export class TeamEditing {
96
107
  /** Fields of its look; any left out come from the look its role suggests. */
97
108
  character?: CharacterInput;
98
109
  task: string;
99
- category?: string;
110
+ /** The values of the arguments the surfaces' place providers add to the creation tool. */
111
+ hints?: Readonly<Record<string, string>>;
100
112
  skills?: string[];
101
113
  /** Turn long-running mode on for its conversations; the speaker must be an owner. */
102
114
  longRunning?: boolean;
@@ -108,6 +120,20 @@ export class TeamEditing {
108
120
  throw new AgentError(
109
121
  "agent_create can only be used during an agent turn.",
110
122
  );
123
+ const {
124
+ name,
125
+ displayName,
126
+ prompt,
127
+ avatarPrompt: _,
128
+ character,
129
+ task,
130
+ hints,
131
+ skills,
132
+ longRunning,
133
+ ...extras
134
+ } = input;
135
+ // A caller written before `hints` gives a provider's argument as a field of its own.
136
+ const given = providerHints(extras, hints);
111
137
  // The opening task starts on the surface the caller's turn runs on, as the web form's does.
112
138
  const working = this.#ctx.turns.workingIn(caller.name);
113
139
  const made = await this.#create(
@@ -117,23 +143,22 @@ export class TeamEditing {
117
143
  creator: this.#ctx.options.store.agent(caller.name),
118
144
  openIn: working ? parseChannelKey(working).surface : undefined,
119
145
  },
120
- input,
146
+ {
147
+ name,
148
+ displayName,
149
+ prompt,
150
+ ...(character ? { character } : {}),
151
+ task,
152
+ ...(given ? { hints: given } : {}),
153
+ ...(skills ? { skills } : {}),
154
+ ...(longRunning === undefined ? {} : { longRunning }),
155
+ },
121
156
  );
122
157
  return made.text;
123
158
  }
124
159
 
125
160
  #helperChain: Promise<void> = Promise.resolve();
126
161
 
127
- /** Closes the thread of a temp knight whose row was never written, logging a failure. */
128
- async #closeOrphan(threadId?: string): Promise<void> {
129
- const { channels, logger } = this.#ctx.options;
130
- await channels
131
- ?.closeThread?.(threadId ?? "")
132
- .catch((err: unknown) =>
133
- logger.warn({ err }, "orphan thread not closed"),
134
- );
135
- }
136
-
137
162
  /** The agent tool: a knight makes a temp knight for one task; see `createHelper`. */
138
163
  createHelper(
139
164
  caller: AgentTurnScope,
@@ -160,27 +185,34 @@ export class TeamEditing {
160
185
  * refused, since the opening task runs as `speaker`): the checks, picture, channel and opening
161
186
  * task of `create`, and the owner's model and thinking. Without a task it waits in its room.
162
187
  */
163
- async createFor(
164
- speaker: Speaker,
165
- input: {
166
- name: string;
167
- displayName: string;
168
- prompt: string;
169
- character?: CharacterInput;
170
- task?: string;
171
- openIn?: string;
172
- category?: string;
173
- skills?: string[];
174
- model?: string;
175
- thinking?: string;
176
- },
177
- ): Promise<Agent> {
188
+ async createFor(speaker: Speaker, input: NewAgent): Promise<Agent> {
178
189
  if (speaker.tier !== "owner")
179
190
  throw new AgentError("Only an owner may create an agent here.");
180
- const { model, thinking, task, openIn, ...rest } = input;
191
+ const {
192
+ model,
193
+ thinking,
194
+ task,
195
+ openIn,
196
+ hints,
197
+ name,
198
+ displayName,
199
+ prompt,
200
+ character,
201
+ skills,
202
+ ...extras
203
+ } = input;
204
+ const given = providerHints(extras, hints);
181
205
  const made = await this.#create(
182
206
  { speaker, by: speaker.name, creator: undefined, openIn },
183
- { ...rest, ...(task ? { task } : {}) },
207
+ {
208
+ name,
209
+ displayName,
210
+ prompt,
211
+ ...(character ? { character } : {}),
212
+ ...(skills ? { skills } : {}),
213
+ ...(task ? { task } : {}),
214
+ ...(given ? { hints: given } : {}),
215
+ },
184
216
  { model, thinking },
185
217
  );
186
218
  return made.agent;
@@ -220,7 +252,7 @@ export class TeamEditing {
220
252
  openIn?: string | undefined;
221
253
  /** Makes the agent a temp knight of this knight, which settles on the parent's model. */
222
254
  parent?: Agent | undefined;
223
- /** The conversation a temp knight is made from: made on Discord, it lives in a thread of the parent's channel, made elsewhere in its rooms alone. */
255
+ /** The conversation a temp knight is made from: it lives in a thread of the parent's place on that surface, and in its rooms alone where no thread is made. */
224
256
  origin?: string | undefined;
225
257
  preset?: string | undefined;
226
258
  },
@@ -232,7 +264,7 @@ export class TeamEditing {
232
264
  avatarPrompt?: string;
233
265
  character?: CharacterInput;
234
266
  task?: string;
235
- category?: string;
267
+ hints?: Readonly<Record<string, string>>;
236
268
  skills?: string[];
237
269
  longRunning?: boolean;
238
270
  },
@@ -241,11 +273,10 @@ export class TeamEditing {
241
273
  thinking?: string | undefined;
242
274
  } = {},
243
275
  ): Promise<{ agent: Agent; text: string }> {
244
- const { store, studio, channels, queue, skills, places, logger } =
245
- this.#ctx.options;
276
+ const { store, studio, queue, skills, places, logger } = this.#ctx.options;
246
277
  this.#refuseSkillsOff(input.skills);
247
278
  const {
248
- category,
279
+ hints,
249
280
  skills: carried = [],
250
281
  character: wanted,
251
282
  avatarPrompt: _ignored,
@@ -254,7 +285,6 @@ export class TeamEditing {
254
285
  ...fields
255
286
  } = input;
256
287
  const modes = longRunning ? this.#longRunning(who.speaker) : undefined;
257
- const categoryName = teamCategory(category, "Agents");
258
288
  store.checkNewName(input.name);
259
289
  skills?.checkRegistered(carried);
260
290
  // An unusable model or thinking fails the create first; a temp knight runs its parent's unless told otherwise.
@@ -268,39 +298,40 @@ export class TeamEditing {
268
298
  settings.thinking === undefined && who.parent
269
299
  ? who.parent.thinking
270
300
  : thinkingSetting(settings.thinking);
271
- // The picture comes before the row and the channel: a render failure fails the create.
301
+ // The picture comes before the row and the place: a render failure fails the create.
272
302
  const taken = store
273
303
  .agents()
274
304
  .flatMap((other) =>
275
305
  other.status === "active" && other.character ? [other.character] : [],
276
306
  );
277
307
  const suggested = suggestCharacter(input, taken);
278
- const character = this.#resolve(wanted ?? {}, suggested);
308
+ const character = resolveLook(wanted ?? {}, suggested);
279
309
  const avatarHash = await studio.render(character);
280
- // Without Discord channels the agent lives in its rooms, which exist as soon as it does.
281
- const onDiscord = who.origin?.startsWith("discord:") !== false;
282
- const channelId = who.parent
283
- ? onDiscord && who.parent.channelId && channels?.createThread
284
- ? await channels.createThread(who.parent.channelId, input.displayName)
285
- : undefined
286
- : await channels?.createChannel(
287
- input.name,
288
- input.displayName,
289
- categoryName,
290
- );
310
+ // Without stored places the agent lives in its rooms, which exist as soon as it does.
311
+ const wish: PlaceWish = {
312
+ kind: "agent",
313
+ name: input.name,
314
+ displayName: input.displayName,
315
+ topic: input.displayName,
316
+ ...(hints ? { hints } : {}),
317
+ };
318
+ const made = await this.#places.make(
319
+ wish,
320
+ who.parent ? { parent: who.parent, origin: who.origin } : undefined,
321
+ );
291
322
  let agent: Agent;
292
323
  try {
293
324
  agent = await store.createAgent({
294
325
  ...fields,
295
326
  character,
296
327
  avatarHash,
297
- ...(channelId ? { channelId } : {}),
298
328
  ...(who.parent ? { parent: who.parent.name } : {}),
299
329
  ...(who.parent && who.origin ? { origin: who.origin } : {}),
300
330
  ...(who.parent && who.preset ? { preset: who.preset } : {}),
301
331
  });
332
+ await this.#places.record(wish, made);
302
333
  } catch (error) {
303
- await this.#closeOrphan(channelId);
334
+ if (who.parent) await this.#places.discard(wish, made);
304
335
  throw error;
305
336
  }
306
337
  try {
@@ -325,7 +356,8 @@ export class TeamEditing {
325
356
  for (const key of places.keysOf(agent.name))
326
357
  await modes.set(key, { longRunning: true }, who.speaker);
327
358
  const avatar = `its picture is the ${character.class} look${modes ? "; long-running mode is on" : ""}`;
328
- const where = channelId ? ` in <#${channelId}>` : "";
359
+ const where =
360
+ made.length > 0 ? ` in ${this.#places.mentions(wish, made)}` : "";
329
361
  if (!task)
330
362
  return {
331
363
  agent,
@@ -371,109 +403,48 @@ export class TeamEditing {
371
403
  };
372
404
  }
373
405
 
374
- /** The agent tool: changes a look, then says what the owner sees. */
375
- async avatar(name: string, look: CharacterInput): Promise<string> {
376
- const agent = await this.dress(name, look);
377
- return `"${agent.displayName}" now looks like a ${characterOf(agent).class}; the new picture shows from its next message.`;
378
- }
379
-
380
- /**
381
- * Changes an agent's look. The input is resolved over the agent's current character; a new
382
- * class keeps the agent's colors unless the input names a palette or colors. The picture is
383
- * rendered before anything is stored, and the character and picture are stored together.
384
- */
385
- async dress(name: string, input: CharacterInput): Promise<Agent> {
386
- const { store, studio, logger } = this.#ctx.options;
387
- const agent = store.activeAgent(name);
388
- const base = characterOf(agent);
389
- const character = this.#resolve(input, base);
390
- let avatarHash: string;
391
- try {
392
- avatarHash = await studio.render(character);
393
- } catch (error) {
394
- throw new AgentError(
395
- `The picture could not be rendered: ${error instanceof Error ? error.message : String(error)}. The previous look stays.`,
396
- );
397
- }
398
- const dressed = await store.updateAgent(name, { character, avatarHash });
399
- logger.info({ agent: name, class: character.class }, "agent dressed");
400
- this.#ctx.changed();
401
- return dressed;
402
- }
403
-
404
- /** @deprecated Use `dress`; removed in 1.0. Draws and stores a new picture. */
405
- async redrawAvatar(
406
- name: string,
407
- mode: AvatarMode,
408
- text?: string,
409
- ): Promise<Agent> {
410
- const { store, studio, logger } = this.#ctx.options;
411
- const agent = store.activeAgent(name);
412
- if (studio.canDraw === false) throw new AgentError(NO_IMAGE_PROVIDER);
413
- if (mode !== "redraw" && !text?.trim())
414
- throw new AgentError(
415
- mode === "edit"
416
- ? "Give the edit instruction as text."
417
- : "Give the new avatar prompt as text.",
418
- );
419
- const avatarPrompt =
420
- mode === "new_prompt" ? (text as string) : agent.avatarPrompt;
421
- if (mode === "new_prompt") await store.updateAgent(name, { avatarPrompt });
422
- let hash: string;
423
- try {
424
- hash =
425
- mode === "edit"
426
- ? await studio.edit(agent.avatarHash, text as string)
427
- : await studio.draw(avatarPrompt);
428
- } catch (error) {
429
- logger.warn({ agent: name, mode, err: error }, "avatar drawing failed");
430
- throw new AgentError(
431
- `The avatar could not be drawn: ${error instanceof Error ? error.message : String(error)}. The previous picture stays.`,
432
- );
433
- }
434
- logger.info({ agent: name, mode }, "avatar redrawn");
435
- return store.updateAgent(name, { avatarHash: hash });
436
- }
437
-
438
- /**
439
- * An input over a base look (see overBase); a bad field is an AgentError that names it.
440
- */
441
- #resolve(input: CharacterInput, base: CharacterSpec): CharacterSpec {
442
- try {
443
- return resolveCharacter(overBase(input, base), base);
444
- } catch (error) {
445
- if (error instanceof CharacterError)
446
- throw new AgentError(`The look is not usable: ${error.message}.`);
447
- throw error;
448
- }
449
- }
450
-
451
406
  async createGroup(input: {
452
407
  name: string;
453
408
  displayName: string;
454
409
  members: string[];
455
410
  host?: string;
456
- category?: string;
411
+ hints?: Readonly<Record<string, string>>;
457
412
  }): Promise<string> {
458
- const { store, channels, logger } = this.#ctx.options;
459
- const { category, ...fields } = input;
460
- const parent = teamCategory(category, "Groups");
413
+ const { store, logger } = this.#ctx.options;
414
+ const {
415
+ name,
416
+ displayName,
417
+ members,
418
+ host: named,
419
+ hints: given,
420
+ ...extras
421
+ } = input;
422
+ const hints = providerHints(extras, given);
423
+ const fields = {
424
+ name,
425
+ displayName,
426
+ members,
427
+ ...(named ? { host: named } : {}),
428
+ };
461
429
  const host =
462
430
  input.host ??
463
431
  (input.members.includes("coordinator")
464
432
  ? "coordinator"
465
433
  : (input.members[0] ?? ""));
466
434
  store.checkNewGroup(input.name, input.members, host, input.displayName);
467
- const topic = groupTopic({ ...fields, host, status: "active" }, store);
468
- const channelId = await channels?.createChannel(input.name, topic, parent);
469
- const group = await store.createGroup({
470
- ...fields,
471
- host,
472
- ...(channelId ? { channelId } : {}),
473
- });
435
+ const wish: PlaceWish = {
436
+ kind: "group",
437
+ name: input.name,
438
+ displayName: input.displayName,
439
+ topic: groupTopic({ ...fields, host, status: "active" }, store),
440
+ ...(hints ? { hints } : {}),
441
+ };
442
+ const made = await this.#places.make(wish);
443
+ const group = await store.createGroup({ ...fields, host });
444
+ await this.#places.record(wish, made);
474
445
  logger.info({ group: group.name, members: group.members }, "group created");
475
446
  this.#ctx.changed();
476
- return `Created the group "${group.displayName}"${channelId ? ` in <#${channelId}>` : ""} with ${group.members.join(", ")}; host ${group.host}.`;
447
+ return `Created the group "${group.displayName}"${made.length > 0 ? ` in ${this.#places.mentions(wish, made)}` : ""} with ${group.members.join(", ")}; host ${group.host}.`;
477
448
  }
478
449
 
479
450
  async updateGroup(
@@ -6,15 +6,21 @@ import { answersTo, helperSurface, isHelper } from "./agent-rules.ts";
6
6
  import type { Agent } from "./agent-store.ts";
7
7
  import type { HelpersEnded } from "./helper-ops.ts";
8
8
  import type { TeamContext } from "./team-options.ts";
9
+ import {
10
+ type MadePlace,
11
+ type PlaceWish,
12
+ TeamPlaceWrites,
13
+ } from "./team-place-writes.ts";
9
14
 
10
15
  /** How often the host looks for finished temp knights past their keep. */
11
16
  const SWEEP_EVERY_MS = 3_600_000;
12
17
 
13
18
  /**
14
19
  * The team's temp knights after they are made: which a knight has, which are finished, and their
15
- * archive, restore, and sweep. A temp knight made on Discord lives in a thread of its parent's
16
- * channel; one made in the web app gets that thread only once someone reaches for it on Discord.
17
- * Archiving one closes its thread, when it has one; an archived one keeps its history.
20
+ * archive, restore, and sweep. A temp knight made on a surface with stored places lives in a thread
21
+ * of its parent's place there; one made in a room gets that thread only once someone reaches for
22
+ * it on that surface. Archiving one closes its thread, when it has one; an archived one keeps its
23
+ * history.
18
24
  */
19
25
  export class TeamHelpers {
20
26
  readonly #ctx: TeamContext;
@@ -22,11 +28,13 @@ export class TeamHelpers {
22
28
  readonly #archiveAgent: (agent: Agent) => Promise<void>;
23
29
  readonly #ended: ((event: HelpersEnded) => void)[] = [];
24
30
  #sweeper: ReturnType<typeof setInterval> | undefined;
25
- /** The threads being made for web-born temp knights, by name, so two reaches make one. */
31
+ /** The threads being made for temp knights born in a room, by name and surface, so two reaches make one. */
26
32
  readonly #placing = new Map<string, Promise<void>>();
33
+ readonly #places: TeamPlaceWrites;
27
34
 
28
35
  constructor(ctx: TeamContext, archiveAgent: (agent: Agent) => Promise<void>) {
29
36
  this.#ctx = ctx;
37
+ this.#places = new TeamPlaceWrites(ctx);
30
38
  this.#archiveAgent = archiveAgent;
31
39
  }
32
40
 
@@ -90,8 +98,7 @@ export class TeamHelpers {
90
98
  }
91
99
 
92
100
  /**
93
- * Archives temp knights: each stops answering, keeps its history, and its Discord thread is
94
- * closed. Names that are no active temp knight are passed over. Says which were archived.
101
+ * Archives temp knights: each stops answering, keeps its history, and its thread is closed. Names that are no active temp knight are passed over. Says which were archived.
95
102
  */
96
103
  async archive(names: readonly string[]): Promise<string[]> {
97
104
  const { store } = this.#ctx.options;
@@ -105,19 +112,20 @@ export class TeamHelpers {
105
112
  return archived;
106
113
  }
107
114
 
108
- /** Archives a temp knight and closes its thread, when it has one; a thread that will not close is logged. */
115
+ /** Archives a temp knight and closes its thread, when it has one; a thread that will not close is logged by the provider. */
109
116
  async archiveOne(agent: Agent): Promise<void> {
110
- const { channels, logger } = this.#ctx.options;
111
117
  await this.#archiveAgent(agent);
112
- if (!agent.channelId || !channels?.closeThread) return;
113
- try {
114
- await channels.closeThread(agent.channelId);
115
- } catch (error) {
116
- logger.warn(
117
- { agent: agent.name, err: error },
118
- "temp knight's thread not closed; it stays silent where it is",
119
- );
120
- }
118
+ await this.#places.keep(this.#wish(agent), true);
119
+ }
120
+
121
+ /** The temp knight as a place owner: its name, shown under its display name. */
122
+ #wish(agent: Agent): PlaceWish {
123
+ return {
124
+ kind: "agent",
125
+ name: agent.name,
126
+ displayName: agent.displayName,
127
+ topic: agent.displayName,
128
+ };
121
129
  }
122
130
 
123
131
  /**
@@ -139,55 +147,63 @@ export class TeamHelpers {
139
147
  }
140
148
 
141
149
  /**
142
- * A `message_agent` call that names "discord", or names nothing from a Discord conversation, gives
143
- * a web-born temp knight its thread first.
150
+ * A `message_agent` call that names a surface with stored places, or names nothing from a
151
+ * conversation of one, gives a temp knight born in a room its thread there first.
144
152
  */
145
153
  async reach(
146
154
  caller: AgentTurnScope,
147
155
  to: string,
148
156
  conversation?: string,
149
157
  ): Promise<void> {
150
- const { store } = this.#ctx.options;
158
+ const { store, places } = this.#ctx.options;
151
159
  const { turns } = this.#ctx;
152
160
  const target = store.agent(to);
153
161
  const speaker = turns.speakerOf(caller);
154
162
  const from = turns.turnChannel(caller);
155
- // Unnamed, a message stays on the sender's surface, so one sent from Discord goes there too.
163
+ // Unnamed, a message stays on the sender's surface, so one sent from there goes there too.
156
164
  const wanted = conversation?.trim() || surfaceOf(from);
157
- if (wanted !== "discord" || !target || !speaker) return;
165
+ const provider = places.providerOf(wanted);
166
+ if (
167
+ provider?.surface !== wanted ||
168
+ provider.storage !== "stored" ||
169
+ !target ||
170
+ !speaker
171
+ )
172
+ return;
158
173
  if (answersTo(target, caller.name, from, speaker))
159
- await this.placeOnDiscord(to);
174
+ await this.placeOn(to, wanted);
160
175
  }
161
176
 
162
177
  /**
163
- * Gives an active temp knight made in the web app its thread under the parent's channel, the
164
- * first time someone reaches for it on Discord. One made on Discord, or before the origin was
165
- * kept, already has its place, and a host without Discord threads makes none; never rejects.
178
+ * Gives an active temp knight born in a room its thread under the parent's place on a surface,
179
+ * the first time someone reaches for it there. One made on that surface, or before the origin
180
+ * was kept, already has its place, and a surface that makes no threads gives none; never rejects.
166
181
  */
167
- placeOnDiscord(name: string): Promise<void> {
168
- const pending = this.#placing.get(name);
182
+ placeOn(name: string, surface: string): Promise<void> {
183
+ const key = `${name}@${surface}`;
184
+ const pending = this.#placing.get(key);
169
185
  if (pending) return pending;
170
- const placing = this.#placeOnDiscord(name).finally(() =>
171
- this.#placing.delete(name),
186
+ const placing = this.#placeOn(name, surface).finally(() =>
187
+ this.#placing.delete(key),
172
188
  );
173
- this.#placing.set(name, placing);
189
+ this.#placing.set(key, placing);
174
190
  return placing;
175
191
  }
176
192
 
177
- async #placeOnDiscord(name: string): Promise<void> {
178
- const { store, channels, logger } = this.#ctx.options;
193
+ async #placeOn(name: string, surface: string): Promise<void> {
194
+ const { store, places, logger } = this.#ctx.options;
179
195
  const agent = store.agent(name);
180
- const surface = helperSurface(agent);
181
- if (agent?.status !== "active" || agent.channelId) return;
182
- if (surface === undefined || surface === "discord") return;
196
+ const born = helperSurface(agent);
197
+ if (agent?.status !== "active" || places.idOf(this.#wish(agent), surface))
198
+ return;
199
+ if (born === undefined || born === surface) return;
183
200
  const parent = store.agent(agent.parent as string);
184
- if (!parent?.channelId || !channels?.createThread) return;
201
+ if (!parent) return;
202
+ const wish = this.#wish(agent);
203
+ let made: MadePlace | undefined;
185
204
  try {
186
- const channelId = await channels.createThread(
187
- parent.channelId,
188
- agent.displayName,
189
- );
190
- await store.updateAgent(name, { channelId });
205
+ made = await this.#places.makeOn(surface, wish, parent);
206
+ if (made) await this.#places.record(wish, [made]);
191
207
  } catch (error) {
192
208
  logger.warn(
193
209
  { agent: name, err: error },
@@ -195,6 +211,7 @@ export class TeamHelpers {
195
211
  );
196
212
  return;
197
213
  }
214
+ if (!made) return;
198
215
  logger.info(
199
216
  { agent: name, parent: parent.name },
200
217
  "temp knight's thread made",
@@ -204,33 +221,37 @@ export class TeamHelpers {
204
221
 
205
222
  /**
206
223
  * Restores one archived temp knight: its thread opens again, or a new one is made when the old
207
- * is gone. One made in the web app never gets a new thread: its old one reopens, if it had one
208
- * that is still there. It comes back finished, with nothing running.
224
+ * is gone. One born in a room never gets a new thread on another surface: its old one reopens,
225
+ * if it had one that is still there. It comes back finished, with nothing running.
209
226
  */
210
227
  async restoreOne(agent: Agent): Promise<void> {
211
- const { store, channels, logger } = this.#ctx.options;
228
+ const { store, places, logger } = this.#ctx.options;
212
229
  const parent = store.agent(agent.parent as string);
213
230
  if (parent?.status !== "active")
214
231
  throw new AgentError(
215
232
  `"${agent.name}" belongs to "${agent.parent}", which is archived; restore it first.`,
216
233
  );
217
- let { channelId } = agent;
218
- const surface = helperSurface(agent);
219
- const bornOnDiscord = surface === undefined || surface === "discord";
220
- if (channels?.createThread && parent.channelId) {
234
+ const wish = this.#wish(agent);
235
+ const born = helperSurface(agent);
236
+ const made: MadePlace[] = [];
237
+ for (const provider of places.stored()) {
238
+ const { surface } = provider;
239
+ const own = places.idOf(wish, surface);
240
+ const bornHere = born === undefined || born === surface;
241
+ if (own === undefined && !bornHere) continue;
242
+ // Away from where it was born, only a thread that is still there is opened again.
221
243
  if (
222
- channelId &&
223
- channels.openThread &&
224
- (await channels.exists(channelId))
244
+ own !== undefined &&
245
+ !bornHere &&
246
+ provider.check &&
247
+ (await provider.check(own).catch(() => "unknown")) !== "ok"
225
248
  )
226
- await channels.openThread(channelId);
227
- else if (bornOnDiscord)
228
- channelId = await channels.createThread(
229
- parent.channelId,
230
- agent.displayName,
231
- );
249
+ continue;
250
+ const place = await this.#places.makeOn(surface, wish, parent);
251
+ if (place) made.push(place);
232
252
  }
233
- await store.restoreAgent(agent.name, channelId);
253
+ await this.#places.record(wish, made);
254
+ await store.restoreAgent(agent.name);
234
255
  logger.info(
235
256
  { name: agent.name, parent: parent.name },
236
257
  "temp knight restored",