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.
@@ -0,0 +1,341 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import type { InboundMessage } from "../contract/channels.ts";
3
+ import type { TurnResult } from "../domain/conversation.ts";
4
+ import { AgentRunError } from "../domain/errors.ts";
5
+ import type { ChannelKey } from "../domain/sessions.ts";
6
+ import { HostStoppingError } from "../kernel/errors.ts";
7
+ import type { Logger } from "../kernel/log.ts";
8
+ import type { RefuseTally } from "./queued-messages.ts";
9
+
10
+ /** What a record tells its `RunningTurns`. */
11
+ interface RecordHooks {
12
+ /** The admission and every turn and queue task under it have ended. */
13
+ closed(): void;
14
+ /** The stopping host refused a turn or queue task under it while it was open. */
15
+ refused(): void;
16
+ }
17
+
18
+ /**
19
+ * The person's messages one admitted turn answers, as the router runs it: the message that started
20
+ * it and those steered into it, and which of them it answered. When a turn run under the admission
21
+ * through `settleTurn` ends with `ok`, whose pipeline then posts the answer, every message the
22
+ * record holds by then counts as answered; a stopped or failed turn answers none, and a message
23
+ * steered in later waits for the next `ok`. A turn runs under the admission when it runs in the
24
+ * admission's work while that is open: its `run`, and what that starts, awaited or not, such as a
25
+ * queue task for a thread it opens, which keeps it open until it ends; a background turn, an
26
+ * agent's message to another agent and a new agent's opening task run outside it, and once the
27
+ * admission's work has ended, later work it set up, such as a timer, no longer counts. A shutdown
28
+ * that cuts it before an answer leaves the
29
+ * messages still unanswered for the next process, drops what its turn handed on for later
30
+ * (`onLeave`), and a turn under it that ends later gives a stopped result instead, so its answer is
31
+ * not posted as well.
32
+ */
33
+ export class TurnRecord {
34
+ readonly #messages: InboundMessage[];
35
+ readonly #answered = new Set<InboundMessage>();
36
+ /** How many turns under it ended `ok`. */
37
+ #answers = 0;
38
+ #left = false;
39
+ readonly #onLeave: { task: () => Promise<void>; since: number }[] = [];
40
+ /** The admission while it runs, plus each turn and queue task running under it. */
41
+ #open = 1;
42
+ /** The channels of the turns and queue tasks running under it, each with how many. */
43
+ readonly #channels = new Map<ChannelKey, number>();
44
+ /** Its admission's work has ended: what runs under it later changes nothing but a left one's late answer. */
45
+ #done = false;
46
+ readonly #hooks: RecordHooks;
47
+
48
+ constructor(message: InboundMessage, hooks: Partial<RecordHooks> = {}) {
49
+ this.#messages = [message];
50
+ const none = () => undefined;
51
+ this.#hooks = {
52
+ closed: hooks.closed ?? none,
53
+ refused: hooks.refused ?? none,
54
+ };
55
+ }
56
+
57
+ /** Its messages, the one that started it first. */
58
+ get messages(): readonly InboundMessage[] {
59
+ return this.#messages;
60
+ }
61
+
62
+ /** Adds a message steered into its turn. */
63
+ add(message: InboundMessage): void {
64
+ this.#messages.push(message);
65
+ }
66
+
67
+ /** Takes back a message its turn did not take after all. */
68
+ remove(message: InboundMessage): void {
69
+ const at = this.#messages.indexOf(message);
70
+ if (at > 0) this.#messages.splice(at, 1);
71
+ this.#answered.delete(message);
72
+ }
73
+
74
+ /** A turn or queue task under it starts, in `channel` when it says; it keeps it open while its admission's work is. */
75
+ begin(channel?: ChannelKey): void {
76
+ if (this.#done) return;
77
+ this.#open += 1;
78
+ if (channel)
79
+ this.#channels.set(channel, (this.#channels.get(channel) ?? 0) + 1);
80
+ }
81
+
82
+ /** The admission, or a turn or queue task under it, ended; `channel` as it began. */
83
+ end(channel?: ChannelKey): void {
84
+ if (this.#done) return;
85
+ const left = (channel && this.#channels.get(channel)) || 0;
86
+ if (channel && left <= 1) this.#channels.delete(channel);
87
+ else if (channel) this.#channels.set(channel, left - 1);
88
+ this.#open -= 1;
89
+ if (this.#open > 0) return;
90
+ this.#done = true;
91
+ this.#hooks.closed();
92
+ }
93
+
94
+ /**
95
+ * The channels its turns and queue tasks run in now; while work runs under it that names none,
96
+ * its admission or a bare `settleTurn` outside any queue task (`context.turns`, the agent team
97
+ * and a queue task name theirs), its first message's channel too.
98
+ */
99
+ channels(): ChannelKey[] {
100
+ let named = 0;
101
+ for (const count of this.#channels.values()) named += count;
102
+ const channels = [...this.#channels.keys()];
103
+ const first = this.#messages[0];
104
+ if (!this.#done && this.#open > named && first)
105
+ channels.push(first.channel);
106
+ return [...new Set(channels)];
107
+ }
108
+
109
+ /** Its messages no `ok` turn answered yet. */
110
+ unanswered(): InboundMessage[] {
111
+ return this.#messages.filter((message) => !this.#answered.has(message));
112
+ }
113
+
114
+ /** How many turns under it ended `ok` so far; `onLeave` takes it as the point a task was asked for. */
115
+ get answers(): number {
116
+ return this.#answers;
117
+ }
118
+
119
+ /** Whether its messages were left for the next process. */
120
+ get left(): boolean {
121
+ return this.#left;
122
+ }
123
+
124
+ /**
125
+ * Runs `task` when its messages are left, unless a turn under it ended `ok` after `since` (its
126
+ * `answers` when the work that asked began): such as removing an agent message kept for the next
127
+ * start, which the next process sends again when it answers the message anew. An agent message a
128
+ * turn sent before it answered belongs to that answer and stays.
129
+ */
130
+ onLeave(task: () => Promise<void>, since = this.#answers): void {
131
+ this.#onLeave.push({ task, since });
132
+ }
133
+
134
+ /**
135
+ * Marks its messages left for the next process at once, then runs what `onLeave` asked, each
136
+ * failure its own; the returned promise ends when they have.
137
+ */
138
+ async leave(): Promise<void> {
139
+ this.#left = true;
140
+ const due = this.#onLeave
141
+ .splice(0)
142
+ .filter(({ since }) => since === this.#answers);
143
+ await Promise.allSettled(due.map(({ task }) => task()));
144
+ }
145
+
146
+ /** The stopping host refused a turn or queue task under it before it ran. */
147
+ refusedByHost(): void {
148
+ if (!this.#done) this.#hooks.refused();
149
+ }
150
+
151
+ /** Whether `onLeave` asked at `since` would run by now: its messages were left and no `ok` came since. */
152
+ droppedSince(since: number): boolean {
153
+ return this.#left && since === this.#answers;
154
+ }
155
+
156
+ /**
157
+ * What a turn that ended under it gives its pipeline: an answer once its messages were left is
158
+ * stopped, and so is the runtime's refusal of a turn asked for once the host stops, so its person
159
+ * is told only that their message is answered after the restart, not to try again.
160
+ */
161
+ settle<R>(result: R): R | StoppedResult {
162
+ if (!isTurnResult(result)) return result;
163
+ if (this.#left) return stoppedByHost();
164
+ if (result.ok) {
165
+ if (this.#done) return result;
166
+ this.#answers += 1;
167
+ for (const message of this.#messages) this.#answered.add(message);
168
+ } else if (
169
+ !result.stopped &&
170
+ result.error.message === STOPPING &&
171
+ !this.#done
172
+ ) {
173
+ // Left with the cut, its person hears only that; work after the admission's keeps "try again".
174
+ this.refusedByHost();
175
+ return stoppedByHost();
176
+ }
177
+ return result;
178
+ }
179
+ }
180
+
181
+ const STOPPING = new HostStoppingError().message;
182
+
183
+ type StoppedResult = { ok: false; error: AgentRunError; stopped: true };
184
+
185
+ const stoppedByHost = (): StoppedResult => ({
186
+ ok: false,
187
+ error: new AgentRunError(STOPPING),
188
+ stopped: true,
189
+ });
190
+
191
+ function isTurnResult(value: unknown): value is TurnResult {
192
+ return (
193
+ typeof value === "object" &&
194
+ value !== null &&
195
+ typeof (value as { ok?: unknown }).ok === "boolean"
196
+ );
197
+ }
198
+
199
+ /**
200
+ * Where a turn outside any record goes back to: the record of the person's message a chain of agent
201
+ * messages started from, and its `answers` when the send that led here was made.
202
+ */
203
+ export interface RecordOrigin {
204
+ record: TurnRecord;
205
+ since: number;
206
+ }
207
+
208
+ const current = new AsyncLocalStorage<
209
+ { record?: TurnRecord; hop?: RecordOrigin; channel?: ChannelKey } | undefined
210
+ >();
211
+
212
+ /** Runs `task` with `record` as the turn record of everything it starts; undefined runs it outside any. */
213
+ export function underRecord<T>(
214
+ record: TurnRecord | undefined,
215
+ task: () => T,
216
+ ): T {
217
+ return current.run(record && { record }, task);
218
+ }
219
+
220
+ /** The turn record of the admission the caller runs under, if any. */
221
+ export function currentRecord(): TurnRecord | undefined {
222
+ return current.getStore()?.record;
223
+ }
224
+
225
+ /**
226
+ * Runs `task` outside any record, as an agent message's exchange: what it starts that goes back to
227
+ * the person's message, such as the next agent message, reads `hop` with `currentHop`. Leaving
228
+ * the exchange the way a record is left, through `underRecord(undefined, …)`, clears it too.
229
+ */
230
+ export function underHop<T>(hop: RecordOrigin | undefined, task: () => T): T {
231
+ return current.run(hop && { hop }, task);
232
+ }
233
+
234
+ /** The origin of the exchange the caller runs in, if any. */
235
+ export function currentHop(): RecordOrigin | undefined {
236
+ return current.getStore()?.hop;
237
+ }
238
+
239
+ /** Runs a queue task of `channel` as it is, telling a turn it runs, such as a bare `settleTurn`, its channel. */
240
+ export function inChannel<T>(channel: ChannelKey, task: () => T): T {
241
+ const store = current.getStore();
242
+ return store ? current.run({ ...store, channel }, task) : task();
243
+ }
244
+
245
+ /** The channel of the queue task the caller runs in, when it runs under a record or an exchange. */
246
+ export function currentChannel(): ChannelKey | undefined {
247
+ return current.getStore()?.channel;
248
+ }
249
+
250
+ /**
251
+ * The records of the admitted turns still running, or with a turn or queue task running under
252
+ * them: the router runs each turn admission through `run`, and the host marks the ones the drain
253
+ * limit finds with `cut`, to leave those that did not answer once the abort grace is over. A record
254
+ * whose turn the runtime refused as the host stopped, before or after the drain limit, is cut as
255
+ * well.
256
+ */
257
+ export class RunningTurns {
258
+ readonly #live = new Set<TurnRecord>();
259
+ /** Each channel's admission running in its queue, which a steered message joins. */
260
+ readonly #running = new Map<ChannelKey, TurnRecord>();
261
+ #cut: TurnRecord[] = [];
262
+
263
+ /** Runs the admission of `message` under a new record, as its channel's running turn. */
264
+ async run(
265
+ message: InboundMessage,
266
+ task: () => Promise<unknown>,
267
+ ): Promise<void> {
268
+ const { channel } = message;
269
+ const record: TurnRecord = new TurnRecord(message, {
270
+ closed: () => this.#live.delete(record),
271
+ refused: () => this.#cut.push(record),
272
+ });
273
+ this.#live.add(record);
274
+ this.#running.set(channel, record);
275
+ try {
276
+ await underRecord(record, task);
277
+ } catch (error) {
278
+ // A turn it asked for was refused as the host stops: its unanswered messages are told with
279
+ // the cut turns once the abort grace is over, within the refusal's time, not at once.
280
+ if (!(error instanceof HostStoppingError)) throw error;
281
+ record.refusedByHost();
282
+ } finally {
283
+ if (this.#running.get(channel) === record) this.#running.delete(channel);
284
+ record.end();
285
+ }
286
+ }
287
+
288
+ /** The channel's running turn, to add a message steered into it; undefined when none runs. */
289
+ running(channel: ChannelKey): TurnRecord | undefined {
290
+ return this.#running.get(channel);
291
+ }
292
+
293
+ /** The channels the open records' turns and queue tasks run in, such as a turn asked for without waiting. */
294
+ busy(): ChannelKey[] {
295
+ return [...new Set([...this.#live].flatMap((record) => record.channels()))];
296
+ }
297
+
298
+ /** Marks every record still open as cut: the drain limit found its turn running. */
299
+ cut(): void {
300
+ this.#cut.push(...this.#live);
301
+ }
302
+
303
+ /** The records marked cut, each once. */
304
+ takeCut(): TurnRecord[] {
305
+ return [...new Set(this.#cut.splice(0))];
306
+ }
307
+
308
+ /**
309
+ * Leaves each cut record's unanswered messages of a person and `tell`s each, counting in `tally`
310
+ * and starting no record once it is `stopped`; `dropping` ends once what they handed on is dropped.
311
+ */
312
+ async leaveCut(
313
+ tally: RefuseTally,
314
+ logger: Logger,
315
+ tell: (message: InboundMessage) => Promise<void>,
316
+ ): Promise<{ dropping: Promise<unknown> }> {
317
+ const dropping: Promise<void>[] = [];
318
+ for (const record of this.takeCut()) {
319
+ // A bot's or an integration's message is told nothing, so its turn's late answer stays.
320
+ const people = record
321
+ .unanswered()
322
+ .filter((message) => !message.authorIsBot && !message.integration);
323
+ // Left only as its channel is told, so one the limit stops before keeps its late answer.
324
+ if (tally.stopped) break;
325
+ if (people.length === 0) continue;
326
+ logger.info(
327
+ { channel: record.messages[0]?.channel },
328
+ "turn cut by the shutdown before it answered; its messages are refused",
329
+ );
330
+ // Left at once; what it handed on is dropped meanwhile, not before its channel is told.
331
+ dropping.push(record.leave());
332
+ for (const message of people) {
333
+ // A message the limit stops before is neither told nor answered (docs/plugins.md).
334
+ if (tally.stopped) break;
335
+ await tell(message);
336
+ tally.refused += 1;
337
+ }
338
+ }
339
+ return { dropping: Promise.all(dropping) };
340
+ }
341
+ }