ShtukbaseStandard
package file→ .shtukbase/packages/schedule/actions/tick.ts

actions/tick.ts

140 lines, 8.0 KB.

  1. // `shtuk run schedule tick [--now ISO] [--dry-run]`: one tick of the schedule. Finds the automations with a schedule
  2. // trigger and `mode: auto` that are due by the run journal, keeps their limits (perHour, perDay) and launches the
  3. // reaction: an agent through its harness package, or an action (a program, or an agent action). Every launch is a
  4. // run page in the journal; the run carries `slot`, the scheduled instant it serves, so a second tick at the same
  5. // time launches nothing. Exit 1 when a launch failed.
  6. import { spawnSync } from 'node:child_process';
  7. import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
  8. import { extname, join } from 'node:path';
  9. import { readPage } from '../../collections/checks/lib/pages.ts';
  10. import { Project, type Rec, count, findFile, map, normPath, recordsOf, text, time } from '../../agents/lib/factlib.ts';
  11. import { args, create, now, slug, update } from '../../agents/lib/write.ts';
  12. import { harnessOf, harnessPkg, runsFolder } from '../../harness/lib/harness.ts';
  13. import { due, iso, runsOf, schedOf } from '../lib/schedule.ts';
  14. const AGENT_KINDS = ['agent', 'assistant', 'specialist', 'harness'];
  15. const PROGRAM_KINDS = ['program', 'cloud'];
  16. const a = args(process.argv.slice(2));
  17. const root = process.cwd();
  18. const nowMs = typeof a.now === 'string' ? time(a.now) : Date.now();
  19. if (nowMs === null) {
  20. console.error(`--now: "${a.now}" is not an ISO time (2026-11-29T07:00:00Z)`);
  21. process.exit(2);
  22. }
  23. const dry = !!a['dry-run'];
  24. const p = new Project(root);
  25. /** A run page for a launch that did not start (no harness, unknown action kind): failed at once, with the reason. */
  26. function refused(auto: Rec, slot: number, what: Record<string, string | undefined>, why: string): void {
  27. const t = now();
  28. create(root, runsFolder(root), `${t.slice(0, 10)}-${t.slice(11, 19).replaceAll(':', '')}-${slug(text(auto.fm.title) || auto.file)}`, {
  29. type: 'Run', title: text(auto.fm.title) || auto.file, automation: auto.id, ...what, woke: 'clock', slot: iso(slot),
  30. started: t, status: 'failed', ended: t, message: why,
  31. }, '');
  32. }
  33. /** An agent through its harness package; the package writes the run. */
  34. function viaHarness(auto: Rec, slot: number, agent: string, prompt: string, action?: string): number {
  35. const file = join(root, agent.replace(/^\/+/, ''));
  36. if (!existsSync(file)) return (refused(auto, slot, { action }, `agent ${agent} does not exist`), 1);
  37. const h = harnessOf(readPage(file).fm);
  38. const hp = harnessPkg(root, h);
  39. if (!hp.installed) return (refused(auto, slot, { agent, action }, `harness "${h || '—'}": the package ${hp.pkg} is not in the project`), 1);
  40. const argv = [join(hp.dir, 'actions', 'ask.ts'), '--agent', agent, '--automation', auto.id, '--woke', 'clock', '--slot', iso(slot),
  41. '--title', text(auto.fm.title) || auto.file, ...(action ? ['--action', action] : []), ...(prompt ? ['--prompt', prompt] : [])];
  42. const r = spawnSync(process.execPath, argv, { cwd: root, stdio: 'inherit' });
  43. return r.status ?? 1;
  44. }
  45. /** A program action: its script (by extension) or its command in a shell, from the project root, with a log. */
  46. function program(auto: Rec, slot: number, act: Rec): number {
  47. const path = text(act.fm.path);
  48. const script = path ? findFile(p, path) : null;
  49. if (path && !script) return (refused(auto, slot, { action: act.id }, `script ${path} does not exist`), 1);
  50. const cmd: [string, string[]] = script
  51. ? (['.ts', '.js', '.mjs'].includes(extname(script)) ? [process.execPath, [script]] : extname(script) === '.py' ? ['python3', [script]] : extname(script) === '.sh' ? ['sh', [script]] : [script, []])
  52. : ['sh', ['-c', text(act.fm.command)]];
  53. const minutes = count(act.fm.timeLimit) ?? 10;
  54. const t = now();
  55. const title = text(auto.fm.title) || auto.file;
  56. const coll = runsFolder(root);
  57. const page = create(root, coll, `${t.slice(0, 10)}-${t.slice(11, 19).replaceAll(':', '')}-${slug(title)}`, {
  58. type: 'Run', title, action: act.id, automation: auto.id, woke: 'clock', slot: iso(slot), started: t, status: 'running',
  59. }, '');
  60. const t0 = Date.now();
  61. const r = spawnSync(cmd[0], cmd[1], { cwd: root, encoding: 'utf8', timeout: minutes * 60_000, maxBuffer: 64 * 1024 * 1024, env: { ...process.env, SHTUK_PROJECT: root } });
  62. const seconds = Math.round((Date.now() - t0) / 100) / 10;
  63. const timedOut = (r.error as NodeJS.ErrnoException | undefined)?.code === 'ETIMEDOUT';
  64. const code = timedOut ? 124 : r.status ?? 1;
  65. const log = `${coll.replace(/\/+$/, '')}/logs/${page.split('/').pop()!.replace(/\.md$/, '')}.log`;
  66. mkdirSync(join(root, coll.replace(/^\/+/, ''), 'logs'), { recursive: true });
  67. writeFileSync(join(root, log.replace(/^\/+/, '')), [`# ${title}`, `command: ${[cmd[0], ...cmd[1]].join(' ')}`, `exit: ${code}`, `seconds: ${seconds}`, '', '## stdout', r.stdout ?? '', '', '## stderr', (r.stderr ?? '') + (r.error && !timedOut ? r.error.message : ''), ''].join('\n'));
  68. const ok = code === 0;
  69. update(join(root, page.replace(/^\/+/, '')), {
  70. status: ok ? 'done' : 'failed', ended: now(), seconds,
  71. evidence: ok ? [log] : undefined,
  72. message: ok ? undefined : timedOut ? `did not finish in ${minutes} min` : `exit code ${code}`,
  73. });
  74. console.log(`run: ${page} (${ok ? 'done' : 'failed'}, ${seconds} s)`);
  75. return ok ? 0 : 1;
  76. }
  77. /** Launches the reaction of an automation. */
  78. function launch(auto: Rec, slot: number): number {
  79. const re = map(auto.fm.reaction) ?? {};
  80. const prompt = text(re.prompt) || auto.body.trim();
  81. if (text(re.agent)) return viaHarness(auto, slot, normPath(re.agent, null, auto.id)!, prompt);
  82. const actPath = normPath(re.action, null, auto.id);
  83. if (!actPath || !existsSync(join(root, actPath.replace(/^\/+/, '')))) return (refused(auto, slot, {}, `action ${text(re.action) || '—'} does not exist`), 1);
  84. const fm = readPage(join(root, actPath.replace(/^\/+/, ''))).fm;
  85. const act: Rec = recordsOf(p, 'FACTION').find((r) => r.id === actPath) ?? { id: actPath, kind: 'Action', fm, body: '', title: '', file: '' };
  86. const kind = text(act.fm.kind);
  87. if (PROGRAM_KINDS.includes(kind)) return program(auto, slot, act);
  88. if (AGENT_KINDS.includes(kind)) {
  89. const agent = normPath(act.fm.agent, null, act.id);
  90. if (!agent) return (refused(auto, slot, { action: act.id }, 'the agent action has no agent field'), 1);
  91. return viaHarness(auto, slot, agent, text(re.prompt) || text(act.fm.prompt) || act.body.trim() || auto.body.trim(), act.id);
  92. }
  93. return (refused(auto, slot, { action: act.id }, `the tick does not run an action of kind "${kind || '—'}" (it can run: ${[...PROGRAM_KINDS, ...AGENT_KINDS].join(', ')})`), 1);
  94. }
  95. let launched = 0, failed = 0;
  96. console.log(`tick ${iso(nowMs)}${dry ? ' (dry run)' : ''}`);
  97. for (const auto of recordsOf(p, 'AUTOMATION')) {
  98. const s = schedOf(auto.fm.trigger);
  99. if (s === null) continue;
  100. const name = auto.id.replace(/^\//, '');
  101. if (typeof s === 'string') {
  102. console.log(` ${name}: the schedule is not read — ${s}`);
  103. continue;
  104. }
  105. if (text(auto.fm.mode) !== 'auto') {
  106. console.log(` ${name}: mode: ${text(auto.fm.mode) || '—'} — the tick runs only mode: auto`);
  107. continue;
  108. }
  109. const runs = runsOf(p, auto);
  110. const d = due(s, runs, nowMs);
  111. if (!d.due) {
  112. console.log(` ${name}: ${d.why}`);
  113. continue;
  114. }
  115. const l = map(auto.fm.limits) ?? {};
  116. const hour = count(l.perHour), day = count(l.perDay);
  117. const inHour = runs.filter((r) => r.at > nowMs - 3_600_000 && r.at <= nowMs).length;
  118. const inDay = runs.filter((r) => r.at > nowMs - 86_400_000 && r.at <= nowMs).length;
  119. if (hour === null && day === null) {
  120. console.log(` ${name}: it is time, but there is no limit (limits.perHour or perDay) — not running`);
  121. continue;
  122. }
  123. if ((hour !== null && inHour >= hour) || (day !== null && inDay >= day)) {
  124. console.log(` ${name}: it is time, but the limit is used up (in an hour ${inHour}/${hour ?? '∞'}, in a day ${inDay}/${day ?? '∞'})`);
  125. continue;
  126. }
  127. console.log(` ${name}: ${d.why} — ${dry ? 'would run' : 'running'} (${s.source})`);
  128. if (dry) continue;
  129. launched++;
  130. if (launch(auto, d.slot) !== 0) failed++;
  131. }
  132. console.log(`launched: ${launched}${failed ? `, failed: ${failed}` : ''}`);
  133. process.exit(failed ? 1 : 0);