cornfield 0.13.2 → 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 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.');
@@ -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
  }
@@ -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>
@@ -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
@@ -194,7 +222,9 @@ export function checksWords(run) {
194
222
 
195
223
  /** One line of a run's timeline, and the runner's words under it (data for the page to escape) */
196
224
  export function timelineWords(entry) {
197
- const by = entry.actor ? ` by ${entry.actor}` : '';
225
+ // A runner's act carries `{ kind: 'runner', label, … }`: shown by its label. An older row's actor is the login, shown as it is
226
+ const who = entry.actor && typeof entry.actor === 'object' ? entry.actor.label : entry.actor;
227
+ const by = who ? ` by ${who}` : '';
198
228
  switch (entry.kind) {
199
229
  case 'requested': return { what: `Requested${by}${entry.ref ? ` under the profile ${entry.ref}` : ''}`, note: '' };
200
230
  case 'claimed': return { what: `Claimed${by}`, note: entry.note || '' };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cornfield",
3
- "version": "0.13.2",
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)",
@@ -79,11 +79,13 @@ 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';
86
87
  import { Refused, countAttempt, throttle } from './throttle.js';
88
+ import { byFromText, byToText, runnerBy } from './review-tokens.js';
87
89
 
88
90
  /** Requests one person may make in a minute (a ceiling of its own; every other action is counted by `ATTEMPTS_PER_MINUTE` and `PER_MINUTE`) */
89
91
  export const AGENT_REQUESTS_PER_MINUTE = 6;
@@ -156,6 +158,12 @@ export function statusOf(row, nowMs, quietMs) {
156
158
  return { status, open: !finished && !quiet, finished, quiet };
157
159
  }
158
160
 
161
+ /** Who a stored `by` is for a hook event: `runner:<label>` for a runner, else the login */
162
+ function actorText(text) {
163
+ const by = byFromText(text);
164
+ return by && typeof by === 'object' ? `runner:${by.label}` : by;
165
+ }
166
+
159
167
  /** The numbers a run is about, as keys for the one-per-subject rule: an issue and a thread are conversations (numbers are shared by issues and pull requests) */
160
168
  function subjectKeys(refs) {
161
169
  const out = [];
@@ -184,7 +192,7 @@ export function publicRun(row, nowMs, quietMs, extra = {}) {
184
192
  claimedAt: row.claimed_at,
185
193
  comment: row.comment_id ? { id: row.comment_id, url: row.comment_url } : null,
186
194
  limits,
187
- report: row.reported_at ? { state: row.state, at: row.reported_at, by: row.reported_by, note: row.note, url: row.url, tokens: row.tokens, cost: row.cost } : null,
195
+ report: row.reported_at ? { state: row.state, at: row.reported_at, by: byFromText(row.reported_by), note: row.note, url: row.url, tokens: row.tokens, cost: row.cost } : null,
188
196
  stopRequested: row.stop_requested_at ? { at: row.stop_requested_at, by: row.stop_requested_by } : null,
189
197
  pull: row.pull != null ? { number: row.pull, state: row.pull_state, url: row.pull_url, by: row.pull_by, trusted: row.pull_trusted === 1, via: row.linked_via } : null,
190
198
  branch: row.branch, headSha: row.head_sha, checks: row.checks, lastActivity: row.last_activity,
@@ -201,7 +209,7 @@ export function publicRun(row, nowMs, quietMs, extra = {}) {
201
209
  */
202
210
  export function timelineOf(row, events, now, quietMs) {
203
211
  const out = [{ at: row.requested_at, kind: 'requested', actor: row.requested_by, ref: row.profile, note: null, url: row.comment_url }];
204
- out.push(...events);
212
+ out.push(...events.map((e) => ({ ...e, actor: byFromText(e.actor) })));
205
213
  if (now.status === 'quiet') out.push({ at: iso(Date.parse(row.last_activity) + quietMs), kind: 'quiet', actor: null, ref: null, note: null, url: null });
206
214
  return out;
207
215
  }
@@ -262,6 +270,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
262
270
  const runnerSet = new Set((Array.isArray(agents.runners) ? agents.runners : []).map(lower));
263
271
  const authorSet = new Set((Array.isArray(agents.authors) ? agents.authors : []).map(lower));
264
272
  const quietMs = quietAfterMs(config);
273
+ const runnerQuietMs = runnerQuietAfterMs(config);
265
274
  const refuseCollisions = agents.refuseCollisions === true;
266
275
  /** How requests travel from now on (`agents.transport`); a run keeps the transport it was asked for with */
267
276
  const transport = /** @type {'forge' | 'push' | 'pull'} */ (agents.transport ?? 'forge');
@@ -688,7 +697,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
688
697
  return {
689
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,
690
699
  triggerSkipped: skipped.length ? { count: skipped.length, last: skipped[0].at, reasons } : null,
691
- refuseCollisions,
700
+ refuseCollisions, runnerPresence: { transport, ...runnerPresence(db, at, runnerQuietMs) },
692
701
  };
693
702
  }
694
703
 
@@ -1078,7 +1087,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1078
1087
  // ---- kept first, then announced ------------------------------------------------------------------------------------------------
1079
1088
  for (const row of cur.values()) {
1080
1089
  const now2 = statusOf(row, at, quietMs);
1081
- if (now2.finished && !FINISHED.includes(before.get(row.run_id) ?? '')) queue(row, 'run.finished', `ev:finished:${cause.get(row.run_id) ?? now2.status}`, row.reported_by ?? row.pull_by, now2.status);
1090
+ if (now2.finished && !FINISHED.includes(before.get(row.run_id) ?? '')) queue(row, 'run.finished', `ev:finished:${cause.get(row.run_id) ?? now2.status}`, actorText(row.reported_by) ?? row.pull_by, now2.status);
1082
1091
  }
1083
1092
  /** @type {typeof events} */
1084
1093
  const fresh = [];
@@ -1119,9 +1128,11 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1119
1128
  // Runners: pull and push (a runner token, server/runner-api.js; spec 0005 D2, D5)
1120
1129
  // -------------------------------------------------------------------------
1121
1130
 
1122
- /** @typedef {{ id: number, label: string }} RunnerToken the runner token a call came with */
1131
+ /** @typedef {{ id: number, label: string, mintedBy?: { login: string, userId: string } }} RunnerToken the runner token a call came with */
1123
1132
 
1124
1133
  const runnerActor = (token) => `runner:${token.label}`;
1134
+ /** What a runner's act writes into the timeline: the runner, with the maintainer who minted the token kept in `mintedBy` */
1135
+ const runnerText = (token) => byToText(runnerBy(token));
1125
1136
 
1126
1137
  /** A run for a runner: the state it is in as cornfield derives it, and whether a maintainer asked it to stop. Nothing else about the run, no credential */
1127
1138
  function runnerView(row) {
@@ -1169,7 +1180,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1169
1180
  const stamp = iso(at);
1170
1181
  const won = typeof runId === 'string' ? db.prepare(`UPDATE runs SET claimed_by = ?, claimed_at = ?, state = 'claimed', reported_at = ?, reported_by = ?, note = NULL, last_activity = MAX(last_activity, ?)
1171
1182
  WHERE run_id = ? AND repo = ? AND transport = 'pull' AND state = 'requested' AND claimed_by IS NULL AND stop_requested_at IS NULL AND last_activity > ?`)
1172
- .run(token.id, stamp, stamp, token.label, stamp, runId, repo, iso(at - quietMs)).changes === 1 : false;
1183
+ .run(token.id, stamp, stamp, runnerText(token), stamp, runId, repo, iso(at - quietMs)).changes === 1 : false;
1173
1184
  const row = typeof runId === 'string' ? /** @type {RunRow | undefined} */ (db.prepare('SELECT * FROM runs WHERE run_id = ? AND repo = ?').get(runId, repo)) : undefined;
1174
1185
  if (!row) throw new Refused(404, 'cornfield has no such request.', 'not-found');
1175
1186
  if (!won) {
@@ -1179,6 +1190,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1179
1190
  if (statusOf(row, at, quietMs).quiet) throw new Refused(409, 'This request has waited past agents.quietAfter and is no longer offered.', 'conflict');
1180
1191
  throw new Refused(409, `This request is ${row.state}; there is nothing to claim.`, 'conflict');
1181
1192
  }
1193
+ keepEvent(db, row.run_id, { key: `claim:${token.id}:${stamp}`, at: stamp, kind: 'claimed', actor: runnerText(token), ref: 'claimed' });
1182
1194
  const checked = validateRequest(safeJson(row.request));
1183
1195
  hooks?.emit('run.claimed', { ...runPayload(row, runnerActor(token)), state: 'claimed' });
1184
1196
  hooks?.emit('run.state', { ...runPayload(row, runnerActor(token)), state: 'claimed' });
@@ -1211,9 +1223,11 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1211
1223
  const changed = db.prepare(`UPDATE runs SET state = ?, reported_at = ?, reported_by = ?, note = ?, url = ?, tokens = COALESCE(?, tokens), cost = COALESCE(?, cost),
1212
1224
  claimed_by = COALESCE(claimed_by, ?), claimed_at = COALESCE(claimed_at, ?), last_activity = MAX(last_activity, ?)
1213
1225
  WHERE run_id = ? AND (claimed_by IS NULL OR claimed_by = ?) AND state NOT IN ('done', 'failed', 'stopped')`)
1214
- .run(r.state, stamp, token.label, r.note ?? null, r.url ?? null, r.tokens ?? null, r.cost ?? null, token.id, stamp, stamp, row.run_id, token.id).changes;
1226
+ .run(r.state, stamp, runnerText(token), r.note ?? null, r.url ?? null, r.tokens ?? null, r.cost ?? null, token.id, stamp, stamp, row.run_id, token.id).changes;
1215
1227
  if (changed !== 1) throw new Refused(409, `Run ${row.run_id} changed while the report was being taken; read it again (GET /api/runs/${row.run_id}).`, 'conflict');
1216
1228
  const after = /** @type {RunRow} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(row.run_id));
1229
+ // A report of `claimed` on a run the claim route already claimed is a report, not a second "Claimed" line
1230
+ keepEvent(db, row.run_id, { key: `report:runner:${token.id}:${stamp}:${r.state}`, at: stamp, kind: r.state === 'claimed' && row.state !== 'claimed' ? 'claimed' : 'report', actor: runnerText(token), ref: r.state, note: r.note ?? null, url: r.url ?? null });
1217
1231
  const actor = runnerActor(token);
1218
1232
  if (r.state === 'claimed' && row.state !== 'claimed') hooks?.emit('run.claimed', { ...runPayload(after, actor), state: r.state });
1219
1233
  if (r.state !== row.state) hooks?.emit('run.state', { ...runPayload(after, actor), state: r.state });
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);
@@ -48,6 +48,46 @@ const TOKEN_SHAPE = /^cf_(?:rt|at|nt)_[A-Za-z0-9_-]{43,128}$/;
48
48
  const LABEL = /^[\p{L}\p{N}][\p{L}\p{N} ._:/()-]*$/u;
49
49
  const COLUMNS = 'id, user_id, login, label, scope, created_at, expires_at, revoked_at, last_used';
50
50
 
51
+ /**
52
+ * Who acted when a runner token did: the runner (the token's label), with the maintainer who minted the token kept apart as `mintedBy`.
53
+ * A runner token does not act as its owner, so the timeline and the audit name the runner (issue #105).
54
+ * @typedef {{ kind: 'runner', label: string, tokenId?: number, mintedBy?: { login: string, userId: string } }} RunnerBy
55
+ * @param {{ id?: number, label: string, mintedBy?: { login: string, userId: string } }} token
56
+ * @returns {RunnerBy}
57
+ */
58
+ export function runnerBy(token) {
59
+ return { kind: 'runner', label: token.label, ...(token.id !== undefined ? { tokenId: token.id } : {}), ...(token.mintedBy ? { mintedBy: token.mintedBy } : {}) };
60
+ }
61
+
62
+ /** The token a runner call carries from here on: its id and label, and the maintainer who minted it */
63
+ export const runnerTokenOf = (row) => ({ id: row.id, label: row.label, mintedBy: { login: row.login, userId: String(row.user_id) } });
64
+
65
+ /**
66
+ * `by` as the TEXT columns keep it: a login stays plain text (the shape every older row has), a runner is JSON. A login never starts with `{`.
67
+ * @param {string | RunnerBy | null | undefined} by
68
+ * @returns {string | null}
69
+ */
70
+ export function byToText(by) {
71
+ if (by == null || by === '') return null;
72
+ return typeof by === 'string' ? by : JSON.stringify(by);
73
+ }
74
+
75
+ /**
76
+ * `by` as it was kept: the runner object, or the plain login of an older row (or null). Text that only looks like JSON is a plain string.
77
+ * @param {string | null | undefined} text
78
+ * @returns {string | RunnerBy | null}
79
+ */
80
+ export function byFromText(text) {
81
+ if (typeof text !== 'string' || text === '') return null;
82
+ if (text.startsWith('{')) {
83
+ try {
84
+ const v = JSON.parse(text);
85
+ if (v && v.kind === 'runner' && typeof v.label === 'string') return v;
86
+ } catch { /* plain text */ }
87
+ }
88
+ return text;
89
+ }
90
+
51
91
  const iso = (ms) => new Date(ms).toISOString();
52
92
 
53
93
  /** The SHA-256 of a token, as hex: what the table keeps */
@@ -46,7 +46,7 @@
46
46
 
47
47
  import { readBody } from './proposals.js';
48
48
  import { ANONYMOUS_PER_MINUTE, NO_TOKEN_LOGIN } from './review-api.js';
49
- import { bearerOf, findToken, scopeOfShape, touchToken } from './review-tokens.js';
49
+ import { bearerOf, findToken, runnerBy, runnerTokenOf, scopeOfShape, touchToken } from './review-tokens.js';
50
50
  import { QUEUE_LIMIT } from './agent-runs.js';
51
51
  import { refusal } from './submit-review.js';
52
52
  import { Refused, countAttempt } from './throttle.js';
@@ -151,13 +151,17 @@ export async function serveRunnerCall(req, res, route, url, ctx) {
151
151
  }
152
152
 
153
153
  const { row, state } = found;
154
- const token = { id: row.id, label: row.label };
154
+ const token = runnerTokenOf(row);
155
+ // The runner acts, not the maintainer who minted its token: the audit names the runner and keeps the maintainer in `mintedBy` (a token of another scope that was presented here is its owner's act)
156
+ const audited = { id: row.id, label: row.label };
157
+ const actor = state === 'wrong-scope' ? row.login : `runner:${row.label}`;
158
+ const by = state === 'wrong-scope' ? {} : { by: runnerBy(token), mintedBy: token.mintedBy };
155
159
  if (state !== 'active') {
156
160
  req.resume();
157
161
  const flood = countAttempt(ctx, row.user_id, now());
158
162
  if (flood) return send(res, flood.status, { ok: false, error: flood.message, code: flood.code }, flood.headers);
159
163
  const wrong = state === 'wrong-scope';
160
- return refuse(row.login, { reason: wrong ? 'wrong-scope' : state, token, ...(wrong ? { scope: row.scope } : {}) }, 403, {
164
+ return refuse(actor, { reason: wrong ? 'wrong-scope' : state, token: audited, ...by, ...(wrong ? { scope: row.scope } : {}) }, 403, {
161
165
  error: wrong ? `This is ${row.scope === 'agent' ? 'an' : 'a'} ${row.scope} token. Runners take a runner token; make one in the dashboard.`
162
166
  : state === 'revoked' ? 'This runner token was revoked; make a new one in the dashboard.' : 'This runner token has expired; make a new one in the dashboard.',
163
167
  code: 'forbidden',
@@ -174,23 +178,22 @@ export async function serveRunnerCall(req, res, route, url, ctx) {
174
178
  if (known !== null && !isMaintainer(known)) {
175
179
  req.resume();
176
180
  await auth.demoted(row.user_id, row.login, known);
177
- return refuse(row.login, { reason: 'owner-not-maintainer', token }, 403, { error: `This runner token's owner, ${row.login}, does not maintain ${repo} any more, so it is revoked.`, code: 'forbidden' });
181
+ return refuse(actor, { reason: 'owner-not-maintainer', token: audited, ...by }, 403, { error: `This runner token's owner, ${row.login}, does not maintain ${repo} any more, so it is revoked.`, code: 'forbidden' });
178
182
  }
179
183
  touchToken(/** @type {import('node:sqlite').DatabaseSync} */ (db), row.id, now());
180
- const who = row.login;
181
184
 
182
185
  try {
183
186
  if (route.action === 'runner-list') {
184
187
  req.resume();
185
188
  if (url.searchParams.get('state') !== 'queued') throw new Refused(400, 'The only listing is ?state=queued: the requests waiting for a runner.', 'invalid');
186
189
  const requests = await runs.queued();
187
- if (requests.length || emptyReadDue(auth, row.id, now())) await audit(who, { token }, 200, { ok: true, count: requests.length });
190
+ if (requests.length || emptyReadDue(auth, row.id, now())) await audit(actor, { token: audited, ...by }, 200, { ok: true, count: requests.length });
188
191
  return send(res, 200, { ok: true, requests, limit: QUEUE_LIMIT });
189
192
  }
190
193
  if (route.action === 'runner-claim') {
191
194
  req.resume();
192
195
  const claimed = await runs.claim(token, route.runId);
193
- await audit(who, { token }, 200, { ok: true, claimed: true }, `${repo}#${claimed.row.target}`);
196
+ await audit(actor, { token: audited, ...by }, 200, { ok: true, claimed: true }, `${repo}#${claimed.row.target}`);
194
197
  return send(res, 200, { ok: true, request: claimed.request, run: claimed.run });
195
198
  }
196
199
  if (method === 'POST') {
@@ -214,21 +217,21 @@ export async function serveRunnerCall(req, res, route, url, ctx) {
214
217
  try {
215
218
  if (problem) throw problem;
216
219
  const done = await runs.report(token, route.runId, body);
217
- await audit(who, { token, ...shape }, 200, { ok: true, state: done.row.state }, `${repo}#${done.row.target}`);
220
+ await audit(actor, { token: audited, ...by, ...shape }, 200, { ok: true, state: done.row.state }, `${repo}#${done.row.target}`);
218
221
  return send(res, 200, { ok: true, run: done.run });
219
222
  } catch (err) {
220
223
  const out = answerFor(err);
221
- await audit(who, { token, ...shape }, out.status, { error: out.body.error, code: out.body.code });
224
+ await audit(actor, { token: audited, ...by, ...shape }, out.status, { error: out.body.error, code: out.body.code });
222
225
  return send(res, out.status, { ok: false, ...out.body }, out.headers);
223
226
  }
224
227
  }
225
228
  req.resume();
226
229
  const view = await runs.runnerGet(token, route.runId);
227
- await audit(who, { token }, 200, { ok: true, state: view.state });
230
+ await audit(actor, { token: audited, ...by }, 200, { ok: true, state: view.state });
228
231
  return send(res, 200, { ok: true, run: view });
229
232
  } catch (err) {
230
233
  const out = answerFor(err);
231
- await audit(who, { token }, out.status, { error: out.body.error, code: out.body.code });
234
+ await audit(actor, { token: audited, ...by }, out.status, { error: out.body.error, code: out.body.code });
232
235
  return send(res, out.status, { ok: false, ...out.body }, out.headers);
233
236
  }
234
237
  }
@@ -250,9 +253,10 @@ export async function serveStrayRunner(req, res, reqPath, ctx) {
250
253
  const presented = bearerOf(req.headers.authorization);
251
254
  let owner = null;
252
255
  let token;
256
+ let by = {};
253
257
  if (presented && auth.enabled) {
254
258
  const found = findToken(await auth.store(), presented, now(), 'runner');
255
- if (found && found.state !== 'wrong-scope') { owner = found.row.login; token = { id: found.row.id, label: found.row.label }; }
259
+ if (found && found.state !== 'wrong-scope') { owner = `runner:${found.row.label}`; token = { id: found.row.id, label: found.row.label }; by = { by: runnerBy(runnerTokenOf(found.row)), mintedBy: runnerTokenOf(found.row).mintedBy }; }
256
260
  }
257
261
  const flood = owner === null ? countAttempt(ctx, NO_TOKEN_LOGIN, now(), ANONYMOUS_PER_MINUTE) : countAttempt(ctx, `runner|${token.id}`, now(), RUNNER_PER_MINUTE);
258
262
  if (flood) return send(res, flood.status, { ok: false, error: flood.message, code: flood.code }, flood.headers);
@@ -260,7 +264,7 @@ export async function serveStrayRunner(req, res, reqPath, ctx) {
260
264
  try {
261
265
  await auth.record({
262
266
  login: owner ?? NO_TOKEN_LOGIN, action: 'runner-call', target: config.forge?.repo ?? '',
263
- request: { via: 'api', reason: 'wrong-route', method: String(req.method).slice(0, 10), path: reqPath.slice(0, 80), ...(token ? { token } : {}) }, status: 403, answer: { error: body.error, code: body.code },
267
+ request: { via: 'api', reason: 'wrong-route', method: String(req.method).slice(0, 10), path: reqPath.slice(0, 80), ...(token ? { token, ...by } : {}) }, status: 403, answer: { error: body.error, code: body.code },
264
268
  });
265
269
  } catch (err) {
266
270
  console.error(`[cornfield] a runner call could not be written to the audit table: ${err instanceof Error ? err.message : err}`);
@@ -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) {