pi-roundtable 0.52.1 → 0.52.3
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 +20 -1
- package/README.md +1 -0
- package/docs/plugins.md +9 -5
- package/package.json +1 -1
- package/src/core/agents/agent-messages.ts +79 -28
- package/src/core/agents/agent-outbox.ts +6 -3
- package/src/core/agents/team-editing.ts +8 -6
- package/src/core/agents/team-turns.ts +4 -2
- package/src/core/config/limits.ts +20 -1
- package/src/core/contract/channels.ts +2 -1
- package/src/core/discord/catch-up-gate.ts +24 -11
- package/src/core/discord/catch-up-journal.ts +4 -4
- package/src/core/host/define-roundtable.ts +5 -1
- package/src/core/host/drain.ts +1 -3
- package/src/core/host/host-registration.ts +2 -0
- package/src/core/host/host.ts +34 -13
- package/src/core/routing/admit-message.ts +75 -0
- package/src/core/routing/channel-queue.ts +11 -2
- package/src/core/routing/channel-router.ts +79 -93
- package/src/core/routing/conversation-turns.ts +103 -93
- package/src/core/routing/queued-messages.ts +27 -16
- package/src/core/routing/settle-turn.ts +38 -5
- package/src/core/routing/stopping-notice.ts +39 -0
- package/src/core/routing/turn-records.ts +341 -0
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,25 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
5
5
|
|
|
6
6
|
## [Unreleased]
|
|
7
7
|
|
|
8
|
+
## [0.52.3] - 2026-11-17
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
|
|
12
|
+
- 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.
|
|
13
|
+
- 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.
|
|
14
|
+
|
|
15
|
+
## [0.52.2] - 2026-11-17
|
|
16
|
+
|
|
17
|
+
### Added
|
|
18
|
+
|
|
19
|
+
- New config keys `abortGraceSeconds` (default 10, 1 to 600) and `refuseWaitingSeconds` (default 15, 1 to 600), and `drain.refuseWaitingMs` in `RoundtableOptions`: how long a shutdown gives the turns it stops at the drain limit to end, and the messages still waiting behind a turn to be refused. The service manager's kill timeout must be longer than `drainSeconds` + `abortGraceSeconds` + `refuseWaitingSeconds` plus a few seconds of teardown; under a 30-second kill, for example, 12 + 5 + 8 leaves five.
|
|
20
|
+
|
|
21
|
+
### Fixed
|
|
22
|
+
|
|
23
|
+
- `discord.catchUp`: during the shutdown, a message addressed to the bot is promised an answer after the restart, and recorded as left, only when routing refuses it because the host stops, that is when a claim would have answered it. A message in a channel the bot does not serve, or one no claim admits, no longer gets a false "will answer this once back" notice.
|
|
24
|
+
- `discord.catchUp`: a message that arrived during the shutdown and could not be recorded as left no longer gets the "send it again" notice, which together with catch-up answering it from the window could answer it twice; it gets no notice and the next process's catch-up answers it.
|
|
25
|
+
- A message waiting behind a running turn is now refused when the shutdown drain ends whatever claim admitted it. Before, only a message whose claim marks waiting messages (a `busy` admission, as the core's own claims give) was refused then; one waiting behind a plugin claim's turn that ignored its abort was neither answered nor told. Such a message is not listed among the channel's queued messages, as before.
|
|
26
|
+
|
|
8
27
|
## [0.52.1] - 2026-11-17
|
|
9
28
|
|
|
10
29
|
### Fixed
|
|
@@ -14,7 +33,7 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
14
33
|
- `discord.catchUp`: a message the live connection delivered without a record, because the database was down at startup, is not caught up a second time by the same process.
|
|
15
34
|
- `discord.catchUp`: the inbound journal is pruned to 30 days every six hours while the host runs, not only at restart. The docs now say what happens when `catchUp` is turned off later.
|
|
16
35
|
- `discord.catchUp`: a mention that has a thread started from it, or a reaction from the bot, counts as answered. Before this fix, the first restart after catch-up was enabled re-delivered mentions answered in a thread, and the bot then posted a false "could not open a thread" notice.
|
|
17
|
-
- `discord.catchUp`: caught-up messages reach routing before the newer live messages in the same channel. A live message waits until catch-up has listed the channels it may read (
|
|
36
|
+
- `discord.catchUp`: caught-up messages reach routing before the newer live messages in the same channel. A live message waits until catch-up has listed the channels it may read (two database queries). In one of those channels, it also waits until catch-up is done.
|
|
18
37
|
|
|
19
38
|
## [0.52.0] - 2026-11-17
|
|
20
39
|
|
package/README.md
CHANGED
|
@@ -194,6 +194,7 @@ A turn works 10 minutes by default before it asks you whether to go on, and 30 m
|
|
|
194
194
|
| `autonomy.yolo.allow`, `autonomy.yolo.card` | none | Hold classes yolo mode may approve beyond its defaults (`shell.rm`, say), and rule names whose calls it approves although the rule reports no classes (`tool:repo_push`, say), and classes or rule names it never approves (`shell.push`, say). By default yolo approves a plain `git push` and writes outside the workspace and cards the other destructive shell classes; see the [plugin guide](docs/plugins.md#hold-classes-and-yolo-mode) |
|
|
195
195
|
| `autonomy.yolo.questionGraceSeconds` | `30` | In a yolo conversation, how long an `ask_user` card holds the turn, 5 to 600; unanswered, the turn goes on with its own best choice and the card stays open |
|
|
196
196
|
| `autonomy.yolo.timeoutCardSeconds` | `60` | In a yolo conversation, how long the timeout card waits, 10 to 3600; unanswered, the turn goes on as if you pressed Continue, up to `autonomy.longRunning.maxSeconds` |
|
|
197
|
+
| `drainSeconds`, `abortGraceSeconds`, `refuseWaitingSeconds` | `180`, `10`, `15` | On a shutdown, how long running turns get to finish, then how long the ones stopped at that limit get to end, then how long the messages still waiting behind a turn get to be refused; the service manager's stop or kill timeout should be longer than the three together, plus a few seconds for the teardown |
|
|
197
198
|
|
|
198
199
|
Without `discord`, or with `discord` but no `discord.guild`, the agents still run when `agents` lists them, in the rooms of a surface that hosts them, such as pi-roundtable-web; the host refuses to start when none does:
|
|
199
200
|
|
package/docs/plugins.md
CHANGED
|
@@ -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.
|
|
@@ -2946,7 +2949,7 @@ A message counts when a person wrote it (not a bot, a webhook or Discord itself)
|
|
|
2946
2949
|
It is left alone when it is older than the window, when it was already taken in, or when it shows an answer: the bot or one of its own webhooks posted in that channel after it, a thread was started from it (by anyone, as the bot answers a mention in a thread), or the bot reacted to it.
|
|
2947
2950
|
The thread and the reaction matter at the first restart after `catchUp` is turned on, when nothing was recorded yet; a mention a person started a thread from is therefore not answered, since one missed answer is preferred to two.
|
|
2948
2951
|
Of what is left, the newest `maxMessages` (default 20, at most 100) go to routing oldest first.
|
|
2949
|
-
They go once every service has started; a live message that came after the connection became ready waits until catch-up has listed the channels it may read (
|
|
2952
|
+
They go once every service has started; a live message that came after the connection became ready waits until catch-up has listed the channels it may read (two database queries, before any request), and, in one of those, until catch-up is done, so the caught-up messages of a channel reach routing before its newer live ones.
|
|
2950
2953
|
Each one passes through the same claims, identity resolution and gates as a live message, with `InboundMessage.caughtUp` set, so a claim may say its answer comes late, for example that the assistant just restarted.
|
|
2951
2954
|
The log carries only counts and ids, never text.
|
|
2952
2955
|
|
|
@@ -2956,10 +2959,11 @@ Whichever records a message first delivers it; the other drops it, so a second r
|
|
|
2956
2959
|
A message that catch-up cannot record is skipped, and a crash after the record but before the turn leaves it unanswered: one missed answer is preferred to two.
|
|
2957
2960
|
The live connection still delivers a message it cannot record, such as while the database is down, and logs it; catch-up in the same process leaves it alone, so only a later restart that finds no answer to it in its channel could answer it again.
|
|
2958
2961
|
Catch-up reads the author of a server message as a member first; when that fails for any reason but the author having left the server, the message is skipped unrecorded, so a later restart may still answer it with the author's roles.
|
|
2959
|
-
Once the old process begins to shut down it runs no new turn, and an addressed message
|
|
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
|
-
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; this covers
|
|
2962
|
-
|
|
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`.
|
|
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.
|
|
2965
2969
|
Each notice is recorded in the journal, so the next process does not take it for an answer; a notice that cannot be recorded is deleted again, and when catch-up cannot look the notices up it leaves that channel unread rather than guess.
|
|
@@ -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 (`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.
|
|
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
|
@@ -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
|
-
|
|
94
|
-
|
|
95
|
-
|
|
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
|
-
|
|
160
|
-
|
|
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
|
-
/**
|
|
244
|
-
|
|
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
|
-
|
|
252
|
-
|
|
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
|
-
|
|
267
|
-
|
|
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
|
-
|
|
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
|
-
|
|
68
|
-
|
|
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
|
-
|
|
386
|
-
|
|
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
|
-
|
|
398
|
-
|
|
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,
|
|
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
|
-
|
|
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({
|
|
@@ -7,8 +7,21 @@ import {
|
|
|
7
7
|
} from "../modes/autonomy.ts";
|
|
8
8
|
import { integer, list, optional, shape, text } from "./schema.ts";
|
|
9
9
|
|
|
10
|
+
/** How long work that was told to stop at the drain limit gets to end before the shutdown goes on. */
|
|
11
|
+
export const ABORT_GRACE_MS = 10_000;
|
|
12
|
+
/** How long the messages still waiting after the drain are given to be refused, before the teardown. */
|
|
13
|
+
export const REFUSE_WAITING_MS = 15_000;
|
|
14
|
+
|
|
10
15
|
/** The configuration's `turnLimits` and `autonomy`: how long a turn works, and what runs without a person. */
|
|
11
16
|
export interface LimitsConfig {
|
|
17
|
+
/**
|
|
18
|
+
* Seconds a shutdown gives the turns it stops at the drain limit to end; 1 to 600, default 10.
|
|
19
|
+
* A service manager's kill timeout should exceed `drainSeconds` + this + `refuseWaitingSeconds`,
|
|
20
|
+
* plus a few seconds for the teardown.
|
|
21
|
+
*/
|
|
22
|
+
abortGraceSeconds?: number;
|
|
23
|
+
/** Seconds a shutdown gives the refusal of the messages still waiting behind a turn; 1 to 600, default 15. */
|
|
24
|
+
refuseWaitingSeconds?: number;
|
|
12
25
|
/**
|
|
13
26
|
* How long one turn may work before it asks the owner on a card whether to go on, or is
|
|
14
27
|
* stopped when it cannot show a card. Time spent waiting on the owner's cards does not count.
|
|
@@ -51,8 +64,10 @@ export interface LimitsConfig {
|
|
|
51
64
|
};
|
|
52
65
|
}
|
|
53
66
|
|
|
54
|
-
/** The
|
|
67
|
+
/** The keys' shapes, spread into the configuration's. */
|
|
55
68
|
export const limitsShape = {
|
|
69
|
+
abortGraceSeconds: optional(integer(1, 600)),
|
|
70
|
+
refuseWaitingSeconds: optional(integer(1, 600)),
|
|
56
71
|
turnLimits: optional(
|
|
57
72
|
shape({
|
|
58
73
|
timeoutSeconds: optional(integer(60, 86_400)),
|
|
@@ -79,6 +94,8 @@ export const limitsShape = {
|
|
|
79
94
|
|
|
80
95
|
/** The limits with their defaults, in ms; `maxMs` is never below `timeoutMs`. */
|
|
81
96
|
export interface ResolvedLimits {
|
|
97
|
+
abortGraceMs: number;
|
|
98
|
+
refuseWaitingMs: number;
|
|
82
99
|
turnLimits: { timeoutMs: number; maxMs: number; cardMs: number };
|
|
83
100
|
autonomy: Autonomy;
|
|
84
101
|
}
|
|
@@ -94,6 +111,8 @@ export function limitsOf(config: LimitsConfig): ResolvedLimits {
|
|
|
94
111
|
);
|
|
95
112
|
const longRunning = autonomy?.longRunning?.maxSeconds;
|
|
96
113
|
return {
|
|
114
|
+
abortGraceMs: secondsOr(config.abortGraceSeconds, ABORT_GRACE_MS),
|
|
115
|
+
refuseWaitingMs: secondsOr(config.refuseWaitingSeconds, REFUSE_WAITING_MS),
|
|
97
116
|
turnLimits: {
|
|
98
117
|
timeoutMs: timeoutSeconds * 1_000,
|
|
99
118
|
maxMs: maxSeconds * 1_000,
|
|
@@ -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. */
|
|
@@ -49,9 +49,11 @@ const DEFAULT_RETRY_MS = 2000;
|
|
|
49
49
|
* Records each addressed message the live gateway delivers before routing hears it, so catch-up
|
|
50
50
|
* after a restart leaves it alone; false for one already recorded, which is not delivered again.
|
|
51
51
|
* A message that cannot be recorded is still delivered, logged, and kept in `unrecorded`.
|
|
52
|
-
* Once the host drains, an addressed message
|
|
53
|
-
*
|
|
54
|
-
*
|
|
52
|
+
* Once the host drains, an addressed message still reaches routing unrecorded, so only one routing
|
|
53
|
+
* refuses as the host stops, one a claim would have answered, is recorded as left: the next process
|
|
54
|
+
* answers it whatever its channel shows since, and its channel is told so once. One that cannot be
|
|
55
|
+
* left gets no notice, as catch-up finds it unrecorded in its window. Any other message routing
|
|
56
|
+
* refuses then tells its channel once to send it again. Each notice is recorded, so
|
|
55
57
|
* catch-up does not take it for an answer, and deleted again when it cannot be.
|
|
56
58
|
*/
|
|
57
59
|
export function journalGate({
|
|
@@ -65,6 +67,9 @@ export function journalGate({
|
|
|
65
67
|
redeliver,
|
|
66
68
|
}: GateOptions): JournalGate {
|
|
67
69
|
const told = { later: new Set<string>(), resend: new Set<string>() };
|
|
70
|
+
// Addressed messages passed during the drain without a record: routing decides whether they are left.
|
|
71
|
+
// An entry routing never refuses stays until the process exits; the drain bounds the set, and the process ends after it.
|
|
72
|
+
const unclaimed = new Set<string>();
|
|
68
73
|
const channelOf = (message: InboundMessage) =>
|
|
69
74
|
message.channel.slice("discord:".length);
|
|
70
75
|
const tell = async (
|
|
@@ -111,7 +116,8 @@ export function journalGate({
|
|
|
111
116
|
channelId: channelOf(message),
|
|
112
117
|
direct: message.isDirect,
|
|
113
118
|
});
|
|
114
|
-
// Left in the journal, the next process answers it whatever its channel shows
|
|
119
|
+
// Left in the journal, the next process answers it whatever its channel shows. A recorded one that
|
|
120
|
+
// cannot be left is told to be sent again; an unrecorded one is told nothing, as catch-up answers it.
|
|
115
121
|
const leave = async (
|
|
116
122
|
message: InboundMessage,
|
|
117
123
|
botId: string,
|
|
@@ -132,6 +138,13 @@ export function journalGate({
|
|
|
132
138
|
return;
|
|
133
139
|
}
|
|
134
140
|
} catch (error) {
|
|
141
|
+
if (!taken) {
|
|
142
|
+
logger.warn(
|
|
143
|
+
{ ...where, err: error },
|
|
144
|
+
"could not leave a message for the next process; unrecorded, catch-up answers it",
|
|
145
|
+
);
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
135
148
|
logger.warn(
|
|
136
149
|
{ ...where, err: error },
|
|
137
150
|
"could not leave a message for the next process; its channel is told to send it again",
|
|
@@ -169,8 +182,9 @@ export function journalGate({
|
|
|
169
182
|
const pass = async (message: InboundMessage, botId: string) => {
|
|
170
183
|
if (!addressed(message)) return true;
|
|
171
184
|
if (draining()) {
|
|
172
|
-
|
|
173
|
-
|
|
185
|
+
// Routing refuses it, through `refused`, only when a claim would have answered it.
|
|
186
|
+
unclaimed.add(message.messageId);
|
|
187
|
+
return true;
|
|
174
188
|
}
|
|
175
189
|
const channelId = channelOf(message);
|
|
176
190
|
const { messageId } = message;
|
|
@@ -184,10 +198,8 @@ export function journalGate({
|
|
|
184
198
|
return false;
|
|
185
199
|
}
|
|
186
200
|
await wait?.(channelId);
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
await leave(message, botId);
|
|
190
|
-
return false;
|
|
201
|
+
// Should the drain have begun meanwhile, routing refuses it, and `refused` leaves it.
|
|
202
|
+
return true;
|
|
191
203
|
} catch (error) {
|
|
192
204
|
unrecorded?.add(messageId);
|
|
193
205
|
logger.warn(
|
|
@@ -199,7 +211,8 @@ export function journalGate({
|
|
|
199
211
|
};
|
|
200
212
|
const refused = async (message: InboundMessage, botId: string) => {
|
|
201
213
|
if (!notify || message.authorIsBot || message.integration) return false;
|
|
202
|
-
if (addressed(message))
|
|
214
|
+
if (addressed(message))
|
|
215
|
+
await leave(message, botId, !unclaimed.delete(message.messageId));
|
|
203
216
|
else await tell("resend", message, botId);
|
|
204
217
|
return true;
|
|
205
218
|
};
|
|
@@ -54,10 +54,6 @@ const migration: Migration = {
|
|
|
54
54
|
},
|
|
55
55
|
};
|
|
56
56
|
|
|
57
|
-
/**
|
|
58
|
-
* The journal over the host's pool, built from closures rather than private fields, so a test
|
|
59
|
-
* proxy can carry it. One insert that does nothing on a conflict decides who records a message.
|
|
60
|
-
*/
|
|
61
57
|
/** Marks a message left by a stopping process, so the next one answers it whatever the channel shows. */
|
|
62
58
|
const leftMigration: Migration = {
|
|
63
59
|
name: "discord-inbound-journal-left",
|
|
@@ -67,6 +63,10 @@ const leftMigration: Migration = {
|
|
|
67
63
|
},
|
|
68
64
|
};
|
|
69
65
|
|
|
66
|
+
/**
|
|
67
|
+
* The journal over the host's pool, built from closures rather than private fields, so a test
|
|
68
|
+
* proxy can carry it. One insert that does nothing on a conflict decides who records a message.
|
|
69
|
+
*/
|
|
70
70
|
export const PgInboundJournal = {
|
|
71
71
|
migrations: [migration, leftMigration],
|
|
72
72
|
attach(sql: SQL): InboundJournal {
|
|
@@ -360,7 +360,11 @@ export async function defineRoundtable(
|
|
|
360
360
|
],
|
|
361
361
|
judgeModel: judgeThrough(modelRuntime, config.judge.model),
|
|
362
362
|
apiKey: (provider) => registry.getApiKeyForProvider(provider),
|
|
363
|
-
drain: {
|
|
363
|
+
drain: {
|
|
364
|
+
limitMs: config.drainMs,
|
|
365
|
+
abortGraceMs: config.abortGraceMs,
|
|
366
|
+
refuseWaitingMs: config.refuseWaitingMs,
|
|
367
|
+
},
|
|
364
368
|
...(discord?.peerBots ? { peerBots: discord.peerBots } : {}),
|
|
365
369
|
...(overrides.aborted ? { aborted: overrides.aborted } : {}),
|
|
366
370
|
},
|
package/src/core/host/drain.ts
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
import { DRAIN_LIMIT_MS } from "../config/config-schema.ts";
|
|
2
|
+
import { ABORT_GRACE_MS } from "../config/limits.ts";
|
|
2
3
|
import type { Logger } from "../kernel/log.ts";
|
|
3
4
|
import type { Service } from "../plugin-api/plugin.ts";
|
|
4
5
|
|
|
5
|
-
/** How long work that was told to stop gets to end before the shutdown goes on without it. */
|
|
6
|
-
const ABORT_GRACE_MS = 10_000;
|
|
7
|
-
|
|
8
6
|
export interface DrainOptions {
|
|
9
7
|
/** What still runs or waits, one entry per piece of work; empty when idle. */
|
|
10
8
|
busy: () => string[];
|
|
@@ -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
|
: {}),
|