pi-roundtable 0.43.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.
package/src/testing.ts CHANGED
@@ -1,54 +1,26 @@
1
1
  import { mkdtempSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
- import type { SQL } from "bun";
5
4
  import { CATALOG } from "./characters/index.ts";
6
5
  import { agentClaim } from "./core/agents/agent-claim.ts";
7
6
  import { ownerAttachmentDir } from "./core/attachments/attachment-dir.ts";
8
7
  import { attachmentPort } from "./core/attachments/attachment-port.ts";
9
8
  import { DISCORD, type DiscordServices } from "./core/builtin/discord.ts";
10
- import type { PeerBotsConfig } from "./core/config/peer-bots.ts";
11
- import type {
12
- ConversationPort,
13
- InboundMessage,
14
- } from "./core/contract/channels.ts";
9
+ import type { InboundMessage } from "./core/contract/channels.ts";
15
10
  import type { Providers } from "./core/contract/providers.ts";
16
- import type {
17
- AgentRuntime,
18
- HeldActionStore,
19
- RuntimeDeps,
20
- } from "./core/contract/runtime.ts";
21
- import type { ServiceKey } from "./core/contract/services.ts";
22
- import type { ChatSurface, SurfacePort } from "./core/contract/surface.ts";
23
- import { CommandCollection } from "./core/discord/command-collection.ts";
24
- import type { ComposedCommands } from "./core/discord/compose-commands.ts";
25
- import type {
26
- CommandGuard,
27
- CommandRegistrar,
28
- InteractionContribution,
29
- } from "./core/discord/interaction-module.ts";
30
- import {
31
- commandGuard,
32
- ownerRootCommand,
33
- } from "./core/discord/owner-command.ts";
34
- import type { DiscordPoster } from "./core/discord/poster/poster.ts";
11
+ import type { AgentRuntime, RuntimeDeps } from "./core/contract/runtime.ts";
35
12
  import { supportOf } from "./core/domain/block-support.ts";
36
- import type { ClientPart, ClientPort } from "./core/domain/client.ts";
37
- import type {
38
- PendingConfirmation,
39
- ReplyFile,
40
- } from "./core/domain/conversation.ts";
13
+ import type { ClientPart } from "./core/domain/client.ts";
14
+ import type { ReplyFile } from "./core/domain/conversation.ts";
41
15
  import type { ChannelKey, SessionContext } from "./core/domain/sessions.ts";
42
16
  import { EventBus } from "./core/host/events.ts";
43
- import { type ListenerConfig, listenerAddress } from "./core/http/listeners.ts";
17
+ import { listenerAddress } from "./core/http/listeners.ts";
44
18
  import { contactsOf } from "./core/identity/identity-view.ts";
45
- import type { OwnerIdentity } from "./core/identity/owner-identity.ts";
46
- import { type Speaker, THE_SPEAKER } from "./core/identity/speakers.ts";
19
+ import { THE_SPEAKER } from "./core/identity/speakers.ts";
47
20
  import { ConfirmationJudge } from "./core/judging/confirmation-judge.ts";
48
- import { NotLinkedError, PluginError } from "./core/kernel/errors.ts";
21
+ import { PluginError } from "./core/kernel/errors.ts";
49
22
  import { silentLogger } from "./core/kernel/log.ts";
50
23
  import { ConversationBackgroundTurns } from "./core/modules/background/background-turns.ts";
51
- import type { HoldCheck } from "./core/plugin-api/holds.ts";
52
24
  import type {
53
25
  Contribution,
54
26
  HostEnv,
@@ -82,15 +54,25 @@ import {
82
54
  import { MessageObservers } from "./core/routing/message-observers.ts";
83
55
  import { PeerBots } from "./core/routing/peer-bots.ts";
84
56
  import { surfacePort } from "./core/routing/surface-port.ts";
85
- import { type ToolTierTable, toolTiers } from "./core/runtime/tool-tiers.ts";
57
+ import { toolTiers } from "./core/runtime/tool-tiers.ts";
86
58
  import { PERSONAL_TARGET } from "./core/shared/personal-target.ts";
87
- import { fakeDiscordPoster } from "./core/testing/fake-poster.ts";
88
59
  import { mapIdentity } from "./core/testing/map-identity.ts";
89
60
  import { memberOf } from "./core/testing/partial.ts";
61
+ import {
62
+ memoryHeldActions,
63
+ partialService,
64
+ routedConversations,
65
+ unlinked,
66
+ } from "./core/testing/plugin-stand-ins.ts";
90
67
  import {
91
68
  callRegisteredTool,
92
69
  registeredTools,
93
70
  } from "./core/testing/run-tool.ts";
71
+ import type {
72
+ RecordedEvent,
73
+ TestPluginOptions,
74
+ TestPluginResult,
75
+ } from "./core/testing/test-plugin-types.ts";
94
76
 
95
77
  // Fixtures for plugin tests.
96
78
 
@@ -104,6 +86,8 @@ export {
104
86
  testDatabaseUrl,
105
87
  } from "./core/testing/database.ts";
106
88
  export { eagerText, useEagerCatalog } from "./core/testing/eager-catalog.ts";
89
+ export type { FakeDiscord } from "./core/testing/fake-discord.ts";
90
+ export { fakeDiscord } from "./core/testing/fake-discord.ts";
107
91
  export type {
108
92
  FakeDiscordPoster,
109
93
  FakeForum,
@@ -134,6 +118,8 @@ export type {
134
118
  RecordingLogger,
135
119
  } from "./core/testing/recording-logger.ts";
136
120
  export { recordingLogger } from "./core/testing/recording-logger.ts";
121
+ export type { ServicePair } from "./core/testing/service-pair.ts";
122
+ export { servicePair } from "./core/testing/service-pair.ts";
137
123
  export type {
138
124
  SurfaceContractAnswerer,
139
125
  SurfaceContractFailure,
@@ -147,219 +133,14 @@ export {
147
133
  } from "./core/testing/surface-contract.ts";
148
134
  export type { TestHost, TestHostOptions } from "./core/testing/test-host.ts";
149
135
  export { testHost } from "./core/testing/test-host.ts";
136
+ export type {
137
+ RecordedEvent,
138
+ TestPluginOptions,
139
+ TestPluginResult,
140
+ } from "./core/testing/test-plugin-types.ts";
150
141
  export type { FakeThreadHost } from "./core/testing/thread-host.ts";
151
142
  export { fakeThreads } from "./core/testing/thread-host.ts";
152
143
 
153
- /**
154
- * A service the plugin under test reads, with the members the test gives it, made by `servicePair(KEY,
155
- * { ... })`. Reading a member the test did not give throws a PluginError that names it.
156
- */
157
- export interface ServicePair {
158
- readonly key: ServiceKey<unknown>;
159
- readonly given: object;
160
- }
161
-
162
- /** Pairs a service key with the members the test gives it, for the `services` option of `testPlugin`. */
163
- export function servicePair<T extends object>(
164
- key: ServiceKey<T>,
165
- given: Partial<T>,
166
- ): ServicePair {
167
- return { key, given };
168
- }
169
-
170
- /** A stand-in for the Discord plugin's `DISCORD` service, made by `fakeDiscord()`. */
171
- export interface FakeDiscord {
172
- /** Give this to `testPlugin`'s `services` option: `{ services: [discord.service] }`. */
173
- readonly service: ServicePair;
174
- /** What `DISCORD.commands` is to the plugin: the real registrar, which refuses what the Discord plugin refuses. */
175
- readonly commands: CommandRegistrar;
176
- /** What `DISCORD.poster` is: the one the test gave, else a `fakeDiscordPoster()`. */
177
- readonly poster: DiscordPoster;
178
- /** What `DISCORD.guard` is: the owner, `owner` unless the test gave another id, serving the root command. */
179
- readonly guard: CommandGuard;
180
- /** Every contribution the plugin added, in the order it added them. */
181
- added(): readonly InteractionContribution[];
182
- /** The tree the Discord plugin would register, composed under the root command the fake was made with. */
183
- compose(): ComposedCommands;
184
- }
185
-
186
- /**
187
- * A `DISCORD` service for a plugin that adds slash commands, without a Discord connection: the
188
- * plugin's `commands.add` calls are recorded, and `compose()` shows the tree Discord would get.
189
- * `rootCommand` is the root command's name, `roundtable` by default. `channelContext` is what
190
- * `DISCORD.channelContext` answers, by default no context, as on a host with it off. Only
191
- * `commands`, `guard`, `poster`, and `channelContext` are given; reading another member throws.
192
- */
193
- export function fakeDiscord(
194
- options: {
195
- ownerId?: string;
196
- rootCommand?: string;
197
- channelContext?: DiscordServices["channelContext"];
198
- poster?: DiscordPoster;
199
- } = {},
200
- ): FakeDiscord {
201
- const collection = new CommandCollection();
202
- const { rootCommand = "roundtable" } = options;
203
- const guard = commandGuard({
204
- ownerId: options.ownerId ?? "owner",
205
- root: rootCommand,
206
- logger: silentLogger(),
207
- });
208
- const poster = options.poster ?? fakeDiscordPoster();
209
- return {
210
- service: servicePair(DISCORD, {
211
- commands: collection.registrar,
212
- guard,
213
- poster,
214
- channelContext: options.channelContext ?? (async () => undefined),
215
- }),
216
- poster,
217
- commands: collection.registrar,
218
- guard,
219
- added: () => collection.added(),
220
- compose: () => collection.compose(ownerRootCommand(rootCommand)),
221
- };
222
- }
223
-
224
- export interface TestPluginOptions {
225
- /** The host environment the plugin sees; default en and UTC. */
226
- env?: Partial<HostEnv>;
227
- /**
228
- * The owner the runtime's dependencies and the agent server's claim know; default `owner`,
229
- * named Owner, who is addressed as they.
230
- */
231
- owner?: { id: string; name: string; pronouns?: OwnerIdentity["pronouns"] };
232
- database?: SQL;
233
- providers?: Partial<Providers>;
234
- /**
235
- * Chat surfaces besides the plugin's own, such as a fake one: they are in `context.surfaces`,
236
- * started with the plugin's services (their messages reach `conversations`), and stopped last.
237
- */
238
- surfaces?: readonly ChatSurface[];
239
- /**
240
- * What the plugin reads from `context.services`, one `servicePair(KEY, { ... })` per service.
241
- * `servicePair(RUNTIME, runtime)` is the runtime that `context.turns` runs turns on, given
242
- * whole rather than member by member; `servicePair(AGENTS, { runtime })` still works when no
243
- * `RUNTIME` is given. Without either, a plugin that fills the `runtime` slot gets the runtime its
244
- * provider builds, under both keys. A service
245
- * not given here reads as absent to `find`, and `get` names this option, except for what the
246
- * host supplies anyway: `BACKGROUND_TURNS`, the real background turns over the test's router,
247
- * and, once `AGENTS` is given, its `approvals` (the real confirmation judge over
248
- * `providers.judge`, when the test gives a judge). Giving `AGENTS` a `team` adds the agent
249
- * server's own claim to the router, answering as the host's would for the `owner`. The router
250
- * resolves who wrote each message through a given `IDENTITY`; without one only the `owner` is
251
- * anyone, at the owner tier, their principal their id.
252
- */
253
- services?: readonly ServicePair[];
254
- /**
255
- * The plugin's conversations: by default a router over the plugin's own `channels` claims, so a
256
- * message a surface delivers reaches them. Methods given here replace the router's.
257
- */
258
- conversations?: Partial<ConversationPort>;
259
- /** Replaces `context.turns`, which by default runs turns over the runtime and the surfaces. */
260
- turns?: ConversationTurns;
261
- /** 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. */
262
- apiKeys?: Readonly<Record<string, string>>;
263
- /** How long the router holds a bare forward for the message that follows it; the host option `conversations.forwardJoinMs`. */
264
- forwardJoinMs?: number;
265
- /** The peer bots the router answers, as the host option `peerBots` (`discord.peerBots`); default none. */
266
- peerBots?: PeerBotsConfig;
267
- /** The addresses `context.listener(id)` reports; a plugin that reads one gets `undefined` for any not listed. */
268
- listeners?: readonly ListenerConfig[];
269
- }
270
-
271
- export interface RecordedEvent {
272
- name: "turnStarted" | "turnEnded" | "changed";
273
- turn?: TurnEvent | TurnEndEvent;
274
- }
275
-
276
- export interface TestPluginResult {
277
- contribution: Contribution;
278
- /** 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>`. */
279
- holds: HoldCheck;
280
- /** What the plugin sees as `context.conversations`, for a test to drive its claims. */
281
- conversations: ConversationPort;
282
- /** What the plugin sees as `context.turns`. */
283
- turns: ConversationTurns;
284
- /** What the plugin sees as `context.surfaces`: its own surfaces and the injected ones. */
285
- surfaces: SurfacePort;
286
- /** The runtime the plugin's `runtime` provider built, given stand-in dependencies; undefined when it fills no such slot. */
287
- runtime: AgentRuntime | undefined;
288
- tools: readonly string[];
289
- tiers: ToolTierTable;
290
- events: RecordedEvent[];
291
- /** Files accepted by successful runTool calls, copied and recorded with their channel. */
292
- files: { channel: ChannelKey; file: ReplyFile }[];
293
- /** Images returned by successful runTool calls, with their channel. */
294
- images: { channel: ChannelKey; image: ClientPart }[];
295
- runTool(
296
- name: string,
297
- args: Record<string, unknown>,
298
- /** `workspace` gives the session a workspace and scratch dir, as an agent's session has. */
299
- options?: {
300
- speaker?: Speaker;
301
- /** Where the turn's request came from, as `ToolTurn.origin` shows it to the tool. */
302
- origin?: string;
303
- /** What the party that started the turn can do for the tool, as `ToolTurn.client` shows it. */
304
- client?: ClientPort;
305
- channel?: ChannelKey;
306
- workspace?: SessionContext["workspace"];
307
- },
308
- ): Promise<string>;
309
- stop(): Promise<void>;
310
- }
311
-
312
- /** The same pre-link failures and wording the host exposes during setup. */
313
- const NOT_LINKED = {
314
- conversations:
315
- "conversations are linked once every plugin is set up. Use them from a service's start or from a handler, not during setup.",
316
- sessions:
317
- "session parts are linked once every plugin is set up. Call sessions() from a service's start or from a handler, not during setup.",
318
- surfaces:
319
- "chat surfaces are linked once every plugin is set up. Use surfaces from a service's start or from a handler, not during setup.",
320
- turns:
321
- "conversation turns are linked once every plugin is set up. Use turns from a service's start or from a handler, not during setup.",
322
- dashboard:
323
- "dashboard lines are linked once every plugin is set up. Call dashboard() from a service's start or from a handler, not during setup.",
324
- chatCommands:
325
- "chat commands are linked once every plugin is set up. Call chatCommands() from a service's start or from a handler, not during setup.",
326
- };
327
-
328
- function unlinked(part: keyof typeof NOT_LINKED): never {
329
- throw new NotLinkedError(NOT_LINKED[part]);
330
- }
331
-
332
- /** Members a probe may ask of any object: a test's partial service is not refused for them. */
333
- const PROBED = new Set(["then", "toJSON", "asymmetricMatch"]);
334
-
335
- /** A service the test gave only some members of: reading another names the option that adds it. */
336
- function partialService<T extends object>(
337
- key: ServiceKey<unknown>,
338
- given: T,
339
- ): T {
340
- return new Proxy(given, {
341
- get(target, member, receiver) {
342
- if (member in target || typeof member === "symbol" || PROBED.has(member))
343
- return Reflect.get(target, member, receiver);
344
- throw new PluginError(
345
- `testPlugin gave service ${key.id} no "${member}". Give it in the services option: testPlugin(plugin, { services: [servicePair(KEY, { ${member}: ... })] }).`,
346
- );
347
- },
348
- });
349
- }
350
-
351
- /** Held actions kept in memory, for the runtime a plugin's provider builds under test. */
352
- function memoryHeldActions(): HeldActionStore {
353
- const held = new Map<ChannelKey, PendingConfirmation>();
354
- return {
355
- load: async (conversation) => held.get(conversation),
356
- save: async (conversation, actions) => {
357
- if (actions) held.set(conversation, actions);
358
- else held.delete(conversation);
359
- },
360
- };
361
- }
362
-
363
144
  /** Build one plugin without Discord or PostgreSQL, retaining the host's validation and tier logic. */
364
145
  // pi-lens-ignore: high-complexity, large-function — one host's context and lifecycle, mirrored end to end
365
146
  export async function testPlugin(
@@ -389,31 +170,10 @@ export async function testPlugin(
389
170
  let linked: LinkedSessions | undefined;
390
171
  let router: ChannelRouter | undefined;
391
172
  const queue = new ChannelQueue();
392
- const conversations: ConversationPort = {
393
- handle: async (message) =>
394
- (router ?? unlinked("conversations")).handle(message),
395
- messageDeleted: async (channel, id, space) =>
396
- (router ?? unlinked("conversations")).messageDeleted(channel, id, space),
397
- messageEdited: async (message) =>
398
- (router ?? unlinked("conversations")).messageEdited(message),
399
- background: async (turn) =>
400
- (router ?? unlinked("conversations")).background(turn),
401
- runsAs: async (turn) => (router ?? unlinked("conversations")).runsAs(turn),
402
- target: (name) => (router ?? unlinked("conversations")).target(name),
403
- startFresh: async (channel) =>
404
- (router ?? unlinked("conversations")).startFresh(channel),
405
- deleteConversation: async (channel) =>
406
- (router ?? unlinked("conversations")).deleteConversation(channel),
407
- stop: (channel) => (router ?? unlinked("conversations")).stop(channel),
408
- postsInPlace: (channel) =>
409
- (router ?? unlinked("conversations")).postsInPlace(channel),
410
- owns: (channel) => (router ?? unlinked("conversations")).owns(channel),
411
- takesBackground: (channel) =>
412
- (router ?? unlinked("conversations")).takesBackground(channel),
413
- takesSystemReports: (channel) =>
414
- (router ?? unlinked("conversations")).takesSystemReports(channel),
415
- ...options.conversations,
416
- };
173
+ const conversations = routedConversations(
174
+ () => router,
175
+ options.conversations,
176
+ );
417
177
  const surfaces = surfacePort(() =>
418
178
  linked
419
179
  ? [...registry.surfaces, ...(options.surfaces ?? [])]