okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Task board: Schedule | Board view on Tasks, derivation with tests, loop record, sidebar count, all 8 localesdca9770ef

main
7.2 KiB142 linesraw
1import { tr } from './i18n';
2import type { LoopRecord } from './types';
3import { LOOP_MAX_FAILURES, LOOP_MAX_RUNS, judgeAnswer, loopEndNote, loopEvery, loopLimitNote, withStopRule, type LoopLimits, type LoopStop } from './loop';
4
5/**
6 * The /loop scheduler. It owns the timer, the count, the time limit and the "the answer says it is done" rule, so a stop condition
7 * is enforced here, in the app, and never left to the model: once a loop has ended nothing is sent again.
8 *
9 * Everything outside (sending the message, reading the answer, adding a line to the chat, the clock) is passed in, so the same code
10 * runs in the app (store.ts) and in the tests with a scripted model and a fake clock.
11 */
12export interface LoopHost {
13  /** Send the message as an ordinary chat turn and resolve when the answer is complete. `answered` is false when nothing was sent (the chat was busy). */
14  send(sessionId: string, message: { text: string; shown: string }): Promise<{ answered: boolean; text: string; failed: boolean }>;
15  /** A line from the app itself in the chat (never sent to the model). */
16  note(sessionId: string, text: string): void;
17  /** False when the chat was deleted: the loop ends quietly. */
18  exists(sessionId: string): boolean;
19  /** True when this chat is open and nothing is being answered. */
20  ready(sessionId: string): boolean;
21  now(): number;
22  setTimer(fn: () => void, ms: number): unknown;
23  clearTimer(handle: unknown): void;
24  /** Keep a small record of the loop on the chat (running, or how it ended) so the task board can show it. Optional: the tests do not need it. */
25  track?(sessionId: string, record: LoopRecord): void;
26}
27
28export interface LoopStart extends LoopLimits { everyMs: number; prompt: string }
29
30interface LoopState extends LoopStart {
31  answers: number;
32  failures: number;
33  startedAt: number;
34  timer: unknown;
35  running: boolean;
36  lastText?: string;
37  nextAt?: number;
38}
39
40export class LoopScheduler {
41  private readonly loops = new Map<string, LoopState>();
42  /** How long to wait before looking again when the chat is busy or not open. */
43  busyRetryMs = 15_000;
44
45  constructor(private readonly host: LoopHost) {}
46
47  isRunning(sessionId: string | null): boolean { return !!sessionId && this.loops.has(sessionId); }
48
49  /** The chats that have a loop going. */
50  ids(): string[] { return [...this.loops.keys()]; }
51
52  private record(sessionId: string, loop: LoopState, endedWhy?: NonNullable<LoopRecord['endedWhy']>) {
53    const record: LoopRecord = { prompt: loop.prompt, everyMs: loop.everyMs, startedAt: loop.startedAt, state: endedWhy ? 'ended' : 'running', answers: loop.answers, ...(loop.maxRuns !== undefined ? { maxRuns: loop.maxRuns } : {}), ...(loop.lastText ? { lastText: loop.lastText } : {}) };
54    if (endedWhy) { record.endedAt = this.host.now(); record.endedWhy = endedWhy; } else if (loop.nextAt !== undefined) record.nextAt = loop.nextAt;
55    try { this.host.track?.(sessionId, record); } catch { /* the record is a courtesy to the board */ }
56  }
57
58  /** What the person is told for /loop with nothing after it. */
59  describe(sessionId: string): string | null {
60    const loop = this.loops.get(sessionId);
61    if (!loop) return null;
62    const limit = loopLimitNote(loop);
63    return tr('A loop is running in this chat: it sends "{0}" {1}, while this chat is open. Type /loop stop to stop it.', [loop.prompt, loopEvery(loop.everyMs)]) + (limit ? ' ' + limit : '');
64  }
65
66  /** The person stopped it (/loop stop or the board's Stop loop). */
67  stop(sessionId: string): boolean { return this.end(sessionId, 'stopped'); }
68
69  private end(sessionId: string, why: NonNullable<LoopRecord['endedWhy']>): boolean {
70    const loop = this.loops.get(sessionId);
71    if (!loop) return false;
72    if (loop.timer) this.host.clearTimer(loop.timer);
73    this.loops.delete(sessionId);
74    this.record(sessionId, loop, why);
75    return true;
76  }
77
78  /** Start a loop and send its first message now. Returns false (and says why in the chat) when the chat already has one. */
79  async start(sessionId: string, command: LoopStart): Promise<boolean> {
80    if (this.loops.has(sessionId)) { this.host.note(sessionId, tr('This chat already has a loop. Type /loop stop first, then start a new one.')); return false; }
81    const loop: LoopState = { ...command, answers: 0, failures: 0, startedAt: this.host.now(), timer: null, running: false };
82    this.loops.set(sessionId, loop);
83    this.record(sessionId, loop);
84    const limit = loopLimitNote(loop);
85    this.host.note(sessionId, tr('Loop started: "{0}" {1}, while this chat is open. Type /loop stop to stop it. For work that must go on with Strata closed, use the Tasks screen.', [loop.prompt, loopEvery(loop.everyMs)]) + (limit ? ' ' + limit : ''));
86    await this.run(sessionId);
87    return true;
88  }
89
90  /** Send once, judge the answer, then either end the loop with a plain note or wait for the next time. */
91  private async run(sessionId: string): Promise<void> {
92    const loop = this.loops.get(sessionId);
93    if (!loop || loop.running) return;
94    loop.running = true;
95    let why: LoopStop | null = null;
96    try {
97      const result = await this.host.send(sessionId, { text: withStopRule(loop.prompt, loop.stopWhen), shown: loop.prompt });
98      // The person may have typed /loop stop while the answer was coming: nothing more happens then.
99      if (this.loops.get(sessionId) !== loop) return;
100      if (result.answered) {
101        loop.lastText = String(result.text ?? '').replace(/\s+/g, ' ').trim().slice(0, 200);
102        if (result.failed) loop.failures += 1; else { loop.failures = 0; loop.answers += 1; }
103        why = judgeAnswer(loop, loop, result, this.host.now());
104      }
105    } catch {
106      if (this.loops.get(sessionId) !== loop) return;
107      loop.failures += 1;
108      if (loop.failures >= LOOP_MAX_FAILURES) why = 'failures';
109    } finally {
110      loop.running = false;
111    }
112    if (why) { this.finish(sessionId, loop, why); return; }
113    this.schedule(sessionId, loop.everyMs);
114  }
115
116  private finish(sessionId: string, loop: LoopState, why: LoopStop) {
117    this.end(sessionId, why);
118    this.host.note(sessionId, loopEndNote(why, loop.answers));
119  }
120
121  private schedule(sessionId: string, ms: number) {
122    const loop = this.loops.get(sessionId);
123    if (!loop) return;
124    loop.nextAt = this.host.now() + ms;
125    this.record(sessionId, loop);
126    loop.timer = this.host.setTimer(() => void this.tick(sessionId), ms);
127  }
128
129  private async tick(sessionId: string): Promise<void> {
130    const loop = this.loops.get(sessionId);
131    if (!loop) return;
132    loop.timer = null;
133    if (!this.host.exists(sessionId)) { this.end(sessionId, 'stopped'); return; }
134    // The time is up, or the count is reached: never fire again, even if the last answer was not judged (a busy chat).
135    if (loop.maxMs !== undefined && this.host.now() - loop.startedAt >= loop.maxMs) { this.finish(sessionId, loop, 'time'); return; }
136    if (loop.maxRuns !== undefined && loop.answers >= loop.maxRuns) { this.finish(sessionId, loop, 'count'); return; }
137    if (loop.answers >= LOOP_MAX_RUNS) { this.finish(sessionId, loop, 'cap'); return; }
138    // Wait for a quiet moment: this chat is open and nothing is being answered.
139    if (!this.host.ready(sessionId)) { this.schedule(sessionId, this.busyRetryMs); return; }
140    await this.run(sessionId);
141  }
142}