pi-roundtable 0.42.0 → 0.44.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 (41) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +1 -0
  3. package/README.zh-TW.md +1 -0
  4. package/docs/plugins.md +3 -1
  5. package/package.json +3 -1
  6. package/src/characters/catalog.ts +7 -750
  7. package/src/characters/class-data.ts +56 -0
  8. package/src/characters/classes-a.ts +235 -0
  9. package/src/characters/classes-b.ts +242 -0
  10. package/src/characters/classes-c.ts +241 -0
  11. package/src/core/agents/agent-claim.ts +6 -2
  12. package/src/core/agents/agent-group-store.ts +176 -0
  13. package/src/core/agents/agent-places.ts +197 -0
  14. package/src/core/agents/agent-schema.ts +37 -3
  15. package/src/core/agents/agent-statements.ts +14 -12
  16. package/src/core/agents/agent-store.ts +81 -211
  17. package/src/core/agents/agent-team-fixture.ts +9 -3
  18. package/src/core/agents/agent-team.ts +6 -8
  19. package/src/core/agents/routes.ts +24 -7
  20. package/src/core/agents/team-options.ts +2 -0
  21. package/src/core/builtin/agent-server-options.ts +101 -0
  22. package/src/core/builtin/agent-server.ts +35 -94
  23. package/src/core/config/config-schema.ts +3 -1
  24. package/src/core/config/config.ts +5 -0
  25. package/src/core/config/team.ts +30 -0
  26. package/src/core/contract/channels.ts +8 -0
  27. package/src/core/db/legacy-channels.ts +92 -0
  28. package/src/core/db/team-move.ts +138 -0
  29. package/src/core/host/define-roundtable.ts +10 -2
  30. package/src/core/host/drain.ts +46 -0
  31. package/src/core/host/host.ts +25 -8
  32. package/src/core/plugin-api/plugin.ts +6 -3
  33. package/src/core/plugin-api/services.ts +4 -5
  34. package/src/core/presentation/diagram-text.ts +17 -8
  35. package/src/core/routing/channel-queue.ts +36 -3
  36. package/src/core/testing/fake-discord.ts +67 -0
  37. package/src/core/testing/partial.ts +8 -0
  38. package/src/core/testing/plugin-stand-ins.ts +95 -0
  39. package/src/core/testing/service-pair.ts +18 -0
  40. package/src/core/testing/test-plugin-types.ts +110 -0
  41. package/src/testing.ts +36 -276
@@ -1,5 +1,6 @@
1
1
  import { DRAIN_LIMIT_MS } from "../config/config-schema.ts";
2
2
  import type { Logger } from "../kernel/log.ts";
3
+ import type { Service } from "../plugin-api/plugin.ts";
3
4
 
4
5
  /** How long work that was told to stop gets to end before the shutdown goes on without it. */
5
6
  const ABORT_GRACE_MS = 10_000;
@@ -56,6 +57,51 @@ export async function drainWork(
56
57
  return left;
57
58
  }
58
59
 
60
+ /** Tells each service the drain begins, as `Service.beginDrain` says; a failure is logged and the rest are still told. */
61
+ export function beginServicesDrain(
62
+ services: readonly Pick<Service, "name" | "beginDrain">[],
63
+ logger: Logger,
64
+ ): void {
65
+ for (const service of services) {
66
+ try {
67
+ service.beginDrain?.();
68
+ } catch (error) {
69
+ logger.error(
70
+ { service: service.name, err: error },
71
+ "the service could not be told the drain begins",
72
+ );
73
+ }
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Tells each service that still has work to stop it, as `Service.abort` says; a failure is
79
+ * logged and the rest are still told. Whether any service told some work.
80
+ */
81
+ export function abortServices(
82
+ services: readonly Pick<Service, "name" | "busy" | "abort">[],
83
+ logger: Logger,
84
+ ): boolean {
85
+ let told = false;
86
+ for (const service of services) {
87
+ if (!service.abort || !service.busy?.().length) continue;
88
+ try {
89
+ const aborted = service.abort();
90
+ logger.warn(
91
+ { service: service.name, told: aborted },
92
+ "stopping the work",
93
+ );
94
+ told ||= aborted;
95
+ } catch (error) {
96
+ logger.error(
97
+ { service: service.name, err: error },
98
+ "the work could not be stopped",
99
+ );
100
+ }
101
+ }
102
+ return told;
103
+ }
104
+
59
105
  /**
60
106
  * Tells each channel's running turn to stop, as the owner's stop does; a failure is logged and the
61
107
  * rest are still told. Whether any turn was running to be told.
@@ -19,7 +19,13 @@ import type {
19
19
  import { RUNTIME } from "../plugin-api/services.ts";
20
20
  import type { ToolTierTable } from "../runtime/tool-tiers.ts";
21
21
  import type { ShellEnvConfig } from "../shared/child-env.ts";
22
- import { type DrainOptions, drainWork, stopTurns } from "./drain.ts";
22
+ import {
23
+ abortServices,
24
+ beginServicesDrain,
25
+ type DrainOptions,
26
+ drainWork,
27
+ stopTurns,
28
+ } from "./drain.ts";
23
29
  import { attempt, startInBackground } from "./host-background.ts";
24
30
  import { Linkage, type RegistrationReport } from "./host-registration.ts";
25
31
 
@@ -276,20 +282,31 @@ export class Roundtable {
276
282
  // Turns already running finish, but nothing new starts from here on, whoever asks.
277
283
  logger.info({ signal }, "shutting down once idle");
278
284
  this.#link.queue.close();
285
+ beginServicesDrain(this.#started, logger);
286
+ const stopQueuedTurns = () =>
287
+ stopTurns(
288
+ this.#link.queue.busy(),
289
+ (channel) => this.#link.router?.stop(channel as ChannelKey) ?? false,
290
+ logger,
291
+ );
279
292
  const left = await drainWork({
280
293
  ...drain,
281
294
  busy: () => [
282
295
  ...this.#link.queue.busy(),
283
296
  ...this.#started.flatMap((service) => service.busy?.() ?? []),
284
297
  ],
285
- // A turn the limit finds still running is stopped, as the owner's stop would.
286
- abort: () =>
287
- stopTurns(
288
- this.#link.queue.busy(),
289
- (channel) => this.#link.router?.stop(channel as ChannelKey) ?? false,
290
- logger,
291
- ),
298
+ // A turn the limit finds still running is stopped, as the owner's stop would, and a
299
+ // service is told to stop its own work before it is stopped.
300
+ abort: () => {
301
+ const turns = stopQueuedTurns();
302
+ const services = abortServices(this.#started, logger);
303
+ return turns || services;
304
+ },
292
305
  });
306
+ // Only what ran before the drain ended finishes; nothing delivered later starts.
307
+ this.#link.queue.seal();
308
+ // A turn that started during the abort grace, a report's, is stopped too, so the teardown does not wait for it.
309
+ if (left.length > 0) stopQueuedTurns();
293
310
  if (left.length > 0) {
294
311
  logger.warn(
295
312
  { aborted: left },
@@ -46,14 +46,17 @@ export interface Service {
46
46
  name: string;
47
47
  start?(): Promise<void> | void;
48
48
  /**
49
- * Starts once every service's `start` and the HTTP listeners are up, without holding up the
50
- * boot: a failure is logged and heard as `serviceStarted` with `failed`, never fatal, and the
51
- * other services' background starts still run. `stop` runs for it like for any started service.
49
+ * Starts once every service's `start` and the HTTP listeners are up, without holding up the boot: a failure is logged, heard
50
+ * as `serviceStarted` with `failed`, never fatal, and the other background starts still run. `stop` runs for it as for any service.
52
51
  */
53
52
  startInBackground?(): Promise<void>;
54
53
  stop?(): Promise<void> | void;
55
54
  /** Work still running or waiting, one entry each; the shutdown drain waits until every list is empty. */
56
55
  busy?(): string[];
56
+ /** As the shutdown begins to wait for work, before the drain: from here on the service should start no work of its own. */
57
+ beginDrain?(): void;
58
+ /** At the drain limit, tells the work `busy` lists to stop gently, before the abort grace and `stop`; whether it told any. */
59
+ abort?(): boolean;
57
60
  }
58
61
 
59
62
  /** How a service's background start ended. */
@@ -264,8 +264,10 @@ export interface AgentChange {
264
264
 
265
265
  /** The agent team as plugins use it: who is in it, what model they run, and their channels. */
266
266
  export interface AgentTeam extends HelperTeam {
267
- /** The team's id: the Discord guild, or `"local"` on a host without Discord. */
267
+ /** The team's id: what its rows are stored under, the Discord guild's id unless the host sets one, else `"local"`. */
268
268
  readonly guildId: string;
269
+ /** The Discord guild the team's channels live in; absent on a team without Discord channels. */
270
+ readonly discordGuild?: string | undefined;
269
271
  /** Called when a turn starts or ends and when an agent or group changes. */
270
272
  onChange(listener: () => void): void;
271
273
  /** Every active agent and group, with what each is doing now. */
@@ -280,10 +282,7 @@ export interface AgentTeam extends HelperTeam {
280
282
  * Discord, the one `coordinator` names (the first seed by default); undefined while none is active.
281
283
  */
282
284
  coordinator(): string | undefined;
283
- /**
284
- * Every key an agent or group is addressed by: its Discord channel when it has one, then its
285
- * room on each surface with `agentRooms`; empty for an unknown name.
286
- */
285
+ /** Every key an agent or group is addressed by: its Discord channel, then its room on each `agentRooms` surface; empty for an unknown name. */
287
286
  roomsOf(name: string): ChannelKey[];
288
287
  /** The model and thinking setting of an agent's next run: its own, or the assistant's. */
289
288
  modelOf(name: string): { model: string; thinking: ThinkingSetting };
@@ -52,6 +52,14 @@ function stop(current: Drawer): void {
52
52
  if (drawer === current) drawer = undefined;
53
53
  }
54
54
 
55
+ type Drawn = { text: string } | "refused" | "slow" | "unavailable";
56
+
57
+ /** What a test replaces: the drawing itself and the clock that measures it, so no test depends on real elapsed time. */
58
+ export interface DrawerSeams {
59
+ draw?: (source: string, waitMs: number) => Drawn;
60
+ now?: () => number;
61
+ }
62
+
55
63
  /**
56
64
  * A drawer of Mermaid diagrams as Unicode box drawing for one reply: it gives undefined for a source
57
65
  * that cannot be shown right (see `mermaidText` of `pi-better-show/server`), is longer than
@@ -65,7 +73,11 @@ function stop(current: Drawer): void {
65
73
  * left undrawn for the budget, or because no worker could be started, is no verdict and is tried
66
74
  * again in a later reply.
67
75
  */
68
- export function diagramDrawer(): (source: string) => string | undefined {
76
+ export function diagramDrawer(
77
+ seams: DrawerSeams = {},
78
+ ): (source: string) => string | undefined {
79
+ const drawOne = seams.draw ?? draw;
80
+ const now = seams.now ?? (() => performance.now());
69
81
  let left = DIAGRAM_TEXT_DEADLINE_MS;
70
82
  let fresh = 0;
71
83
  return (source) => {
@@ -82,9 +94,9 @@ export function diagramDrawer(): (source: string) => string | undefined {
82
94
  if (fresh >= MAX_DRAWN_PER_REPLY || left <= 0) return undefined;
83
95
  fresh += 1;
84
96
  const waitMs = left;
85
- const started = performance.now();
86
- const result = draw(source, waitMs);
87
- left -= performance.now() - started;
97
+ const started = now();
98
+ const result = drawOne(source, waitMs);
99
+ left -= now() - started;
88
100
  if (typeof result === "object") remember(source, result.text);
89
101
  else if (result === "refused") remember(source, null);
90
102
  else if (result === "slow" && waitMs >= DIAGRAM_TEXT_DEADLINE_MS) {
@@ -110,10 +122,7 @@ function remember(source: string, text: string | null): void {
110
122
  }
111
123
  }
112
124
 
113
- function draw(
114
- source: string,
115
- waitMs: number,
116
- ): { text: string } | "refused" | "slow" | "unavailable" {
125
+ function draw(source: string, waitMs: number): Drawn {
117
126
  if (unavailable) return "unavailable";
118
127
  drawer ??= start();
119
128
  const current = drawer;
@@ -1,3 +1,4 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
1
2
  import type { ChannelKey } from "../domain/sessions.ts";
2
3
  import { HostStoppingError } from "../kernel/errors.ts";
3
4
 
@@ -6,7 +7,10 @@ export class ChannelQueue {
6
7
  readonly #tails = new Map<ChannelKey, Promise<unknown>>();
7
8
  readonly #sizes = new Map<ChannelKey, number>();
8
9
  readonly #listeners: ((channel: ChannelKey) => void)[] = [];
10
+ /** Set inside `finishing`, so what a delivery starts and awaits sees the queue as open. */
11
+ readonly #finishing = new AsyncLocalStorage<true>();
9
12
  #closed = false;
13
+ #sealed = false;
10
14
 
11
15
  /** Called whenever a channel's count of running and waiting tasks changes. */
12
16
  onChange(listener: (channel: ChannelKey) => void): void {
@@ -17,9 +21,16 @@ export class ChannelQueue {
17
21
  for (const listener of this.#listeners) listener(channel);
18
22
  }
19
23
 
20
- /** Whether the host is shutting down, so no task starts any more. */
24
+ /**
25
+ * Whether the host is shutting down, so no task starts any more; false for work inside
26
+ * `finishing` until the queue is sealed.
27
+ */
21
28
  get closed(): boolean {
22
- return this.#closed;
29
+ return this.#closed && !this.#admitted();
30
+ }
31
+
32
+ #admitted(): boolean {
33
+ return !this.#sealed && this.#finishing.getStore() === true;
23
34
  }
24
35
 
25
36
  /**
@@ -30,9 +41,31 @@ export class ChannelQueue {
30
41
  this.#closed = true;
31
42
  }
32
43
 
44
+ /**
45
+ * Ends the drain: from now on `finishing` admits nothing either. The host seals the queue once
46
+ * the drain has waited, before it stops the services.
47
+ */
48
+ seal(): void {
49
+ this.#closed = true;
50
+ this.#sealed = true;
51
+ }
52
+
53
+ /**
54
+ * Runs `task` as the delivery of work the shutdown drain waits for, such as the report of a
55
+ * task that was running when the host began to stop. A queue task started inside it, and
56
+ * everything that task awaits, is admitted although the queue is closed, until the drain ends.
57
+ * Outside a shutdown it changes nothing.
58
+ */
59
+ finishing<T>(task: () => Promise<T>): Promise<T> {
60
+ return this.#finishing.run(true, task);
61
+ }
62
+
33
63
  run<T>(channel: ChannelKey, task: () => Promise<T>): Promise<T> {
64
+ const admitted = this.#admitted();
34
65
  const start = () =>
35
- this.#closed ? Promise.reject(new HostStoppingError()) : task();
66
+ this.#closed && !(admitted && !this.#sealed)
67
+ ? Promise.reject(new HostStoppingError())
68
+ : task();
36
69
  this.#sizes.set(channel, this.size(channel) + 1);
37
70
  this.#changed(channel);
38
71
  const previous = this.#tails.get(channel) ?? Promise.resolve();
@@ -0,0 +1,67 @@
1
+ import { DISCORD, type DiscordServices } from "../builtin/discord.ts";
2
+ import { CommandCollection } from "../discord/command-collection.ts";
3
+ import type { ComposedCommands } from "../discord/compose-commands.ts";
4
+ import type {
5
+ CommandGuard,
6
+ CommandRegistrar,
7
+ InteractionContribution,
8
+ } from "../discord/interaction-module.ts";
9
+ import { commandGuard, ownerRootCommand } from "../discord/owner-command.ts";
10
+ import type { DiscordPoster } from "../discord/poster/poster.ts";
11
+ import { silentLogger } from "../kernel/log.ts";
12
+ import { fakeDiscordPoster } from "./fake-poster.ts";
13
+ import { type ServicePair, servicePair } from "./service-pair.ts";
14
+
15
+ /** A stand-in for the Discord plugin's `DISCORD` service, made by `fakeDiscord()`. */
16
+ export interface FakeDiscord {
17
+ /** Give this to `testPlugin`'s `services` option: `{ services: [discord.service] }`. */
18
+ readonly service: ServicePair;
19
+ /** What `DISCORD.commands` is to the plugin: the real registrar, which refuses what the Discord plugin refuses. */
20
+ readonly commands: CommandRegistrar;
21
+ /** What `DISCORD.poster` is: the one the test gave, else a `fakeDiscordPoster()`. */
22
+ readonly poster: DiscordPoster;
23
+ /** What `DISCORD.guard` is: the owner, `owner` unless the test gave another id, serving the root command. */
24
+ readonly guard: CommandGuard;
25
+ /** Every contribution the plugin added, in the order it added them. */
26
+ added(): readonly InteractionContribution[];
27
+ /** The tree the Discord plugin would register, composed under the root command the fake was made with. */
28
+ compose(): ComposedCommands;
29
+ }
30
+
31
+ /**
32
+ * A `DISCORD` service for a plugin that adds slash commands, without a Discord connection: the
33
+ * plugin's `commands.add` calls are recorded, and `compose()` shows the tree Discord would get.
34
+ * `rootCommand` is the root command's name, `roundtable` by default. `channelContext` is what
35
+ * `DISCORD.channelContext` answers, by default no context, as on a host with it off. Only
36
+ * `commands`, `guard`, `poster`, and `channelContext` are given; reading another member throws.
37
+ */
38
+ export function fakeDiscord(
39
+ options: {
40
+ ownerId?: string;
41
+ rootCommand?: string;
42
+ channelContext?: DiscordServices["channelContext"];
43
+ poster?: DiscordPoster;
44
+ } = {},
45
+ ): FakeDiscord {
46
+ const collection = new CommandCollection();
47
+ const { rootCommand = "roundtable" } = options;
48
+ const guard = commandGuard({
49
+ ownerId: options.ownerId ?? "owner",
50
+ root: rootCommand,
51
+ logger: silentLogger(),
52
+ });
53
+ const poster = options.poster ?? fakeDiscordPoster();
54
+ return {
55
+ service: servicePair(DISCORD, {
56
+ commands: collection.registrar,
57
+ guard,
58
+ poster,
59
+ channelContext: options.channelContext ?? (async () => undefined),
60
+ }),
61
+ poster,
62
+ commands: collection.registrar,
63
+ guard,
64
+ added: () => collection.added(),
65
+ compose: () => collection.compose(ownerRootCommand(rootCommand)),
66
+ };
67
+ }
@@ -19,3 +19,11 @@ export function partial<T extends object>(given: Partial<T>): T {
19
19
  },
20
20
  }) as T;
21
21
  }
22
+
23
+ /** A member of an object that may be a `partial()` stand-in: its value, or undefined when the stand-in was not given it. */
24
+ export function memberOf<T extends object, K extends keyof T>(
25
+ object: T,
26
+ member: K,
27
+ ): T[K] | undefined {
28
+ return Reflect.has(object, member) ? object[member] : undefined;
29
+ }
@@ -0,0 +1,95 @@
1
+ import type { ConversationPort } from "../contract/channels.ts";
2
+ import type { HeldActionStore } from "../contract/runtime.ts";
3
+ import type { ServiceKey } from "../contract/services.ts";
4
+ import type { PendingConfirmation } from "../domain/conversation.ts";
5
+ import type { ChannelKey } from "../domain/sessions.ts";
6
+ import { NotLinkedError, PluginError } from "../kernel/errors.ts";
7
+ import type { ChannelRouter } from "../routing/channel-router.ts";
8
+
9
+ /** The same pre-link failures and wording the host exposes during setup. */
10
+ export const NOT_LINKED = {
11
+ conversations:
12
+ "conversations are linked once every plugin is set up. Use them from a service's start or from a handler, not during setup.",
13
+ sessions:
14
+ "session parts are linked once every plugin is set up. Call sessions() from a service's start or from a handler, not during setup.",
15
+ surfaces:
16
+ "chat surfaces are linked once every plugin is set up. Use surfaces from a service's start or from a handler, not during setup.",
17
+ turns:
18
+ "conversation turns are linked once every plugin is set up. Use turns from a service's start or from a handler, not during setup.",
19
+ dashboard:
20
+ "dashboard lines are linked once every plugin is set up. Call dashboard() from a service's start or from a handler, not during setup.",
21
+ chatCommands:
22
+ "chat commands are linked once every plugin is set up. Call chatCommands() from a service's start or from a handler, not during setup.",
23
+ };
24
+
25
+ export function unlinked(part: keyof typeof NOT_LINKED): never {
26
+ throw new NotLinkedError(NOT_LINKED[part]);
27
+ }
28
+
29
+ /** Members a probe may ask of any object: a test's partial service is not refused for them. */
30
+ const PROBED = new Set(["then", "toJSON", "asymmetricMatch"]);
31
+
32
+ /** A service the test gave only some members of: reading another names the option that adds it. */
33
+ export function partialService<T extends object>(
34
+ key: ServiceKey<unknown>,
35
+ given: T,
36
+ ): T {
37
+ return new Proxy(given, {
38
+ get(target, member, receiver) {
39
+ if (member in target || typeof member === "symbol" || PROBED.has(member))
40
+ return Reflect.get(target, member, receiver);
41
+ throw new PluginError(
42
+ `testPlugin gave service ${key.id} no "${member}". Give it in the services option: testPlugin(plugin, { services: [servicePair(KEY, { ${member}: ... })] }).`,
43
+ );
44
+ },
45
+ });
46
+ }
47
+
48
+ /** Held actions kept in memory, for the runtime a plugin's provider builds under test. */
49
+ export function memoryHeldActions(): HeldActionStore {
50
+ const held = new Map<ChannelKey, PendingConfirmation>();
51
+ return {
52
+ load: async (conversation) => held.get(conversation),
53
+ save: async (conversation, actions) => {
54
+ if (actions) held.set(conversation, actions);
55
+ else held.delete(conversation);
56
+ },
57
+ };
58
+ }
59
+
60
+ /** A conversation port that reads the router once the host links it, and throws before; `overrides` replace its methods. */
61
+ export function routedConversations(
62
+ router: () => ChannelRouter | undefined,
63
+ overrides: Partial<ConversationPort> | undefined,
64
+ ): ConversationPort {
65
+ return {
66
+ handle: async (message) =>
67
+ (router() ?? unlinked("conversations")).handle(message),
68
+ messageDeleted: async (channel, id, space) =>
69
+ (router() ?? unlinked("conversations")).messageDeleted(
70
+ channel,
71
+ id,
72
+ space,
73
+ ),
74
+ messageEdited: async (message) =>
75
+ (router() ?? unlinked("conversations")).messageEdited(message),
76
+ background: async (turn) =>
77
+ (router() ?? unlinked("conversations")).background(turn),
78
+ runsAs: async (turn) =>
79
+ (router() ?? unlinked("conversations")).runsAs(turn),
80
+ target: (name) => (router() ?? unlinked("conversations")).target(name),
81
+ startFresh: async (channel) =>
82
+ (router() ?? unlinked("conversations")).startFresh(channel),
83
+ deleteConversation: async (channel) =>
84
+ (router() ?? unlinked("conversations")).deleteConversation(channel),
85
+ stop: (channel) => (router() ?? unlinked("conversations")).stop(channel),
86
+ postsInPlace: (channel) =>
87
+ (router() ?? unlinked("conversations")).postsInPlace(channel),
88
+ owns: (channel) => (router() ?? unlinked("conversations")).owns(channel),
89
+ takesBackground: (channel) =>
90
+ (router() ?? unlinked("conversations")).takesBackground(channel),
91
+ takesSystemReports: (channel) =>
92
+ (router() ?? unlinked("conversations")).takesSystemReports(channel),
93
+ ...overrides,
94
+ };
95
+ }
@@ -0,0 +1,18 @@
1
+ import type { ServiceKey } from "../contract/services.ts";
2
+
3
+ /**
4
+ * A service the plugin under test reads, with the members the test gives it, made by `servicePair(KEY,
5
+ * { ... })`. Reading a member the test did not give throws a PluginError that names it.
6
+ */
7
+ export interface ServicePair {
8
+ readonly key: ServiceKey<unknown>;
9
+ readonly given: object;
10
+ }
11
+
12
+ /** Pairs a service key with the members the test gives it, for the `services` option of `testPlugin`. */
13
+ export function servicePair<T extends object>(
14
+ key: ServiceKey<T>,
15
+ given: Partial<T>,
16
+ ): ServicePair {
17
+ return { key, given };
18
+ }
@@ -0,0 +1,110 @@
1
+ import type { SQL } from "bun";
2
+ import type { PeerBotsConfig } from "../config/peer-bots.ts";
3
+ import type { ConversationPort } from "../contract/channels.ts";
4
+ import type { Providers } from "../contract/providers.ts";
5
+ import type { AgentRuntime } from "../contract/runtime.ts";
6
+ import type { ChatSurface, SurfacePort } from "../contract/surface.ts";
7
+ import type { ClientPart, ClientPort } from "../domain/client.ts";
8
+ import type { ReplyFile } from "../domain/conversation.ts";
9
+ import type { ChannelKey, SessionContext } from "../domain/sessions.ts";
10
+ import type { ListenerConfig } from "../http/listeners.ts";
11
+ import type { OwnerIdentity } from "../identity/owner-identity.ts";
12
+ import type { Speaker } from "../identity/speakers.ts";
13
+ import type { HoldCheck } from "../plugin-api/holds.ts";
14
+ import type {
15
+ Contribution,
16
+ HostEnv,
17
+ TurnEndEvent,
18
+ TurnEvent,
19
+ } from "../plugin-api/plugin.ts";
20
+ import type { ConversationTurns } from "../routing/conversation-turns.ts";
21
+ import type { ToolTierTable } from "../runtime/tool-tiers.ts";
22
+ import type { ServicePair } from "./service-pair.ts";
23
+
24
+ export interface TestPluginOptions {
25
+ /** The host environment the plugin sees; default en and UTC. */
26
+ env?: Partial<HostEnv>;
27
+ /**
28
+ * The owner the runtime's dependencies and the agent server's claim know; default `owner`,
29
+ * named Owner, who is addressed as they.
30
+ */
31
+ owner?: { id: string; name: string; pronouns?: OwnerIdentity["pronouns"] };
32
+ database?: SQL;
33
+ providers?: Partial<Providers>;
34
+ /**
35
+ * Chat surfaces besides the plugin's own, such as a fake one: they are in `context.surfaces`,
36
+ * started with the plugin's services (their messages reach `conversations`), and stopped last.
37
+ */
38
+ surfaces?: readonly ChatSurface[];
39
+ /**
40
+ * What the plugin reads from `context.services`, one `servicePair(KEY, { ... })` per service.
41
+ * `servicePair(RUNTIME, runtime)` is the runtime that `context.turns` runs turns on, given
42
+ * whole rather than member by member; `servicePair(AGENTS, { runtime })` still works when no
43
+ * `RUNTIME` is given. Without either, a plugin that fills the `runtime` slot gets the runtime its
44
+ * provider builds, under both keys. A service
45
+ * not given here reads as absent to `find`, and `get` names this option, except for what the
46
+ * host supplies anyway: `BACKGROUND_TURNS`, the real background turns over the test's router,
47
+ * and, once `AGENTS` is given, its `approvals` (the real confirmation judge over
48
+ * `providers.judge`, when the test gives a judge). Giving `AGENTS` a `team` adds the agent
49
+ * server's own claim to the router, answering as the host's would for the `owner`. The router
50
+ * resolves who wrote each message through a given `IDENTITY`; without one only the `owner` is
51
+ * anyone, at the owner tier, their principal their id.
52
+ */
53
+ services?: readonly ServicePair[];
54
+ /**
55
+ * The plugin's conversations: by default a router over the plugin's own `channels` claims, so a
56
+ * message a surface delivers reaches them. Methods given here replace the router's.
57
+ */
58
+ conversations?: Partial<ConversationPort>;
59
+ /** Replaces `context.turns`, which by default runs turns over the runtime and the surfaces. */
60
+ turns?: ConversationTurns;
61
+ /** The credentials `context.apiKey` returns, by provider name; a provider not listed reads as having none, as on a host not logged in to it. */
62
+ apiKeys?: Readonly<Record<string, string>>;
63
+ /** How long the router holds a bare forward for the message that follows it; the host option `conversations.forwardJoinMs`. */
64
+ forwardJoinMs?: number;
65
+ /** The peer bots the router answers, as the host option `peerBots` (`discord.peerBots`); default none. */
66
+ peerBots?: PeerBotsConfig;
67
+ /** The addresses `context.listener(id)` reports; a plugin that reads one gets `undefined` for any not listed. */
68
+ listeners?: readonly ListenerConfig[];
69
+ }
70
+
71
+ export interface RecordedEvent {
72
+ name: "turnStarted" | "turnEnded" | "changed";
73
+ turn?: TurnEvent | TurnEndEvent;
74
+ }
75
+
76
+ export interface TestPluginResult {
77
+ contribution: Contribution;
78
+ /** The hold rules the plugin contributed, chained as the host links them: the description of a call that must be approved first, or undefined. `holds.inTurn(tool, input, context, turn)` asks them as a turn does, so a hold that looks things up (and may return a promise) is called with the turn; the plain call has no turn, and counts a hold that declares `turn` as held under `run <tool>`. */
79
+ holds: HoldCheck;
80
+ /** What the plugin sees as `context.conversations`, for a test to drive its claims. */
81
+ conversations: ConversationPort;
82
+ /** What the plugin sees as `context.turns`. */
83
+ turns: ConversationTurns;
84
+ /** What the plugin sees as `context.surfaces`: its own surfaces and the injected ones. */
85
+ surfaces: SurfacePort;
86
+ /** The runtime the plugin's `runtime` provider built, given stand-in dependencies; undefined when it fills no such slot. */
87
+ runtime: AgentRuntime | undefined;
88
+ tools: readonly string[];
89
+ tiers: ToolTierTable;
90
+ events: RecordedEvent[];
91
+ /** Files accepted by successful runTool calls, copied and recorded with their channel. */
92
+ files: { channel: ChannelKey; file: ReplyFile }[];
93
+ /** Images returned by successful runTool calls, with their channel. */
94
+ images: { channel: ChannelKey; image: ClientPart }[];
95
+ runTool(
96
+ name: string,
97
+ args: Record<string, unknown>,
98
+ /** `workspace` gives the session a workspace and scratch dir, as an agent's session has. */
99
+ options?: {
100
+ speaker?: Speaker;
101
+ /** Where the turn's request came from, as `ToolTurn.origin` shows it to the tool. */
102
+ origin?: string;
103
+ /** What the side that started the turn can do for the tool, as `ToolTurn.client` shows it. */
104
+ client?: ClientPort;
105
+ channel?: ChannelKey;
106
+ workspace?: SessionContext["workspace"];
107
+ },
108
+ ): Promise<string>;
109
+ stop(): Promise<void>;
110
+ }