@popcorn245/cornfield 0.14.0 → 0.16.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/agent-contract.js +53 -19
- package/core/agent-contract.schema.json +33 -1
- package/core/config.js +17 -4
- package/explorer/forge-panel.js +57 -3
- package/explorer/index.html +2 -0
- package/explorer/runs-model.js +56 -1
- package/explorer/runs-view.js +25 -4
- package/package.json +1 -1
- package/server/agent-api.js +10 -3
- package/server/agent-runs.js +173 -22
- package/server/db.js +78 -1
- package/server/hooks.js +11 -4
- package/server/runner-presence.js +96 -0
- package/server/server.js +8 -2
package/server/hooks.js
CHANGED
|
@@ -28,9 +28,13 @@
|
|
|
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
|
-
*
|
|
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
|
|
33
|
+
* run.claimed run.state run.waiting run.answered run.stopRequested run.finished a run was claimed by its runner, changed state, reported
|
|
34
|
+
* `waiting` (it asks a maintainer), was answered, was asked to stop, ended. They are
|
|
32
35
|
* seen when cornfield looks (the spec poll, server/spec-poll.js), each once. Their body is their own:
|
|
33
|
-
* `{ event, at, runId, state, pull?, issue?, actor, mapUrl }`
|
|
36
|
+
* `{ event, at, runId, state, pull?, issue?, action?, actor, mapUrl }`; `action` (continue, stop or reply) is only on `run.answered`,
|
|
37
|
+
* and a reply's words are never in it
|
|
34
38
|
*
|
|
35
39
|
* **Triggers listen in-process.** `subscribe(fn)` hands a function the same moments the hooks fire at, with the payload resolved, whether or not
|
|
36
40
|
* any hook asks for them (server/triggers.js: `spec.approved`, `build.opened`, `thread.message`). A thread's payload then also holds the
|
|
@@ -216,17 +220,20 @@ export function createHooks({ hooks, secret, fetch: doFetch = globalThis.fetch,
|
|
|
216
220
|
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
221
|
return JSON.stringify({ event, at: new Date(now()).toISOString(), trigger: t, by: p.by ?? null, reason: p.reason ?? null, mapUrl: publicUrl || null });
|
|
218
222
|
}
|
|
223
|
+
// The runner that went quiet: its label and when it last polled, never a token
|
|
224
|
+
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
225
|
// 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
226
|
if (event === 'agent.requested') {
|
|
221
227
|
const checked = validateRequest(p.request);
|
|
222
228
|
if (!checked.ok) throw new Error(checked.error);
|
|
223
229
|
return JSON.stringify({ event, at: new Date(now()).toISOString(), request: checked.value, actor: p.actor ?? null, mapUrl: publicUrl || null });
|
|
224
230
|
}
|
|
225
|
-
// The events of a run (claimed, state, stopRequested, finished) say which run, in what state, and about what
|
|
231
|
+
// The events of a run (claimed, state, waiting, answered, stopRequested, finished) say which run, in what state, and about what
|
|
226
232
|
if (event.startsWith('run.')) {
|
|
227
233
|
return JSON.stringify({
|
|
228
234
|
event, at: new Date(now()).toISOString(), runId: p.runId ?? null, state: p.state ?? null,
|
|
229
|
-
...(p.pull != null ? { pull: p.pull } : {}), ...(p.issue != null ? { issue: p.issue } : {}),
|
|
235
|
+
...(p.pull != null ? { pull: p.pull } : {}), ...(p.issue != null ? { issue: p.issue } : {}),
|
|
236
|
+
...(event === 'run.answered' && ['continue', 'stop', 'reply'].includes(p.action) ? { action: p.action } : {}), actor: p.actor ?? null, mapUrl: publicUrl || null,
|
|
230
237
|
});
|
|
231
238
|
}
|
|
232
239
|
// A thread's event is only which thread, which comment, who and what it links to: never the words said
|
|
@@ -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) {
|