pi-roundtable 0.52.2 → 0.53.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,24 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.53.0] - 2026-11-18
9
+
10
+ ### Added
11
+
12
+ - pi-roundtable-mcp, pi-roundtable-web: Agents get `connector_list`, `connector_add` and `connector_remove` for the owner's MCP connectors, and none takes or shows a connector's URL. `connector_list` gives each connector's name, host, tool count and purpose. `connector_remove` is held under a new rule, `connector`, which yolo mode never approves; its card names the connector and its host only. `connector_add` takes a name and purpose only. With pi-roundtable-web it returns a one-time link (an hour, single use) to the connectors page's add form, filled in, where the owner pastes the URL; the asking conversation then gets a follow-up with the outcome. On Discord it points the owner to `/<root> connector add`.
13
+ - pi-roundtable-mcp, pi-roundtable-web: The web console stores those add requests (never a URL) in `web_connector_add_requests`, serves them under `api/connectors/requests/<id>`, and opens the add form at `#/connectors?add=<id>`.
14
+
15
+ ### Changed
16
+
17
+ - pi-roundtable-web: The chat home in the side column keeps its pins and its folder tabs to one row each. Five pins share the row and more scroll sideways, so no pin sits alone on a second row; the folder tabs no longer wrap but scroll sideways as on a phone, shorter (36px) and tighter there, as a pointer needs no 48px target.
18
+
19
+ ## [0.52.3] - 2026-11-17
20
+
21
+ ### Fixed
22
+
23
+ - A turn the shutdown cuts short no longer loses its message: a turn still running at the drain limit that has not answered by the end of the abort grace (stopped, failed, or still running) has each person's message it has not answered, the one that started it and those steered into it, refused as a waiting message is, before the messages waiting behind turns and the teardown, within `refuseWaitingSeconds`. With `discord.catchUp` an addressed one is recorded as left, its channel is told once that it will be answered after the restart, and the next process answers it once; elsewhere its channel is told once to send it again. A message is answered once a turn run through `settleTurn` (`context.turns`, the agent team) in the work of its admission, including tasks it queues, ends `ok`; a background turn, another agent's `message_agent` turn and a new agent's opening task do not count. An agent message the cut turn's chain sent, at any hop, is taken out of the outbox again when its person's message is refused, since the turn runs again. A turn or queue task of the admission that the stopping host refuses (asked for during the drain) refuses its unanswered messages too, and the refused turn's result is the stopped one rather than a failure that asks to try again. A turn under a refused message that ends later posts the stopped notice instead of its answer, so the message is not answered twice. What the cut turn did before it stopped is not undone: a write held for approval is held again in the next process's turn, but a call that ran without approval may run again.
24
+ - At the drain limit of a shutdown, the host stops the running turn of a channel whose claim has no `stop`, such as a plugin's claim that runs its turns through `context.turns`, with the runtime's `stop(channel)`, so the turn ends within the abort grace instead of running on until the process exits. The drain also waits for, and at its limit stops, a turn a message's admission started without waiting for it, through `context.turns`, a queue of its own (stopped only when keyed by the turn's channel; see `docs/plugins.md`) or a bare `settleTurn` (in the channel of the queue task it runs in, or else of its first message), which ran outside the channel queue the drain watched. A claim's own `stop` is used as before, and the Stop button and `conversations.stop` are unchanged.
25
+
8
26
  ## [0.52.2] - 2026-11-17
9
27
 
10
28
  ### Added
package/docs/plugins.md CHANGED
@@ -1098,7 +1098,7 @@ defineTool({
1098
1098
 
1099
1099
  #### Hold classes and yolo mode
1100
1100
 
1101
- Every held call carries its **hold classes**: ids of the form `<rule>.<class>` that name why it is held. They are what yolo mode (below) judges, and they are recorded with the call as `HeldCall.holdClasses`, so they survive a restart. A rule reports them with `holdClasses(tool, input, context)`, which lists every reason the call is held, not only the first. **Report only classes that are safe to approve with no one looking: a rule that reports classes has opted its calls in to yolo mode**, which approves them unless the config cards them. A rule that reports none leaves its calls **unclassed**: they carry the rule's bare name (`mail` for a rule called `mail`) and yolo cards them, unless `autonomy.yolo.allow` lists that name. A tool's own `hold` is a rule named `tool:<name>`, so it is unclassed, and `autonomy.yolo.allow: ["tool:repo_push"]` approves a `repo_push` tool's calls. Every reported id must start with the rule's name and a dot; one that does not, such as another rule's id, leaves the call unclassed, as does a `holdClasses` that throws. A rule that stands for other rules' calls, as the one that holds saving a precheck script does, declares `relay: true` and may list their ids instead; its calls also carry `<rule>.relay`, so `autonomy.yolo.card: ["precheck-scripts"]` cards them. A rule name has no dot. The same holds for `HoldDescription.classes`, and a hold check built without `holdChain` has no classes: yolo cards its calls. A rule that describes a call in a turn may name the classes in the description instead: `{ text, classes: ["repo.push"] }` (`HoldDescription.classes`). When several rules hold one call, its classes are all of theirs, so one unclassed or carded rule cards it. `holdChain(rules)` reports them as `classesOf(tool, input, context)` and, with the description, as `inTurnWithClasses(...)` (`ClassedHold`), which also asks the rules after the first that holds the call; a hold check built without `holdChain` has none. A rule declared `yolo: "never"` is one yolo mode never approves: its calls carry the class `<rule>.yolo-never` whatever it reports, which yolo always cards, and the host refuses to start when `autonomy.yolo.allow` names the rule or one of its classes (a turn nobody can answer still fails its held call closed). `mcp-connectors` holds a connector's tool through such a rule, `mcp-hints`, when its server's hints mark it `destructiveHint: true` or `readOnlyHint: false`; `VirtualServer.hints` carries the hints.
1101
+ Every held call carries its **hold classes**: ids of the form `<rule>.<class>` that name why it is held. They are what yolo mode (below) judges, and they are recorded with the call as `HeldCall.holdClasses`, so they survive a restart. A rule reports them with `holdClasses(tool, input, context)`, which lists every reason the call is held, not only the first. **Report only classes that are safe to approve with no one looking: a rule that reports classes has opted its calls in to yolo mode**, which approves them unless the config cards them. A rule that reports none leaves its calls **unclassed**: they carry the rule's bare name (`mail` for a rule called `mail`) and yolo cards them, unless `autonomy.yolo.allow` lists that name. A tool's own `hold` is a rule named `tool:<name>`, so it is unclassed, and `autonomy.yolo.allow: ["tool:repo_push"]` approves a `repo_push` tool's calls. Every reported id must start with the rule's name and a dot; one that does not, such as another rule's id, leaves the call unclassed, as does a `holdClasses` that throws. A rule that stands for other rules' calls, as the one that holds saving a precheck script does, declares `relay: true` and may list their ids instead; its calls also carry `<rule>.relay`, so `autonomy.yolo.card: ["precheck-scripts"]` cards them. A rule name has no dot. The same holds for `HoldDescription.classes`, and a hold check built without `holdChain` has no classes: yolo cards its calls. A rule that describes a call in a turn may name the classes in the description instead: `{ text, classes: ["repo.push"] }` (`HoldDescription.classes`). When several rules hold one call, its classes are all of theirs, so one unclassed or carded rule cards it. `holdChain(rules)` reports them as `classesOf(tool, input, context)` and, with the description, as `inTurnWithClasses(...)` (`ClassedHold`), which also asks the rules after the first that holds the call; a hold check built without `holdChain` has none. A rule declared `yolo: "never"` is one yolo mode never approves: its calls carry the class `<rule>.yolo-never` whatever it reports, which yolo always cards, and the host refuses to start when `autonomy.yolo.allow` names the rule or one of its classes (a turn nobody can answer still fails its held call closed). `mcp-connectors` holds a connector's tool through such a rule, `mcp-hints`, when its server's hints mark it `destructiveHint: true` or `readOnlyHint: false`; `VirtualServer.hints` carries the hints. It holds every `connector_remove` call through another, `connector`, whose card names the connector and its host only.
1102
1102
 
1103
1103
  **Yolo mode.** In a conversation whose `yolo` mode an owner switched on ([`MODES`](#conversation-modes-modes)), the server decides a held call before any card opens, and approves it without one only when **all** of these hold at that moment:
1104
1104
 
@@ -2496,6 +2496,9 @@ A message sent while a turn runs is first offered to that turn (`busy.steer`); o
2496
2496
  A claim may have `stop(channel)`, which stops the channel's running turn and returns whether one was running; the Stop button, `conversations.stop`, and every other stop go through it.
2497
2497
  The router calls only the owning claim's `stop`, returning `false` when that method is absent.
2498
2498
  Give `stop` to a claim whose conversations run turns that can be interrupted.
2499
+ One exception: at the drain limit of a shutdown, the host stops the running turn of a channel whose claim has no `stop`, or that no claim owns, with the runtime's `stop(channel)`, which stops a turn the claim ran through `context.turns` in that channel; a claim with `stop` is asked as always.
2500
+
2501
+ A turn the shutdown cuts short, one still running at the drain limit or, for one the drain did not count, when the drain ends, that has not answered by the end of the abort grace has each person's message it has not answered, the one that started it and those steered into it, handed to its surface's `refuseStopping` as a refused message is, or its channel told once to send it again, before the messages waiting behind turns and before the services stop, within the same `refuseWaitingSeconds`. Once that time is up, a cut turn not yet reached is neither refused nor told and keeps its late answer, and a message of the turn being refused at that moment is neither told nor answered. A turn run through `settleTurn` (which `context.turns` and the agent team use) that ends `ok` in the admission's work while that is open answers every message the admission holds by then. That work is its `run` and what that starts, awaited or not, through `context.queue.run`, a queue of its own (`channelQueue()`), `context.turns.run` or a bare `settleTurn` called before `run` returns (or before that work ends), such as a task it queues for a thread it opens, which keeps the admission's work open until it ends; work that only starts once all of that has ended, such as a timer's, no longer counts. The drain waits for all of it: a queue task or a `context.turns` turn in its own channel, a bare `settleTurn` in the channel of the queue task it runs in or, outside any, in that of the admission's first message, where the stop at the drain limit (that channel's claim's `stop`, else the runtime's) reaches it only when it runs in that channel and that stop covers it; a queue of your own keyed by anything other than the channel the turn runs in, such as one lock key or a user, gets no stop at the drain limit, so use `context.turns` or key the queue by that channel. A message steered in after that waits for the next `ok`; since an `ok` counts for every message the admission holds by then, one steered in while another turn of the admission ran, such as a turn it queued, counts as answered by that turn's `ok`. A turn or queue task of that work that the stopping host refuses, such as one asked for during the drain (the queue's or `context.turns`'s `HostStoppingError`, or the runtime's refusal), leaves the admission's unanswered messages the same way, whenever that was, though told only with the cut turns once the abort grace is over, and the refused turn's result is the stopped one instead of a failure, so the person is not told to try again as well. A stopped or failed turn answers nothing, and neither does a background turn the admission asks for (`conversations.background`), another agent's turn that `message_agent` starts, or a new agent's opening task. The answer counts when its turn ends, before its pipeline posts it, so an answer whose post the teardown cuts off is lost. An agent message that any hop of the chain started by the cut turn sent, or an answer it waits for, is kept for the next start as before, and taken out again when the person's message is refused, since the turn runs again and sends it again; one whose send came before a turn of that admission answered stays kept, and the refusal does not wait for the outbox; when that message was not addressed, its author is asked to send it again, and if they do not, the agent message is not sent either. A turn under a message refused this way that ends later gives a stopped result, so its answer is not posted as well; text the turn posted as it went stays in the channel. For a claim's own turns this means: post the answer through `context.turns` or `settleTurn`, since an answer posted any other way is not seen and a cut turn's message is refused even after it; start a turn that does not answer the person, such as a triage step, as a background turn, since an `ok` from it counts as the answer. Work the cut turn did before it was stopped, such as tool calls, is not undone, and the next process runs the message again: a write held for approval was not made and is held again, but a call that ran without one may run twice.
2499
2502
 
2500
2503
  For a claim with its own conversations, return the conversation's kind from `startFresh`.
2501
2504
  Run turns with [`context.turns`](#personas-and-contextturns-conversations-of-a-kind-of-your-own), which handles typing, the stop control, events, and replies.
@@ -2959,6 +2962,7 @@ Catch-up reads the author of a server message as a member first; when that fails
2959
2962
  Once the old process begins to shut down it runs no new turn, and an addressed message that routing refuses for that reason, whether it arrives then or already waits behind a running turn, is recorded as left (a `left_at` time in the journal), and its channel is told once that the message will be answered after the restart. Routing decides first: a message no claim would answer, such as one in a channel the bot does not serve, is neither left nor promised an answer.
2960
2963
  The next process answers each message left within the last day first, whatever was posted in its channel since and whatever `windowMinutes`, the page and `maxMessages` say, and takes it from the journal as it does, so it is answered once.
2961
2964
  A message still waiting behind a turn that outlives the drain is refused, and so left, once the drain ends and before the services stop, within 15 seconds for all of them (`refuseWaitingSeconds`); this covers every message waiting behind a turn, whether or not its claim's admission has a `busy` mark. A message another process already took in is left alone, with no notice.
2965
+ The message a turn the shutdown cut short was answering, and each one steered into it, is left the same way, first, unless that turn answered by the end of the abort grace (see [`channels`](#channels-conversations-of-your-own)); the turn is stopped through the runtime when its claim has no `stop`.
2962
2966
  A message that cannot be recorded as left gets no notice when it arrived during the shutdown, since it has no record and the next catch-up finds it in its window; one recorded before gets the notice to send it again instead.
2963
2967
  Any other person's message that routing refuses then tells its channel once to send it again, as without catch-up.
2964
2968
  The Discord surface does this through the optional `ChatSurface.refuseStopping(message)`, which routing calls for a person's message it refuses while the host stops; a surface a plugin contributes may implement it too, and returns true when it told the channel itself, so routing posts no restart notice.
@@ -4422,7 +4426,7 @@ The same host may call `run()` again after that.
4422
4426
  On `SIGTERM` or `SIGINT` the bot takes no new work at once, finishes what runs, and stops serving last:
4423
4427
 
4424
4428
  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.
4425
- 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 (`abortGraceSeconds` in the config, `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. Messages still waiting behind a turn, whatever claim admitted them, are then refused within 15 seconds (`refuseWaitingSeconds` in the config, `drain.refuseWaitingMs`) before the services stop. The service manager's stop or kill timeout must be longer than `drainSeconds` + `abortGraceSeconds` + `refuseWaitingSeconds` plus a few seconds for the teardown; a shorter one cuts the refusal and teardown off, and a message waiting behind a turn that ignores its abort is then neither answered nor told. Under a 30-second kill, for example, `drainSeconds: 12`, `abortGraceSeconds: 5` and `refuseWaitingSeconds: 8` leave five seconds.
4429
+ 2. It waits until the channel queue is empty, no turn or task a message's admission started without waiting for it (through `context.turns`, a queue of its own, or a bare `settleTurn`) still runs, 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 (through the runtime for a claim without `stop`) and calls `abort()` of each service that still has work, gives them ten seconds (`abortGraceSeconds` in the config, `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. The messages of each turn cut short that did not answer by then, and messages still waiting behind a turn, whatever claim admitted them, are then refused within 15 seconds (`refuseWaitingSeconds` in the config, `drain.refuseWaitingMs`) before the services stop. The service manager's stop or kill timeout must be longer than `drainSeconds` + `abortGraceSeconds` + `refuseWaitingSeconds` plus a few seconds for the teardown; a shorter one cuts the refusal and teardown off, and a message of a cut turn or waiting behind one is then neither answered nor told. Under a 30-second kill, for example, `drainSeconds: 12`, `abortGraceSeconds: 5` and `refuseWaitingSeconds: 8` leave five seconds.
4426
4430
  3. Every plugin hears `shutdown(left)`, while every service is still running.
4427
4431
  4. The HTTP listener closes, so no request reaches a service that has stopped.
4428
4432
  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.52.2",
3
+ "version": "0.53.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",
@@ -6,6 +6,12 @@ import { addressee, type Speaker } from "../identity/speakers.ts";
6
6
  import { HostStoppingError } from "../kernel/errors.ts";
7
7
  import { intercomPlain } from "../presentation/intercom.ts";
8
8
  import { isQuiet } from "../presentation/reply-body.ts";
9
+ import {
10
+ currentHop,
11
+ currentRecord,
12
+ type RecordOrigin,
13
+ underHop,
14
+ } from "../routing/turn-records.ts";
9
15
  import type { OutboxEntry, StoredOutboxEntry } from "./agent-outbox.ts";
10
16
  import {
11
17
  agentFailureText,
@@ -90,13 +96,27 @@ export class AgentMessages {
90
96
  peer: this.#peer(target),
91
97
  text,
92
98
  });
93
- void queue
94
- .run(targetChannel, async () =>
95
- this.#exchange(sender, target, text, chain, targetChannel, parent),
96
- )
99
+ // The person's message this send goes back to: the exchange runs outside its record, so the
100
+ // target's answer is not taken for the sender's, and what any later hop keeps for the next
101
+ // start is taken out again once a shutdown leaves that message, which is then asked again.
102
+ // A send under the record counts its answers then; a later hop takes those of the send it follows.
103
+ const record = currentRecord();
104
+ const origin = record ? { record, since: record.answers } : currentHop();
105
+ void underHop(origin, () =>
106
+ queue.run(targetChannel, async () =>
107
+ this.#exchange(
108
+ sender,
109
+ target,
110
+ text,
111
+ chain,
112
+ { targetChannel, senderChannel: parent },
113
+ origin,
114
+ ),
115
+ ),
116
+ )
97
117
  .catch((error: unknown) => {
98
118
  if (error instanceof HostStoppingError) {
99
- this.#keep({
119
+ this.#keep(origin, {
100
120
  kind: "message",
101
121
  sender: sender.name,
102
122
  target: target.name,
@@ -156,8 +176,11 @@ export class AgentMessages {
156
176
  target: Agent,
157
177
  text: string,
158
178
  chain: Chain,
159
- targetChannel: ChannelKey,
160
- senderChannel: ChannelKey,
179
+ {
180
+ targetChannel,
181
+ senderChannel,
182
+ }: { targetChannel: ChannelKey; senderChannel: ChannelKey },
183
+ origin: RecordOrigin | undefined,
161
184
  ): Promise<void> {
162
185
  const { queue, logger } = this.#host.options;
163
186
  await this.#host.post(targetChannel, this.#host.current(sender), {
@@ -213,7 +236,7 @@ export class AgentMessages {
213
236
  .catch((error: unknown) => {
214
237
  if (error instanceof HostStoppingError) {
215
238
  // The sender would wait for this answer forever, so it waits in the outbox for the next start.
216
- this.#keep({
239
+ this.#keep(origin, {
217
240
  kind: "reply",
218
241
  sender: current.name,
219
242
  target: target.name,
@@ -240,31 +263,59 @@ export class AgentMessages {
240
263
  );
241
264
  }
242
265
 
243
- /** Writes an entry the queue refused to the outbox; the write is waited for by the shutdown. */
244
- #keep(entry: OutboxEntry): void {
266
+ /**
267
+ * Writes an entry the queue refused to the outbox; the write is waited for by the shutdown. When
268
+ * the shutdown leaves the person's message of the turn that sent it, the entry is taken out
269
+ * again, or not written at all: the next process answers that message anew, or its author is
270
+ * asked to send it again, and the turn sends it again then.
271
+ */
272
+ #keep(origin: RecordOrigin | undefined, entry: OutboxEntry): void {
245
273
  const { store, logger } = this.#host.options;
274
+ const about = { kind: entry.kind, from: entry.sender, to: entry.target };
275
+ if (origin?.record.droppedSince(origin.since)) {
276
+ logger.info(
277
+ about,
278
+ "agent message dropped: its person's message is asked again after the restart",
279
+ );
280
+ return;
281
+ }
246
282
  const write = this.#lastKept
247
283
  .then(() => store.outbox.keep(entry))
248
284
  .then(
249
- () =>
250
- logger.info(
251
- { kind: entry.kind, from: entry.sender, to: entry.target },
252
- "agent message kept for the next start",
253
- ),
254
- (error: unknown) =>
285
+ (id) => {
286
+ logger.info(about, "agent message kept for the next start");
287
+ return id;
288
+ },
289
+ (error: unknown) => {
255
290
  logger.error(
256
- {
257
- kind: entry.kind,
258
- from: entry.sender,
259
- to: entry.target,
260
- err: error,
261
- },
291
+ { ...about, err: error },
262
292
  "agent message lost: not kept for the next start",
263
- ),
293
+ );
294
+ return undefined;
295
+ },
264
296
  );
265
- this.#lastKept = write;
266
- this.#keeping.add(write);
267
- void write.finally(() => this.#keeping.delete(write));
297
+ this.#lastKept = write.then(() => undefined);
298
+ const kept = write.then(() => undefined);
299
+ this.#keeping.add(kept);
300
+ void kept.finally(() => this.#keeping.delete(kept));
301
+ origin?.record.onLeave(async () => {
302
+ const id = await write;
303
+ if (id === undefined) return;
304
+ try {
305
+ const taken = await store.outbox.claim(id);
306
+ logger.info(
307
+ about,
308
+ taken
309
+ ? "kept agent message dropped: its person's message is asked again after the restart"
310
+ : "kept agent message already taken",
311
+ );
312
+ } catch (error) {
313
+ logger.warn(
314
+ { ...about, err: error },
315
+ "kept agent message not dropped; it is replayed after the restart",
316
+ );
317
+ }
318
+ }, origin.since);
268
319
  }
269
320
 
270
321
  /**
@@ -361,8 +412,8 @@ export class AgentMessages {
361
412
  target,
362
413
  entry.text,
363
414
  chain,
364
- entry.channel,
365
- origin,
415
+ { targetChannel: entry.channel, senderChannel: origin },
416
+ undefined,
366
417
  );
367
418
  } finally {
368
419
  this.#host.helpers.end(target.name);
@@ -64,10 +64,13 @@ export class AgentOutbox {
64
64
  this.#guild = guildId;
65
65
  }
66
66
 
67
- async keep(entry: OutboxEntry): Promise<void> {
68
- await this.#sql`
67
+ /** Keeps the entry, returning its id. */
68
+ async keep(entry: OutboxEntry): Promise<number> {
69
+ const rows: { id: string | number }[] = await this.#sql`
69
70
  INSERT INTO agent_outbox (guild_id, channel, payload)
70
- VALUES (${this.#guild}, ${entry.channel}, ${JSON.stringify(entry)}::jsonb)`;
71
+ VALUES (${this.#guild}, ${entry.channel}, ${JSON.stringify(entry)}::jsonb)
72
+ RETURNING id`;
73
+ return Number(rows[0]?.id);
71
74
  }
72
75
 
73
76
  /** Every kept entry, oldest first. */
@@ -9,6 +9,7 @@ import { SYSTEM_PRINCIPAL } from "../identity/principal-store.ts";
9
9
  import { addressee, type Speaker } from "../identity/speakers.ts";
10
10
  import type { ConversationModes } from "../modes/conversation-modes.ts";
11
11
  import type { AgentChange, NewAgent } from "../plugin-api/services.ts";
12
+ import { underRecord } from "../routing/turn-records.ts";
12
13
  import { openingTaskText } from "./agent-prompt.ts";
13
14
  import { modelSetting, thinkingSetting } from "./agent-settings.ts";
14
15
  import type { Agent } from "./agent-store.ts";
@@ -382,8 +383,9 @@ export class TeamEditing {
382
383
  text: `Created "${agent.displayName}" (${agent.name})${where}; ${avatar}. It has no room to start its opening task in yet.`,
383
384
  };
384
385
  }
385
- void queue
386
- .run(home, () =>
386
+ // Outside the turn that made the agent: the opening task does not answer that turn's message.
387
+ void underRecord(undefined, () =>
388
+ queue.run(home, () =>
387
389
  this.#ctx.turns.answerBackground(
388
390
  home,
389
391
  who.speaker,
@@ -393,10 +395,10 @@ export class TeamEditing {
393
395
  addressee(who.speaker, this.#ctx.options.owner),
394
396
  ),
395
397
  ),
396
- )
397
- .catch((error: unknown) =>
398
- logger.error({ agent: agent.name, err: error }, "opening turn failed"),
399
- );
398
+ ),
399
+ ).catch((error: unknown) =>
400
+ logger.error({ agent: agent.name, err: error }, "opening turn failed"),
401
+ );
400
402
  return {
401
403
  agent,
402
404
  text: `Created "${agent.displayName}" (${agent.name})${where}; ${avatar}. It is starting on its opening task now.`,
@@ -8,7 +8,7 @@ import { AgentError } from "../domain/errors.ts";
8
8
  import type { AgentTurnScope } from "../domain/ports.ts";
9
9
  import type { Speaker } from "../identity/speakers.ts";
10
10
  import { isQuiet, replyBody } from "../presentation/reply-body.ts";
11
- import { endOf, settleTurn } from "../routing/settle-turn.ts";
11
+ import { endOf, settleTurnIn } from "../routing/settle-turn.ts";
12
12
  import { toolTiers } from "../runtime/tool-tiers.ts";
13
13
  import { withReplyFiles } from "../shared/reply-files.ts";
14
14
  import { AgentMessages } from "./agent-messages.ts";
@@ -205,7 +205,9 @@ export class TeamTurns {
205
205
  const progress = roomProgress(this.#options, postTo);
206
206
  let result: TurnResult;
207
207
  try {
208
- result = await settleTurn(
208
+ // Named for a turn outside a queue task too; inside one, the task's channel is the same.
209
+ result = await settleTurnIn(
210
+ postTo,
209
211
  () =>
210
212
  withReplyFiles(this.#posts.carriesFiles(postTo), () =>
211
213
  this.#options.runtime().runTurn({
@@ -322,7 +322,8 @@ export interface ChannelClaim {
322
322
  startFresh(channel: ChannelKey): Promise<string>;
323
323
  /**
324
324
  * Stops the channel's running turn; true when one was running. The router asks only the claim
325
- * that owns the channel, and a claim without `stop` has nothing to stop there.
325
+ * that owns the channel, and a claim without `stop` has nothing to stop there, except at the
326
+ * drain limit of a shutdown, when the host stops its turn with the runtime's `stop`.
326
327
  */
327
328
  stop?(channel: ChannelKey): boolean;
328
329
  /** Removes the channel's conversation for good; a claim without one refuses. */
@@ -250,6 +250,8 @@ export class Linkage {
250
250
  surfaces: this.#surfaces(),
251
251
  logger,
252
252
  observers: this.observers,
253
+ // A shutdown stops a turn of a claim without `stop` as the runtime would.
254
+ stopTurn: (channel) => services.find(RUNTIME)?.stop(channel) ?? false,
253
255
  ...(this.#options.peerBots
254
256
  ? { peerBots: new PeerBots(this.#options.peerBots) }
255
257
  : {}),
@@ -299,45 +299,64 @@ export class Roundtable {
299
299
  logger.info({ signal }, "shutting down once idle");
300
300
  this.#link.queue.close();
301
301
  beginServicesDrain(this.#started, logger);
302
+ // The queue's channels, and those where a message's turn runs outside it.
303
+ const turnChannels = () => [
304
+ ...new Set([
305
+ ...this.#link.queue.busy(),
306
+ ...(this.#link.router?.busy() ?? []),
307
+ ]),
308
+ ];
302
309
  const stopQueuedTurns = () =>
303
310
  stopTurns(
304
- this.#link.queue.busy(),
305
- (channel) => this.#link.router?.stop(channel as ChannelKey) ?? false,
311
+ turnChannels(),
312
+ (channel) => this.#link.router?.abort(channel as ChannelKey) ?? false,
306
313
  logger,
307
314
  );
308
315
  const left = await drainWork({
309
316
  ...drain,
310
317
  busy: () => [
311
- ...this.#link.queue.busy(),
318
+ ...turnChannels(),
312
319
  ...this.#started.flatMap((service) => service.busy?.() ?? []),
313
320
  ],
314
321
  // A turn the limit finds still running is stopped, as the owner's stop would, and a
315
322
  // service is told to stop its own work before it is stopped.
316
323
  abort: () => {
324
+ // What still runs now was cut short: unless it answers in the grace, its messages are left.
325
+ this.#link.router?.cutRunning();
317
326
  const turns = stopQueuedTurns();
318
327
  const services = abortServices(this.#started, logger);
319
328
  return turns || services;
320
329
  },
321
330
  });
322
- // Only what ran before the drain ended finishes; nothing delivered later starts.
331
+ // Only what ran before the drain ended finishes; nothing delivered later starts. A message's
332
+ // turn still running that the drain did not count, such as one a `finishing` delivery routed, is cut now.
323
333
  this.#link.queue.seal();
324
- // A message still waiting behind a turn never starts: its channel is told while the services run.
334
+ this.#link.router?.cutRunning();
335
+ // A cut turn that did not answer, then a message still waiting behind a turn, never answers:
336
+ // their channels are told while the services run, the cut first, as its message came first.
325
337
  // Counted as it goes, and told to start no more once the limit passes.
326
338
  const tally = { refused: 0, failed: 0, stopped: false };
339
+ const router = this.#link.router;
327
340
  const told = await attempt(() =>
328
341
  withinMs(
329
342
  drain?.refuseWaitingMs ?? REFUSE_WAITING_MS,
330
- this.#link.router?.refuseWaiting(tally),
343
+ router?.leaveCut(tally).then(async ({ dropping }) => {
344
+ await router.refuseWaiting(tally);
345
+ await dropping;
346
+ }),
331
347
  ),
332
348
  );
333
349
  tally.stopped = true;
334
350
  if (!told.ok || tally.failed > 0)
335
351
  logger.error(
336
352
  { err: told.ok ? undefined : told.error, ...tally },
337
- "not every waiting message was refused; the rest are not answered",
353
+ "not every cut or waiting message was refused; the rest are not answered",
338
354
  );
339
355
  else if (tally.refused > 0)
340
- logger.info({ refused: tally.refused }, "waiting messages refused");
356
+ logger.info(
357
+ { refused: tally.refused },
358
+ "cut and waiting messages refused",
359
+ );
341
360
  // A turn that started during the abort grace, a report's, is stopped too, so the teardown does not wait for it.
342
361
  if (left.length > 0) stopQueuedTurns();
343
362
  if (left.length > 0) {
@@ -0,0 +1,75 @@
1
+ import type {
2
+ Admission,
3
+ ChannelClaim,
4
+ InboundMessage,
5
+ } from "../contract/channels.ts";
6
+ import type { Contact, ContactAssessor } from "../identity/contact.ts";
7
+ import type { Logger } from "../kernel/log.ts";
8
+ import { actorOf } from "./actor-of.ts";
9
+
10
+ export interface AdmitOptions {
11
+ logger: Logger;
12
+ /** Who the authors of messages are; without it, no message carries a speaker. */
13
+ contacts?: ContactAssessor;
14
+ /** The surfaces already warned that their messages carry no actor. */
15
+ warned: Set<string>;
16
+ }
17
+
18
+ /**
19
+ * The claim's admission of the message, which carries the speaker its author resolves to; one
20
+ * who cannot be resolved, such as while the database is down, reaches the claim as no one. The
21
+ * author's contact is recorded, such as their first contact linked, only once the claim takes
22
+ * the message, so a message nobody serves links or makes no one. A linked author the rules
23
+ * refuse is still recorded as seen at no tier as the message is assessed, whether or not a
24
+ * claim then takes it, at most once in a while. When that record fails, or finds them someone
25
+ * else or no one now, such as linked elsewhere meanwhile, the message is dropped: it would run
26
+ * as a principal that may not exist, such as one only assessed at a first contact. The claim
27
+ * hears it through the admission's `dropped` or `unanswered`.
28
+ */
29
+ export async function admitMessage(
30
+ claim: ChannelClaim,
31
+ message: InboundMessage,
32
+ { logger, contacts, warned }: AdmitOptions,
33
+ ): Promise<{ admission: Admission; message: InboundMessage } | undefined> {
34
+ const { speaker: _given, ...facts } = message;
35
+ const actor = actorOf(message, warned, logger);
36
+ let contact: Contact | undefined;
37
+ if (actor && contacts)
38
+ try {
39
+ contact = await contacts.assess(actor, {
40
+ conversation: message.channel,
41
+ });
42
+ } catch (error) {
43
+ logger.error(
44
+ { channel: message.channel, err: error },
45
+ "could not resolve who wrote a message; it reaches its claim as no one",
46
+ );
47
+ }
48
+ const admittedAs: InboundMessage = contact
49
+ ? { ...facts, speaker: Object.freeze({ ...contact.speaker }) }
50
+ : facts;
51
+ const admission = claim.admit(admittedAs);
52
+ if (!admission) return undefined;
53
+ if (!contact) return { admission, message: admittedAs };
54
+ try {
55
+ const taken = await contact.take();
56
+ if (taken?.principalId === contact.speaker.principalId)
57
+ return { admission, message: admittedAs };
58
+ logger.warn(
59
+ { channel: message.channel },
60
+ "the author of a message was linked elsewhere, or refused, while it was admitted; it does not run",
61
+ );
62
+ } catch (error) {
63
+ logger.error(
64
+ { channel: message.channel, err: error },
65
+ "could not record who wrote a message; it does not run",
66
+ );
67
+ }
68
+ if (admission.kind === "turn") admission.dropped?.();
69
+ else
70
+ admission.unanswered({
71
+ status: "skipped",
72
+ reason: "its author was not who they were when it was admitted",
73
+ });
74
+ return undefined;
75
+ }
@@ -1,6 +1,7 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import type { ChannelKey } from "../domain/sessions.ts";
3
3
  import { HostStoppingError } from "../kernel/errors.ts";
4
+ import { currentRecord, inChannel } from "./turn-records.ts";
4
5
 
5
6
  /** Runs tasks one at a time per channel, in arrival order; different channels run independently. */
6
7
  export class ChannelQueue {
@@ -76,11 +77,18 @@ export class ChannelQueue {
76
77
  }
77
78
 
78
79
  run<T>(channel: ChannelKey, task: () => Promise<T>): Promise<T> {
80
+ // Queued from a message's admission, it keeps that admission's turn record open until it ends,
81
+ // so a turn it runs after the admission returned still answers or leaves that message.
82
+ const record = currentRecord();
83
+ record?.begin(channel);
79
84
  const admitted = this.#admitted();
80
85
  const start = () => {
81
- if (this.#closed && !(admitted && !this.#sealed))
86
+ if (this.#closed && !(admitted && !this.#sealed)) {
87
+ record?.refusedByHost();
82
88
  return Promise.reject(new HostStoppingError());
83
- return admitted ? this.#finishing.run(1, task) : task();
89
+ }
90
+ const inQueue = () => inChannel(channel, task);
91
+ return admitted ? this.#finishing.run(1, inQueue) : inQueue();
84
92
  };
85
93
  this.#sizes.set(channel, this.size(channel) + 1);
86
94
  this.#changed(channel);
@@ -94,6 +102,7 @@ export class ChannelQueue {
94
102
  else this.#sizes.delete(channel);
95
103
  if (this.#tails.get(channel) === tail) this.#tails.delete(channel);
96
104
  this.#changed(channel);
105
+ record?.end(channel);
97
106
  });
98
107
  return result;
99
108
  }