okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
dca9770ef
main
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). */ 14send ( 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). */ 16note ( sessionId :string , text :string ) :void ; 17/** False when the chat was deleted: the loop ends quietly. */ 18exists ( sessionId :string ) :boolean ; 19/** True when this chat is open and nothing is being answered. */ 20ready ( sessionId :string ) :boolean ; 21now () :number ; 22setTimer ( fn :() => void , ms :number ) :unknown ; 23clearTimer ( 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. */ 25track ?( sessionId :string , record :LoopRecord ) :void ; 26} 27 28export interface LoopStart extends LoopLimits { everyMs :number ; prompt :string } 29 30interface LoopState extends LoopStart { 31answers :number ; 32failures :number ; 33startedAt :number ; 34timer :unknown ; 35running :boolean ; 36lastText ?:string ; 37nextAt ?:number ; 38} 39 40export class LoopScheduler { 41private readonly loops = new Map < string , LoopState >(); 42/** How long to wait before looking again when the chat is busy or not open. */ 43busyRetryMs = 15_000 ; 44 45constructor ( private readonly host :LoopHost ) {} 46 47isRunning ( sessionId :string | null ) :boolean { return !! sessionId && this . loops . has ( sessionId ); } 48 49/** The chats that have a loop going. */ 50ids () :string [] { return [ ...this . loops . keys ()]; } 51 52private record ( sessionId :string , loop :LoopState , endedWhy ?:NonNullable < LoopRecord [ 'endedWhy' ]>) { 53const 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 } :{}) }; 54if ( endedWhy ) { record . endedAt = this . host . now (); record . endedWhy = endedWhy ; } else if ( loop . nextAt !== undefined ) record . nextAt = loop . nextAt ; 55try { 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. */ 59describe ( sessionId :string ) :string | null { 60const loop = this . loops . get ( sessionId ); 61if ( ! loop ) return null ; 62const limit = loopLimitNote ( loop ); 63return 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). */ 67stop ( sessionId :string ) :boolean { return this . end ( sessionId , 'stopped' ); } 68 69private end ( sessionId :string , why :NonNullable < LoopRecord [ 'endedWhy' ]>) :boolean { 70const loop = this . loops . get ( sessionId ); 71if ( ! loop ) return false ; 72if ( loop . timer ) this . host . clearTimer ( loop . timer ); 73this . loops . delete ( sessionId ); 74this . record ( sessionId , loop , why ); 75return 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. */ 79async start ( sessionId :string , command :LoopStart ) :Promise < boolean > { 80if ( 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 ; } 81const loop :LoopState = { ...command , answers :0 , failures :0 , startedAt :this . host . now (), timer :null , running :false }; 82this . loops . set ( sessionId , loop ); 83this . record ( sessionId , loop ); 84const limit = loopLimitNote ( loop ); 85this . 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 :'' )); 86await this . run ( sessionId ); 87return true ; 88} 89 90/** Send once, judge the answer, then either end the loop with a plain note or wait for the next time. */ 91private async run ( sessionId :string ) :Promise < void > { 92const loop = this . loops . get ( sessionId ); 93if ( ! loop || loop . running ) return ; 94loop . running = true ; 95let why :LoopStop | null = null ; 96try { 97const 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. 99if ( this . loops . get ( sessionId ) !== loop ) return ; 100if ( result . answered ) { 101loop . lastText = String ( result . text ?? '' ). replace ( / \s+ / g , ' ' ). trim (). slice ( 0 , 200 ); 102if ( result . failed ) loop . failures += 1 ; else { loop . failures = 0 ; loop . answers += 1 ; } 103why = judgeAnswer ( loop , loop , result , this . host . now ()); 104} 105} catch { 106if ( this . loops . get ( sessionId ) !== loop ) return ; 107loop . failures += 1 ; 108if ( loop . failures >= LOOP_MAX_FAILURES ) why = 'failures' ; 109} finally { 110loop . running = false ; 111} 112if ( why ) { this . finish ( sessionId , loop , why ); return ; } 113this . schedule ( sessionId , loop . everyMs ); 114} 115 116private finish ( sessionId :string , loop :LoopState , why :LoopStop ) { 117this . end ( sessionId , why ); 118this . host . note ( sessionId , loopEndNote ( why , loop . answers )); 119} 120 121private schedule ( sessionId :string , ms :number ) { 122const loop = this . loops . get ( sessionId ); 123if ( ! loop ) return ; 124loop . nextAt = this . host . now () + ms ; 125this . record ( sessionId , loop ); 126loop . timer = this . host . setTimer (() => void this . tick ( sessionId ), ms ); 127} 128 129private async tick ( sessionId :string ) :Promise < void > { 130const loop = this . loops . get ( sessionId ); 131if ( ! loop ) return ; 132loop . timer = null ; 133if ( ! 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). 135if ( loop . maxMs !== undefined && this . host . now () - loop . startedAt >= loop . maxMs ) { this . finish ( sessionId , loop , 'time' ); return ; } 136if ( loop . maxRuns !== undefined && loop . answers >= loop . maxRuns ) { this . finish ( sessionId , loop , 'count' ); return ; } 137if ( 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. 139if ( ! this . host . ready ( sessionId )) { this . schedule ( sessionId , this . busyRetryMs ); return ; } 140await this . run ( sessionId ); 141} 142}