okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ff18fbb86
main
1/** 2* Small host-owned schedules. No catch-up bursts. A task runs as the agent (a Harness session of its own) under the mode it was 3* given when it was created: `plan` (looks, changes nothing), `manual` (asks first: nobody is there to answer, so it stops at the 4* first thing that needs a yes and says what that was) or `bypass` (full access). The default is `plan`. 5*/ 6import { randomUUID } from 'node:crypto' ; 7import { lastLine } from './task-report.mjs' ; 8const frequencies = [ 'hourly' , 'daily' , 'weekdays' , 'weekly' ]; 9export const TASK_MODES = [ 'plan' , 'manual' , 'bypass' ]; 10export function validateTask ( input ) { 11const title = String ( input . title ?? '' ). trim (), prompt = String ( input . prompt ?? '' ). trim (); 12if ( ! title || title . length > 120 ) throw new Error ( 'Use a task name of 1–120 characters.' ); 13if ( ! prompt || prompt . length > 12000 ) throw new Error ( 'Use instructions of 1–12,000 characters.' ); 14if ( ! frequencies . includes ( input . frequency )) throw new Error ( 'Choose a supported schedule.' ); 15if ( ! /^ ([ 01 ] \d | 2 [ 0 - 3 ]) : [ 0 - 5 ] \d$ / . test ( input . at ?? '' )) throw new Error ( 'Choose a valid time.' ); 16const weekday = Number ( input . weekday ?? 1 ); 17if ( ! Number . isInteger ( weekday ) || weekday < 0 || weekday > 6 ) throw new Error ( 'Choose a weekday.' ); 18const timeZone = String ( input . timeZone ?? 'UTC' ); 19new Intl . DateTimeFormat ( 'en' , { timeZone}). format (); 20const mode = input . mode ?? 'plan' ; 21if ( ! TASK_MODES . includes ( mode )) throw new Error ( 'Choose what this task may do.' ); 22return { title, prompt, frequency :input . frequency , at :input . at , weekday, timeZone, mode, enabled :input . enabled !== false }; 23} 24export function nextRun ( task , after = Date . now ()) { 25const format = new Intl . DateTimeFormat ( 'en-GB' , { timeZone :task . timeZone , year :'numeric' , month :'2-digit' , day :'2-digit' , weekday :'short' , hour :'2-digit' , minute :'2-digit' , hourCycle :'h23' }); 26const previous = Object . fromEntries ( format . formatToParts ( after ). map ( v => [ v . type , v . value ])); 27const previousDate = ` ${ previous . year } - ${ previous . month } - ${ previous . day } ` ; 28const days = [ 'Sun' , 'Mon' , 'Tue' , 'Wed' , 'Thu' , 'Fri' , 'Sat' ]; 29// Search real minutes, so DST gaps are skipped and offsets remain correct. 30const start = Math . floor ( after / 60000 ) * 60000 + 60000 ; 31for ( let n = 0 ; n < 8 * 24 * 60 ; n ++ ) { 32const time = start + n * 60000 ; 33const p = Object . fromEntries ( format . formatToParts ( time ). map ( v => [ v . type , v . value ])); 34const clock = ` ${ p . hour } : ${ p . minute } ` ; 35// A daily run is once per calendar day, even when the clock repeats an hour. 36if ( task . frequency !== 'hourly' && ` ${ p . year } - ${ p . month } - ${ p . day } ` === previousDate && ` ${ previous . hour } : ${ previous . minute } ` >= task . at ) continue ; 37if ( task . frequency === 'hourly' ?p . minute !== '00' :clock !== task . at ) continue ; 38if ( task . frequency === 'weekdays' && [ 'Sat' , 'Sun' ]. includes ( p . weekday )) continue ; 39if ( task . frequency === 'weekly' && p . weekday !== days [ task . weekday ]) continue ; 40return new Date ( time ). toISOString (); 41} 42throw new Error ( 'Could not calculate the next run.' ); 43} 44export function createTaskService ({ read, write, run, notify= () => {}, now= Date . now , timeoutMs= 15 * 60_000 }) { 45let records = read (). map ( t => ({ ...t , status :t . status === 'running' ?'interrupted' :t . status , nextRunAt :t . enabled && ! t . archived ?nextRun ( t , now ()) :null })); 46const controllers = new Map (); 47const save = () => write ( records ); 48if ( records . length ) save (); 49const list = () => records ; 50function find ( id ) { const t = records . find ( t => t . id === id ); if ( ! t ) throw new Error ( 'Task not found.' ); return t ; } 51function put ( input , id ) { 52const old = id ?find ( id ) :null ; 53if ( old ?. status === 'running' ) throw new Error ( 'Stop the current run before editing.' ); 54const fields = validateTask ({ ...old , ...input }); 55const task = { ...old , ...fields , id :old ?. id ?? randomUUID (), createdAt :old ?. createdAt ?? new Date ( now ()). toISOString (), status :old ?. status ?? 'idle' , archived :input . archived ?? old ?. archived ?? false }; 56// "I have seen this": the board hides a finished or failed run the person dismissed. It is only a mark; the result stays in the task. 57if ( 'ackedAt' in input ) task . ackedAt = input . ackedAt ?String ( input . ackedAt ) :null ; 58task . nextRunAt = task . enabled && ! task . archived ?nextRun ( task , now ()) :null ; 59records = old ?records . map ( t => t . id === id ?task :t ) :[ ...records , task ]; save (); return task ; 60} 61async function execute ( id ) { 62const t = find ( id ); if ( t . status === 'running' ) return ; 63if ( t . archived ) throw new Error ( 'Restore this task first.' ); 64const controller = new AbortController (); controllers . set ( id , controller ); 65// A new run replaces the last one's problem (error and the note that something needed a yes) and its dismissal, so the board only ever shows the newest. 66t . status = 'running' ; t . lastRunAt = new Date ( now ()). toISOString (); t . error = null ; t . attention = null ; t . ackedAt = null ; t . lastLine = null ; t . finishedAt = null ; t . files = []; 67t . nextRunAt = t . enabled ?nextRun ( t , now ()) :null ; save (); 68const timeout = setTimeout (() => controller . abort (), timeoutMs ); timeout . unref ?.(); 69try { const result = await run ( t , controller . signal ); t . output = result . text . slice ( 0 , 100000 ); t . demo = result . demo ; t . attention = result . attention ?? null ; t . lastLine = lastLine ( result . text ); t . files = Array . isArray ( result . files ) ?result . files . slice ( 0 , 30 ) :[]; t . status = 'done' ; } 70catch ( e ) { t . status = controller . signal . aborted ?'cancelled' :'error' ; t . error = controller . signal . aborted ?'Run stopped.' :String ( e . message ?? e ); } 71finally { t . finishedAt = new Date ( now ()). toISOString (); clearTimeout ( timeout ); controllers . delete ( id ); save (); try { notify ( t ); } catch { /* a notification is a courtesy */ } } 72} 73function tick () { for ( const t of records ) if ( t . enabled && ! t . archived && t . status !== 'running' && t . nextRunAt && Date . parse ( t . nextRunAt ) <= now ()) void execute ( t . id ); } 74return { list, put, execute, tick, stop :id => controllers . get ( id )?. abort (), close :() => controllers . forEach ( c => c . abort ()) }; 75}