pi-roundtable 0.42.0 → 0.43.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/CHANGELOG.md CHANGED
@@ -5,6 +5,30 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.43.0] - 2026-11-09
9
+
10
+ ### Added
11
+
12
+ - pi-roundtable-mcp: `ConnectorRegistry.resync(name)` and `resyncAll()`, on `CONNECTORS` as `resync(name)` and `resyncAll()` and on Discord as `/<root> connector resync [name]`. A resync has the gateway read the connector's upstream server again, then sets its virtual server's tools to the gateway's current ones (names longer than `maxToolName` are skipped and reported as at add) and reads their hints, so an upstream that renamed tools is picked up, each renamed tool with the hints its upstream gives it, without removing the connector and entering its token again. A tool that keeps its name keeps the hints the gateway first stored for it, because the gateway's refresh does not update them: for hints that changed upstream under the same name, remove and add the connector again, or set the hints on the gateway. The gateway, the virtual server, the token, the purpose and the stored row stay; `version` changes when the tools or their hints did. Resyncs run one at a time.
13
+ - pi-roundtable-mcp: A failure before the gateway reads the upstream leaves the connector as it was. The gateway's own refresh drops the tools the upstream no longer offers from the virtual server, so a failure after it (the upstream offers no usable tool, or a later request fails) may leave the virtual server with fewer tools until the next resync; it is logged as such. Until the new tools are read back, the connector lists both the old and the new tool names with their hints, so the `mcp-hints` rule holds a renamed destructive tool even when the read-back fails.
14
+ - pi-roundtable-mcp: A resync makes five admin requests per connector and spaces them by `resyncIntervalMs` (default 1200, 50 a minute, half of the gateway's limit of 100 a minute, which locks the admin account for 15 minutes when exceeded; 0 turns pacing off). When the gateway answers 429, or 401, 403 or 423 (the account refused or locked), `resyncAll` stops there without retrying: the connector that met it and the ones after it are reported as not resynced, a single `resync` fails with `ConnectorRateLimited`, and every resync is refused without a request for `resyncLockoutMs` (default 15 minutes).
15
+ - pi-roundtable-mcp: The gateway's admin client gains `refreshGateway` and `setServerTools`, its tool type optional `gatewayId` and `hints`, its error type an optional `status`, and `ConnectorMessages` the keys `resyncDescription`, `resyncNameOption`, `resyncedTitle`, `resyncedAllTitle`, `resyncedFooter`, `resyncChanges`, `resyncUnchanged`, `resyncFailed`, `resyncNotAttempted` and the gateway's refresh-failure message. `ConnectorRateLimited` is exported.
16
+ - pi-roundtable-mcp: **Breaking for hosts that implement `Connectors`:** the type gains `resync` and `resyncAll`, which such a host needs to provide.
17
+ - pi-roundtable-mcp: `mcpConnectors` resyncs every stored connector in its preflight, after loading them, at that pace. A failure is logged. The `listFooter` text mentions `resync`.
18
+ - pi-roundtable-coding, pi-roundtable-drawing: `pi-roundtable-coding` exports `DEFAULT_TOOL_TEXT`, the shipped description and argument text of every repository tool, so a host sets `toolText` for only the wording that differs and sees what an upgrade changed. The `presentation` hooks `list`, `changeReport`, `taskStarted` and `taskQueued` now receive the package's own text as a last argument, so a host can append to it instead of replacing it.
19
+ - pi-roundtable-coding, pi-roundtable-drawing: `pi-roundtable-drawing` takes a `toolText` option, the same for its five tools, and exports `DEFAULT_DRAWING_TOOL_TEXT`; unset text keeps the package wording, and a tool or argument the plugin does not have stops the start.
20
+ - `team.id` gives the team the id its rows are stored under, independent of `discord.guild` (default the guild's id, else `local`), and `team.formerIds` lists the ids it was stored under before: their rows move to the team's id at every boot, and a team without Discord channels loses the channel ids they carried. `AgentTeam.discordGuild` names the guild the team's channels live in, which the web console links by.
21
+
22
+ ### Fixed
23
+
24
+ - A deploy no longer cuts a coding worker short without a word. The shutdown drain (`drainSeconds`, now up to 14,400) waits for the desk's running workers and for reports still being delivered. A service can now tell the drain began (`Service.beginDrain()`): the coding desk then starts no queued task, reports each as "not started: host restarting, dispatch again after restart", and refuses `repo_task` with the same message. At the limit the drain calls the new `Service.abort()` before `stop()`, and the desk stops each worker with SIGTERM (the worker saves its tracked changes in a `wip:` commit, `stopGraceMs` of 5 seconds before SIGKILL), keeps its branch and worktree unmerged, and reports where they are.
25
+ - A coding worker that is cancelled or runs out of time is killed at once and its branch is never merged into the clone, even when its worktree is clean; the report names the kept branch and worktree. Only a host shutdown saves a `wip:` commit. `CodingDesk.stop()` stops workers the same way and waits at most `stopWaitMs` (15 seconds) for reports.
26
+ - New `QueuePort.finishing(task)` (absent on an older host): a queue task started inside it, and what it awaits, is admitted although the host is shutting down, until the drain ends. The coding plugin delivers every report through it, so the report of a worker that ends during the drain is no longer refused with "the host is shutting down". After the abort grace the host tells the turns still running in the queue to stop once more, so a report turn begun during the grace cannot run past the drain.
27
+ - A coding worker that gets SIGTERM from outside the desk (a `systemctl kill`, a cgroup-wide stop, a manual `kill`) still saves its `wip:` commit but now reports a `stopped` failure; the desk refuses to merge that run, keeps its branch and worktree, and says so in the report. A run that already timed out is reported as timed out even when `interrupt()` or `stop()` lands afterwards.
28
+ - A team that moves between Discord guilds clears the channel ids of the rows from any former id that is not its current guild, so start creates fresh channels instead of archiving the team. Two former ids that hold the same key no longer fail every boot: the one listed first moves, and a warning names the rows that stay behind. A team without Discord channels also clears the channel ids its own rows hold. `testPlugin` gives the agent claim the team's Discord guild again.
29
+ - A team without Discord channels ignores a channel id still stored on an agent or group: its primary place is its room, and a notice or report no longer goes to a deleted channel.
30
+ - pi-roundtable-web: A device that was refused an answer as `answered` no longer keeps its own lock on the block: the server's record decides, so when the first device's send fails and the row comes back without the answer, the page opens the block again too (0.42.0 said so, but only the server half was in).
31
+
8
32
  ## [0.42.0] - 2026-11-08
9
33
 
10
34
  ### Added
package/README.md CHANGED
@@ -202,6 +202,7 @@ Without `discord`, or with `discord` but no `discord.guild`, the agents still ru
202
202
  | `discord.guild` | none | The agent server's guild, where the agents' channels, categories and `#dashboard` live; needs `discord.entryChannel` and `http.publicUrl`. Left out, the bot keeps serving the plugins' claims, slash commands and the owner's direct messages in every guild it is in, and the team lives in the app's rooms as without `discord`: `agents` is required and `entryChannel` is an error |
203
203
  | `agents` | none | The first team, created once. Without `discord.guild`, a seed has no `channelId` and the team's rows are kept under the id `local` |
204
204
  | `coordinator` | the first of `agents` | Without `discord.guild`, the agent the owner's general requests come to; it cannot be archived. With `discord.guild` it is an error: the entry channel's agent coordinates |
205
+ | `team.id`, `team.formerIds` | the `discord.guild` id, else `local`; none | The id the team's rows are stored under, independent of the guild, and the ids it was stored under before: their rows move to it at every boot, and without Discord channels lose their channel ids |
205
206
  | `skills` | on with `agents` | The skills addon; without `discord` it is on only when `agents` lists some |
206
207
  | `helpers` | 4 per knight, 12 in all, archived 24 hours after finishing | Temp knights, the helpers a knight makes with `helper_create` for one task and clears with `helper_end`: `{ perParent, perHost, archiveFinishedAfterHours }`; `false` offers neither tool |
207
208
 
package/README.zh-TW.md CHANGED
@@ -197,6 +197,7 @@ export default {
197
197
  | `discord.guild` | 無 | agent server 的伺服器,agent 的頻道、分類與 `#dashboard` 都在這裡;需要 `discord.entryChannel` 與 `http.publicUrl`。不設時,bot 仍在它加入的每個伺服器服務外掛的 claim、斜線指令與主人的私訊,團隊則像沒有 `discord` 時一樣住在 app 的房間:必須設 `agents`,設 `entryChannel` 會出錯 |
198
198
  | `agents` | 無 | 第一批團隊,只建立一次。沒有 `discord.guild` 時,種子沒有 `channelId`,團隊的資料列記在 id `local` 之下 |
199
199
  | `coordinator` | `agents` 的第一位 | 沒有 `discord.guild` 時,接手主人一般請求的 agent,不能被封存。有 `discord.guild` 時設它會出錯:由入口頻道的 agent 協調 |
200
+ | `team.id`、`team.formerIds` | `discord.guild` 的 id,否則 `local`;無 | 團隊資料列存放用的 id(與 guild 無關),以及先前用過的 id:其資料列每次啟動時搬到新 id,沒有 Discord 頻道時一併清掉頻道 id |
200
201
  | `skills` | 有 `agents` 時開啟 | 技能 addon;沒有 `discord` 時,只有 `agents` 列了 agent 才會開 |
201
202
  | `helpers` | 每位騎士 4 位、全站 12 位,結束 24 小時後封存 | 臨時騎士:騎士用 `helper_create` 為單一任務做出、完成後用 `helper_end` 清掉的幫手。設定為 `{ perParent, perHost, archiveFinishedAfterHours }`;`false` 兩個工具都不提供 |
202
203
 
package/docs/plugins.md CHANGED
@@ -1443,6 +1443,8 @@ test("the handlers record a turn, a team change, and the shutdown", async () =>
1443
1443
  A service has a name and optional `start`, `stop`, and `busy`.
1444
1444
  Services start once everything is set up and stop in reverse order.
1445
1445
  `busy` lists the work still running, one entry each; a shutdown waits until every service's list is empty, for at most the drain limit (three minutes by default, `drainSeconds` in the config), so a deploy rarely cuts work short.
1446
+ `beginDrain`, when the service has it, is called once as the shutdown begins to wait, before `busy` is first read: from then on the service starts no work of its own, such as a queued task.
1447
+ `abort`, when the service has it, is called once at the drain limit if the service still lists work: it tells that work to stop gently, as the owner's stop does a turn, and returns whether it told any. The host then waits the abort grace (`drain.abortGraceMs`) for `busy` to empty before it calls `stop`, so `stop` need not be the first signal. A report that work sends as it ends goes through `context.queue.finishing(task)` (absent on a host that predates it; call the task directly then): a queue task started inside it is admitted although the host is shutting down, until the drain ends.
1446
1448
  The host adds its own channel queue to that wait, so a surface that queues its turns through `context.queue` needs no `busy` for them.
1447
1449
 
1448
1450
  A service may also have `startInBackground`.
@@ -4254,7 +4256,7 @@ The same host may call `run()` again after that.
4254
4256
  On `SIGTERM` or `SIGINT` the bot takes no new work at once, finishes what runs, and stops serving last:
4255
4257
 
4256
4258
  1. It stops starting work: the channel queue closes (`context.queue.closed` turns true), and from then on no new turn starts, whoever asks. A message that arrives is not run; its channel gets one short "restarting, try again shortly" reply, except a bot's or an integration's message, which is only logged. A background turn (a schedule's, a delegated task's report, an error report) is skipped, and so is a turn a plugin asks of `context.turns.run`, which rejects with `HostStoppingError`; a task for the queue that has not started, whether queued before or after, is refused with the same error. The scheduler claims nothing, so a due schedule stays due and fires after the next start if it is less than twelve hours late. A turn that is already running finishes. A plugin that starts turns from a timer or a route of its own should check `context.queue.closed` first.
4257
- 2. It waits until the channel queue is empty and no service reports `busy()` work, for at most three minutes (`drainSeconds` in the config, `drain.limitMs` in `RoundtableOptions`). If work is left, it stops each running turn as the owner's stop does, gives them ten seconds (`drain.abortGraceMs`) to end, and goes on; whatever is left is logged and given up on.
4259
+ 2. It waits until the channel queue is empty and no service reports `busy()` work, for at most three minutes by default (`drainSeconds` in the config, up to 14,400, that is four hours; `drain.limitMs` in `RoundtableOptions`). If work is left, it stops each running turn as the owner's stop does and calls `abort()` of each service that still has work, gives them ten seconds (`drain.abortGraceMs`) to end, and goes on; whatever is left is logged and given up on, and a turn still running in the queue after the grace is told to stop once more. Work that ends during the wait delivers its report through `context.queue.finishing`, which the queue admits until the wait is over; the queue is sealed after it.
4258
4260
  3. Every plugin hears `shutdown(left)`, while every service is still running.
4259
4261
  4. The HTTP listener closes, so no request reaches a service that has stopped.
4260
4262
  5. Services stop in the reverse of the order they started.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-roundtable",
3
- "version": "0.42.0",
3
+ "version": "0.43.0",
4
4
  "description": "A plugin-driven Pi agent server for one owner, reached through Discord or the web",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -50,9 +50,13 @@ export interface AgentClaimOptions {
50
50
  * router resolved, `"owners"` only the owner tier; a webhook's report is the same either way.
51
51
  */
52
52
  speakers?: "everyone" | "owners";
53
+ /**
54
+ * The Discord guild the agents' channels live in: a message from it is the agent server's even
55
+ * outside the channels it knows. Not the team's id; absent for a team without Discord channels.
56
+ */
57
+ discordGuild?: string | undefined;
53
58
  team: Pick<
54
59
  DiscordAgentTeam,
55
- | "guildId"
56
60
  | "owns"
57
61
  | "answerOwner"
58
62
  | "answerGroup"
@@ -183,7 +187,7 @@ export function agentClaim(options: AgentClaimOptions): ChannelClaim {
183
187
  owns: (channel, space) =>
184
188
  discordIdOf(channel) !== undefined
185
189
  ? team.owns(channel) !== undefined ||
186
- (space !== undefined && space === team.guildId)
190
+ (space !== undefined && space === options.discordGuild)
187
191
  : roomOf(channel, surface.roomSurfaces?.() ?? []) !== undefined &&
188
192
  team.owns(channel) !== undefined,
189
193
  admit: (message) => {
@@ -259,14 +259,20 @@ export const eventLog: string[] = [];
259
259
  const PLUGIN_SELECTION = { tools: ["memory_add"], groups: ["workspace"] };
260
260
 
261
261
  /**
262
- * Waits until every queued channel task has settled and every active agent has its avatar,
263
- * which startup draws in the background; a fixed sleep was too short on a slow runner.
262
+ * Waits until every queued channel task has settled, every active agent has its avatar, which
263
+ * startup draws in the background, and every temp knight whose task ended is stamped finished
264
+ * (the stamp is written after the turn, off the queue; with an action held, a knight stays
265
+ * working); a fixed sleep was too short on a slow runner.
264
266
  */
265
267
  export async function settle(): Promise<void> {
266
268
  const deadline = Date.now() + 10_000;
267
269
  const quiet = () =>
268
270
  queue.busy().length === 0 &&
269
- store.agents().every((a) => a.status !== "active" || a.avatarHash);
271
+ store.agents().every((a) => a.status !== "active" || a.avatarHash) &&
272
+ (runtime.held.size > 0 ||
273
+ store
274
+ .agents()
275
+ .every((a) => !a.parent || a.status !== "active" || a.finishedAt));
270
276
  while (!quiet() && Date.now() < deadline) await Bun.sleep(5);
271
277
  // Work the last task queued is still finishing.
272
278
  await Bun.sleep(20);
@@ -91,6 +91,10 @@ export class DiscordAgentTeam implements AgentOps, AgentTeam {
91
91
  return this.#options.guildId;
92
92
  }
93
93
 
94
+ get discordGuild(): string | undefined {
95
+ return this.#options.discordGuild;
96
+ }
97
+
94
98
  /** Called when a turn starts or ends and when an agent or group changes. */
95
99
  onChange(listener: () => void): void {
96
100
  this.#listeners.push(listener);
@@ -105,10 +109,7 @@ export class DiscordAgentTeam implements AgentOps, AgentTeam {
105
109
  return teamStatus(this.#context);
106
110
  }
107
111
 
108
- /**
109
- * The agent or group that owns a channel of the agent server: by Discord channel, or by room on
110
- * a surface that hosts rooms.
111
- */
112
+ /** The agent or group that owns a channel of the agent server, by Discord channel or by room. */
112
113
  owns(channel: ChannelKey): "agent" | "group" | undefined {
113
114
  const { store, surfaces } = this.#options;
114
115
  return channelOwner(
@@ -120,10 +121,7 @@ export class DiscordAgentTeam implements AgentOps, AgentTeam {
120
121
  );
121
122
  }
122
123
 
123
- /**
124
- * The name of the coordinator: the agent in the entry channel, or, on a host without Discord,
125
- * the one the configuration names; undefined while none is active.
126
- */
124
+ /** The coordinator's name: the entry channel's agent, else the configured one; undefined while none is active. */
127
125
  coordinator(): string | undefined {
128
126
  return coordinatorOf(this.#options.store, this.#options)?.name;
129
127
  }
@@ -67,6 +67,11 @@ export interface RoutesOptions {
67
67
  /** The conversation an agent last ran a turn in. */
68
68
  latest?: (agent: string) => ChannelKey | undefined;
69
69
  logger?: RoutesLogger;
70
+ /**
71
+ * Whether the team has Discord channels; default true. A team without them has no Discord place
72
+ * for an agent: a channel id still stored on a row, such as one a former guild left, is ignored.
73
+ */
74
+ discordChannels?: boolean;
70
75
  }
71
76
 
72
77
  /** What the surfaces the host registered can hold, read when the agent server links. */
@@ -88,10 +93,24 @@ export class Routes implements RoutingTable {
88
93
  readonly #routing: ResolvedRouting | undefined;
89
94
  readonly #options: RoutesOptions;
90
95
  readonly #warned = new Set<string>();
96
+ readonly #discordChannels: boolean;
91
97
 
92
98
  constructor(options: RoutesOptions) {
93
99
  this.#options = options;
94
100
  this.#routing = options.routing;
101
+ this.#discordChannels = options.discordChannels ?? true;
102
+ }
103
+
104
+ /** The agent's places in order, its Discord channel first when the team has Discord channels. */
105
+ #keys(name: string): ChannelKey[] {
106
+ const keys = keysOf(
107
+ this.#options.store,
108
+ name,
109
+ this.#options.roomSurfaces(),
110
+ );
111
+ return this.#discordChannels
112
+ ? keys
113
+ : keys.filter((key) => parseChannelKey(key).surface !== "discord");
95
114
  }
96
115
 
97
116
  /**
@@ -121,7 +140,9 @@ export class Routes implements RoutingTable {
121
140
  ? (rooms[0] as string)
122
141
  : surface;
123
142
  if (wanted === "discord")
124
- return agent.channelId ? discordKey(agent.channelId) : undefined;
143
+ return agent.channelId && this.#discordChannels
144
+ ? discordKey(agent.channelId)
145
+ : undefined;
125
146
  return rooms.includes(wanted) ? agentRoomKey(wanted, name) : undefined;
126
147
  }
127
148
 
@@ -143,7 +164,7 @@ export class Routes implements RoutingTable {
143
164
  "the agent has no place on its primary surface; its auto place is used",
144
165
  );
145
166
  }
146
- return keysOf(this.#options.store, name, this.#options.roomSurfaces())[0];
167
+ return this.#keys(name)[0];
147
168
  }
148
169
 
149
170
  /**
@@ -225,11 +246,7 @@ export class Routes implements RoutingTable {
225
246
  from === undefined ? undefined : parseChannelKey(from).surface;
226
247
  if (to === "latest" && surface !== undefined) {
227
248
  const last = latest?.(name);
228
- const keys = keysOf(
229
- this.#options.store,
230
- name,
231
- this.#options.roomSurfaces(),
232
- );
249
+ const keys = this.#keys(name);
233
250
  if (
234
251
  last !== undefined &&
235
252
  keys.includes(last) &&
@@ -17,6 +17,8 @@ export interface AgentTeamOptions
17
17
  * rows the team keeps.
18
18
  */
19
19
  guildId: string;
20
+ /** The Discord guild the team's channels live in, which is not the team's id when the host sets one; absent without Discord channels. */
21
+ discordGuild?: string | undefined;
20
22
  /** The first team, read and inserted once on start; an agent already stored is never overwritten. */
21
23
  seeds: () => readonly AgentSeed[];
22
24
  /** Sections the plugins add to every agent turn's system prompt, read before each run. */
@@ -0,0 +1,101 @@
1
+ import type { ModelRuntime } from "@earendil-works/pi-coding-agent";
2
+ import type { ResolvedHelpers } from "../config/helpers.ts";
3
+ import type { ResolvedRouting } from "../config/routing.ts";
4
+ import type { ModelRef } from "../domain/models.ts";
5
+ import type { OwnerIdentity } from "../identity/owner-identity.ts";
6
+ import type { ErrorReporter } from "../ops/error-reporter.ts";
7
+ import type { AgentSessionsSlot } from "../runtime/runtime-plugin.ts";
8
+
9
+ /**
10
+ * The id of a team that has no id of its own and no Discord guild: the rows the team keeps are
11
+ * stored under it.
12
+ */
13
+ export const LOCAL_TEAM_ID = "local";
14
+
15
+ export interface AgentServerOptions {
16
+ /**
17
+ * The Discord guild the team's channels live in. Absent on a host without Discord, or whose bot
18
+ * has no agent guild: the team has no channels, and its agents live in the rooms of the
19
+ * surfaces that host them. Without `teamId` the team is stored under the guild's id.
20
+ */
21
+ guildId?: string;
22
+ /**
23
+ * The id the team's rows are stored under, independent of the guild; default `guildId`, else
24
+ * `LOCAL_TEAM_ID`.
25
+ */
26
+ teamId?: string;
27
+ /**
28
+ * The ids the team was stored under before, such as a guild it no longer lives in: their rows
29
+ * move to `teamId` at every boot (`moveTeam`), and, without Discord channels, lose the channel
30
+ * ids they carried.
31
+ */
32
+ formerTeamIds?: readonly string[];
33
+ /** The channel the coordinator lives in; set with `guildId`, never with `coordinator`. */
34
+ entryChannelId?: string;
35
+ /**
36
+ * The coordinator's name on a host without Discord, where no entry channel names it; the first
37
+ * seed when absent. Refused with `entryChannelId`.
38
+ */
39
+ coordinator?: string;
40
+ owner: OwnerIdentity & { id: string };
41
+ /** The assistant's display name, as the confirmation judge names it. */
42
+ assistant: string;
43
+ /** Shared with the rest of the host, so logins refresh in one place; lists the models an agent may run. */
44
+ modelRuntime: ModelRuntime;
45
+ dataDir: string;
46
+ /** The model of agents and of the assistant. */
47
+ model: ModelRef;
48
+ /** How sure the confirmation judge must be before its answer is used. */
49
+ judgeThreshold: number;
50
+ /** Where the agent server hands the runtime plugin its per-agent settings. */
51
+ agents?: AgentSessionsSlot;
52
+ /** The shell's shared working directory. */
53
+ workDir: string;
54
+ /**
55
+ * The agents' scratch dir, created with mode 0700 when the agent server starts: their shell's
56
+ * TMPDIR, where writes and removals run without a hold.
57
+ */
58
+ scratchDir?: string;
59
+ /** The host account the agents' shell and file tools run as. */
60
+ shellUser: string;
61
+ /**
62
+ * Whose turns in the agents' channels load memory: `"everyone"` (the default) or `"owners"`;
63
+ * see `AgentSessions.memory`.
64
+ */
65
+ memory?: "everyone" | "owners";
66
+ /**
67
+ * Who the agents answer in their channels and groups' channels: `"everyone"` (the default) or
68
+ * `"owners"`, which leaves a speaker below the owner tier unanswered.
69
+ */
70
+ speakers?: "everyone" | "owners";
71
+ /**
72
+ * Limits of the downloads of a message's files (`discord.attachmentDownload`): `deadlineMs`
73
+ * for all of a message's files together (default 60 s), `idleMs` for one file to send no byte
74
+ * (default 10 s).
75
+ */
76
+ attachmentDownload?: { deadlineMs?: number; idleMs?: number };
77
+ /** The prompt every agent starts with, and the one for speakers other than the owner. */
78
+ prompts: { shared: string; guest?: string };
79
+ /** The listener the avatar pictures are served on; none mounts no route, and a surface serves them through `AGENTS.avatars.serve`. */
80
+ avatarListener?: string;
81
+ /**
82
+ * The origin the agents' pictures are served from. Without one a picture's URL is
83
+ * `/avatars/<hash>.png`, which the surface that serves the pictures resolves against its origin.
84
+ */
85
+ avatarUrl?: string;
86
+ /**
87
+ * Render every agent's picture again at start (`characters.refreshAvatars`) and set it where
88
+ * its hash differs from the stored one; default false.
89
+ */
90
+ refreshAvatars?: boolean;
91
+ /** The assistant's neutral avatar: the style reference and the picture of an agent without one. */
92
+ avatarReference: string;
93
+ /** The picture used instead when `avatarReference` cannot be read as one; the failure is logged. */
94
+ avatarNeutral?: string;
95
+ /** Reports the process's own errors to an agent; without one nothing is reported. */
96
+ errorReporter?: ErrorReporter;
97
+ /** The checked `routing` block: where work no person started lands. Without it every place is what it was before `routing`. */
98
+ routing?: ResolvedRouting;
99
+ /** The temp knights' limits; `false` leaves `helper_create` and `helper_end` out. Without it the defaults apply. */
100
+ helpers?: ResolvedHelpers | false;
101
+ }
@@ -1,6 +1,5 @@
1
1
  import { chmodSync, lstatSync, mkdirSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import type { ModelRuntime } from "@earendil-works/pi-coding-agent";
4
3
  import type { SQL } from "bun";
5
4
  import { agentClaim } from "../agents/agent-claim.ts";
6
5
  import { AgentDashboard } from "../agents/agent-dashboard.ts";
@@ -13,23 +12,16 @@ import { modeOrigins } from "../agents/helper-modes.ts";
13
12
  import { Routes } from "../agents/routes.ts";
14
13
  import { agentOfChannel, discordKey } from "../agents/team-keys.ts";
15
14
  import { ownerAttachmentDir } from "../attachments/attachment-dir.ts";
16
- import type { ResolvedHelpers } from "../config/helpers.ts";
17
- import type { ResolvedRouting } from "../config/routing.ts";
18
15
  import { ROOM_LAYOUT } from "../contract/room-layout.ts";
19
16
  import type { AgentSessions } from "../contract/runtime.ts";
17
+ import { moveTeam } from "../db/team-move.ts";
20
18
  import type { ChannelKey } from "../domain/conversation.ts";
21
19
  import { ConfigError } from "../domain/errors.ts";
22
- import {
23
- AUTO_THINKING,
24
- formatModelRef,
25
- type ModelRef,
26
- } from "../domain/models.ts";
20
+ import { AUTO_THINKING, formatModelRef } from "../domain/models.ts";
27
21
  import type { SessionTool } from "../domain/sessions.ts";
28
- import type { OwnerIdentity } from "../identity/owner-identity.ts";
29
22
  import type { Tier } from "../identity/speakers.ts";
30
23
  import { ConfirmationJudge } from "../judging/confirmation-judge.ts";
31
24
  import type { Logger } from "../kernel/log.ts";
32
- import type { ErrorReporter } from "../ops/error-reporter.ts";
33
25
  import type { PluginContext, RoundtablePlugin } from "../plugin-api/plugin.ts";
34
26
  import {
35
27
  AGENTS,
@@ -43,92 +35,18 @@ import {
43
35
  } from "../plugin-api/services.ts";
44
36
  import { splitReply } from "../presentation/reply-splitter.ts";
45
37
  import { agentPromptExtension } from "../runtime/extensions/agent-prompt.ts";
46
- import type { AgentSessionsSlot } from "../runtime/runtime-plugin.ts";
47
38
  import { DISCORD } from "./discord.ts";
48
39
  import { agentOnly } from "./session-tool.ts";
49
40
 
50
- /**
51
- * The id of the team on a host without Discord, in place of the Discord guild: the rows the team
52
- * keeps are stored under it, as under the guild's id on a host with Discord.
53
- */
54
- export const LOCAL_TEAM_ID = "local";
41
+ export {
42
+ type AgentServerOptions,
43
+ LOCAL_TEAM_ID,
44
+ } from "./agent-server-options.ts";
55
45
 
56
- export interface AgentServerOptions {
57
- /**
58
- * The Discord guild the team lives in. Absent on a host without Discord, or whose bot has no
59
- * agent guild: the team is then `LOCAL_TEAM_ID`, it has no channels, and its agents live in the
60
- * rooms of the surfaces that host them.
61
- */
62
- guildId?: string;
63
- /** The channel the coordinator lives in; set with `guildId`, never with `coordinator`. */
64
- entryChannelId?: string;
65
- /**
66
- * The coordinator's name on a host without Discord, where no entry channel names it; the first
67
- * seed when absent. Refused with `entryChannelId`.
68
- */
69
- coordinator?: string;
70
- owner: OwnerIdentity & { id: string };
71
- /** The assistant's display name, as the confirmation judge names it. */
72
- assistant: string;
73
- /** Shared with the rest of the host, so logins refresh in one place; lists the models an agent may run. */
74
- modelRuntime: ModelRuntime;
75
- dataDir: string;
76
- /** The model of agents and of the assistant. */
77
- model: ModelRef;
78
- /** How sure the confirmation judge must be before its answer is used. */
79
- judgeThreshold: number;
80
- /** Where the agent server hands the runtime plugin its per-agent settings. */
81
- agents?: AgentSessionsSlot;
82
- /** The shell's shared working directory. */
83
- workDir: string;
84
- /**
85
- * The agents' scratch dir, created with mode 0700 when the agent server starts: their shell's
86
- * TMPDIR, where writes and removals run without a hold.
87
- */
88
- scratchDir?: string;
89
- /** The host account the agents' shell and file tools run as. */
90
- shellUser: string;
91
- /**
92
- * Whose turns in the agents' channels load memory: `"everyone"` (the default) or `"owners"`;
93
- * see `AgentSessions.memory`.
94
- */
95
- memory?: "everyone" | "owners";
96
- /**
97
- * Who the agents answer in their channels and groups' channels: `"everyone"` (the default) or
98
- * `"owners"`, which leaves a speaker below the owner tier unanswered.
99
- */
100
- speakers?: "everyone" | "owners";
101
- /**
102
- * Limits of the downloads of a message's files (`discord.attachmentDownload`): `deadlineMs`
103
- * for all of a message's files together (default 60 s), `idleMs` for one file to send no byte
104
- * (default 10 s).
105
- */
106
- attachmentDownload?: { deadlineMs?: number; idleMs?: number };
107
- /** The prompt every agent starts with, and the one for speakers other than the owner. */
108
- prompts: { shared: string; guest?: string };
109
- /** The listener the avatar pictures are served on; none mounts no route, and a surface serves them through `AGENTS.avatars.serve`. */
110
- avatarListener?: string;
111
- /**
112
- * The origin the agents' pictures are served from. Without one a picture's URL is
113
- * `/avatars/<hash>.png`, which the surface that serves the pictures resolves against its origin.
114
- */
115
- avatarUrl?: string;
116
- /**
117
- * Render every agent's picture again at start (`characters.refreshAvatars`) and set it where
118
- * its hash differs from the stored one; default false.
119
- */
120
- refreshAvatars?: boolean;
121
- /** The assistant's neutral avatar: the style reference and the picture of an agent without one. */
122
- avatarReference: string;
123
- /** The picture used instead when `avatarReference` cannot be read as one; the failure is logged. */
124
- avatarNeutral?: string;
125
- /** Reports the process's own errors to an agent; without one nothing is reported. */
126
- errorReporter?: ErrorReporter;
127
- /** The checked `routing` block: where work no person started lands. Without it every place is what it was before `routing`. */
128
- routing?: ResolvedRouting;
129
- /** The temp knights' limits; `false` leaves `helper_create` and `helper_end` out. Without it the defaults apply. */
130
- helpers?: ResolvedHelpers | false;
131
- }
46
+ import {
47
+ type AgentServerOptions,
48
+ LOCAL_TEAM_ID,
49
+ } from "./agent-server-options.ts";
132
50
 
133
51
  /** The name of the agent server's plugin, as `serviceStarted` events name it. */
134
52
  export const AGENT_SERVER_PLUGIN = "agent-server";
@@ -201,7 +119,7 @@ export function agentServerPlugin(
201
119
  throw new ConfigError(
202
120
  "the agent server: entryChannelId and coordinator both name the coordinator. Set the entry channel with Discord, the coordinator without it.",
203
121
  );
204
- const teamId = options.guildId ?? LOCAL_TEAM_ID;
122
+ const teamId = options.teamId ?? options.guildId ?? LOCAL_TEAM_ID;
205
123
  /** Set once the plugin has set up; the preflight reads it after every plugin linked. */
206
124
  let hostsRooms: (() => boolean) | undefined;
207
125
  let linkRoutes: (() => void) | undefined;
@@ -209,7 +127,17 @@ export function agentServerPlugin(
209
127
  name: AGENT_SERVER_PLUGIN,
210
128
  // The agent server's own tables; the host runs them before any setup, in this order. The
211
129
  // held actions' table is the runtime plugin's.
212
- migrations: PgAgentStore.migrations(teamId),
130
+ migrations: [
131
+ ...PgAgentStore.migrations(teamId),
132
+ // After the agents' tables, and the prompts', skills' and conversations' before it.
133
+ moveTeam({
134
+ from: options.formerTeamIds ?? [],
135
+ to: teamId,
136
+ ...(options.guildId === undefined
137
+ ? { clearChannels: true }
138
+ : { discordGuild: options.guildId }),
139
+ }),
140
+ ],
213
141
  provides: [AGENTS],
214
142
  requires: [RUNTIME],
215
143
  // A team with no Discord channels is reached through rooms only; without a surface that
@@ -292,6 +220,7 @@ export function agentServerPlugin(
292
220
  store,
293
221
  roomSurfaces: () => surfaces.roomSurfaces(),
294
222
  latest: (agent) => store.conversations.latest(agent),
223
+ discordChannels: channels !== undefined,
295
224
  logger,
296
225
  });
297
226
  // The surfaces the rules name are registered by the time every plugin has set up.
@@ -303,6 +232,7 @@ export function agentServerPlugin(
303
232
  const built: DiscordAgentTeam = new DiscordAgentTeam({
304
233
  routes,
305
234
  guildId: teamId,
235
+ discordGuild: options.guildId,
306
236
  ...(options.entryChannelId !== undefined
307
237
  ? { entryChannelId: options.entryChannelId }
308
238
  : {}),
@@ -447,6 +377,7 @@ export function agentServerPlugin(
447
377
  channels: [
448
378
  agentClaim({
449
379
  owner: options.owner,
380
+ discordGuild: options.guildId,
450
381
  ...(options.speakers ? { speakers: options.speakers } : {}),
451
382
  team: built,
452
383
  runtime: running,
@@ -28,6 +28,7 @@ import {
28
28
  text,
29
29
  } from "./schema.ts";
30
30
  import { skillsField } from "./skills-config.ts";
31
+ import { teamField } from "./team.ts";
31
32
 
32
33
  /** The shape `roundtable.config.ts` is checked against: every key, its type and its bounds. */
33
34
  const tierMembers = shape({
@@ -132,6 +133,7 @@ export const configSchema = shape({
132
133
  ),
133
134
  ),
134
135
  coordinator: optional(text),
136
+ team: teamField,
135
137
  characters: optional(
136
138
  shape({ skins: optional(skinTones), refreshAvatars: optional(bool) }),
137
139
  ),
@@ -155,7 +157,7 @@ export const configSchema = shape({
155
157
  ops: optional(shape({ agent: optional(text), conversation: optional(text) })),
156
158
  routing: routingShape,
157
159
  helpers: optional(helpersField),
158
- drainSeconds: optional(integer(1, 3_600)),
160
+ drainSeconds: optional(integer(1, 14_400)),
159
161
  ...limitsShape,
160
162
  interimText: optional(oneOf<InterimTextMode>("on", "off")),
161
163
  interimPrimaryChars: optional(integer(1, 100_000)),
@@ -48,6 +48,7 @@ import {
48
48
  routingOf,
49
49
  } from "./routing.ts";
50
50
  import type { SkillsConfig } from "./skills-config.ts";
51
+ import { type ResolvedTeam, type TeamConfig, teamOf } from "./team.ts";
51
52
 
52
53
  export type { DiscordConfig };
53
54
 
@@ -177,6 +178,8 @@ export interface RoundtableConfig extends LimitsConfig, ShellEnvConfig {
177
178
  * the first. With `discord.guild` the agent in `discord.entryChannel` is the coordinator, and this key is refused.
178
179
  */
179
180
  coordinator?: string;
181
+ /** Where the team's rows are stored, and the ids they moved from; see `TeamConfig`. */
182
+ team?: TeamConfig;
180
183
  /**
181
184
  * How the agents' characters are drawn, everywhere the host draws them: the web console, its
182
185
  * round table and the agents' pictures on Discord. `skins` is exactly six `#rrggbb` skin tones
@@ -324,6 +327,7 @@ export interface ResolvedConfig extends ResolvedLimits {
324
327
  agents: AgentSeed[];
325
328
  /** The coordinator's name; set only without `discord.guild` and with `agents`: the configured one, else the first seed. */
326
329
  coordinator?: string;
330
+ team: ResolvedTeam;
327
331
  /** How the agents' characters are drawn: the six skin tones, the package's own unless `characters.skins` is set. */
328
332
  characters: { skins: readonly Hex[]; refreshAvatars: boolean };
329
333
  /** Undefined when no `http` is configured, and the host opens no `public` listener. */
@@ -456,6 +460,7 @@ export function resolveConfig(input: unknown): ResolvedConfig {
456
460
  ...(!agentGuild && config.agents?.[0]
457
461
  ? { coordinator: config.coordinator ?? config.agents[0].name }
458
462
  : {}),
463
+ team: teamOf(config.team),
459
464
  characters: {
460
465
  skins: skinsOf(config.characters?.skins),
461
466
  refreshAvatars: config.characters?.refreshAvatars ?? false,
@@ -0,0 +1,30 @@
1
+ import { list, optional, shape, text } from "./schema.ts";
2
+
3
+ /**
4
+ * The team's identity in the database, independent of any Discord guild. `id` is what the rows the
5
+ * team keeps (agents, groups, skills, prompts, presets) are stored under; default the id of
6
+ * `discord.guild`, else `"local"`. `formerIds` are the ids the team was stored under before, such
7
+ * as a guild it left: their rows move to `id` at every boot (a row the team already holds stays),
8
+ * and without Discord channels lose the channel ids they carried.
9
+ */
10
+ export interface TeamConfig {
11
+ id?: string;
12
+ formerIds?: string[];
13
+ }
14
+
15
+ /** What the host reads: `id` is left out when the Discord guild or the local team gives it. */
16
+ export interface ResolvedTeam {
17
+ id?: string;
18
+ formerIds: readonly string[];
19
+ }
20
+
21
+ export const teamField = optional(
22
+ shape({ id: optional(text), formerIds: optional(list(text)) }),
23
+ );
24
+
25
+ export function teamOf(team: TeamConfig | undefined): ResolvedTeam {
26
+ return {
27
+ ...(team?.id === undefined ? {} : { id: team.id }),
28
+ formerIds: team?.formerIds ?? [],
29
+ };
30
+ }
@@ -427,6 +427,14 @@ export type MessageObserver = (
427
427
  /** The host's channel queue, as plugins use it. */
428
428
  export interface QueuePort {
429
429
  run<T>(channel: ChannelKey, task: () => Promise<T>): Promise<T>;
430
+ /**
431
+ * Runs `task` as the delivery of work the shutdown drain waits for, such as a coding worker's
432
+ * report: a queue task it starts, and what that task awaits, is admitted although the host is
433
+ * shutting down, `closed` reads false there, and the drain waits for it as for any task. It
434
+ * ends when the drain does; after that the task is refused as any other. Absent on a host that
435
+ * predates it: call `task` directly then.
436
+ */
437
+ finishing?<T>(task: () => Promise<T>): Promise<T>;
430
438
  /** Tasks of the channel running or waiting. */
431
439
  size(channel: ChannelKey): number;
432
440
  /** Channels with a task running or waiting. */
@@ -0,0 +1,103 @@
1
+ import type { Migration } from "./migrations.ts";
2
+
3
+ export interface TeamMoveOptions {
4
+ /** The ids the team was stored under before, such as a Discord guild it no longer lives in. */
5
+ from: readonly string[];
6
+ /** The team's id now. */
7
+ to: string;
8
+ /**
9
+ * The Discord guild the team's channels live in. The channel ids of the rows moved from any other
10
+ * former id are cleared: they name channels of a guild the team left, so start creates new ones.
11
+ */
12
+ discordGuild?: string;
13
+ /**
14
+ * The team has no Discord channels: the channel ids of the rows it moves, and of the rows it
15
+ * already holds, are cleared. Default false.
16
+ */
17
+ clearChannels?: boolean;
18
+ }
19
+
20
+ /** The tables whose rows hold a Discord channel id. */
21
+ const CHANNEL_TABLES = new Set(["agents", "agent_groups"]);
22
+
23
+ /**
24
+ * Moves a former team's rows to the team id: every row of a table with a `guild_id` column whose id
25
+ * is one of `from`, in the tables the host's plugins keep (agents, groups, skills, prompts, presets,
26
+ * outbox, conversations). Rows of other guilds stay, such as the `discord_*` grants and audit of the
27
+ * guilds a bot still serves. A row whose key the team already holds stays where it is (a warning
28
+ * names it), so a second boot changes nothing; of two former ids holding one key, the one listed
29
+ * first moves.
30
+ *
31
+ * It runs at every boot, after the migrations that create the tables and before any setup, so the
32
+ * team's seeds find their agents already moved.
33
+ */
34
+ export function moveTeam(options: TeamMoveOptions): Migration {
35
+ const from = [...new Set(options.from)].filter((id) => id !== options.to);
36
+ return {
37
+ name: "team-move",
38
+ runs: "every-boot",
39
+ up: (sql) =>
40
+ sql.begin(async (tx) => {
41
+ if (from.length === 0 && !options.clearChannels) return;
42
+ const tables: { table: string; key: string[] | null }[] = await tx`
43
+ SELECT c.table_name AS table,
44
+ (SELECT array_agg(a.attname::text ORDER BY a.attnum)
45
+ FROM pg_constraint p
46
+ JOIN pg_attribute a
47
+ ON a.attrelid = p.conrelid AND a.attnum = ANY (p.conkey)
48
+ WHERE p.conrelid = format('%I', c.table_name)::regclass
49
+ AND p.contype = 'p' AND a.attname <> 'guild_id') AS key
50
+ FROM information_schema.columns c
51
+ JOIN information_schema.tables t
52
+ ON t.table_schema = c.table_schema AND t.table_name = c.table_name
53
+ WHERE c.table_schema = current_schema() AND c.column_name = 'guild_id'
54
+ AND t.table_type = 'BASE TABLE' AND c.table_name NOT LIKE 'discord\\_%'
55
+ ORDER BY c.table_name`;
56
+ for (const { table, key } of tables) {
57
+ const channels = CHANNEL_TABLES.has(table);
58
+ if (options.clearChannels && channels)
59
+ await tx.unsafe(
60
+ `UPDATE "${table}" SET channel_id = NULL WHERE guild_id = $1 AND channel_id IS NOT NULL`,
61
+ [options.to],
62
+ );
63
+ const match = (key ?? [])
64
+ .map((column) => `l."${column}" = t."${column}"`)
65
+ .join(" AND ");
66
+ // One former id at a time, in the listed order: the first to hold a key wins, and the
67
+ // later ones find it taken.
68
+ for (const id of from) {
69
+ const taken = match
70
+ ? ` AND NOT EXISTS (SELECT 1 FROM "${table}" l WHERE l.guild_id = $1 AND ${match})`
71
+ : "";
72
+ const clear =
73
+ channels &&
74
+ (options.clearChannels ||
75
+ (options.discordGuild !== undefined &&
76
+ id !== options.discordGuild))
77
+ ? ", channel_id = NULL"
78
+ : "";
79
+ await tx.unsafe(
80
+ `UPDATE "${table}" t SET guild_id = $1${clear} WHERE t.guild_id = $2${taken}`,
81
+ [options.to, id],
82
+ );
83
+ }
84
+ if (!match || from.length === 0) continue;
85
+ const kept: Record<string, unknown>[] = await tx.unsafe(
86
+ `SELECT t.guild_id, ${key?.map((column) => `t."${column}"`).join(", ")} FROM "${table}" t
87
+ WHERE t.guild_id = ANY ($2::text[])
88
+ AND EXISTS (SELECT 1 FROM "${table}" l WHERE l.guild_id = $1 AND ${match})`,
89
+ [options.to, from],
90
+ );
91
+ if (kept.length > 0)
92
+ console.warn(
93
+ `team-move: ${kept.length} row(s) of "${table}" stay under their former id, because team "${options.to}" already holds the same key: ${kept
94
+ .map(
95
+ ({ guild_id, ...rest }) =>
96
+ `${guild_id}/${Object.values(rest).join("/")}`,
97
+ )
98
+ .join(", ")}`,
99
+ );
100
+ }
101
+ }),
102
+ };
103
+ }
@@ -173,6 +173,11 @@ function discordAssembly(
173
173
  };
174
174
  }
175
175
 
176
+ /** The id the team's rows are stored under: the configured one, else the agent guild's, else `local`. */
177
+ function teamIdOf(config: ResolvedConfig): string {
178
+ return config.team.id ?? config.discord?.guild ?? LOCAL_TEAM_ID;
179
+ }
180
+
176
181
  /**
177
182
  * The agent server and what only it uses, each in its place in the plugin list: the skills addon
178
183
  * and the seed agents. Its team lives in the Discord guild `discord.guild` names when there is one,
@@ -195,6 +200,7 @@ function agentAssembly(
195
200
  ): AgentAssembly {
196
201
  const { name, discord } = config;
197
202
  const owner = discordOwnerOf(config);
203
+ const teamId = teamIdOf(config);
198
204
  const sharedPrompt = config.prompts.shared
199
205
  ? readPrompt(config.prompts.shared, "prompts.shared")
200
206
  : readPrompt(join(ASSETS, "prompts", "shared.md"), "prompts.shared");
@@ -206,7 +212,7 @@ function agentAssembly(
206
212
  skills: config.skills
207
213
  ? [
208
214
  skillsPlugin({
209
- guildId: discord?.guild ?? LOCAL_TEAM_ID,
215
+ guildId: teamId,
210
216
  reposDir: config.skills.reposDir ?? join(config.dataDir, "repos"),
211
217
  writtenDir: join(config.dataDir, "skills"),
212
218
  builtinDir: config.skills.builtinDir ?? join(ASSETS, "skills"),
@@ -215,6 +221,8 @@ function agentAssembly(
215
221
  ]
216
222
  : [],
217
223
  agentServer: agentServerPlugin({
224
+ teamId,
225
+ formerTeamIds: config.team.formerIds,
218
226
  // Without the agent guild the team lives in the app's rooms, as on a host without Discord.
219
227
  ...(discord?.guild
220
228
  ? {
@@ -358,7 +366,7 @@ export async function defineRoundtable(
358
366
  scheduleStorePlugin(),
359
367
  precheckPlugin(),
360
368
  // Before the agent server and the operator's plugins, which register the texts the owner edits.
361
- promptsPlugin({ guildId: discord?.guild ?? LOCAL_TEAM_ID }),
369
+ promptsPlugin({ guildId: teamIdOf(config) }),
362
370
  // Before Discord, whose services hand out its instance, and the modules and agent server that use it.
363
371
  threadsPlugin({ dataDir: config.dataDir }),
364
372
  channelContextPlugin(),
@@ -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();
@@ -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
+ }
package/src/testing.ts CHANGED
@@ -86,6 +86,7 @@ import { type ToolTierTable, toolTiers } from "./core/runtime/tool-tiers.ts";
86
86
  import { PERSONAL_TARGET } from "./core/shared/personal-target.ts";
87
87
  import { fakeDiscordPoster } from "./core/testing/fake-poster.ts";
88
88
  import { mapIdentity } from "./core/testing/map-identity.ts";
89
+ import { memberOf } from "./core/testing/partial.ts";
89
90
  import {
90
91
  callRegisteredTool,
91
92
  registeredTools,
@@ -587,10 +588,9 @@ export async function testPlugin(
587
588
  ? [
588
589
  agentClaim({
589
590
  owner,
590
- // SAFETY: the claim reads the concrete team's members (guildId, owns, answerOwner, answerGroup, answerBackground, startFresh), which a test that gives a team for it supplies.
591
- team: agentServer.team as unknown as Parameters<
592
- typeof agentClaim
593
- >[0]["team"],
591
+ discordGuild: memberOf(agentServer.team, "discordGuild"),
592
+ // SAFETY: the claim reads the concrete team's members (owns, answerOwner, answerGroup, answerBackground, startFresh), which a test that gives a team for it supplies.
593
+ team: agentServer.team as never,
594
594
  runtime: {
595
595
  steer: (...args) => services.get(AGENTS).runtime.steer(...args),
596
596
  stop: (channel) => services.get(AGENTS).runtime.stop(channel),