pi-roundtable 0.53.6 → 0.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +6 -2
  3. package/README.zh-TW.md +6 -2
  4. package/docs/plugins.md +199 -7
  5. package/package.json +3 -1
  6. package/runner/Dockerfile +46 -0
  7. package/runner/Dockerfile.dockerignore +5 -0
  8. package/src/cli/checks/images.ts +3 -2
  9. package/src/cli/checks/preset.ts +20 -0
  10. package/src/cli/checks/runner.ts +45 -0
  11. package/src/cli/doctor.ts +7 -1
  12. package/src/core/agents/agent-claim.ts +7 -4
  13. package/src/core/agents/agent-prompt.ts +11 -2
  14. package/src/core/agents/helper-workspace.ts +72 -0
  15. package/src/core/agents/team-options.ts +2 -0
  16. package/src/core/agents/team-prompt.ts +12 -1
  17. package/src/core/builtin/agent-server.ts +8 -0
  18. package/src/core/builtin/polls.ts +67 -0
  19. package/src/core/builtin/runner.ts +139 -0
  20. package/src/core/config/config-schema.ts +4 -0
  21. package/src/core/config/config.ts +49 -185
  22. package/src/core/config/preset.ts +51 -0
  23. package/src/core/config/resolve-config.ts +175 -0
  24. package/src/core/config/runner-config.ts +80 -0
  25. package/src/core/contract/polls.ts +71 -0
  26. package/src/core/contract/runtime.ts +12 -0
  27. package/src/core/contract/surface.ts +13 -0
  28. package/src/core/discord/discord-polls.ts +156 -0
  29. package/src/core/discord/discord-replies.ts +55 -0
  30. package/src/core/discord/discord-surface.ts +13 -43
  31. package/src/core/domain/errors.ts +5 -0
  32. package/src/core/domain/sessions.ts +8 -1
  33. package/src/core/host/define-roundtable.ts +8 -0
  34. package/src/core/host/host-registration.ts +7 -0
  35. package/src/core/host/host.ts +8 -0
  36. package/src/core/i18n/schedules.ts +2 -0
  37. package/src/core/modules/polls/poll-result-turns.ts +124 -0
  38. package/src/core/modules/polls/poll-rules.ts +108 -0
  39. package/src/core/modules/polls/poll-service.ts +477 -0
  40. package/src/core/modules/polls/poll-store.ts +336 -0
  41. package/src/core/modules/polls/poll-tools.ts +118 -0
  42. package/src/core/modules/polls/poll-turn-text.ts +60 -0
  43. package/src/core/plugin-api/define.ts +9 -2
  44. package/src/core/plugin-api/holds.ts +2 -0
  45. package/src/core/plugin-api/plugin.ts +8 -0
  46. package/src/core/runner/protocol.ts +456 -0
  47. package/src/core/runner/runner-client.ts +450 -0
  48. package/src/core/runner/runner-drivers.ts +356 -0
  49. package/src/core/runner/runner-files.ts +102 -0
  50. package/src/core/runner/runner-holds.ts +76 -0
  51. package/src/core/runner/runner-port.ts +77 -0
  52. package/src/core/runner/runner-probe.ts +53 -0
  53. package/src/core/runner/runner-prompt.ts +36 -0
  54. package/src/core/runner/runner-session.ts +131 -0
  55. package/src/core/runner/runner-tiers.ts +20 -0
  56. package/src/core/runner/runner-tools.ts +325 -0
  57. package/src/core/runner/settings.ts +108 -0
  58. package/src/core/runtime/conversation-sessions.ts +73 -15
  59. package/src/core/runtime/extensions/approval-card.ts +29 -2
  60. package/src/core/runtime/extensions/confirmation-gate.ts +24 -63
  61. package/src/core/runtime/extensions/gate-card.ts +105 -0
  62. package/src/core/runtime/extensions/yolo.ts +17 -3
  63. package/src/core/runtime/pi-agent-runtime.ts +37 -68
  64. package/src/core/runtime/runtime-plugin.ts +9 -0
  65. package/src/core/runtime/runtime-types.ts +29 -1
  66. package/src/core/runtime/session-factory.ts +59 -62
  67. package/src/core/runtime/session-shell.ts +43 -0
  68. package/src/core/runtime/session-tool-names.ts +78 -0
  69. package/src/core/runtime/turn-selection.ts +97 -0
  70. package/src/core/shared/generate-image-tool.ts +4 -4
  71. package/src/core/shared/poll-target.ts +14 -0
  72. package/src/core/shared/workspace-files.ts +42 -4
  73. package/src/core/testing/fake-polls.ts +131 -0
  74. package/src/core/testing/fake-runner.ts +146 -0
  75. package/src/core/testing/surface-contract-approvals.ts +215 -0
  76. package/src/core/testing/surface-contract-polls.ts +142 -0
  77. package/src/core/testing/surface-contract.ts +32 -208
  78. package/src/core/tool-set.snapshot.json +8 -0
  79. package/src/index.ts +17 -0
  80. package/src/kit/index.ts +6 -0
  81. package/src/kit/polls.ts +8 -0
  82. package/src/runner-server/exec.ts +174 -0
  83. package/src/runner-server/file-helper.ts +208 -0
  84. package/src/runner-server/files.ts +93 -0
  85. package/src/runner-server/host.ts +65 -0
  86. package/src/runner-server/main.ts +89 -0
  87. package/src/runner-server/server.ts +318 -0
  88. package/src/runner-server/shared-dirs.ts +45 -0
  89. package/src/runner-server/state.ts +293 -0
  90. package/src/runner-server/transports.ts +187 -0
  91. package/src/testing.ts +7 -0
@@ -0,0 +1,108 @@
1
+ import type { PollLimits, SurfacePolls } from "../../contract/polls.ts";
2
+ import type { ChatSurface } from "../../contract/surface.ts";
3
+ import type { ChannelKey } from "../../domain/conversation.ts";
4
+ import { PollError } from "../../domain/errors.ts";
5
+
6
+ /** The host's rules for polls, within what each surface allows. */
7
+ export interface PollRules {
8
+ /** The most polls open at once in one conversation. */
9
+ maxOpen: number;
10
+ minDurationMs: number;
11
+ maxDurationMs: number;
12
+ /** How long the results of an ended poll are tried, from the first try or a restart. */
13
+ readForMs: number;
14
+ /** The first wait between tries, doubled each time up to `retryMaxMs`. */
15
+ retryFirstMs: number;
16
+ retryMaxMs: number;
17
+ /** How long a reported poll's row is kept. */
18
+ keepDays: number;
19
+ /**
20
+ * How long a poll stored but not yet posted is left to the process posting it; after that
21
+ * another process takes it for one whose process stopped, and discards it.
22
+ */
23
+ postGraceMs: number;
24
+ /**
25
+ * How long a result turn one process claimed is left to it; after that another process takes
26
+ * it for one whose process stopped, and runs it. Longer than any result turn runs.
27
+ */
28
+ reportLeaseMs: number;
29
+ }
30
+
31
+ export const POLL_RULES: PollRules = {
32
+ maxOpen: 3,
33
+ minDurationMs: 60_000,
34
+ maxDurationMs: 7 * 24 * 3_600_000,
35
+ readForMs: 3_600_000,
36
+ retryFirstMs: 60_000,
37
+ retryMaxMs: 15 * 60_000,
38
+ keepDays: 30,
39
+ postGraceMs: 2 * 60_000,
40
+ reportLeaseMs: 3 * 3_600_000,
41
+ };
42
+
43
+ /** At least two answers, as every poll needs. */
44
+ const MIN_ANSWERS = 2;
45
+
46
+ /** What `poll_create` asks for. */
47
+ export interface PollRequest {
48
+ question: string;
49
+ answers: readonly string[];
50
+ multi: boolean;
51
+ closesInMinutes: number;
52
+ }
53
+
54
+ /** A surface's polls in a channel, or why there are none. */
55
+ export function pollsOf(
56
+ surfaces: { of(channel: ChannelKey): ChatSurface | undefined },
57
+ channel: ChannelKey,
58
+ ): SurfacePolls {
59
+ const surface = surfaces.of(channel);
60
+ if (!surface)
61
+ throw new PollError(
62
+ "This conversation is on no chat surface, so there is nowhere to post a poll.",
63
+ );
64
+ if (!surface.polls)
65
+ throw new PollError(
66
+ `${surface.label ?? surface.surface} has no native polls, so a poll cannot be posted in this conversation.`,
67
+ );
68
+ return surface.polls;
69
+ }
70
+
71
+ /** The request, trimmed, within the surface's limits and the host's rules. */
72
+ export function checked(
73
+ request: PollRequest,
74
+ limits: PollLimits,
75
+ rules: PollRules,
76
+ ): PollRequest & { durationMs: number } {
77
+ const question = request.question.trim();
78
+ const answers = request.answers.map((answer) => answer.trim());
79
+ if (!question) throw new PollError("question is required.");
80
+ if (question.length > limits.questionChars)
81
+ throw new PollError(
82
+ `The question is ${question.length} characters; a poll here takes at most ${limits.questionChars}.`,
83
+ );
84
+ if (answers.length < MIN_ANSWERS || answers.length > limits.answers)
85
+ throw new PollError(
86
+ `A poll here has ${MIN_ANSWERS} to ${limits.answers} answers; ${answers.length} were given.`,
87
+ );
88
+ const long = answers.find((answer) => answer.length > limits.answerChars);
89
+ if (long !== undefined)
90
+ throw new PollError(
91
+ `The answer ${JSON.stringify(long)} is ${long.length} characters; an answer here takes at most ${limits.answerChars}.`,
92
+ );
93
+ if (answers.some((answer) => !answer))
94
+ throw new PollError("Every answer needs text.");
95
+ if (new Set(answers).size !== answers.length)
96
+ throw new PollError("Each answer must differ from the others.");
97
+ const durationMs = request.closesInMinutes * 60_000;
98
+ const longest = Math.min(rules.maxDurationMs, limits.maxDurationMs);
99
+ if (
100
+ !Number.isFinite(durationMs) ||
101
+ durationMs < rules.minDurationMs ||
102
+ durationMs > longest
103
+ )
104
+ throw new PollError(
105
+ `closes_in_minutes must be from ${Math.ceil(rules.minDurationMs / 60_000)} to ${Math.floor(longest / 60_000)}.`,
106
+ );
107
+ return { ...request, question, answers, durationMs };
108
+ }
@@ -0,0 +1,477 @@
1
+ import type {
2
+ BackgroundTurn,
3
+ ConversationPort,
4
+ ScheduledOutcome,
5
+ } from "../../contract/channels.ts";
6
+ import type { ChatSurface } from "../../contract/surface.ts";
7
+ import type { ChannelKey } from "../../domain/conversation.ts";
8
+ import { PollError } from "../../domain/errors.ts";
9
+ import type { Speaker } from "../../identity/speakers.ts";
10
+ import type { Logger } from "../../kernel/log.ts";
11
+ import { POLL_TARGET } from "../../shared/poll-target.ts";
12
+ import {
13
+ checked,
14
+ POLL_RULES,
15
+ type PollRequest,
16
+ type PollRules,
17
+ pollsOf,
18
+ } from "./poll-rules.ts";
19
+ import type {
20
+ Poll,
21
+ PollEndReason,
22
+ PollFinding,
23
+ PollStore,
24
+ } from "./poll-store.ts";
25
+ import { pollTurnText } from "./poll-turn-text.ts";
26
+
27
+ /** A timer the service arms; returns a function that cancels it. Replaceable in tests. */
28
+ export type PollTimer = (ms: number, run: () => void) => () => void;
29
+
30
+ /** The longest one timer waits; a later deadline is armed again when it fires. */
31
+ const MAX_TIMER_MS = 2_147_000_000;
32
+
33
+ const realTimer: PollTimer = (ms, run) => {
34
+ const timer = setTimeout(run, Math.min(ms, MAX_TIMER_MS));
35
+ timer.unref?.();
36
+ return () => clearTimeout(timer);
37
+ };
38
+
39
+ /** How long `stop` waits for a surface call in flight; what it leaves is picked up at the next start. */
40
+ const STOP_WAIT_MS = 10_000;
41
+
42
+ export interface PollServiceOptions {
43
+ store: PollStore;
44
+ surfaces: { of(channel: ChannelKey): ChatSurface | undefined };
45
+ conversations: Pick<
46
+ ConversationPort,
47
+ "background" | "runsAs" | "takesBackground"
48
+ >;
49
+ logger: Logger;
50
+ rules?: Partial<PollRules>;
51
+ now?: () => Date;
52
+ timer?: PollTimer;
53
+ }
54
+
55
+ function outcomeText(outcome: ScheduledOutcome): string {
56
+ switch (outcome.status) {
57
+ case "ran":
58
+ return "ran";
59
+ case "failed":
60
+ return `failed: ${outcome.error}`;
61
+ case "skipped":
62
+ return `skipped: ${outcome.reason}`;
63
+ default:
64
+ return outcome satisfies never;
65
+ }
66
+ }
67
+
68
+ const messageOf = (error: unknown) =>
69
+ error instanceof Error ? error.message : String(error);
70
+
71
+ /**
72
+ * Posts polls on the surfaces that have them, ends each at its deadline or when its starter or an
73
+ * owner asks, reads its results, and brings them back to its conversation as a turn run as the
74
+ * starter: a background turn, never a message, so it can neither confirm nor spend a held
75
+ * action's approval. Every step is stored, so a restart picks up where it was; a claim on the row
76
+ * keeps two processes from reporting one poll twice.
77
+ */
78
+ export class PollService {
79
+ readonly #options: PollServiceOptions;
80
+ readonly #rules: PollRules;
81
+ readonly #now: () => Date;
82
+ readonly #timer: PollTimer;
83
+ /** The armed deadline and retry timers, by poll id. */
84
+ readonly #armed = new Map<number, () => void>();
85
+ readonly #running = new Set<Promise<void>>();
86
+ #prune: (() => void) | undefined;
87
+ #stopped = false;
88
+
89
+ constructor(options: PollServiceOptions) {
90
+ this.#options = options;
91
+ this.#rules = { ...POLL_RULES, ...options.rules };
92
+ this.#now = options.now ?? (() => new Date());
93
+ this.#timer = options.timer ?? realTimer;
94
+ }
95
+
96
+ get rules(): PollRules {
97
+ return this.#rules;
98
+ }
99
+
100
+ /** Picks up every poll not yet reported, and prunes old ones daily. */
101
+ async start(): Promise<void> {
102
+ this.#stopped = false;
103
+ await this.#pruneOld();
104
+ const day = 24 * 3_600_000;
105
+ const daily = () => {
106
+ this.#prune = this.#timer(day, () => {
107
+ void this.#pruneOld();
108
+ daily();
109
+ });
110
+ };
111
+ daily();
112
+ for (const poll of await this.#options.store.unfinished())
113
+ await this.#pickUp(poll);
114
+ }
115
+
116
+ /**
117
+ * Takes up a poll another process may have left: arms one open and posted; leaves one being
118
+ * posted, or whose result turn runs, to its process for a while and looks again then; discards
119
+ * one never posted; and finishes or reports the rest, as a new claim.
120
+ */
121
+ async #pickUp(poll: Poll): Promise<void> {
122
+ const { store, logger } = this.#options;
123
+ const now = this.#now().getTime();
124
+ if (poll.status === "open") {
125
+ if (poll.surfacePollId) {
126
+ this.#arm(poll);
127
+ return;
128
+ }
129
+ const posting = poll.createdAt.getTime() + this.#rules.postGraceMs;
130
+ if (posting > now) {
131
+ this.#later(poll.id, posting - now);
132
+ return;
133
+ }
134
+ // Never posted: the process stopped between storing and posting it.
135
+ await store.discard(poll.id);
136
+ logger.warn({ poll: poll.id }, "poll never posted; discarded");
137
+ return;
138
+ }
139
+ const lease = this.#rules.reportLeaseMs;
140
+ if (poll.status === "ended" && poll.reportingAt) {
141
+ const held = poll.reportingAt.getTime() + lease;
142
+ if (held > now) {
143
+ this.#later(poll.id, held - now);
144
+ return;
145
+ }
146
+ }
147
+ const resumed = await store.resume(poll, new Date(now - lease));
148
+ if (!resumed) return;
149
+ this.#track(
150
+ resumed.status === "ending"
151
+ ? this.#finish(resumed, 0, new Date(now))
152
+ : this.#report(resumed),
153
+ );
154
+ }
155
+
156
+ /** Reads the poll again after `ms` and takes it up then, unless it was reported meanwhile. */
157
+ #later(id: number, ms: number): void {
158
+ this.#armed.get(id)?.();
159
+ this.#armed.set(
160
+ id,
161
+ this.#timer(ms, () => {
162
+ this.#armed.delete(id);
163
+ if (this.#stopped) return;
164
+ this.#track(
165
+ (async () => {
166
+ const poll = await this.#options.store.get(id);
167
+ if (poll && poll.status !== "reported") await this.#pickUp(poll);
168
+ })(),
169
+ );
170
+ }),
171
+ );
172
+ }
173
+
174
+ /** Starts no new work; what is stored is picked up at the next start. */
175
+ beginDrain(): void {
176
+ this.#stopped = true;
177
+ }
178
+
179
+ /** Cancels every timer and waits a little for work in flight. */
180
+ async stop(): Promise<void> {
181
+ this.#stopped = true;
182
+ this.#prune?.();
183
+ for (const cancel of this.#armed.values()) cancel();
184
+ this.#armed.clear();
185
+ let timer: ReturnType<typeof setTimeout> | undefined;
186
+ await Promise.race([
187
+ Promise.allSettled([...this.#running]),
188
+ new Promise((resolve) => {
189
+ timer = setTimeout(resolve, STOP_WAIT_MS);
190
+ }),
191
+ ]);
192
+ clearTimeout(timer);
193
+ }
194
+
195
+ /** Resolves once the work started so far has settled; for tests. */
196
+ async idle(): Promise<void> {
197
+ while (this.#running.size > 0) await Promise.allSettled([...this.#running]);
198
+ }
199
+
200
+ /** Posts a poll in the channel for the speaker; refuses with a PollError the model reads. */
201
+ async create(
202
+ channel: ChannelKey,
203
+ speaker: Speaker,
204
+ request: PollRequest,
205
+ ): Promise<Poll> {
206
+ const { store } = this.#options;
207
+ if (this.#stopped)
208
+ throw new PollError(
209
+ "The host is shutting down, so no poll can be started now; start it again once the host is back.",
210
+ );
211
+ const polls = pollsOf(this.#options.surfaces, channel);
212
+ const asked = checked(request, polls.limits, this.#rules);
213
+ const starter = {
214
+ principalId: speaker.principalId,
215
+ id: speaker.id,
216
+ name: speaker.name,
217
+ tier: speaker.tier,
218
+ };
219
+ await this.#comesBack(channel, starter);
220
+ const now = this.#now();
221
+ const closesAt = new Date(now.getTime() + asked.durationMs);
222
+ const made = await store.create(
223
+ {
224
+ channel,
225
+ starter,
226
+ question: asked.question,
227
+ answers: asked.answers,
228
+ multi: asked.multi,
229
+ closesAt,
230
+ createdAt: now,
231
+ },
232
+ this.#rules.maxOpen,
233
+ new Date(now.getTime() - this.#rules.postGraceMs),
234
+ );
235
+ if ("reached" in made)
236
+ throw new PollError(
237
+ `This conversation has ${made.reached} open polls, the most it may have; end one with poll_end first.`,
238
+ );
239
+ const poll = made.created;
240
+ let pollId: string;
241
+ try {
242
+ ({ pollId } = await polls.post(channel, {
243
+ question: poll.question,
244
+ answers: poll.answers,
245
+ multi: poll.multi,
246
+ closesAt,
247
+ }));
248
+ } catch (error) {
249
+ await store.discard(poll.id);
250
+ throw new PollError(`The poll could not be posted: ${messageOf(error)}`);
251
+ }
252
+ let kept: boolean;
253
+ try {
254
+ kept = await store.posted(poll.id, pollId);
255
+ } catch (error) {
256
+ // A poll the host cannot keep is closed again rather than left open with no one to read it.
257
+ await polls.end(channel, pollId).catch(() => undefined);
258
+ await store.discard(poll.id).catch(() => undefined);
259
+ throw error;
260
+ }
261
+ if (!kept) {
262
+ await polls.end(channel, pollId).catch(() => undefined);
263
+ throw new PollError(
264
+ "The poll was posted, but another process cleared it meanwhile, so it was closed again; start it again.",
265
+ );
266
+ }
267
+ const posted = { ...poll, surfacePollId: pollId };
268
+ this.#arm(posted);
269
+ return posted;
270
+ }
271
+
272
+ /**
273
+ * Ends the channel's open polls the speaker may end, one or all: a poll's starter, or an owner.
274
+ * Returns the polls it ended, whose results come back in a turn after the running one, and those
275
+ * open polls it left because they are someone else's.
276
+ */
277
+ async end(
278
+ channel: ChannelKey,
279
+ speaker: Speaker,
280
+ pollId?: number,
281
+ ): Promise<{ ended: Poll[]; others: Poll[] }> {
282
+ const open = await this.#options.store.openIn(channel);
283
+ const chosen =
284
+ pollId === undefined ? open : open.filter((poll) => poll.id === pollId);
285
+ if (chosen.length === 0)
286
+ throw new PollError(
287
+ pollId === undefined
288
+ ? "No poll is open in this conversation."
289
+ : `No poll #${pollId} is open in this conversation.`,
290
+ );
291
+ const own = (poll: Poll) =>
292
+ poll.starter.principalId === speaker.principalId;
293
+ const may = (poll: Poll) => own(poll) || speaker.tier === "owner";
294
+ const mayEnd = chosen.filter(may);
295
+ if (mayEnd.length === 0)
296
+ throw new PollError(
297
+ `Only the person who started a poll, or an owner, may end it: ${chosen
298
+ .map((poll) => `#${poll.id} is ${poll.starter.name}'s`)
299
+ .join(", ")}.`,
300
+ );
301
+ const ended: Poll[] = [];
302
+ for (const poll of mayEnd) {
303
+ const claimed = await this.#claim(
304
+ poll.id,
305
+ own(poll) ? "starter" : "owner",
306
+ );
307
+ if (claimed) ended.push(claimed);
308
+ }
309
+ return { ended, others: chosen.filter((poll) => !may(poll)) };
310
+ }
311
+
312
+ /** Refuses a poll whose results could not come back to the channel as the starter's turn. */
313
+ async #comesBack(
314
+ channel: ChannelKey,
315
+ starter: Poll["starter"],
316
+ ): Promise<void> {
317
+ const { conversations } = this.#options;
318
+ const refused = (why: string) =>
319
+ new PollError(
320
+ `A poll's results could not come back to this conversation: ${why}`,
321
+ );
322
+ if (!conversations.takesBackground(channel))
323
+ throw refused("it takes no turns that nobody wrote.");
324
+ let runs: Awaited<ReturnType<typeof conversations.runsAs>>;
325
+ try {
326
+ runs = await conversations.runsAs({
327
+ channel,
328
+ target: POLL_TARGET.name,
329
+ author: {
330
+ principalId: starter.principalId,
331
+ id: starter.id,
332
+ name: starter.name,
333
+ },
334
+ tier: starter.tier,
335
+ turnId: "poll-check",
336
+ text: "",
337
+ });
338
+ } catch (error) {
339
+ throw refused(
340
+ `whom it would run as could not be checked (${messageOf(error)}).`,
341
+ );
342
+ }
343
+ if ("skipped" in runs) throw refused(`${runs.skipped}.`);
344
+ }
345
+
346
+ /** The turn that brings a poll's results back: the starter's, at their tier when they started it. */
347
+ #turn(poll: Poll): BackgroundTurn {
348
+ return {
349
+ channel: poll.channel,
350
+ target: POLL_TARGET.name,
351
+ author: {
352
+ principalId: poll.starter.principalId,
353
+ id: poll.starter.id,
354
+ name: poll.starter.name,
355
+ },
356
+ tier: poll.starter.tier,
357
+ turnId: `poll-${poll.id}`,
358
+ text: pollTurnText(poll),
359
+ };
360
+ }
361
+
362
+ /** Arms the poll's deadline; one already due ends now. */
363
+ #arm(poll: Poll): void {
364
+ this.#armed.get(poll.id)?.();
365
+ const wait = poll.closesAt.getTime() - this.#now().getTime();
366
+ this.#armed.set(
367
+ poll.id,
368
+ this.#timer(Math.max(0, wait), () => {
369
+ this.#armed.delete(poll.id);
370
+ if (this.#stopped) return;
371
+ // A deadline past the longest timer is armed again.
372
+ if (poll.closesAt.getTime() > this.#now().getTime()) this.#arm(poll);
373
+ else
374
+ this.#track(this.#claim(poll.id, "deadline").then(() => undefined));
375
+ }),
376
+ );
377
+ }
378
+
379
+ /** Takes the poll from open to ending and reads it in the background; undefined when it was taken. */
380
+ async #claim(id: number, reason: PollEndReason): Promise<Poll | undefined> {
381
+ const claimed = await this.#options.store.claimEnd(id, reason, this.#now());
382
+ if (!claimed) return undefined;
383
+ this.#armed.get(id)?.();
384
+ this.#armed.delete(id);
385
+ this.#track(this.#finish(claimed, 0, claimed.endingSince ?? this.#now()));
386
+ return claimed;
387
+ }
388
+
389
+ #track(work: Promise<void>): void {
390
+ const tracked = work
391
+ .catch((error: unknown) =>
392
+ this.#options.logger.error({ err: error }, "poll work failed"),
393
+ )
394
+ .finally(() => this.#running.delete(tracked));
395
+ this.#running.add(tracked);
396
+ }
397
+
398
+ /**
399
+ * Ends the poll on its surface and reads it, trying again for `readForMs` from `since` (when
400
+ * this process took the poll, as it ended or at a restart); then stores it and reports.
401
+ */
402
+ async #finish(poll: Poll, tries: number, since: Date): Promise<void> {
403
+ if (this.#stopped) return;
404
+ const { logger, store } = this.#options;
405
+ let finding: PollFinding;
406
+ try {
407
+ const polls = pollsOf(this.#options.surfaces, poll.channel);
408
+ const id = poll.surfacePollId;
409
+ if (!id) throw new Error("the poll was never posted");
410
+ await polls.end(poll.channel, id);
411
+ const results = await polls.results(poll.channel, id);
412
+ finding =
413
+ results === "gone" ? { kind: "gone" } : { kind: "results", results };
414
+ } catch (error) {
415
+ const left =
416
+ since.getTime() + this.#rules.readForMs - this.#now().getTime();
417
+ if (left > 0) {
418
+ const wait = Math.min(
419
+ this.#rules.retryFirstMs * 2 ** tries,
420
+ this.#rules.retryMaxMs,
421
+ left,
422
+ );
423
+ logger.warn(
424
+ { poll: poll.id, err: error, retryMs: wait },
425
+ "poll results not read; trying again",
426
+ );
427
+ this.#armed.set(
428
+ poll.id,
429
+ this.#timer(wait, () => {
430
+ this.#armed.delete(poll.id);
431
+ this.#track(this.#finish(poll, tries + 1, since));
432
+ }),
433
+ );
434
+ return;
435
+ }
436
+ logger.error({ poll: poll.id, err: error }, "poll results unreadable");
437
+ finding = { kind: "unreadable", error: messageOf(error) };
438
+ }
439
+ const ended = await store.finish(poll, finding);
440
+ if (!ended) return;
441
+ await this.#report(ended);
442
+ }
443
+
444
+ /**
445
+ * Claims the result turn, runs it as the starter, and records how it went; while stopping, it is
446
+ * left for the next start. The claim keeps a process that starts meanwhile from running it too.
447
+ */
448
+ async #report(ended: Poll): Promise<void> {
449
+ if (this.#stopped) return;
450
+ const { conversations, store, logger } = this.#options;
451
+ const poll = await store.claimReport(ended, this.#now());
452
+ if (!poll) return;
453
+ const outcome = await conversations.background(this.#turn(poll));
454
+ // A turn the stopping host refused is reported by the next process instead, at once.
455
+ if (outcome.status !== "ran" && this.#stopped) {
456
+ await store.releaseReport(poll);
457
+ return;
458
+ }
459
+ if (outcome.status !== "ran")
460
+ logger.warn(
461
+ { poll: poll.id, channel: poll.channel, outcome },
462
+ "poll results not answered",
463
+ );
464
+ await store.report(poll, outcomeText(outcome));
465
+ }
466
+
467
+ async #pruneOld(): Promise<void> {
468
+ const before = new Date(
469
+ this.#now().getTime() - this.#rules.keepDays * 24 * 3_600_000,
470
+ );
471
+ try {
472
+ await this.#options.store.prune(before);
473
+ } catch (error) {
474
+ this.#options.logger.warn({ err: error }, "old polls not pruned");
475
+ }
476
+ }
477
+ }