@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.
@@ -8,8 +8,9 @@
8
8
  * - **A run id,** `run-` and a 26 character ULID (Crockford base32): `newRunId`, `isRunId`.
9
9
  * - **The request,** JSON v1, checked strictly (`validateRequest`, `createRequest`). It carries no credential, ever: a field
10
10
  * named like a token, a secret or a password is refused, and so is a value shaped like one.
11
- * - **The report** a runner may send (`validateReport`: claimed, working, done, failed, stopped) and **the stop request**
12
- * cornfield sends (`validateStopRequest`: `stop-requested`).
11
+ * - **The report** a runner may send (`validateReport`: claimed, working, waiting, done, failed, stopped), **the stop request**
12
+ * cornfield sends (`validateStopRequest`: `stop-requested`) and **the answer** a maintainer gives a run that reported `waiting`
13
+ * (`validateAnswer`: `answered`, with an `action` of continue, stop or reply).
13
14
  * - **The fenced block,** one form for all three, modelled on the review block of ADR 0005 (server/reviews.js):
14
15
  *
15
16
  * Asked for a code run `run-01JC…` on #12 (maintainer-one, in cornfield).
@@ -20,7 +21,7 @@
20
21
  *
21
22
  * `formatRunComment` writes it (the human line is defused, so it pings and links nobody), `readRunBlocks` and
22
23
  * `parseRunBlocks` read it back: tolerant of the text around a block, strict about what is inside. A block that is not
23
- * strictly a request, a report or a stop request is skipped, and `readRunBlocks` says which and why.
24
+ * strictly a request, a report, a stop request or an answer is skipped, and `readRunBlocks` says which and why.
24
25
  * - **The trailer,** `Cornfield-Run: run-…` on its own line of a pull request body or a commit message, with the run id in a
25
26
  * branch name as the fallback (`parseTrailer`, `runIdFromBranch`, `findRunId`).
26
27
  *
@@ -40,11 +41,13 @@
40
41
  * @typedef {{ minutes?: number, turns?: number, cost?: number }} RunLimits
41
42
  * @typedef {{ version: 1, runId: string, kind: RunKind, profile?: string, refs: RunRefs, branch?: string, brief: string,
42
43
  * limits?: RunLimits, nodes?: string[], requestedBy: string, requestedAt: string, trigger?: { event: 'spec.approved' | 'build.opened' | 'thread.message', by: string, ref: string } }} RunRequest
43
- * @typedef {'claimed' | 'working' | 'done' | 'failed' | 'stopped'} ReportState
44
+ * @typedef {'claimed' | 'working' | 'waiting' | 'done' | 'failed' | 'stopped'} ReportState
44
45
  * @typedef {{ state: ReportState, note?: string, url?: string, tokens?: number, cost?: number }} RunReport
45
46
  * @typedef {{ state: 'stop-requested', note?: string }} StopRequest
47
+ * @typedef {'continue' | 'stop' | 'reply'} AnswerAction
48
+ * @typedef {{ state: 'answered', action: AnswerAction, text?: string }} RunAnswer
46
49
  * @typedef {{ ok: true, value: any } | { ok: false, error: string }} Checked
47
- * @typedef {{ runId: string, type: 'request', value: RunRequest } | { runId: string, type: 'report', value: RunReport } | { runId: string, type: 'stop-request', value: StopRequest }} RunBlock
50
+ * @typedef {{ runId: string, type: 'request', value: RunRequest } | { runId: string, type: 'report', value: RunReport } | { runId: string, type: 'stop-request', value: StopRequest } | { runId: string, type: 'answer', value: RunAnswer }} RunBlock
48
51
  */
49
52
 
50
53
  import { defuse } from './defuse.js';
@@ -58,11 +61,14 @@ const randomBytes = (n) => globalThis.crypto.getRandomValues(new Uint8Array(n));
58
61
 
59
62
  export const CONTRACT_VERSION = 1;
60
63
  export const RUN_KINDS = ['code', 'summary', 'brief', 'proposal'];
61
- export const REPORT_STATES = ['claimed', 'working', 'done', 'failed', 'stopped'];
64
+ export const REPORT_STATES = ['claimed', 'working', 'waiting', 'done', 'failed', 'stopped'];
62
65
  export const STOP_STATE = 'stop-requested';
66
+ /** The state of an answer block, and what a maintainer may answer a `waiting` run */
67
+ export const ANSWER_STATE = 'answered';
68
+ export const ANSWER_ACTIONS = ['continue', 'stop', 'reply'];
63
69
  /** The brief, in characters */
64
70
  export const MAX_BRIEF_CHARS = 20000;
65
- /** A report's or a stop request's note, in characters */
71
+ /** A report's or a stop request's note, and an answer's text, in characters */
66
72
  export const MAX_NOTE_CHARS = 4000;
67
73
  export const MAX_URL_CHARS = 2000;
68
74
  export const MAX_NODES = 100;
@@ -91,6 +97,7 @@ const REF_KEYS = ['issue', 'proposal', 'pull', 'thread'];
91
97
  const LIMIT_KEYS = ['minutes', 'turns', 'cost'];
92
98
  const REPORT_KEYS = ['state', 'note', 'url', 'tokens', 'cost'];
93
99
  const STOP_KEYS = ['state', 'note'];
100
+ const ANSWER_KEYS = ['state', 'action', 'text'];
94
101
 
95
102
  // ---------------------------------------------------------------------------
96
103
  // Patterns. Each is plain ECMAScript with no flags, so the JSON Schema can carry the same source.
@@ -391,7 +398,7 @@ export function createRequest(fields, { profiles, now = Date.now, random } = {})
391
398
  }
392
399
 
393
400
  // ---------------------------------------------------------------------------
394
- // The report, and the stop request
401
+ // The report, the stop request and the answer
395
402
  // ---------------------------------------------------------------------------
396
403
 
397
404
  function noteAndUrl(body, no) {
@@ -448,18 +455,43 @@ export function validateStopRequest(body) {
448
455
  return { ok: true, value: { state: STOP_STATE, ...(body.note !== undefined ? { note: body.note } : {}) } };
449
456
  }
450
457
 
458
+ /**
459
+ * Checks an answer: `{ state: 'answered', action, text? }`. A maintainer sends it to a run that reported `waiting`: `continue` (go on),
460
+ * `stop` (the same as a stop request) or `reply` (go on with `text`, which a reply must have). cornfield or a maintainer sends it; the
461
+ * runner decides what it means.
462
+ * @param {unknown} body
463
+ * @returns {Checked}
464
+ */
465
+ export function validateAnswer(body) {
466
+ const no = (error) => ({ ok: false, error });
467
+ if (!isObject(body)) return no('An answer is a JSON object with a state.');
468
+ const keys = keyProblem(body, ANSWER_KEYS, 'An answer');
469
+ if (keys) return no(keys);
470
+ const secret = valueProblem(body, 'The answer');
471
+ if (secret) return no(secret);
472
+ if (body.state !== ANSWER_STATE) return no(`"state" is "${ANSWER_STATE}".`);
473
+ if (!ANSWER_ACTIONS.includes(body.action)) return no(`"action" is one of ${ANSWER_ACTIONS.join(', ')}.`);
474
+ if (body.text !== undefined) {
475
+ const problem = text(body.text, 'text', MAX_NOTE_CHARS);
476
+ if (problem) return no(problem);
477
+ }
478
+ if (body.action === 'reply' && (body.text === undefined || body.text.trim() === '')) return no('A reply has "text": what the maintainer says.');
479
+ return { ok: true, value: { state: ANSWER_STATE, action: body.action, ...(body.text !== undefined && body.text.trim() !== '' ? { text: body.text } : {}) } };
480
+ }
481
+
451
482
  /**
452
483
  * Checks whatever a `cornfield-run` block holds, by its shape: a `version` makes it a request, the state `stop-requested` a
453
- * stop request, any other state a report.
484
+ * stop request, the state `answered` an answer, any other state a report.
454
485
  * @param {unknown} body
455
486
  * @param {{ profiles?: string[] }} [opts]
456
- * @returns {{ ok: true, type: 'request' | 'report' | 'stop-request', value: any } | { ok: false, error: string }}
487
+ * @returns {{ ok: true, type: 'request' | 'report' | 'stop-request' | 'answer', value: any } | { ok: false, error: string }}
457
488
  */
458
489
  export function validateRunBody(body, opts) {
459
490
  if (Array.isArray(body)) return { ok: false, error: 'A cornfield-run block holds one JSON object, not a list.' };
460
491
  if (!isObject(body)) return { ok: false, error: 'A cornfield-run block holds one JSON object.' };
461
492
  const [type, checked] = 'version' in body || 'runId' in body ? ['request', validateRequest(body, opts)]
462
493
  : body.state === STOP_STATE ? ['stop-request', validateStopRequest(body)]
494
+ : body.state === ANSWER_STATE ? ['answer', validateAnswer(body)]
463
495
  : 'state' in body ? ['report', validateReport(body)]
464
496
  : ['request', validateRequest(body, opts)]; // neither shape: the request check names the first key or field that is wrong
465
497
  return checked.ok ? { ok: true, type, value: checked.value } : checked;
@@ -471,7 +503,7 @@ export function validateRunBody(body, opts) {
471
503
 
472
504
  const FENCE = '```';
473
505
 
474
- /** The block for a checked request, report or stop request, as text: the fence named for the run, the JSON, the closing fence. Throws on anything that is not strictly one. */
506
+ /** The block for a checked request, report, stop request or answer, as text: the fence named for the run, the JSON, the closing fence. Throws on anything that is not strictly one. */
475
507
  export function formatRunBlock(runId, body, opts) {
476
508
  if (!isRunId(runId)) throw new TypeError(`${shown(runId)} is not a run id.`);
477
509
  const checked = validateRunBody(body, opts);
@@ -492,14 +524,15 @@ function defaultLine(runId, type, value) {
492
524
  return `Asked for a ${value.kind} run \`${runId}\` on ${about}${value.profile ? ` with the profile ${value.profile}` : ''} (${value.requestedBy}, in cornfield).`;
493
525
  }
494
526
  if (type === 'stop-request') return `Asked run \`${runId}\` to stop.`;
527
+ if (type === 'answer') return `Answered run \`${runId}\`: ${value.action}.`;
495
528
  return `Run \`${runId}\`: ${value.state}.`;
496
529
  }
497
530
 
498
531
  /**
499
- * The text of a comment for a request, a report or a stop request: a human line (defused: it pings and links nobody), the note of a
500
- * report or stop request quoted and defused, then the block. The block keeps every value as sent, for the runner.
532
+ * The text of a comment for a request, a report, a stop request or an answer: a human line (defused: it pings and links nobody), the note of a
533
+ * report or stop request quoted and defused (an answer's text is in the block only), then the block. The block keeps every value as sent, for the runner.
501
534
  * @param {string} runId
502
- * @param {RunRequest | RunReport | StopRequest} body
535
+ * @param {RunRequest | RunReport | StopRequest | RunAnswer} body
503
536
  * @param {{ line?: string, profiles?: string[] }} [opts] `line`: your own human line, in place of the default
504
537
  * @returns {string}
505
538
  */
@@ -507,7 +540,8 @@ export function formatRunComment(runId, body, { line, profiles } = {}) {
507
540
  const block = formatRunBlock(runId, body, { profiles });
508
541
  const checked = validateRunBody(body, { profiles });
509
542
  const head = oneLine(line ?? defaultLine(runId, checked.type, checked.value));
510
- const note = checked.type === 'request' ? '' : (checked.value.note ?? '').trim();
543
+ // An answer's text is the maintainer's words to the runner: it travels in the block only, never quoted beside it
544
+ const note = checked.type === 'request' || checked.type === 'answer' ? '' : (checked.value.note ?? '').trim();
511
545
  const quoted = note ? `\n\n${defuse(note).split(/\r?\n/).map((l) => (l ? `> ${l}` : '>')).join('\n')}` : '';
512
546
  const out = `${head}${quoted}\n\n${block}`;
513
547
  if (out.length > MAX_COMMENT_CHARS) throw new RangeError(`That is too long for a comment (${out.length} characters, at most ${MAX_COMMENT_CHARS}); shorten the brief or the note.`);
@@ -545,7 +579,7 @@ export function* fencedBlocks(text) {
545
579
 
546
580
  /**
547
581
  * Every block a comment's text holds, in order, and every block that was refused with the reason. A block that is not strictly a
548
- * request, a report or a stop request is refused: not JSON, a list, two objects, a key it does not have, a credential, a fence
582
+ * request, a report, a stop request or an answer is refused: not JSON, a list, two objects, a key it does not have, a credential, a fence
549
583
  * that names no run id, a request for another run than its fence names. Text around a block, a quoted block (`> ```…`), an
550
584
  * indented one, one nobody closed, and one inside another fence (a ```` example) are ignored (`fencedBlocks`). Nothing is thrown,
551
585
  * and the time it takes is linear in the text.
@@ -626,8 +660,8 @@ export function runAuthors(comments) {
626
660
  * - `blocks`: from an author `trust(login)` accepts, in a comment not edited after it was posted;
627
661
  * - `ignored`: well formed, but from someone else (or a deleted account), or in an edited comment: the spec wants one audit row
628
662
  * for each, so they are kept with the reason;
629
- * - `refused`: not strictly a request, report or stop request (`readRunBlocks`), with the author.
630
- * Whom to trust is the caller's to decide, because it takes the forge: a maintainer now for a request or a stop, a login in
663
+ * - `refused`: not strictly a request, report, stop request or answer (`readRunBlocks`), with the author.
664
+ * Whom to trust is the caller's to decide, because it takes the forge: a maintainer now for a request, a stop or an answer, a login in
631
665
  * `agents.runners` or a maintainer for a report (spec 0005). `trust` is asked once per block, with the block, so it can tell them
632
666
  * apart.
633
667
  * @param {RunComment[]} comments
@@ -665,7 +699,7 @@ export function parseRunBlocks(body, opts) {
665
699
  * drops the ones whose author is not a maintainer, or whose comment was edited), or null. Later wins.
666
700
  * @param {RunBlock[]} blocks
667
701
  * @param {string} runId
668
- * @param {'request' | 'report' | 'stop-request'} type
702
+ * @param {'request' | 'report' | 'stop-request' | 'answer'} type
669
703
  * @returns {RunBlock | null}
670
704
  */
671
705
  export function latestBlock(blocks, runId, type) {
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://json-schema.org/draft/2020-12/schema",
3
3
  "$id": "https://github.com/popcorn245/CornField/blob/main/core/agent-contract.schema.json",
4
4
  "title": "cornfield agent contract, version 1",
5
- "description": "The JSON a cornfield-run fenced block holds: a request, a report or a stop request. docs/agent-contract.md says what each means. Checks the shape; a few rules are the validator's alone (the configured profile list, that a date is a real one), and are listed in the docs.",
5
+ "description": "The JSON a cornfield-run fenced block holds: a request, a report, a stop request or an answer. docs/agent-contract.md says what each means. Checks the shape; a few rules are the validator's alone (the configured profile list, that a date is a real one, that a reply has text), and are listed in the docs.",
6
6
  "oneOf": [
7
7
  {
8
8
  "$ref": "#/$defs/request"
@@ -12,6 +12,9 @@
12
12
  },
13
13
  {
14
14
  "$ref": "#/$defs/stopRequest"
15
+ },
16
+ {
17
+ "$ref": "#/$defs/answer"
15
18
  }
16
19
  ],
17
20
  "$defs": {
@@ -227,6 +230,7 @@
227
230
  "enum": [
228
231
  "claimed",
229
232
  "working",
233
+ "waiting",
230
234
  "done",
231
235
  "failed",
232
236
  "stopped"
@@ -285,6 +289,34 @@
285
289
  }
286
290
  }
287
291
  }
292
+ },
293
+ "answer": {
294
+ "description": "A maintainer answering a run that reported waiting: continue, stop (the same as a stop request) or reply with text. The runner decides what it means.",
295
+ "type": "object",
296
+ "additionalProperties": false,
297
+ "required": [
298
+ "state",
299
+ "action"
300
+ ],
301
+ "properties": {
302
+ "state": {
303
+ "const": "answered"
304
+ },
305
+ "action": {
306
+ "enum": [
307
+ "continue",
308
+ "stop",
309
+ "reply"
310
+ ]
311
+ },
312
+ "text": {
313
+ "type": "string",
314
+ "maxLength": 4000,
315
+ "not": {
316
+ "pattern": "(?<![A-Za-z0-9])gh[pousr]_[A-Za-z0-9]{30,}|(?<![A-Za-z0-9])github_pat_[A-Za-z0-9_]{20,}|(?<![A-Za-z0-9])glpat-[A-Za-z0-9_-]{15,}|(?<![A-Za-z0-9])gto-[A-Za-z0-9]{20,}|(?<![A-Za-z0-9])cf_(?:rt|at|nt)_[A-Za-z0-9_-]{20,}|(?<![A-Za-z0-9])sk-(?=[A-Za-z0-9_-]{20})[A-Za-z_-]{0,40}[0-9]|(?<![A-Za-z0-9])AKIA[0-9A-Z]{16}|(?<![A-Za-z0-9])AIza[0-9A-Za-z_-]{35}|(?<![A-Za-z0-9])xox[abprs]-[A-Za-z0-9-]{10,}|(?<![A-Za-z0-9])eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{5,}|-----BEGIN [A-Z ]{0,40}PRIVATE KEY-----|(?<![A-Za-z0-9])[bB][eE][aA][rR][eE][rR][ \\t]+(?=[A-Za-z0-9._~+/=-]{20})[A-Za-z._~+/=-]{0,40}[0-9]|(?<![A-Za-z0-9+.-])[A-Za-z][A-Za-z0-9+.-]{0,31}://[^\\s/@:]+:[^\\s/@]+@"
317
+ }
318
+ }
319
+ }
288
320
  }
289
321
  }
290
322
  }
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.waiting', 'run.answered', '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, answerUrl, answerBody, answerWordsFor, 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,7 +119,9 @@ 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
124
+ runReplies: new Map(), // the reply typed so far for each waiting run, so a repaint (the runs are looked at again) keeps it
123
125
  agent: null, // { opener, refs, posting } while the Start an agent dialog is open
124
126
  };
125
127
 
@@ -206,6 +208,12 @@ async function loadRuns(refresh, { say = true } = {}) {
206
208
  syncRunsPoll();
207
209
  if (ui.runSel) relightRun();
208
210
  const said = say ? changeWords(before, ui.runs.data.runs) : [];
211
+ // 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
212
+ // shown is kept, not worked out again from the last listing: a runner that goes quiet is the same listing judged later
213
+ const was = ui.runnerSaid;
214
+ const is = runnerState(ui.runs.data.runnerPresence, now());
215
+ ui.runnerSaid = is;
216
+ if (say && was && is && was !== is) said.push(runnerWords(ui.runs.data.runnerPresence, now()));
209
217
  if (said.length) announce(said.join('. '));
210
218
  }
211
219
 
@@ -1036,6 +1044,8 @@ function findAgain(el) {
1036
1044
  if (el.dataset.forgeRerun) return `[data-forge-rerun="${el.dataset.forgeRerun}"]`;
1037
1045
  if (el.dataset.forgeAgent) return `[data-forge-agent="${el.dataset.forgeAgent}"]`;
1038
1046
  if (el.dataset.forgeStop) return `[data-forge-stop="${el.dataset.forgeStop}"]`;
1047
+ if (el.dataset.runReply) return `[data-run-reply="${el.dataset.runReply}"]`;
1048
+ if (el.dataset.runAnswer) return `[data-run-answer="${el.dataset.runAnswer}"][data-run-id="${el.dataset.runId}"]`;
1039
1049
  if (el.dataset.runSelect) return `[data-run-select="${el.dataset.runSelect}"]`;
1040
1050
  if (el.dataset.runTimeline) return `[data-run-timeline="${el.dataset.runTimeline}"]`;
1041
1051
  return null;
@@ -1116,6 +1126,7 @@ function paintRuns() {
1116
1126
  note.hidden = !words;
1117
1127
  note.className = `hx-forge-notice${!(ui.runs && ui.runs.error) && ui.runNote && ui.runNote.ok ? ' hx-forge-notice--ok' : ''}`;
1118
1128
  note.textContent = words;
1129
+ paintRunner('forge-runs-runner', data);
1119
1130
  const trig = $('forge-runs-trigger');
1120
1131
  if (trig) {
1121
1132
  const skipped = data ? triggerNotice(data) : '';
@@ -1127,13 +1138,22 @@ function paintRuns() {
1127
1138
  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
1139
  }
1129
1140
 
1141
+ /** 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 */
1142
+ function paintRunner(id, data) {
1143
+ const el = $(id);
1144
+ if (!el) return;
1145
+ const words = data ? runnerWords(data.runnerPresence, now()) : '';
1146
+ el.hidden = !words;
1147
+ el.textContent = words;
1148
+ }
1149
+
1130
1150
  /** What the Runs view needs to know of the page */
1131
1151
  function viewContext() {
1132
1152
  const f = ui.config && ui.config.forge;
1133
1153
  const base = f && safeUrl(f.url) ? f.url.replace(/\/+$/, '') : null;
1134
1154
  return {
1135
1155
  esc: escHtml, safeUrl, forgeName: forgeName(), forgeType: f ? f.type : 'github', repoUrl: base && f.repo ? `${base}/${f.repo}` : null,
1136
- now: now(), nodes: state.nodes, selected: ui.runSel, timelines: ui.runTimelines, busy: !!ui.busy,
1156
+ now: now(), nodes: state.nodes, selected: ui.runSel, timelines: ui.runTimelines, replies: ui.runReplies, busy: !!ui.busy,
1137
1157
  };
1138
1158
  }
1139
1159
 
@@ -1424,6 +1444,7 @@ async function openAgent(ref, opener) {
1424
1444
  if (!ui.agent) return;
1425
1445
  const profiles = (ui.runs && ui.runs.data && ui.runs.data.profiles) || [];
1426
1446
  $('agent-start-about').textContent = `About ${aboutWords(refs)}`;
1447
+ paintRunner('agent-start-runner', ui.runs && ui.runs.data);
1427
1448
  $('agent-kind').innerHTML = KINDS.map(([v, l]) => option(v, l, v === 'code')).join('');
1428
1449
  $('agent-profile').innerHTML = option('', 'No profile', true) + profiles.map((p) => option(p, p, false)).join('');
1429
1450
  $('agent-profile-field').hidden = !profiles.length;
@@ -1529,6 +1550,35 @@ async function stopRun(runId) {
1529
1550
  paint();
1530
1551
  }
1531
1552
 
1553
+ /** Answers a waiting run: Continue, Stop, or a reply with the text typed. One POST, then the runs are read again */
1554
+ async function answerRun(runId, action) {
1555
+ if (ui.busy) return;
1556
+ const text = ui.runReplies.get(runId) || '';
1557
+ if (action === 'reply' && text.trim() === '') {
1558
+ ui.runNote = { text: 'Write a reply first.', ok: false };
1559
+ announce(ui.runNote.text);
1560
+ paint();
1561
+ return;
1562
+ }
1563
+ // Where the focus goes back to once it is sent: the reply field after a reply (empty, for the next one), the button after Continue; while the
1564
+ // buttons are disabled the focus has nowhere to stay, so it is put back by hand. A run that no longer asks (a Stop) gets its Timeline button
1565
+ const back = action === 'reply' ? `[data-run-reply="${runId}"]` : `[data-run-answer="${action}"][data-run-id="${runId}"]`;
1566
+ ui.busy = 'answer';
1567
+ ui.runNote = null;
1568
+ announce(`Answering ${runId}`);
1569
+ paint();
1570
+ const res = await post(answerUrl(runId), answerBody(action, text));
1571
+ ui.busy = '';
1572
+ if (res.ok && action === 'reply') ui.runReplies.delete(runId);
1573
+ ui.runNote = { text: answerWordsFor(res.status, res.body, runId, action), ok: res.ok };
1574
+ announce(ui.runNote.text);
1575
+ await loadRuns(false, { say: false });
1576
+ paint();
1577
+ const panel = $('forge-panel');
1578
+ const to = panel && [back, `[data-run-timeline="${runId}"]`].map((sel) => panel.querySelector(sel)).find((el) => el && !el.disabled);
1579
+ if (to && to !== document.activeElement) to.focus();
1580
+ }
1581
+
1532
1582
  // ---------------------------------------------------------------------------
1533
1583
  // Opening and closing
1534
1584
  // ---------------------------------------------------------------------------
@@ -1660,6 +1710,8 @@ function onClick(e) {
1660
1710
  if (agent) { openAgent(agent.dataset.forgeAgent, `[data-forge-agent="${agent.dataset.forgeAgent}"]`); return; }
1661
1711
  const stop = t.closest('[data-forge-stop]');
1662
1712
  if (stop) { stopRun(stop.dataset.forgeStop); return; }
1713
+ const answer = t.closest('[data-run-answer]');
1714
+ if (answer) { answerRun(answer.dataset.runId, answer.dataset.runAnswer); return; }
1663
1715
  const pick = t.closest('[data-run-select]');
1664
1716
  if (pick) { selectRun(pick.dataset.runSelect); return; }
1665
1717
  const timeline = t.closest('[data-run-timeline]');
@@ -1724,6 +1776,7 @@ function onChange(e) {
1724
1776
  }
1725
1777
 
1726
1778
  function onInput(e) {
1779
+ if (e.target.dataset && e.target.dataset.runReply) { ui.runReplies.set(e.target.dataset.runReply, e.target.value); return; }
1727
1780
  if (e.target.id !== 'forge-text') return;
1728
1781
  ui.filters.text = e.target.value;
1729
1782
  filtersChanged(false);
@@ -1733,6 +1786,7 @@ function onInput(e) {
1733
1786
 
1734
1787
  /** Escape anywhere in the panel closes it, and the button has the focus again (a field's own Escape comes first) */
1735
1788
  function onKey(e) {
1789
+ if (e.key === 'Enter' && e.target.dataset && e.target.dataset.runReply && !e.defaultPrevented) { e.preventDefault(); answerRun(e.target.dataset.runReply, 'reply'); return; }
1736
1790
  if (e.key === 'Enter' && e.target.id === 'notes-tag' && !e.defaultPrevented) { e.preventDefault(); postDraft(); return; }
1737
1791
  if (e.key === 'Escape' && !e.defaultPrevented && ui.notes.confirm && e.target.closest && e.target.closest('#notes-confirm')) {
1738
1792
  e.preventDefault();
@@ -1830,5 +1884,5 @@ export function resetForgePanelForTests(clock = () => Date.now()) {
1830
1884
  runsTimer = 0;
1831
1885
  pageAway = false;
1832
1886
  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 });
1887
+ Object.assign(ui, { runSel: null, runTimelines: new Set(), runReplies: new Map(), 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
1888
  }
@@ -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>
@@ -11,6 +11,7 @@ import { relativeTime } from './review-model.js';
11
11
  export const RUNS_URL = '/api/agent-runs';
12
12
  export const runsUrl = (follow) => (follow ? `${RUNS_URL}?follow=1` : RUNS_URL);
13
13
  export const stopUrl = (runId) => `${RUNS_URL}/${encodeURIComponent(runId)}/stop`;
14
+ export const answerUrl = (runId) => `${RUNS_URL}/${encodeURIComponent(runId)}/answer`;
14
15
 
15
16
  /** The kinds of run (the contract's), and what each asks the runner for */
16
17
  export const KINDS = Object.freeze([
@@ -32,7 +33,7 @@ export function aboutWords(refs) {
32
33
  /** The state of a run, said short */
33
34
  export function statusWords(run) {
34
35
  const words = {
35
- requested: 'Requested', claimed: 'Claimed', working: 'Working', done: 'Done', failed: 'Failed', stopped: 'Stopped',
36
+ requested: 'Requested', claimed: 'Claimed', working: 'Working', waiting: 'Waiting', done: 'Done', failed: 'Failed', stopped: 'Stopped',
36
37
  'stop-requested': 'Stop requested', quiet: 'Quiet', merged: 'Merged', closed: 'Closed',
37
38
  };
38
39
  return words[run.status] || run.status;
@@ -44,6 +45,9 @@ export function statusWhy(run) {
44
45
  case 'quiet': return 'Nothing reported or pushed for a while, so it no longer counts toward the limit. A report or a push brings it back.';
45
46
  case 'stop-requested': return `${run.stopRequested && run.stopRequested.by ? run.stopRequested.by : 'A maintainer'} asked it to stop. The runner decides what that means; this stays until it says stopped, or the run goes quiet.`;
46
47
  case 'requested': return 'Waiting for a runner to pick it up. cornfield only asks; it starts nothing.';
48
+ case 'waiting': return run.answer
49
+ ? `${run.answer.by || 'A maintainer'} answered: ${answerWords(run.answer)}. The runner picks the answer up and goes on; answer again to change it until it does.`
50
+ : 'The runner stopped to ask and goes on once a maintainer answers: Continue, Stop, or a reply.';
47
51
  default: return '';
48
52
  }
49
53
  }
@@ -85,12 +89,62 @@ export function triggerNotice(data) {
85
89
  /** Whether a Stop is offered: the run is open and nobody has asked it to stop yet */
86
90
  export const canStop = (run) => run.open === true && !run.stopRequested;
87
91
 
92
+ /** Whether the run asks for an answer (Continue, Stop, Reply): the runner reported `waiting` and nobody has asked it to stop */
93
+ export const canAnswer = (run) => run.open === true && run.status === 'waiting' && !run.stopRequested;
94
+
95
+ /** An answer, said short: "continue", "stop", "reply: use the second plan" */
96
+ export function answerWords(answer) {
97
+ if (!answer) return '';
98
+ return answer.action === 'reply' ? `reply: ${answer.text || ''}`.trim() : answer.action;
99
+ }
100
+
101
+ /** The body of an answer: the action, and a reply's text (trimmed); Continue and Stop carry none */
102
+ export function answerBody(action, text) {
103
+ return action === 'reply' ? { action, text: (text || '').trim() } : { action };
104
+ }
105
+
106
+ /** What an answer came to */
107
+ export function answerWordsFor(status, body, runId, action) {
108
+ if (status === null) return 'cornfield did not answer; nothing was sent.';
109
+ if (status === 401) return 'Your sign-in has ended. Sign in again to answer a run.';
110
+ if (body && body.ok) return action === 'stop' ? `Asked ${runId} to stop. The runner decides what that means.` : `Answered ${runId}: ${action}. The runner picks it up and goes on.`;
111
+ return (body && body.error) || `The answer was refused (${status}).`;
112
+ }
113
+
88
114
  /** The summary line over the list: "2 open of 3 allowed, 5 runs" */
89
115
  export function runsStatus(data) {
90
116
  const n = data.runs.length;
91
117
  return `${data.open} open of ${data.maxOpen} allowed, ${n} ${n === 1 ? 'run' : 'runs'}`;
92
118
  }
93
119
 
120
+ /** "20 s", "5 min", "2 h": how long ago, short enough for a line */
121
+ function agoShort(ms) {
122
+ const s = Math.max(0, Math.round(ms / 1000));
123
+ if (s < 60) return `${s} s`;
124
+ if (s < 3600) return `${Math.floor(s / 60)} min`;
125
+ return `${Math.floor(s / 3600)} h`;
126
+ }
127
+
128
+ /**
129
+ * Whether a runner is there, from the runs listing's `runnerPresence` (issue #99): 'online', 'offline' (it polled once, not lately), 'none' (no
130
+ * 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.
131
+ */
132
+ export function runnerState(presence, nowMs) {
133
+ if (!presence || presence.transport !== 'pull') return null;
134
+ const seen = typeof presence.lastSeen === 'string' ? Date.parse(presence.lastSeen) : NaN;
135
+ if (!Number.isFinite(seen)) return 'none';
136
+ return nowMs - seen < (presence.quietAfterMs || 180_000) ? 'online' : 'offline';
137
+ }
138
+
139
+ /** 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 */
140
+ export function runnerWords(presence, nowMs) {
141
+ const state = runnerState(presence, nowMs);
142
+ if (state === 'online') return `Runner online · last seen ${agoShort(nowMs - Date.parse(presence.lastSeen))} ago`;
143
+ if (state === 'offline') return `No runner has polled for ${agoShort(nowMs - Date.parse(presence.lastSeen))}: a queued run will wait`;
144
+ if (state === 'none') return 'No runner has polled yet: a queued run will wait';
145
+ return '';
146
+ }
147
+
94
148
  /**
95
149
  * 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
150
  * @param {{ kind: string, profile?: string, brief?: string, refs: object, force?: boolean }} input
@@ -206,6 +260,7 @@ export function timelineWords(entry) {
206
260
  case 'pull-opened': return { what: `Opened pull request ${entry.ref || ''}${by}`.trim(), note: '' };
207
261
  case 'checks': return { what: { success: 'Checks passed', failure: 'Checks failed', running: 'Checks running', none: 'No checks' }[entry.ref] || 'Checks changed', note: '' };
208
262
  case 'stop-requested': return { what: `Asked to stop${by}`, note: entry.note || '' };
263
+ case 'answered': return { what: `Answered ${entry.ref || ''}${by}`.replace(/\s+/g, ' ').trim(), note: entry.note || '' };
209
264
  case 'merged': return { what: `Landed: pull request ${entry.ref || ''} merged`, note: '' };
210
265
  case 'closed': return { what: `Pull request ${entry.ref || ''} closed without landing`, note: '' };
211
266
  case 'quiet': return { what: 'Went quiet: nothing reported or pushed for a while', note: '' };