@popcorn245/cornfield 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/core/config.js +17 -4
- package/explorer/forge-panel.js +20 -2
- package/explorer/index.html +2 -0
- package/explorer/runs-model.js +28 -0
- package/package.json +1 -1
- package/server/agent-runs.js +4 -2
- package/server/hooks.js +4 -0
- package/server/runner-presence.js +96 -0
- package/server/server.js +8 -2
package/core/config.js
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* },
|
|
14
14
|
* forge: { type: 'github', url: 'https://github.com', repo: 'owner/name' }, // or type 'forgejo'; mergeMethod: 'merge' | 'squash' | 'rebase'; baseBranch: 'main'
|
|
15
15
|
* deploys: { workflows: ['*deploy*'], restarts: { 'Deploy web': ['stack-web'] } }, // which workflow runs are deploys, and what they restart (docs/deploys.md)
|
|
16
|
-
* agents: { authors: [], labels: [], branchPrefixes: [], bots: true }, // what marks work as made by an agent (docs/agents.md); and how runs are asked for and followed: transport, maxOpen, profiles, runners, quietAfter, limits (docs/config.md#agents)
|
|
16
|
+
* agents: { authors: [], labels: [], branchPrefixes: [], bots: true }, // what marks work as made by an agent (docs/agents.md); and how runs are asked for and followed: transport, maxOpen, profiles, runners, quietAfter, runnerQuietAfter, limits (docs/config.md#agents)
|
|
17
17
|
* port: 3350,
|
|
18
18
|
* host: '127.0.0.1', // loopback, unless sign-in is configured with an https publicUrl (server/bind.js)
|
|
19
19
|
* publicUrl: null, // the origin people open it at; sign-in needs it (server/auth.js)
|
|
@@ -70,7 +70,7 @@ export const FORGE_TYPES = ['github', 'forgejo'];
|
|
|
70
70
|
/** How a pull request cornfield lands is merged (`forge.mergeMethod`): the way the repo lands its pull requests */
|
|
71
71
|
export const MERGE_METHODS = ['merge', 'squash', 'rebase'];
|
|
72
72
|
/** The events a hook may ask for (`hooks[].events`), and what each one means: docs/config.md#hooks */
|
|
73
|
-
export const HOOK_EVENTS = Object.freeze(['spec.ready', 'spec.approved', 'spec.sentBack', 'build.opened', 'pr.landed', 'session.expiring', 'thread.opened', 'thread.message', 'thread.linked', 'agent.requested', 'run.claimed', 'run.state', 'run.stopRequested', 'run.finished', 'trigger.skipped']);
|
|
73
|
+
export const HOOK_EVENTS = Object.freeze(['spec.ready', 'spec.approved', 'spec.sentBack', 'build.opened', 'pr.landed', 'session.expiring', 'thread.opened', 'thread.message', 'thread.linked', 'agent.requested', 'run.claimed', 'run.state', 'run.stopRequested', 'run.finished', 'trigger.skipped', 'runner.offline']);
|
|
74
74
|
/** The events that come from looking at threads (server/threads.js): a poll that wants any of them looks at threads too */
|
|
75
75
|
export const THREAD_EVENTS = Object.freeze(['thread.opened', 'thread.message', 'thread.linked']);
|
|
76
76
|
/** The keys of `threads` when it is an object, and the label's longest length */
|
|
@@ -129,6 +129,10 @@ export const QUIET_MIN_MS = 5 * 60_000;
|
|
|
129
129
|
export const QUIET_MAX_MS = 30 * 24 * 3_600_000;
|
|
130
130
|
/** The most profiles and runners a config lists */
|
|
131
131
|
export const MAX_PROFILES = 20;
|
|
132
|
+
/** `agents.runnerQuietAfter`: how long no live runner token may go without polling before the runner is offline (pull transport, issue #99); its bounds in milliseconds */
|
|
133
|
+
export const DEFAULT_RUNNER_QUIET_AFTER = '3m';
|
|
134
|
+
export const RUNNER_QUIET_MIN_MS = 60_000;
|
|
135
|
+
export const RUNNER_QUIET_MAX_MS = 3_600_000;
|
|
132
136
|
export const MAX_RUNNERS = 50;
|
|
133
137
|
|
|
134
138
|
/**
|
|
@@ -137,6 +141,9 @@ export const MAX_RUNNERS = 50;
|
|
|
137
141
|
*/
|
|
138
142
|
export const quietAfterMs = (config) => parseDuration(config.agents?.quietAfter ?? DEFAULT_QUIET_AFTER) ?? parseDuration(DEFAULT_QUIET_AFTER);
|
|
139
143
|
|
|
144
|
+
/** How long a runner token may go without polling before no runner is online, in milliseconds: `agents.runnerQuietAfter`, '3m' unless set */
|
|
145
|
+
export const runnerQuietAfterMs = (config) => parseDuration(config.agents?.runnerQuietAfter ?? DEFAULT_RUNNER_QUIET_AFTER) ?? parseDuration(DEFAULT_RUNNER_QUIET_AFTER);
|
|
146
|
+
|
|
140
147
|
export const DEFAULTS = Object.freeze({
|
|
141
148
|
title: null,
|
|
142
149
|
derivers: ['starter', 'personas', 'cloud'],
|
|
@@ -152,7 +159,7 @@ export const DEFAULTS = Object.freeze({
|
|
|
152
159
|
personas: { roles: null, parent: 'root' },
|
|
153
160
|
cloud: { parent: 'root' },
|
|
154
161
|
releaseNotes: { breakingLabel: 'breaking' },
|
|
155
|
-
agents: { authors: [], labels: [], branchPrefixes: [], bots: true, transport: 'forge', maxOpen: DEFAULT_MAX_OPEN, profiles: [], runners: [], quietAfter: DEFAULT_QUIET_AFTER, limits: {}, on: {}, refuseCollisions: false },
|
|
162
|
+
agents: { authors: [], labels: [], branchPrefixes: [], bots: true, transport: 'forge', maxOpen: DEFAULT_MAX_OPEN, profiles: [], runners: [], quietAfter: DEFAULT_QUIET_AFTER, runnerQuietAfter: DEFAULT_RUNNER_QUIET_AFTER, limits: {}, on: {}, refuseCollisions: false },
|
|
156
163
|
hooks: [],
|
|
157
164
|
hookPoll: { specs: '5m' },
|
|
158
165
|
threads: { label: 'idea' },
|
|
@@ -168,7 +175,7 @@ export const PROPOSALS_KEYS = Object.freeze(['dir', 'approveLands']);
|
|
|
168
175
|
/** The keys of `worktrees` when it is an object: the folder, and how many days without a change leave a worktree out of the list (default: none is left out) */
|
|
169
176
|
export const WORKTREES_KEYS = Object.freeze(['dir', 'maxAgeDays']);
|
|
170
177
|
const MAX_WORKTREE_AGE_DAYS = 36500;
|
|
171
|
-
const AGENT_KEYS = ['authors', 'labels', 'branchPrefixes', 'bots', 'transport', 'maxOpen', 'profiles', 'runners', 'quietAfter', 'limits', 'on', 'refuseCollisions'];
|
|
178
|
+
const AGENT_KEYS = ['authors', 'labels', 'branchPrefixes', 'bots', 'transport', 'maxOpen', 'profiles', 'runners', 'quietAfter', 'runnerQuietAfter', 'limits', 'on', 'refuseCollisions'];
|
|
172
179
|
const PROFILE_NAME = new RegExp(PROFILE_SOURCE);
|
|
173
180
|
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
174
181
|
const isText = (v) => typeof v === 'string' && v.trim() !== '';
|
|
@@ -391,6 +398,12 @@ function agentRunProblems(a) {
|
|
|
391
398
|
else if (ms < QUIET_MIN_MS) out.push(`agents.quietAfter ${JSON.stringify(a.quietAfter)} is under the floor of 5m; use "5m" or more.`);
|
|
392
399
|
else if (ms > QUIET_MAX_MS) out.push(`agents.quietAfter ${JSON.stringify(a.quietAfter)} is over the ceiling of 30 days; use "720h" or less.`);
|
|
393
400
|
}
|
|
401
|
+
if (a.runnerQuietAfter !== undefined) {
|
|
402
|
+
const ms = parseDuration(a.runnerQuietAfter);
|
|
403
|
+
if (ms === null) out.push('agents.runnerQuietAfter is a duration like "3m" or "10m": how long a runner may go without polling before it counts as offline (3m unless set).');
|
|
404
|
+
else if (ms < RUNNER_QUIET_MIN_MS) out.push(`agents.runnerQuietAfter ${JSON.stringify(a.runnerQuietAfter)} is under the floor of 1m; use "1m" or more.`);
|
|
405
|
+
else if (ms > RUNNER_QUIET_MAX_MS) out.push(`agents.runnerQuietAfter ${JSON.stringify(a.runnerQuietAfter)} is over the ceiling of 1h; use "60m" or less.`);
|
|
406
|
+
}
|
|
394
407
|
if (a.on !== undefined) out.push(...triggerProblems(a));
|
|
395
408
|
if (a.limits !== undefined) {
|
|
396
409
|
if (!isObject(a.limits)) out.push('agents.limits is { minutes?, turns?, cost? }: hints the runner may enforce.');
|
package/explorer/forge-panel.js
CHANGED
|
@@ -69,7 +69,7 @@ import { relativeTime } from './review-model.js';
|
|
|
69
69
|
import { LAYER_DEFS, toggleLayer } from './layers.js';
|
|
70
70
|
import { WORK_URL, groupWork, filterGroups, groupWords, workStatus, markWords } from './agents-model.js';
|
|
71
71
|
import {
|
|
72
|
-
RUNS_URL, runsUrl, stopUrl, KINDS, aboutWords, statusWords, statusWhy, runMeta, canStop, runsStatus, triggerNotice, startBody, startWords, stopWords, confirmStartWords, litOfRun, changeWords,
|
|
72
|
+
RUNS_URL, runsUrl, stopUrl, KINDS, aboutWords, statusWords, statusWhy, runMeta, canStop, runsStatus, runnerState, runnerWords, triggerNotice, startBody, startWords, stopWords, confirmStartWords, litOfRun, changeWords,
|
|
73
73
|
} from './runs-model.js';
|
|
74
74
|
import { runsHtml } from './runs-view.js';
|
|
75
75
|
import { setRunsOnMap, clearRunsOnMap } from './runs-map.js';
|
|
@@ -119,6 +119,7 @@ const ui = {
|
|
|
119
119
|
runs: null, // { data, error } of the Agents tab's runs: what /api/agent-runs answered
|
|
120
120
|
runNote: null, // { text, ok }: what the last Stop came to
|
|
121
121
|
runSel: null, // the run lit on the map (Light on the map), by id
|
|
122
|
+
runnerSaid: null, // the runner state last shown ('online', 'offline', 'none'; null off the pull transport), so a change is said once
|
|
122
123
|
runTimelines: new Set(), // the runs whose timeline is open
|
|
123
124
|
agent: null, // { opener, refs, posting } while the Start an agent dialog is open
|
|
124
125
|
};
|
|
@@ -206,6 +207,12 @@ async function loadRuns(refresh, { say = true } = {}) {
|
|
|
206
207
|
syncRunsPoll();
|
|
207
208
|
if (ui.runSel) relightRun();
|
|
208
209
|
const said = say ? changeWords(before, ui.runs.data.runs) : [];
|
|
210
|
+
// A runner appearing or going quiet is said once, when the state changes (the line itself is plain text, not a live region). The state last
|
|
211
|
+
// shown is kept, not worked out again from the last listing: a runner that goes quiet is the same listing judged later
|
|
212
|
+
const was = ui.runnerSaid;
|
|
213
|
+
const is = runnerState(ui.runs.data.runnerPresence, now());
|
|
214
|
+
ui.runnerSaid = is;
|
|
215
|
+
if (say && was && is && was !== is) said.push(runnerWords(ui.runs.data.runnerPresence, now()));
|
|
209
216
|
if (said.length) announce(said.join('. '));
|
|
210
217
|
}
|
|
211
218
|
|
|
@@ -1116,6 +1123,7 @@ function paintRuns() {
|
|
|
1116
1123
|
note.hidden = !words;
|
|
1117
1124
|
note.className = `hx-forge-notice${!(ui.runs && ui.runs.error) && ui.runNote && ui.runNote.ok ? ' hx-forge-notice--ok' : ''}`;
|
|
1118
1125
|
note.textContent = words;
|
|
1126
|
+
paintRunner('forge-runs-runner', data);
|
|
1119
1127
|
const trig = $('forge-runs-trigger');
|
|
1120
1128
|
if (trig) {
|
|
1121
1129
|
const skipped = data ? triggerNotice(data) : '';
|
|
@@ -1127,6 +1135,15 @@ function paintRuns() {
|
|
|
1127
1135
|
list.innerHTML = data.runs.length ? runsHtml(viewContext(), data.runs) : '<li class="hx-forge-empty hx-faint">No agent has been asked for yet. Start one from an issue or a proposal.</li>';
|
|
1128
1136
|
}
|
|
1129
1137
|
|
|
1138
|
+
/** The one line on whether a runner is polling (pull transport only), in the Runs view and the Start dialog; hidden where it does not apply */
|
|
1139
|
+
function paintRunner(id, data) {
|
|
1140
|
+
const el = $(id);
|
|
1141
|
+
if (!el) return;
|
|
1142
|
+
const words = data ? runnerWords(data.runnerPresence, now()) : '';
|
|
1143
|
+
el.hidden = !words;
|
|
1144
|
+
el.textContent = words;
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1130
1147
|
/** What the Runs view needs to know of the page */
|
|
1131
1148
|
function viewContext() {
|
|
1132
1149
|
const f = ui.config && ui.config.forge;
|
|
@@ -1424,6 +1441,7 @@ async function openAgent(ref, opener) {
|
|
|
1424
1441
|
if (!ui.agent) return;
|
|
1425
1442
|
const profiles = (ui.runs && ui.runs.data && ui.runs.data.profiles) || [];
|
|
1426
1443
|
$('agent-start-about').textContent = `About ${aboutWords(refs)}`;
|
|
1444
|
+
paintRunner('agent-start-runner', ui.runs && ui.runs.data);
|
|
1427
1445
|
$('agent-kind').innerHTML = KINDS.map(([v, l]) => option(v, l, v === 'code')).join('');
|
|
1428
1446
|
$('agent-profile').innerHTML = option('', 'No profile', true) + profiles.map((p) => option(p, p, false)).join('');
|
|
1429
1447
|
$('agent-profile-field').hidden = !profiles.length;
|
|
@@ -1830,5 +1848,5 @@ export function resetForgePanelForTests(clock = () => Date.now()) {
|
|
|
1830
1848
|
runsTimer = 0;
|
|
1831
1849
|
pageAway = false;
|
|
1832
1850
|
clearRunsOnMap();
|
|
1833
|
-
Object.assign(ui, { runSel: null, runTimelines: new Set(), thread: null, threadDetail: null, threadError: '', litThread: null, idea: freshIdea(), config: null, open: false, kind: 'pulls', filters: defaultFilters(), lists: {}, work: null, workFilters: { agentsOnly: false, finished: false }, loading: false, error: '', selected: null, detail: null, landing: null, detailError: '', lit: null, deploy: null, deployItem: null, litDeploy: null, nodesSeen: null, busy: '', note: null, confirm: null, actNote: null, notes: freshNotes(), runs: null, runNote: null, agent: null });
|
|
1851
|
+
Object.assign(ui, { runSel: null, runTimelines: new Set(), thread: null, threadDetail: null, threadError: '', litThread: null, idea: freshIdea(), config: null, open: false, kind: 'pulls', filters: defaultFilters(), lists: {}, work: null, workFilters: { agentsOnly: false, finished: false }, loading: false, error: '', selected: null, detail: null, landing: null, detailError: '', lit: null, deploy: null, deployItem: null, litDeploy: null, nodesSeen: null, busy: '', note: null, confirm: null, actNote: null, notes: freshNotes(), runs: null, runnerSaid: null, runNote: null, agent: null });
|
|
1834
1852
|
}
|
package/explorer/index.html
CHANGED
|
@@ -278,6 +278,7 @@
|
|
|
278
278
|
<section id="forge-runs" class="hx-forge-runs" aria-labelledby="forge-runs-title" hidden>
|
|
279
279
|
<h3 id="forge-runs-title" class="hx-forge-runs-title">Agent runs</h3>
|
|
280
280
|
<p id="forge-runs-status" class="hx-forge-meta hx-faint"></p>
|
|
281
|
+
<p id="forge-runs-runner" class="hx-forge-meta" hidden></p>
|
|
281
282
|
<p id="forge-runs-note" class="hx-forge-notice" hidden></p>
|
|
282
283
|
<p id="forge-runs-trigger" class="hx-forge-notice" hidden></p>
|
|
283
284
|
<ul id="forge-runs-list" class="hx-forge-files" aria-label="Runs"></ul>
|
|
@@ -361,6 +362,7 @@
|
|
|
361
362
|
<div class="hx-confirm glass" role="dialog" aria-modal="true" aria-labelledby="agent-start-title" aria-describedby="agent-start-words">
|
|
362
363
|
<h2 id="agent-start-title" class="hx-confirm-title">Start an agent</h2>
|
|
363
364
|
<p id="agent-start-about" class="hx-forge-meta"></p>
|
|
365
|
+
<p id="agent-start-runner" class="hx-forge-meta" hidden></p>
|
|
364
366
|
<form id="agent-start-form" class="hx-forge-confirm" novalidate>
|
|
365
367
|
<label class="hx-forge-field">Kind of run<select id="agent-kind" class="hx-forge-select"></select></label>
|
|
366
368
|
<label id="agent-profile-field" class="hx-forge-field" hidden>Profile<select id="agent-profile" class="hx-forge-select"></select></label>
|
package/explorer/runs-model.js
CHANGED
|
@@ -91,6 +91,34 @@ export function runsStatus(data) {
|
|
|
91
91
|
return `${data.open} open of ${data.maxOpen} allowed, ${n} ${n === 1 ? 'run' : 'runs'}`;
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
+
/** "20 s", "5 min", "2 h": how long ago, short enough for a line */
|
|
95
|
+
function agoShort(ms) {
|
|
96
|
+
const s = Math.max(0, Math.round(ms / 1000));
|
|
97
|
+
if (s < 60) return `${s} s`;
|
|
98
|
+
if (s < 3600) return `${Math.floor(s / 60)} min`;
|
|
99
|
+
return `${Math.floor(s / 3600)} h`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Whether a runner is there, from the runs listing's `runnerPresence` (issue #99): 'online', 'offline' (it polled once, not lately), 'none' (no
|
|
104
|
+
* live runner token has polled), or null where it does not apply (not the pull transport). Worked out against `nowMs`, so it ages on the page.
|
|
105
|
+
*/
|
|
106
|
+
export function runnerState(presence, nowMs) {
|
|
107
|
+
if (!presence || presence.transport !== 'pull') return null;
|
|
108
|
+
const seen = typeof presence.lastSeen === 'string' ? Date.parse(presence.lastSeen) : NaN;
|
|
109
|
+
if (!Number.isFinite(seen)) return 'none';
|
|
110
|
+
return nowMs - seen < (presence.quietAfterMs || 180_000) ? 'online' : 'offline';
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The one line: "Runner online · last seen 20 s ago", or "No runner has polled for 5 min: a queued run will wait"; '' where it does not apply */
|
|
114
|
+
export function runnerWords(presence, nowMs) {
|
|
115
|
+
const state = runnerState(presence, nowMs);
|
|
116
|
+
if (state === 'online') return `Runner online · last seen ${agoShort(nowMs - Date.parse(presence.lastSeen))} ago`;
|
|
117
|
+
if (state === 'offline') return `No runner has polled for ${agoShort(nowMs - Date.parse(presence.lastSeen))}: a queued run will wait`;
|
|
118
|
+
if (state === 'none') return 'No runner has polled yet: a queued run will wait';
|
|
119
|
+
return '';
|
|
120
|
+
}
|
|
121
|
+
|
|
94
122
|
/**
|
|
95
123
|
* The body of a start. Only what the person chose; the server writes the run id, the time and who asked, and checks the rest.
|
|
96
124
|
* @param {{ kind: string, profile?: string, brief?: string, refs: object, force?: boolean }} input
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@popcorn245/cornfield",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"description": "A self-hostable dev dashboard with the topology map at its centre: proposals on the map, scenarios, outages and what-if edits, for any repo.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "popcorn245 (https://github.com/popcorn245)",
|
package/server/agent-runs.js
CHANGED
|
@@ -79,7 +79,8 @@ import fs from 'node:fs';
|
|
|
79
79
|
import path from 'node:path';
|
|
80
80
|
import { ForgeError, isMaintainer } from './forge.js';
|
|
81
81
|
import { createRequest, findRunId, formatRunComment, runAuthors, runBlocksOf, runIdFromBranch, validateReport, validateRequest, MAX_NOTE_CHARS } from '../core/agent-contract.js';
|
|
82
|
-
import { quietAfterMs } from '../core/config.js';
|
|
82
|
+
import { quietAfterMs, runnerQuietAfterMs } from '../core/config.js';
|
|
83
|
+
import { runnerPresence } from './runner-presence.js';
|
|
83
84
|
import { nodesForFile, parseMentions, resolveMentions } from '../core/mentions.js';
|
|
84
85
|
import { readTopology } from '../core/validate.js';
|
|
85
86
|
import { findPullProposal, listPullProposals, pullProposals, readPullProposal } from './proposal-pulls.js';
|
|
@@ -269,6 +270,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
269
270
|
const runnerSet = new Set((Array.isArray(agents.runners) ? agents.runners : []).map(lower));
|
|
270
271
|
const authorSet = new Set((Array.isArray(agents.authors) ? agents.authors : []).map(lower));
|
|
271
272
|
const quietMs = quietAfterMs(config);
|
|
273
|
+
const runnerQuietMs = runnerQuietAfterMs(config);
|
|
272
274
|
const refuseCollisions = agents.refuseCollisions === true;
|
|
273
275
|
/** How requests travel from now on (`agents.transport`); a run keeps the transport it was asked for with */
|
|
274
276
|
const transport = /** @type {'forge' | 'push' | 'pull'} */ (agents.transport ?? 'forge');
|
|
@@ -695,7 +697,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
695
697
|
return {
|
|
696
698
|
runs: rows.map((r) => publicRun(r, at, quietMs, extras.get(r.run_id))), open: openRows(db, at).length, maxOpen: cap, profiles, limits: agents.limits || {}, quietAfter: agents.quietAfter, runners: [...runnerSet].length,
|
|
697
699
|
triggerSkipped: skipped.length ? { count: skipped.length, last: skipped[0].at, reasons } : null,
|
|
698
|
-
refuseCollisions,
|
|
700
|
+
refuseCollisions, runnerPresence: { transport, ...runnerPresence(db, at, runnerQuietMs) },
|
|
699
701
|
};
|
|
700
702
|
}
|
|
701
703
|
|
package/server/hooks.js
CHANGED
|
@@ -28,6 +28,8 @@
|
|
|
28
28
|
* trigger.skipped an opt-in trigger (`agents.on`, server/triggers.js) was going to request a run and did not: the maintainer whose act caused it has no
|
|
29
29
|
* live sign-in (`reason: 'no-session'`), or the request was refused (the cap, the one-run-per-subject rule, the rate limit: the refusal's code).
|
|
30
30
|
* Its body is its own: `{ event, at, trigger: { event, by, ref }, by, reason, mapUrl }`
|
|
31
|
+
* runner.offline on the pull transport, the last live runner token has not polled for `agents.runnerQuietAfter` (3 minutes unless set; server/runner-presence.js).
|
|
32
|
+
* Once, and again only after a runner has been seen online again. Its body is its own: `{ event, at, label, lastSeen, mapUrl }`, never a token
|
|
31
33
|
* run.claimed run.state run.stopRequested run.finished a run was claimed by its runner, changed state, was asked to stop, ended. They are
|
|
32
34
|
* seen when cornfield looks (the spec poll, server/spec-poll.js), each once. Their body is their own:
|
|
33
35
|
* `{ event, at, runId, state, pull?, issue?, actor, mapUrl }`
|
|
@@ -216,6 +218,8 @@ export function createHooks({ hooks, secret, fetch: doFetch = globalThis.fetch,
|
|
|
216
218
|
const t = p.trigger && typeof p.trigger === 'object' ? { event: p.trigger.event ?? null, by: p.trigger.by ?? null, ref: p.trigger.ref ?? null } : null;
|
|
217
219
|
return JSON.stringify({ event, at: new Date(now()).toISOString(), trigger: t, by: p.by ?? null, reason: p.reason ?? null, mapUrl: publicUrl || null });
|
|
218
220
|
}
|
|
221
|
+
// The runner that went quiet: its label and when it last polled, never a token
|
|
222
|
+
if (event === 'runner.offline') return JSON.stringify({ event, at: new Date(now()).toISOString(), label: p.label ?? null, lastSeen: p.lastSeen ?? null, mapUrl: publicUrl || null });
|
|
219
223
|
// A request goes out as it was posted, and is checked once more on the way: nothing like a credential can leave through a hook
|
|
220
224
|
if (event === 'agent.requested') {
|
|
221
225
|
const checked = validateRequest(p.request);
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module server/runner-presence
|
|
3
|
+
*
|
|
4
|
+
* Whether a runner is there (issue #99). On the pull transport a queued run waits for a runner that asks for it; when none does, nothing says
|
|
5
|
+
* so. A runner token's last poll is already kept: `review_tokens.last_used` is set by every call a live runner token makes to the runner API
|
|
6
|
+
* (server/runner-api.js: the queue read, a claim, a report), and a runner token is good for no other route, so for this scope `last_used` *is*
|
|
7
|
+
* the last poll and nothing new is stored.
|
|
8
|
+
*
|
|
9
|
+
* - `runnerPresence` reads it: the live runner tokens (not revoked, not expired) that have polled, each `{ label, lastSeen }`, newest first, and
|
|
10
|
+
* `online` when the newest poll is within `agents.runnerQuietAfter` (3 minutes unless set). A token no one has polled with is not a runner yet.
|
|
11
|
+
* - `createRunnerWatch` fires the `runner.offline` hook event, once: when a runner was seen online and the last live one has now been quiet
|
|
12
|
+
* for the window. It fires again only after a runner has been seen online again. A token revoked or expired is no runner, and ending one on
|
|
13
|
+
* purpose is not news. After a restart the first look only learns the state, so a runner that was already quiet is not announced twice.
|
|
14
|
+
* Only a poll newer than the one last announced re-arms it, so the clock stepping back cannot announce the same quiet spell twice.
|
|
15
|
+
* The body is `{ event, at, label, lastSeen, mapUrl }`: the label of the runner that polled last, never a token (server/hooks.js).
|
|
16
|
+
*
|
|
17
|
+
* Only the pull transport has runners that ask, so the watch is made for it alone. Times are ISO strings in the file; `now` is milliseconds.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const iso = (ms) => new Date(ms).toISOString();
|
|
21
|
+
|
|
22
|
+
/** How often the watch looks, at most: a window is minutes, so half a minute is soon enough and costs one query */
|
|
23
|
+
export const WATCH_EVERY_MS = 30_000;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @typedef {{ label: string, lastSeen: string }} SeenRunner
|
|
27
|
+
* @typedef {{ online: boolean, lastSeen: string | null, quietAfterMs: number, runners: SeenRunner[] }} RunnerPresence
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The live runner tokens that have polled, and whether one did within `quietMs`.
|
|
32
|
+
* @param {import('node:sqlite').DatabaseSync} db
|
|
33
|
+
* @param {number} now
|
|
34
|
+
* @param {number} quietMs
|
|
35
|
+
* @returns {RunnerPresence}
|
|
36
|
+
*/
|
|
37
|
+
export function runnerPresence(db, now, quietMs) {
|
|
38
|
+
const rows = /** @type {{ label: string, last_used: string }[]} */ (db.prepare(
|
|
39
|
+
"SELECT label, last_used FROM review_tokens WHERE scope = 'runner' AND revoked_at IS NULL AND expires_at > ? AND last_used IS NOT NULL ORDER BY last_used DESC, id DESC LIMIT 50",
|
|
40
|
+
).all(iso(now)));
|
|
41
|
+
const runners = rows.map((r) => ({ label: r.label, lastSeen: r.last_used }));
|
|
42
|
+
const newest = runners.length ? Date.parse(runners[0].lastSeen) : NaN;
|
|
43
|
+
return { online: Number.isFinite(newest) && now - newest < quietMs, lastSeen: runners.length ? runners[0].lastSeen : null, quietAfterMs: quietMs, runners };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The watch: `check()` looks once and fires `runner.offline` when it is due; `start()` looks every `WATCH_EVERY_MS` until `close()`.
|
|
48
|
+
* @param {{
|
|
49
|
+
* auth: { store: () => Promise<import('node:sqlite').DatabaseSync> },
|
|
50
|
+
* hooks: { emit: (event: string, payload: object) => void } | null,
|
|
51
|
+
* quietMs: number,
|
|
52
|
+
* now?: () => number,
|
|
53
|
+
* timer?: { setInterval: Function, clearInterval: Function },
|
|
54
|
+
* }} opts
|
|
55
|
+
*/
|
|
56
|
+
export function createRunnerWatch({ auth, hooks, quietMs, now = Date.now, timer = { setInterval, clearInterval } }) {
|
|
57
|
+
/** Whether a runner has been seen online since the last time one was announced offline */
|
|
58
|
+
let armed = false;
|
|
59
|
+
/** The last poll an announcement was about: only a newer one re-arms, so a clock stepped back cannot make one quiet spell fire twice */
|
|
60
|
+
let announced = null;
|
|
61
|
+
let handle = null;
|
|
62
|
+
let closed = false;
|
|
63
|
+
|
|
64
|
+
/** @returns {Promise<'online' | 'offline' | 'quiet' | 'none'>} what this look found: 'offline' only when the event was fired */
|
|
65
|
+
async function check() {
|
|
66
|
+
const db = await auth.store();
|
|
67
|
+
if (closed) return 'none';
|
|
68
|
+
const p = runnerPresence(db, now(), quietMs);
|
|
69
|
+
if (p.online) {
|
|
70
|
+
if (announced === null || (p.lastSeen !== null && Date.parse(p.lastSeen) > Date.parse(announced))) armed = true;
|
|
71
|
+
return 'online';
|
|
72
|
+
}
|
|
73
|
+
if (!p.runners.length) { armed = false; return 'none'; }
|
|
74
|
+
if (!armed) return 'quiet';
|
|
75
|
+
armed = false;
|
|
76
|
+
announced = p.lastSeen;
|
|
77
|
+
hooks?.emit('runner.offline', { label: p.runners[0].label, lastSeen: p.lastSeen });
|
|
78
|
+
return 'offline';
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return {
|
|
82
|
+
check,
|
|
83
|
+
start() {
|
|
84
|
+
if (closed || handle) return;
|
|
85
|
+
const look = () => { check().catch((err) => console.error(`[cornfield] runner presence could not be checked: ${err instanceof Error ? err.message : err}`)); };
|
|
86
|
+
look();
|
|
87
|
+
handle = timer.setInterval(look, WATCH_EVERY_MS);
|
|
88
|
+
if (handle && typeof handle.unref === 'function') handle.unref();
|
|
89
|
+
},
|
|
90
|
+
close() {
|
|
91
|
+
closed = true;
|
|
92
|
+
if (handle !== null) timer.clearInterval(handle);
|
|
93
|
+
handle = null;
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
package/server/server.js
CHANGED
|
@@ -48,7 +48,7 @@ import http from 'node:http';
|
|
|
48
48
|
import path from 'node:path';
|
|
49
49
|
import { createHash, randomBytes } from 'node:crypto';
|
|
50
50
|
import { fileURLToPath } from 'node:url';
|
|
51
|
-
import { browserSources, BUILTIN_SOURCES, parseDuration, specPollMs, triggersOf, DEFAULTS, hookWants, ideaLabel } from '../core/config.js';
|
|
51
|
+
import { browserSources, BUILTIN_SOURCES, parseDuration, specPollMs, triggersOf, DEFAULTS, hookWants, ideaLabel, runnerQuietAfterMs } from '../core/config.js';
|
|
52
52
|
import { CLOUD_FILE } from '../core/cloud.js';
|
|
53
53
|
import { decodePath, inside, notFound, sendFile } from './files.js';
|
|
54
54
|
import { serveProposals } from './proposals.js';
|
|
@@ -65,6 +65,7 @@ import { createAuth, signInSettings } from './auth.js';
|
|
|
65
65
|
import { createHooks, hooksSettings } from './hooks.js';
|
|
66
66
|
import { createLander } from './lander.js';
|
|
67
67
|
import { createSpecPoll } from './spec-poll.js';
|
|
68
|
+
import { createRunnerWatch } from './runner-presence.js';
|
|
68
69
|
import { createTriggers } from './triggers.js';
|
|
69
70
|
|
|
70
71
|
export const CORNFIELD_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
@@ -191,6 +192,10 @@ export function createCornfieldServer(config, opts = {}) {
|
|
|
191
192
|
const runsEvery = config.hookPoll === undefined ? DEFAULTS.hookPoll.specs : config.hookPoll.specs;
|
|
192
193
|
const pollMs = specMs ?? (runs && runsEvery !== false ? parseDuration(runsEvery) : null);
|
|
193
194
|
const specPoll = pollMs ? createSpecPoll({ config, where, auth, hooks, runs, specs: specMs !== null, intervalMs: pollMs, now: opts.now, timer: opts.specPollTimer }) : null;
|
|
195
|
+
// On the pull transport, says once (the `runner.offline` hook event) when the last live runner has stopped polling; only if a hook asks for it
|
|
196
|
+
const runnerWatch = runs && transport === 'pull' && hooks && hookWants(config, ['runner.offline'])
|
|
197
|
+
? createRunnerWatch({ auth, hooks, quietMs: runnerQuietAfterMs(config), now: opts.now, timer: opts.runnerWatchTimer })
|
|
198
|
+
: null;
|
|
194
199
|
let serverClosed = false;
|
|
195
200
|
const proxies = Object.entries(config.proxy || {});
|
|
196
201
|
const houseSource = config.sources.house && (config.sources.house === 'house' || config.sources.house.use === 'house') ? config.sources.house : null;
|
|
@@ -230,13 +235,14 @@ export function createCornfieldServer(config, opts = {}) {
|
|
|
230
235
|
}
|
|
231
236
|
});
|
|
232
237
|
server.on('listening', () => {
|
|
238
|
+
runnerWatch?.start();
|
|
233
239
|
if (specMs !== null) specPoll?.start();
|
|
234
240
|
else if (specPoll && runs) {
|
|
235
241
|
// Runs asked for before a restart are followed again from the start
|
|
236
242
|
runs.hasWork().then((work) => { if (work && !serverClosed) specPoll.start(); }).catch(() => {});
|
|
237
243
|
}
|
|
238
244
|
});
|
|
239
|
-
server.on('close', () => { serverClosed = true; specPoll?.close(); lander?.close(); hooks?.close(); auth.close(); });
|
|
245
|
+
server.on('close', () => { serverClosed = true; specPoll?.close(); runnerWatch?.close(); lander?.close(); hooks?.close(); auth.close(); });
|
|
240
246
|
return server;
|
|
241
247
|
|
|
242
248
|
async function answer(req, res) {
|