pi-roundtable 0.45.1 → 0.46.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 (70) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/docs/plugins.md +32 -7
  3. package/package.json +1 -1
  4. package/src/characters/compose.ts +7 -3
  5. package/src/characters/index.ts +1 -0
  6. package/src/characters/parts-face.ts +4 -1
  7. package/src/core/agents/agent-claim.ts +2 -2
  8. package/src/core/agents/agent-group-store.ts +74 -1
  9. package/src/core/agents/agent-places.ts +32 -0
  10. package/src/core/agents/agent-ports.ts +0 -94
  11. package/src/core/agents/agent-prompt.ts +3 -1
  12. package/src/core/agents/agent-team-fixture.ts +48 -7
  13. package/src/core/agents/agent-team.ts +54 -59
  14. package/src/core/agents/agent-tools.ts +34 -166
  15. package/src/core/agents/message-target.ts +3 -2
  16. package/src/core/agents/routes.ts +2 -1
  17. package/src/core/agents/team-editing.ts +121 -150
  18. package/src/core/agents/team-helpers.ts +80 -59
  19. package/src/core/agents/team-keys.ts +16 -26
  20. package/src/core/agents/team-lifecycle.ts +155 -99
  21. package/src/core/agents/team-looks.ts +102 -0
  22. package/src/core/agents/team-options.ts +12 -11
  23. package/src/core/agents/team-place-writes.ts +193 -0
  24. package/src/core/agents/team-places.ts +30 -0
  25. package/src/core/agents/team-posts.ts +42 -73
  26. package/src/core/agents/team-selection.ts +10 -2
  27. package/src/core/agents/team-status.ts +3 -2
  28. package/src/core/agents/team-text.ts +13 -46
  29. package/src/core/agents/team-turn-types.ts +11 -16
  30. package/src/core/agents/team-turns.ts +7 -6
  31. package/src/core/builtin/agent-server-options.ts +27 -6
  32. package/src/core/builtin/agent-server.ts +65 -69
  33. package/src/core/builtin/discord.ts +58 -8
  34. package/src/core/builtin/modules.ts +2 -0
  35. package/src/core/contract/agent-channels.ts +97 -0
  36. package/src/core/contract/channels.ts +10 -4
  37. package/src/core/contract/discord-key.ts +15 -0
  38. package/src/core/contract/places.ts +8 -2
  39. package/src/core/db/legacy-channels.ts +31 -0
  40. package/src/core/discord/agent-dashboard-service.ts +55 -0
  41. package/src/core/{agents → discord}/agent-dashboard.ts +7 -2
  42. package/src/core/discord/agent-discord.ts +1 -1
  43. package/src/core/discord/agent-guild.ts +87 -0
  44. package/src/core/{agents/team-layout.ts → discord/agent-layout.ts} +9 -29
  45. package/src/core/discord/agent-places.ts +52 -33
  46. package/src/core/discord/agent-tools.ts +210 -0
  47. package/src/core/discord/connection.ts +4 -1
  48. package/src/core/discord/discord-surface.ts +9 -14
  49. package/src/core/discord/place-fake-client.ts +59 -0
  50. package/src/core/host/define-roundtable.ts +7 -5
  51. package/src/core/modules/delegation/delegator.ts +5 -0
  52. package/src/core/plugin-api/agent-ops.ts +123 -0
  53. package/src/core/plugin-api/agent-server-ids.ts +9 -0
  54. package/src/core/plugin-api/define.ts +9 -0
  55. package/src/core/plugin-api/plugin.ts +2 -0
  56. package/src/core/plugin-api/services.ts +6 -0
  57. package/src/core/registry/contributions.ts +3 -0
  58. package/src/core/routing/channel-queue.ts +28 -12
  59. package/src/core/runtime/pi-agent-runtime.ts +1 -1
  60. package/src/core/runtime/runtime-plugin.ts +1 -0
  61. package/src/core/runtime/runtime-types.ts +6 -0
  62. package/src/core/{agents/agent-team-fake-channels.ts → testing/fake-agent-channels.ts} +5 -1
  63. package/src/core/testing/fake-pager-places.ts +16 -2
  64. package/src/core/testing/modules.ts +2 -1
  65. package/src/core/testing/place-contract.ts +3 -2
  66. package/src/core/testing/team-places.ts +75 -7
  67. package/src/core/testing/test-host.ts +20 -16
  68. package/src/discord/index.ts +5 -0
  69. package/src/kit/channels.ts +1 -2
  70. package/src/kit/support.ts +9 -5
@@ -8,12 +8,14 @@ import {
8
8
  Partials,
9
9
  type REST,
10
10
  } from "discord.js";
11
- import type { AgentChannels, DashboardBoard } from "../agents/agent-ports.ts";
11
+ import type {
12
+ AgentChannels,
13
+ DashboardBoard,
14
+ } from "../contract/agent-channels.ts";
12
15
  import type {
13
16
  ChannelContext,
14
17
  ChannelContextOptions,
15
18
  } from "../contract/channel-context.ts";
16
- import type { PlaceProvider } from "../contract/places.ts";
17
19
  import type {
18
20
  ChatSurface,
19
21
  SurfaceMessageEvents,
@@ -34,7 +36,6 @@ import type { MemberJoinedEvent } from "../plugin-api/event-types.ts";
34
36
  import { chunksFor } from "../presentation/reply-chunks.ts";
35
37
  import { threadsOfHost } from "../threads/host-threads.ts";
36
38
  import { DiscordAgentChannels, DiscordDashboard } from "./agent-discord.ts";
37
- import { discordPlaces } from "./agent-places.ts";
38
39
  import {
39
40
  type ContextSourceMessage,
40
41
  contextSourceOf,
@@ -137,6 +138,11 @@ export class DiscordSurface
137
138
  ): Promise<ChannelContext | undefined> =>
138
139
  this.#options.channelContext?.(message, options);
139
140
 
141
+ /** The discord.js client, with which the agent guild's place provider checks its stored channels. */
142
+ client(): Client {
143
+ return this.#client;
144
+ }
145
+
140
146
  /** The client's REST queue, whose rate limits every request of this process shares. */
141
147
  rest(): REST {
142
148
  return this.#client.rest;
@@ -172,17 +178,6 @@ export class DiscordSurface
172
178
  );
173
179
  }
174
180
 
175
- /** The agent team's places in the agent guild: its channels and threads, as a place provider. */
176
- agentPlaces(guildId: string): PlaceProvider {
177
- return discordPlaces({
178
- client: this.#client,
179
- guild: guildId,
180
- channels: this.agentChannels(guildId),
181
- onRemoved: (listener) => this.onChannelDeleted(listener),
182
- logger: this.#options.logger,
183
- });
184
- }
185
-
186
181
  /** Threads for background dispatches, in the channel that started each. */
187
182
  threadHost(): DiscordThreadHost {
188
183
  return new DiscordThreadHost(this.#client);
@@ -0,0 +1,59 @@
1
+ import { type Client, DiscordAPIError } from "discord.js";
2
+
3
+ /** What a stand-in server says of a channel id. */
4
+ export interface FakeServer {
5
+ /** The server the agent guild is. */
6
+ guild: string;
7
+ /** Whether the channel was deleted. */
8
+ gone(id: string): boolean;
9
+ /** Whether the channel is one of another server. */
10
+ foreign(id: string): boolean;
11
+ /** Whether the server answers Missing Access (50001) for the channel, as for one of a server the bot left. */
12
+ denied?(id: string): boolean;
13
+ /** The ids of the agent guild's channels, as its list gives them; absent = none. */
14
+ listed?(): readonly string[];
15
+ /** Whether the request fails with an error that says nothing of the channel. */
16
+ fails?(id: string): boolean;
17
+ }
18
+
19
+ /**
20
+ * A discord.js client that only answers `channels.fetch`, as a place provider's `check` asks it:
21
+ * a channel of the agent guild, one of another server, or Discord's own "unknown channel".
22
+ */
23
+ export function fakeDiscordClient(server: FakeServer): Client {
24
+ const fetch = async (id: string) => {
25
+ if (server.fails?.(id)) throw new Error("the server did not answer");
26
+ if (server.denied?.(id))
27
+ throw new DiscordAPIError(
28
+ { message: "Missing Access", code: 50001 },
29
+ 50001,
30
+ 403,
31
+ "GET",
32
+ `/channels/${id}`,
33
+ {},
34
+ );
35
+ if (server.gone(id))
36
+ throw new DiscordAPIError(
37
+ { message: "Unknown Channel", code: 10003 },
38
+ 10003,
39
+ 404,
40
+ "GET",
41
+ `/channels/${id}`,
42
+ {},
43
+ );
44
+ return {
45
+ isDMBased: () => false,
46
+ guildId: server.foreign(id) ? "999999999999999999" : server.guild,
47
+ };
48
+ };
49
+ // SAFETY: the provider reads nothing of the client but `channels.fetch` and the agent guild's channel list.
50
+ const guilds = {
51
+ fetch: async () => ({
52
+ channels: {
53
+ fetch: async () =>
54
+ new Map((server.listed?.() ?? []).map((id) => [id, {}])),
55
+ },
56
+ }),
57
+ };
58
+ return { channels: { fetch }, guilds } as unknown as Client;
59
+ }
@@ -4,7 +4,7 @@ import { join } from "node:path";
4
4
  import { ModelRegistry, ModelRuntime } from "@earendil-works/pi-coding-agent";
5
5
  import { agentServerPlugin, LOCAL_TEAM_ID } from "../builtin/agent-server.ts";
6
6
  import { channelContextPlugin } from "../builtin/channel-context.ts";
7
- import { discordPlugin } from "../builtin/discord.ts";
7
+ import { discordFormerChannelOps, discordPlugin } from "../builtin/discord.ts";
8
8
  import { discordAdminPlugin } from "../builtin/discord-admin.ts";
9
9
  import { identityPlugin } from "../builtin/identity.ts";
10
10
  import { modulesPlugin, schedulerPlugin } from "../builtin/modules.ts";
@@ -154,6 +154,9 @@ function discordAssembly(
154
154
  ownerName: owner.name,
155
155
  rootCommand: discord.rootCommand,
156
156
  ...(discord.guild ? { agentGuild: discord.guild } : {}),
157
+ ...(discord.guild && discord.entryChannel
158
+ ? { entryChannel: discord.entryChannel }
159
+ : {}),
157
160
  dataDir: config.dataDir,
158
161
  ...(discord.refusalHint === undefined
159
162
  ? {}
@@ -225,12 +228,11 @@ function agentAssembly(
225
228
  teamId,
226
229
  formerTeamIds: config.team.formerIds,
227
230
  // Without the agent guild the team lives in the app's rooms, as on a host without Discord.
231
+ // With the agent guild the Discord plugin names the coordinator by its entry channel.
228
232
  ...(discord?.guild
229
233
  ? {
230
- guildId: discord.guild,
231
- ...(discord.entryChannel
232
- ? { entryChannelId: discord.entryChannel }
233
- : {}),
234
+ placeSpaces: [{ surface: "discord", space: discord.guild }],
235
+ formerChannelOps: discordFormerChannelOps(discord.guild),
234
236
  }
235
237
  : config.coordinator
236
238
  ? { coordinator: config.coordinator }
@@ -3,6 +3,7 @@ import type { ChannelKey } from "../../domain/conversation.ts";
3
3
  import { DelegationError } from "../../domain/errors.ts";
4
4
  import { messages } from "../../i18n/index.ts";
5
5
  import type { Tier } from "../../identity/speakers.ts";
6
+ import { HostStoppingError } from "../../kernel/errors.ts";
6
7
  import type { Logger } from "../../kernel/log.ts";
7
8
  import { timeZone } from "../../kernel/time.ts";
8
9
  import type { Delegator } from "../../plugin-api/services.ts";
@@ -49,6 +50,8 @@ export interface DelegatorOptions {
49
50
  threads?: Pick<DispatchThreads, "open">;
50
51
  logger: Logger;
51
52
  timeoutMs?: number;
53
+ /** True while the host's shutdown drain runs; a job started then is refused, as any new work. */
54
+ draining?: () => boolean;
52
55
  }
53
56
 
54
57
  const MAX_TASK_CHARS = 4_000;
@@ -73,6 +76,8 @@ export class DefaultDelegator implements Delegator {
73
76
  start(
74
77
  request: Omit<DelegationJob, "id" | "startedAt" | "thread">,
75
78
  ): DelegationJob {
79
+ if (this.#options.draining?.())
80
+ throw new DelegationError(new HostStoppingError().message);
76
81
  const title = request.title.trim();
77
82
  const task = request.task.trim();
78
83
  if (!title || !task)
@@ -0,0 +1,123 @@
1
+ import type { CharacterInput } from "../../characters/index.ts";
2
+ import type {
3
+ HelperFields,
4
+ PresetAction,
5
+ } from "../agents/helper-preset-ops.ts";
6
+ import type { AgentTurnScope } from "../domain/ports.ts";
7
+
8
+ /**
9
+ * Discord's side of `AgentOps.arrange` and `AgentOps.read`, which the host hands the team while
10
+ * the two stay on `AgentOps`: what the Discord plugin's `channel_arrange` and `channel_read` run.
11
+ */
12
+ export type FormerChannelOps = Pick<AgentOps, "arrange" | "read">;
13
+
14
+ /** What `AgentOps.arrange` and `AgentOps.read` refuse with when the team has no Discord channels. */
15
+ export const NO_CHANNELS =
16
+ "This host has no Discord channels: the agents live in rooms of a chat surface, so there is nothing to arrange or read here.";
17
+
18
+ /**
19
+ * What the agent tools do; the agent team implements it. Each returns text for the model.
20
+ * `arrange`, `read`, and the `category` of `create` and `createGroup` are what 0.45 had: the
21
+ * Discord plugin's own tools and its `category` argument took their place, and they stay here,
22
+ * deprecated, until 1.0.
23
+ */
24
+ export interface AgentOps {
25
+ list(): Promise<string>;
26
+ get(name: string): string;
27
+ update(
28
+ name: string,
29
+ change: {
30
+ displayName?: string;
31
+ prompt?: string;
32
+ model?: string;
33
+ thinking?: string;
34
+ },
35
+ /** Who changes it: the agent whose turn asks, for the prompt history. */
36
+ by?: string,
37
+ ): Promise<string>;
38
+ create(
39
+ caller: AgentTurnScope,
40
+ input: {
41
+ name: string;
42
+ displayName: string;
43
+ prompt: string;
44
+ /** Fields of its look; any left out come from the look its role suggests. */
45
+ character?: CharacterInput;
46
+ task: string;
47
+ /** @deprecated Discord's category for its channel; give it as `hints.category`. Removed in 1.0. */
48
+ category?: string;
49
+ /** The values of the arguments the surfaces' place providers add to the tool, by name. */
50
+ hints?: Readonly<Record<string, string>>;
51
+ skills?: string[];
52
+ /** Turn long-running mode on for its conversations; an owner's turn only. */
53
+ longRunning?: boolean;
54
+ },
55
+ ): Promise<string>;
56
+ /** Makes a temp knight of the caller for one task; the answer returns to the caller's conversation. */
57
+ helperCreate(
58
+ caller: AgentTurnScope,
59
+ input: HelperFields & { name?: string; task: string },
60
+ ): Promise<string>;
61
+ /** Saves, lists, or deletes the caller's own temp-knight presets. */
62
+ helperPreset(caller: AgentTurnScope, action: PresetAction): Promise<string>;
63
+ /** Archives the caller's own temp knights: the named ones, or every one that is finished. */
64
+ helperEnd(
65
+ caller: AgentTurnScope,
66
+ names: readonly string[] | "finished",
67
+ ): Promise<string>;
68
+ /** Changes an agent's look; a field left out stays as it is. */
69
+ avatar(name: string, look: CharacterInput): Promise<string>;
70
+ /** Queues the message and returns at once. */
71
+ /**
72
+ * Hands a request to another agent, in its conversation on the sender's surface, or in the
73
+ * `conversation` named: "discord", "web" (or a room surface's name), or one of its conversation keys.
74
+ */
75
+ message(
76
+ caller: AgentTurnScope,
77
+ to: string,
78
+ text: string,
79
+ conversation?: string,
80
+ ): string;
81
+ /**
82
+ * Readies the place a message is about to reach: a temp knight made in the web app gets its
83
+ * Discord thread when the caller may message it and names "discord". Never rejects.
84
+ */
85
+ reach?(
86
+ caller: AgentTurnScope,
87
+ to: string,
88
+ conversation?: string,
89
+ ): Promise<void>;
90
+ createGroup(input: {
91
+ name: string;
92
+ displayName: string;
93
+ members: string[];
94
+ host?: string;
95
+ /** @deprecated Discord's category for its channel; give it as `hints.category`. Removed in 1.0. */
96
+ category?: string;
97
+ /** The values of the arguments the surfaces' place providers add to the tool, by name. */
98
+ hints?: Readonly<Record<string, string>>;
99
+ }): Promise<string>;
100
+ updateGroup(
101
+ name: string,
102
+ change: { displayName?: string; members?: string[]; host?: string },
103
+ ): Promise<string>;
104
+ archive(caller: AgentTurnScope, name: string): Promise<string>;
105
+ /**
106
+ * Sorts the agent guild's channels into categories, as the Discord plugin's `channel_arrange`
107
+ * tool does; refused on a host whose team has no Discord channels.
108
+ * @deprecated The Discord plugin contributes `channel_arrange`, which an agent's turn carries;
109
+ * a plugin that arranges channels itself uses `DISCORD.connection.agentChannels`. Removed in 1.0.
110
+ */
111
+ arrange(entries: { category: string; names: string[] }[]): Promise<string>;
112
+ /**
113
+ * Reads a channel's messages, as the Discord plugin's `channel_read` tool does; refused on a
114
+ * host whose team has no Discord channels.
115
+ * @deprecated The Discord plugin contributes `channel_read`, which an agent's turn carries; a
116
+ * plugin that reads channels itself uses `DISCORD.connection.agentChannels`. Removed in 1.0.
117
+ */
118
+ read(
119
+ channel: string,
120
+ around: string | undefined,
121
+ limit: number | undefined,
122
+ ): Promise<string>;
123
+ }
@@ -0,0 +1,9 @@
1
+ /** The name of the agent server's plugin, as `serviceStarted` events name it. */
2
+ export const AGENT_SERVER_PLUGIN = "agent-server";
3
+
4
+ /**
5
+ * The agent server's service that starts the team in the background: once its `serviceStarted`
6
+ * event says `ready`, the agents' places are up, and what shows the team, such as Discord's
7
+ * dashboard, starts.
8
+ */
9
+ export const AGENT_TEAM_SERVICE = "team";
@@ -109,6 +109,12 @@ export interface ToolSpec<Schema extends TObject> {
109
109
  minTier: Tier;
110
110
  /** Whether agents carry the tool in their turns; default true. */
111
111
  agent?: boolean;
112
+ /**
113
+ * Whether a temp knight's turns leave the tool out, as they leave out making agents and
114
+ * groups, archiving and scheduling: work a knight started would have no one to end it. Default
115
+ * false.
116
+ */
117
+ withheldFromHelpers?: boolean;
112
118
  /**
113
119
  * A short description of what the call would do when it must wait for approval; undefined lets it
114
120
  * run. It may answer later, after looking something up as the turn's speaker, such as a name to
@@ -160,6 +166,8 @@ export interface ToolContribution {
160
166
  readonly name: string;
161
167
  readonly minTier: Tier;
162
168
  readonly agent: boolean;
169
+ /** Whether a temp knight's turns leave the tool out. */
170
+ readonly withheldFromHelpers?: boolean;
163
171
  /** The extension that registers the tool in a session. */
164
172
  readonly session: SessionTool;
165
173
  /** The hold rule for the tool's `hold`, when it has one. */
@@ -231,6 +239,7 @@ export function defineTool<Schema extends TObject>(
231
239
  name,
232
240
  minTier: spec.minTier,
233
241
  agent: spec.agent ?? true,
242
+ withheldFromHelpers: spec.withheldFromHelpers ?? false,
234
243
  session,
235
244
  };
236
245
  if (!hold && !approvers) return contribution;
@@ -293,6 +293,8 @@ export interface LinkedSessions {
293
293
  requiredTools: readonly string[];
294
294
  /** The tools plugins defined for agents, by name. */
295
295
  agentTools: readonly string[];
296
+ /** Those of `agentTools` a temp knight's turns leave out. Optional, because a host that links sessions by hand may leave it out, and then none is withheld. */
297
+ agentToolsWithheldFromHelpers?: readonly string[];
296
298
  /** Every plugin's agent selection merged, read before each agent turn. */
297
299
  agentSelection(): ToolSelection;
298
300
  /** Told which commands each built session registers, so only declared commands that exist are listed; a host that links sessions by hand may leave it out, and then no declared command is listed. */
@@ -223,7 +223,10 @@ export interface NewAgent {
223
223
  * without it, or for a surface with no rooms, where `agent_create` runs it: the agent's Discord channel, else its first room.
224
224
  */
225
225
  openIn?: string;
226
+ /** @deprecated Discord's category for its channel; give it as `hints.category`. Removed in 1.0. */
226
227
  category?: string;
228
+ /** The values of the arguments the surfaces' place providers add to `agent_create` (`createArguments`), by name, such as Discord's `category`. */
229
+ hints?: Readonly<Record<string, string>>;
227
230
  /** Skills it carries; refused when the skills addon is off. */
228
231
  skills?: string[];
229
232
  model?: string;
@@ -324,7 +327,10 @@ export interface AgentTeam extends HelperTeam {
324
327
  displayName: string;
325
328
  members: string[];
326
329
  host?: string;
330
+ /** @deprecated Discord's category for its channel; give it as `hints.category`. Removed in 1.0. */
327
331
  category?: string;
332
+ /** The values of the arguments the surfaces' place providers add to `group_create`, by name, such as Discord's `category`. */
333
+ hints?: Readonly<Record<string, string>>;
328
334
  }): Promise<string>;
329
335
  /** Changes a group's display name, members (all of them) or host. */
330
336
  updateGroup(
@@ -409,6 +409,9 @@ export function linkSessions(registry: Registry): LinkedSessions {
409
409
  personaMemory: (kind) => personas.get(kind)?.memory ?? "speaker",
410
410
  requiredTools: [...new Set(registry.requiredTools)],
411
411
  agentTools: registry.tools.flatMap((t) => (t.agent ? [t.name] : [])),
412
+ agentToolsWithheldFromHelpers: registry.tools.flatMap((t) =>
413
+ t.agent && t.withheldFromHelpers ? [t.name] : [],
414
+ ),
412
415
  agentSelection: () => mergeSelections(registry.agentSelections),
413
416
  chatCommands: registry.chatCommandSources,
414
417
  };
@@ -7,8 +7,11 @@ export class ChannelQueue {
7
7
  readonly #tails = new Map<ChannelKey, Promise<unknown>>();
8
8
  readonly #sizes = new Map<ChannelKey, number>();
9
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>();
10
+ /**
11
+ * Set inside `finishing`, so what a delivery starts and awaits sees the queue as open: 0 in the
12
+ * delivery itself, 1 in the queue task it started, which starts no queue task of its own.
13
+ */
14
+ readonly #finishing = new AsyncLocalStorage<0 | 1>();
12
15
  #closed = false;
13
16
  #sealed = false;
14
17
 
@@ -26,11 +29,22 @@ export class ChannelQueue {
26
29
  * `finishing` until the queue is sealed.
27
30
  */
28
31
  get closed(): boolean {
29
- return this.#closed && !this.#admitted();
32
+ return (
33
+ this.#closed && (this.#sealed || this.#finishing.getStore() === undefined)
34
+ );
35
+ }
36
+
37
+ /**
38
+ * Whether the host is shutting down, whatever the scope: unlike `closed`, `finishing` does not
39
+ * mask it, so work that a delivery's own turn spawns, such as a transient task, reads it true.
40
+ */
41
+ get draining(): boolean {
42
+ return this.#closed;
30
43
  }
31
44
 
45
+ /** Whether a queue task started here is admitted: the delivery's own, not one that task spawns. */
32
46
  #admitted(): boolean {
33
- return !this.#sealed && this.#finishing.getStore() === true;
47
+ return !this.#sealed && this.#finishing.getStore() === 0;
34
48
  }
35
49
 
36
50
  /**
@@ -52,20 +66,22 @@ export class ChannelQueue {
52
66
 
53
67
  /**
54
68
  * 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.
69
+ * task that was running when the host began to stop. A queue task started inside it runs
70
+ * although the queue is closed, with `closed` reading false, until the drain ends; a queue
71
+ * task that task starts in turn is refused, as is anything else the shutdown refuses
72
+ * (`draining`, which stays true there). Outside a shutdown it changes nothing.
58
73
  */
59
74
  finishing<T>(task: () => Promise<T>): Promise<T> {
60
- return this.#finishing.run(true, task);
75
+ return this.#finishing.run(0, task);
61
76
  }
62
77
 
63
78
  run<T>(channel: ChannelKey, task: () => Promise<T>): Promise<T> {
64
79
  const admitted = this.#admitted();
65
- const start = () =>
66
- this.#closed && !(admitted && !this.#sealed)
67
- ? Promise.reject(new HostStoppingError())
68
- : task();
80
+ const start = () => {
81
+ if (this.#closed && !(admitted && !this.#sealed))
82
+ return Promise.reject(new HostStoppingError());
83
+ return admitted ? this.#finishing.run(1, task) : task();
84
+ };
69
85
  this.#sizes.set(channel, this.size(channel) + 1);
70
86
  this.#changed(channel);
71
87
  const previous = this.#tails.get(channel) ?? Promise.resolve();
@@ -386,7 +386,7 @@ export class PiAgentRuntime implements AgentRuntime {
386
386
  ): Promise<string> {
387
387
  const { dataDir } = this.#options;
388
388
  const { signal } = task;
389
- if (this.#options.stopping?.())
389
+ if (this.#options.stopping?.() || this.#options.draining?.())
390
390
  throw new AgentRunError(new HostStoppingError().message);
391
391
  // A task works at the tier of the turn that started it; without one there is no tier to take.
392
392
  const turn = this.#turns.get(scope.turn);
@@ -228,6 +228,7 @@ export function runtimePlugin(
228
228
  ? { images: providers.images }
229
229
  : {}),
230
230
  stopping: () => context.queue.closed,
231
+ draining: () => context.queue.draining ?? context.queue.closed,
231
232
  get agents() {
232
233
  return agents();
233
234
  },
@@ -137,6 +137,12 @@ export interface PiAgentRuntimeOptions {
137
137
  turnAbortGraceMs?: number;
138
138
  /** Whether the host is shutting down: a turn or a task is then refused before it starts. */
139
139
  stopping?: () => boolean;
140
+ /**
141
+ * Whether the host is shutting down, even inside the delivery of a report the drain waits for,
142
+ * where `stopping` reads false so that the report's own turn can run: a task that turn spawns
143
+ * is refused when this reads true. Default: never.
144
+ */
145
+ draining?: () => boolean;
140
146
  /**
141
147
  * Whether a turn given a place for interim posts shows the text it writes before its final
142
148
  * answer as it goes; default "on". "off" posts only the final reply.
@@ -4,13 +4,17 @@ import type {
4
4
  AgentPost,
5
5
  CategoryLayout,
6
6
  ChannelMessage,
7
- } from "./agent-ports.ts";
7
+ } from "../contract/agent-channels.ts";
8
8
 
9
9
  /** The Discord channels of a team, recorded: what was posted, made, moved and read. */
10
10
  export class FakeChannels implements AgentChannels {
11
11
  posts: { channelId: string; post: AgentPost }[] = [];
12
12
  created: string[] = [];
13
13
  deleted = new Set<string>();
14
+ /** Channels that are another server's. */
15
+ foreign = new Set<string>();
16
+ /** Channels whose check fails with an error that says nothing of them. */
17
+ failing = new Set<string>();
14
18
  #next = 2000;
15
19
  async post(channelId: string, post: AgentPost) {
16
20
  this.posts.push({ channelId, post });
@@ -14,6 +14,8 @@ export const PAGER = "pager";
14
14
  interface Page {
15
15
  name: string;
16
16
  topic: string;
17
+ /** The page this one was made under, for a temp knight's thread. */
18
+ parent?: string;
17
19
  archived: boolean;
18
20
  messages: { id: number; author: string; text: string }[];
19
21
  }
@@ -28,6 +30,12 @@ export class FakePager {
28
30
  readonly #listeners: ((id: string) => void)[] = [];
29
31
  #next = 1;
30
32
  #message = 1;
33
+ readonly #prefix: string;
34
+
35
+ /** `prefix` starts the ids of the pages it makes (`pg-1`), so a test that binds ids of its own cannot meet them. */
36
+ constructor(prefix = "pg") {
37
+ this.#prefix = prefix;
38
+ }
31
39
 
32
40
  readonly provider: PlaceProvider = {
33
41
  surface: PAGER,
@@ -65,10 +73,11 @@ export class FakePager {
65
73
  existing.archived = false;
66
74
  return spec.existing;
67
75
  }
68
- const id = `pg-${this.#next++}`;
76
+ const id = `${this.#prefix}-${this.#next++}`;
69
77
  this.pages.set(id, {
70
78
  name: spec.name,
71
79
  topic: spec.topic,
80
+ ...(spec.parent === undefined ? {} : { parent: spec.parent }),
72
81
  archived: false,
73
82
  messages: [],
74
83
  });
@@ -77,7 +86,7 @@ export class FakePager {
77
86
  remove: async (id) => {
78
87
  const page = this.pages.get(id);
79
88
  if (page) page.archived = true;
80
- return `Its page ${id} is kept.`;
89
+ return `; its page ${id} is kept.`;
81
90
  },
82
91
  check: async (id): Promise<PlaceCheck> => {
83
92
  if (id.startsWith("other-")) return "foreign";
@@ -93,6 +102,11 @@ export class FakePager {
93
102
  mention: (key) => `page ${parseChannelKey(key).id}`,
94
103
  };
95
104
 
105
+ /** The network already has a page `id` that the team did not make, as a bound place would be. */
106
+ adopt(id: string, name: string, topic = name): void {
107
+ this.pages.set(id, { name, topic, archived: false, messages: [] });
108
+ }
109
+
96
110
  /** Everything a person reading the page of `key` has seen. */
97
111
  seen(key: ChannelKey): readonly PlaceSeen[] {
98
112
  return (this.pages.get(parseChannelKey(key).id)?.messages ?? []).map(
@@ -208,9 +208,10 @@ export async function setUpModules(
208
208
  void record.posted.push({ channel, text: reply.chunks.join("") }),
209
209
  },
210
210
  ]);
211
- // SAFETY: setup and the preflight read only the logger, the conversations' background, targets and owners, the surfaces, the direct channels, and the services.
211
+ // SAFETY: setup and the preflight read only the logger, the conversations' background, targets and owners, the surfaces, the direct channels, and the services, and the queue's drain flags.
212
212
  const context = {
213
213
  logger: silentLogger(),
214
+ queue: { closed: false, draining: false },
214
215
  conversations: {
215
216
  target: (name: string) =>
216
217
  options.ownerTarget !== false && name === PERSONAL_TARGET.name
@@ -325,8 +325,9 @@ const CHECKS: readonly Check[] = [
325
325
  if (id === undefined) return;
326
326
  const line = await provider.remove?.(id, { ...spec, helper: false });
327
327
  expectThat(
328
- line === undefined || typeof line === "string",
329
- "remove resolved to something that is no line of text",
328
+ line === undefined ||
329
+ (typeof line === "string" && /^[;,]\s/.test(line)),
330
+ 'remove resolved to something that is no line of text starting with its own separator, `; ` or `, `, as `Archived "<name>"; its channel is kept.` reads',
330
331
  );
331
332
  if (provider.check)
332
333
  expectThat(