包文件→ .shtukbase/packages/schedule/actions/tick.ts
actions/tick.ts
140 行, 8.0 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // `shtuk run schedule tick [--now ISO] [--dry-run]`: one tick of the schedule. Finds the automations with a schedule
- // trigger and `mode: auto` that are due by the run journal, keeps their limits (perHour, perDay) and launches the
- // reaction: an agent through its harness package, or an action (a program, or an agent action). Every launch is a
- // run page in the journal; the run carries `slot`, the scheduled instant it serves, so a second tick at the same
- // time launches nothing. Exit 1 when a launch failed.
- import { spawnSync } from 'node:child_process';
- import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
- import { extname, join } from 'node:path';
- import { readPage } from '../../collections/checks/lib/pages.ts';
- import { Project, type Rec, count, findFile, map, normPath, recordsOf, text, time } from '../../agents/lib/factlib.ts';
- import { args, create, now, slug, update } from '../../agents/lib/write.ts';
- import { harnessOf, harnessPkg, runsFolder } from '../../harness/lib/harness.ts';
- import { due, iso, runsOf, schedOf } from '../lib/schedule.ts';
- const AGENT_KINDS = ['agent', 'assistant', 'specialist', 'harness'];
- const PROGRAM_KINDS = ['program', 'cloud'];
- const a = args(process.argv.slice(2));
- const root = process.cwd();
- const nowMs = typeof a.now === 'string' ? time(a.now) : Date.now();
- if (nowMs === null) {
- console.error(`--now: "${a.now}" is not an ISO time (2026-11-29T07:00:00Z)`);
- process.exit(2);
- }
- const dry = !!a['dry-run'];
- const p = new Project(root);
- /** A run page for a launch that did not start (no harness, unknown action kind): failed at once, with the reason. */
- function refused(auto: Rec, slot: number, what: Record<string, string | undefined>, why: string): void {
- const t = now();
- create(root, runsFolder(root), `${t.slice(0, 10)}-${t.slice(11, 19).replaceAll(':', '')}-${slug(text(auto.fm.title) || auto.file)}`, {
- type: 'Run', title: text(auto.fm.title) || auto.file, automation: auto.id, ...what, woke: 'clock', slot: iso(slot),
- started: t, status: 'failed', ended: t, message: why,
- }, '');
- }
- /** An agent through its harness package; the package writes the run. */
- function viaHarness(auto: Rec, slot: number, agent: string, prompt: string, action?: string): number {
- const file = join(root, agent.replace(/^\/+/, ''));
- if (!existsSync(file)) return (refused(auto, slot, { action }, `agent ${agent} does not exist`), 1);
- const h = harnessOf(readPage(file).fm);
- const hp = harnessPkg(root, h);
- if (!hp.installed) return (refused(auto, slot, { agent, action }, `harness "${h || '—'}": the package ${hp.pkg} is not in the project`), 1);
- const argv = [join(hp.dir, 'actions', 'ask.ts'), '--agent', agent, '--automation', auto.id, '--woke', 'clock', '--slot', iso(slot),
- '--title', text(auto.fm.title) || auto.file, ...(action ? ['--action', action] : []), ...(prompt ? ['--prompt', prompt] : [])];
- const r = spawnSync(process.execPath, argv, { cwd: root, stdio: 'inherit' });
- return r.status ?? 1;
- }
- /** A program action: its script (by extension) or its command in a shell, from the project root, with a log. */
- function program(auto: Rec, slot: number, act: Rec): number {
- const path = text(act.fm.path);
- const script = path ? findFile(p, path) : null;
- if (path && !script) return (refused(auto, slot, { action: act.id }, `script ${path} does not exist`), 1);
- const cmd: [string, string[]] = script
- ? (['.ts', '.js', '.mjs'].includes(extname(script)) ? [process.execPath, [script]] : extname(script) === '.py' ? ['python3', [script]] : extname(script) === '.sh' ? ['sh', [script]] : [script, []])
- : ['sh', ['-c', text(act.fm.command)]];
- const minutes = count(act.fm.timeLimit) ?? 10;
- const t = now();
- const title = text(auto.fm.title) || auto.file;
- const coll = runsFolder(root);
- const page = create(root, coll, `${t.slice(0, 10)}-${t.slice(11, 19).replaceAll(':', '')}-${slug(title)}`, {
- type: 'Run', title, action: act.id, automation: auto.id, woke: 'clock', slot: iso(slot), started: t, status: 'running',
- }, '');
- const t0 = Date.now();
- 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 } });
- const seconds = Math.round((Date.now() - t0) / 100) / 10;
- const timedOut = (r.error as NodeJS.ErrnoException | undefined)?.code === 'ETIMEDOUT';
- const code = timedOut ? 124 : r.status ?? 1;
- const log = `${coll.replace(/\/+$/, '')}/logs/${page.split('/').pop()!.replace(/\.md$/, '')}.log`;
- mkdirSync(join(root, coll.replace(/^\/+/, ''), 'logs'), { recursive: true });
- 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'));
- const ok = code === 0;
- update(join(root, page.replace(/^\/+/, '')), {
- status: ok ? 'done' : 'failed', ended: now(), seconds,
- evidence: ok ? [log] : undefined,
- message: ok ? undefined : timedOut ? `did not finish in ${minutes} min` : `exit code ${code}`,
- });
- console.log(`run: ${page} (${ok ? 'done' : 'failed'}, ${seconds} s)`);
- return ok ? 0 : 1;
- }
- /** Launches the reaction of an automation. */
- function launch(auto: Rec, slot: number): number {
- const re = map(auto.fm.reaction) ?? {};
- const prompt = text(re.prompt) || auto.body.trim();
- if (text(re.agent)) return viaHarness(auto, slot, normPath(re.agent, null, auto.id)!, prompt);
- const actPath = normPath(re.action, null, auto.id);
- if (!actPath || !existsSync(join(root, actPath.replace(/^\/+/, '')))) return (refused(auto, slot, {}, `action ${text(re.action) || '—'} does not exist`), 1);
- const fm = readPage(join(root, actPath.replace(/^\/+/, ''))).fm;
- const act: Rec = recordsOf(p, 'FACTION').find((r) => r.id === actPath) ?? { id: actPath, kind: 'Action', fm, body: '', title: '', file: '' };
- const kind = text(act.fm.kind);
- if (PROGRAM_KINDS.includes(kind)) return program(auto, slot, act);
- if (AGENT_KINDS.includes(kind)) {
- const agent = normPath(act.fm.agent, null, act.id);
- if (!agent) return (refused(auto, slot, { action: act.id }, 'the agent action has no agent field'), 1);
- return viaHarness(auto, slot, agent, text(re.prompt) || text(act.fm.prompt) || act.body.trim() || auto.body.trim(), act.id);
- }
- 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);
- }
- let launched = 0, failed = 0;
- console.log(`tick ${iso(nowMs)}${dry ? ' (dry run)' : ''}`);
- for (const auto of recordsOf(p, 'AUTOMATION')) {
- const s = schedOf(auto.fm.trigger);
- if (s === null) continue;
- const name = auto.id.replace(/^\//, '');
- if (typeof s === 'string') {
- console.log(` ${name}: the schedule is not read — ${s}`);
- continue;
- }
- if (text(auto.fm.mode) !== 'auto') {
- console.log(` ${name}: mode: ${text(auto.fm.mode) || '—'} — the tick runs only mode: auto`);
- continue;
- }
- const runs = runsOf(p, auto);
- const d = due(s, runs, nowMs);
- if (!d.due) {
- console.log(` ${name}: ${d.why}`);
- continue;
- }
- const l = map(auto.fm.limits) ?? {};
- const hour = count(l.perHour), day = count(l.perDay);
- const inHour = runs.filter((r) => r.at > nowMs - 3_600_000 && r.at <= nowMs).length;
- const inDay = runs.filter((r) => r.at > nowMs - 86_400_000 && r.at <= nowMs).length;
- if (hour === null && day === null) {
- console.log(` ${name}: it is time, but there is no limit (limits.perHour or perDay) — not running`);
- continue;
- }
- if ((hour !== null && inHour >= hour) || (day !== null && inDay >= day)) {
- console.log(` ${name}: it is time, but the limit is used up (in an hour ${inHour}/${hour ?? '∞'}, in a day ${inDay}/${day ?? '∞'})`);
- continue;
- }
- console.log(` ${name}: ${d.why} — ${dry ? 'would run' : 'running'} (${s.source})`);
- if (dry) continue;
- launched++;
- if (launch(auto, d.slot) !== 0) failed++;
- }
- console.log(`launched: ${launched}${failed ? `, failed: ${failed}` : ''}`);
- process.exit(failed ? 1 : 0);