cornfield 0.20.0 → 0.21.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 +7 -2
- package/core/agent-contract.schema.json +4 -0
- package/explorer/explorer.css +3 -0
- package/explorer/forge-panel.js +99 -21
- package/explorer/index.html +7 -1
- package/explorer/runs-model.js +47 -11
- package/explorer/runs-view.js +22 -6
- package/package.json +1 -1
- package/server/agent-api.js +11 -3
- package/server/agent-runs.js +50 -10
package/core/agent-contract.js
CHANGED
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
* @typedef {{ issue?: number, proposal?: string, pull?: number, thread?: number }} RunRefs
|
|
41
41
|
* @typedef {{ minutes?: number, turns?: number, cost?: number, tokens?: number }} RunLimits
|
|
42
42
|
* @typedef {{ version: 1, runId: string, kind: RunKind, profile?: string, refs: RunRefs, branch?: string, brief: string,
|
|
43
|
-
* limits?: RunLimits, nodes?: string[], requestedBy: string, requestedAt: string, trigger?: { event: 'spec.approved' | 'build.opened' | 'thread.message', by: string, ref: string } }} RunRequest
|
|
43
|
+
* limits?: RunLimits, nodes?: string[], requestedBy: string, requestedAt: string, retryOf?: string, trigger?: { event: 'spec.approved' | 'build.opened' | 'thread.message', by: string, ref: string } }} RunRequest
|
|
44
44
|
* @typedef {'claimed' | 'working' | 'waiting' | 'done' | 'failed' | 'stopped'} ReportState
|
|
45
45
|
* @typedef {{ state: ReportState, note?: string, url?: string, tokens?: number, cost?: number }} RunReport
|
|
46
46
|
* @typedef {{ state: 'stop-requested', note?: string }} StopRequest
|
|
@@ -89,7 +89,7 @@ export const RUN_TAG = 'cornfield-run';
|
|
|
89
89
|
/** The key of the trailer */
|
|
90
90
|
export const TRAILER_KEY = 'Cornfield-Run';
|
|
91
91
|
|
|
92
|
-
const REQUEST_KEYS = ['version', 'runId', 'kind', 'profile', 'refs', 'branch', 'brief', 'limits', 'nodes', 'requestedBy', 'requestedAt', 'trigger'];
|
|
92
|
+
const REQUEST_KEYS = ['version', 'runId', 'kind', 'profile', 'refs', 'branch', 'brief', 'limits', 'nodes', 'requestedBy', 'requestedAt', 'retryOf', 'trigger'];
|
|
93
93
|
const TRIGGER_KEYS = ['event', 'by', 'ref'];
|
|
94
94
|
/** The events an opt-in trigger may fire on (`agents.on`, spec 0005 D10): each is something a maintainer did */
|
|
95
95
|
export const TRIGGER_EVENTS = Object.freeze(['spec.approved', 'build.opened', 'thread.message']);
|
|
@@ -345,6 +345,10 @@ export function validateRequest(body, { profiles } = {}) {
|
|
|
345
345
|
}
|
|
346
346
|
}
|
|
347
347
|
|
|
348
|
+
if (body.retryOf !== undefined) {
|
|
349
|
+
if (!isRunId(body.retryOf)) return no('"retryOf" is the run id of the run this one starts again, like run-01JC8Z3Q5M7VXK2RT9N4B6HDEF.');
|
|
350
|
+
}
|
|
351
|
+
|
|
348
352
|
if (body.nodes !== undefined) {
|
|
349
353
|
if (!Array.isArray(body.nodes)) return no('"nodes" is a list of node ids.');
|
|
350
354
|
if (body.nodes.length > MAX_NODES) return no(`"nodes" has at most ${MAX_NODES} ids.`);
|
|
@@ -369,6 +373,7 @@ export function validateRequest(body, { profiles } = {}) {
|
|
|
369
373
|
if (body.nodes !== undefined) value.nodes = [...body.nodes];
|
|
370
374
|
value.requestedBy = body.requestedBy;
|
|
371
375
|
value.requestedAt = body.requestedAt;
|
|
376
|
+
if (body.retryOf !== undefined) value.retryOf = body.retryOf;
|
|
372
377
|
if (body.trigger !== undefined) {
|
|
373
378
|
if (!isObject(body.trigger)) return no('"trigger" is { event, by, ref }: what caused an automatic request.');
|
|
374
379
|
const triggerKeys = keyProblem(body.trigger, TRIGGER_KEYS, '"trigger"');
|
|
@@ -190,6 +190,10 @@
|
|
|
190
190
|
"type": "string",
|
|
191
191
|
"pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,3})?Z$"
|
|
192
192
|
},
|
|
193
|
+
"retryOf": {
|
|
194
|
+
"description": "Only on a request that starts again on an earlier run that failed or was stopped, or a request a runner refused: that run's id. A record, never an instruction; cornfield checks it names a run of the same repo that failed or was stopped.",
|
|
195
|
+
"$ref": "#/$defs/runId"
|
|
196
|
+
},
|
|
193
197
|
"trigger": {
|
|
194
198
|
"description": "Only on an automatic request (agents.on): what caused it. A maintainer's act, never a run's output.",
|
|
195
199
|
"type": "object",
|
package/explorer/explorer.css
CHANGED
|
@@ -825,6 +825,9 @@ button.hx-proposal-item:focus-visible { outline: 2px solid var(--hx-indigo); out
|
|
|
825
825
|
.hx-forge-filters { display: grid; grid-template-columns: 1fr 1fr; gap: 6px 8px; }
|
|
826
826
|
.hx-forge-field { display: flex; flex-direction: column; gap: 2px; min-width: 0; font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: var(--hx-slate-400); }
|
|
827
827
|
.hx-forge-field--text { grid-column: 1 / -1; }
|
|
828
|
+
/* The Start dialog's four limits: two a row, under their legend */
|
|
829
|
+
.hx-forge-limits { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px 8px; margin: 0; padding: 0; border: 0; }
|
|
830
|
+
.hx-forge-limits > legend { padding: 0 0 4px; }
|
|
828
831
|
.hx-forge-select, .hx-forge-input { width: 100%; min-width: 0; padding: 5px 8px; border-radius: 8px; border: 1px solid var(--hx-line); background: var(--hx-well); color: var(--hx-ink); font: inherit; font-size: 12px; font-weight: 400; text-transform: none; letter-spacing: 0; user-select: text; }
|
|
829
832
|
.hx-forge-input::placeholder { color: var(--hx-slate-500); }
|
|
830
833
|
.hx-forge-input:focus-visible { outline: 2px solid var(--hx-indigo); outline-offset: 2px; }
|
package/explorer/forge-panel.js
CHANGED
|
@@ -69,7 +69,7 @@ import { relativeTime } from './review-model.js';
|
|
|
69
69
|
import { LAYER_DEFS, toggleLayer } from './layers.js';
|
|
70
70
|
import { WORK_URL, groupWork, filterGroups, groupWords, workStatus, markWords } from './agents-model.js';
|
|
71
71
|
import {
|
|
72
|
-
RUNS_URL, runsUrl, stopUrl, runOnThread, threadRunWords, runTone, answerUrl, answerBody, answerWordsFor, KINDS, aboutWords, statusWords, statusWhy, runMeta, canStop, runsStatus, runnerState, runnerWords, triggerNotice, totalsLines, handLines,
|
|
72
|
+
RUNS_URL, runsUrl, stopUrl, runOnThread, threadRunWords, canRetry, retryRefs, retryWords, limitsFromFields, defaultLimits, LIMIT_KEYS, briefUrl, runTone, answerUrl, answerBody, answerWordsFor, KINDS, aboutWords, statusWords, statusWhy, runMeta, canStop, runsStatus, runnerState, runnerWords, triggerNotice, totalsLines, handLines, startBody, startWords, stopWords, confirmStartWords, litOfRun, changeWords,
|
|
73
73
|
} from './runs-model.js';
|
|
74
74
|
import { runsHtml, totalsHtml } from './runs-view.js';
|
|
75
75
|
import { setRunsOnMap, clearRunsOnMap } from './runs-map.js';
|
|
@@ -122,7 +122,8 @@ const ui = {
|
|
|
122
122
|
runnerSaid: null, // the runner state last shown ('online', 'offline', 'none'; null off the pull transport), so a change is said once
|
|
123
123
|
runTimelines: new Set(), // the runs whose timeline is open
|
|
124
124
|
runReplies: new Map(), // the reply typed so far for each waiting run, so a repaint (the runs are looked at again) keeps it
|
|
125
|
-
agent: null, // { opener, refs, posting } while the Start an agent dialog is open
|
|
125
|
+
agent: null, // { opener, refs, posting, retryOf, filled } while the Start an agent dialog is open
|
|
126
|
+
retrying: false, // a Start again reading its run's whole brief, so a second click does nothing
|
|
126
127
|
};
|
|
127
128
|
|
|
128
129
|
/** The Release notes view: the draft loaded for a tag, and where the confirm step is */
|
|
@@ -1052,6 +1053,7 @@ function findAgain(el) {
|
|
|
1052
1053
|
if (el.dataset.forgeRerun) return `[data-forge-rerun="${el.dataset.forgeRerun}"]`;
|
|
1053
1054
|
if (el.dataset.forgeAgent) return `[data-forge-agent="${el.dataset.forgeAgent}"]`;
|
|
1054
1055
|
if (el.dataset.forgeStop) return `[data-forge-stop="${el.dataset.forgeStop}"]`;
|
|
1056
|
+
if (el.dataset.forgeRetry) return `[data-forge-retry="${el.dataset.forgeRetry}"]`;
|
|
1055
1057
|
if (el.dataset.runReply) return `[data-run-reply="${el.dataset.runReply}"]`;
|
|
1056
1058
|
if (el.dataset.runAnswer) return `[data-run-answer="${el.dataset.runAnswer}"][data-run-id="${el.dataset.runId}"]`;
|
|
1057
1059
|
if (el.dataset.runSelect) return `[data-run-select="${el.dataset.runSelect}"]`;
|
|
@@ -1451,25 +1453,37 @@ function keepFocusInAgent(e) {
|
|
|
1451
1453
|
if (ui.agent && el && !el.contains(e.target)) $('agent-kind').focus();
|
|
1452
1454
|
}
|
|
1453
1455
|
|
|
1454
|
-
/**
|
|
1455
|
-
|
|
1456
|
+
/**
|
|
1457
|
+
* Opens the Start an agent dialog for `issue:<n>` or `proposal:<slug>`; the focus goes to the first field. The limit fields hold what the request
|
|
1458
|
+
* starts from (the config's, for the profile). With `again` (a run that failed or was stopped) it is **Start again**: the same kind, refs,
|
|
1459
|
+
* profile, brief and limits filled in, all editable, and the request will carry `retryOf`. `brief` is that run's whole brief when the list's was cut
|
|
1460
|
+
*/
|
|
1461
|
+
async function openAgent(ref, opener, again = null, brief = null) {
|
|
1456
1462
|
if (!agentEl() || ui.agent) return;
|
|
1457
1463
|
const at = ref.indexOf(':');
|
|
1458
1464
|
const type = ref.slice(0, at);
|
|
1459
1465
|
const value = ref.slice(at + 1);
|
|
1460
|
-
const refs = type === 'proposal' ? { proposal: value } : { issue: Number(value) };
|
|
1461
|
-
ui.agent = { opener, refs, posting: false };
|
|
1466
|
+
const refs = again ? retryRefs(again) : type === 'proposal' ? { proposal: value } : { issue: Number(value) };
|
|
1467
|
+
ui.agent = { opener, refs, posting: false, retryOf: again ? again.runId : null };
|
|
1462
1468
|
// The profiles the config lists come with the runs: asked for if the Agents tab has not been opened yet
|
|
1463
1469
|
if (!ui.runs) { await loadRuns(false); if (ui.kind === 'work') paint(); }
|
|
1464
1470
|
if (!ui.agent) return;
|
|
1465
1471
|
const profiles = (ui.runs && ui.runs.data && ui.runs.data.profiles) || [];
|
|
1466
1472
|
$('agent-start-about').textContent = `About ${aboutWords(refs)}`;
|
|
1467
1473
|
paintRunner('agent-start-runner', ui.runs && ui.runs.data);
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
$('agent-
|
|
1474
|
+
const kind = again ? again.kind : 'code';
|
|
1475
|
+
// The old run's profile stays on offer even if the config no longer lists it: the server then says so, in its words
|
|
1476
|
+
const shown = again && again.profile && !profiles.includes(again.profile) ? [...profiles, again.profile] : profiles;
|
|
1477
|
+
$('agent-kind').innerHTML = KINDS.map(([v, l]) => option(v, l, v === kind)).join('');
|
|
1478
|
+
$('agent-profile').innerHTML = option('', 'No profile', !(again && again.profile)) + shown.map((p) => option(p, p, !!again && p === again.profile)).join('');
|
|
1479
|
+
$('agent-profile-field').hidden = !shown.length;
|
|
1480
|
+
$('agent-profile').value = again && again.profile ? again.profile : ''; // as well as `selected`, which not every DOM honours
|
|
1481
|
+
$('agent-start-title').textContent = again ? 'Start again' : 'Start an agent';
|
|
1482
|
+
const note = $('agent-retry-note');
|
|
1483
|
+
note.hidden = !again;
|
|
1484
|
+
note.textContent = again ? retryWords(again) : '';
|
|
1485
|
+
fillLimits(again ? again.limits || {} : limitDefaultsNow());
|
|
1486
|
+
$('agent-brief').value = brief ?? (again && typeof again.brief === 'string' ? again.brief : '');
|
|
1473
1487
|
$('agent-force').checked = false;
|
|
1474
1488
|
$('agent-force-field').hidden = true;
|
|
1475
1489
|
$('agent-start-msg').hidden = true;
|
|
@@ -1482,16 +1496,54 @@ async function openAgent(ref, opener) {
|
|
|
1482
1496
|
document.addEventListener('focusin', keepFocusInAgent);
|
|
1483
1497
|
agentEl().hidden = false;
|
|
1484
1498
|
$('agent-kind').focus();
|
|
1485
|
-
announce(
|
|
1499
|
+
announce(`${again ? 'Start again' : 'Start an agent'} on ${aboutWords(refs)}. ${confirmStartWords(refs, forgeName())}`);
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
/** "Start again" on a run that failed or was stopped. A brief the list shows cut is read whole first: the dialog never starts from part of one */
|
|
1503
|
+
async function startAgain(runId) {
|
|
1504
|
+
const run = ui.runs && ui.runs.data ? ui.runs.data.runs.find((r) => r.runId === runId) : null;
|
|
1505
|
+
if (!run || !canRetry(run) || ui.agent || ui.retrying) return;
|
|
1506
|
+
let brief = null;
|
|
1507
|
+
if (run.briefCut) {
|
|
1508
|
+
ui.retrying = true;
|
|
1509
|
+
const res = await request(briefUrl(runId), false);
|
|
1510
|
+
ui.retrying = false;
|
|
1511
|
+
if (!res.ok || typeof res.body.brief !== 'string') {
|
|
1512
|
+
ui.runNote = { text: `The brief of ${runId} could not be read, so Start again did not open: ${errorWords(res.status, res.body)}`, ok: false };
|
|
1513
|
+
paint();
|
|
1514
|
+
announce(ui.runNote.text);
|
|
1515
|
+
return;
|
|
1516
|
+
}
|
|
1517
|
+
brief = res.body.brief;
|
|
1518
|
+
}
|
|
1519
|
+
const about = run.refs.proposal != null ? `proposal:${run.refs.proposal}` : `issue:${run.refs.issue ?? run.refs.thread}`;
|
|
1520
|
+
openAgent(about, `[data-forge-retry="${runId}"]`, run, brief);
|
|
1486
1521
|
}
|
|
1487
1522
|
|
|
1488
|
-
/**
|
|
1489
|
-
function
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1523
|
+
/** Takes the person to another run of the list: the row scrolls into view and has the focus */
|
|
1524
|
+
function goToRun(runId) {
|
|
1525
|
+
bringIntoView([...document.querySelectorAll('#forge-runs-list [data-run]')].find((r) => r.dataset.run === runId));
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
/** The limits the config gives a request under the chosen profile */
|
|
1529
|
+
const limitDefaultsNow = () => defaultLimits(ui.runs && ui.runs.data && ui.runs.data.limits, $('agent-profile-field').hidden ? '' : $('agent-profile').value);
|
|
1530
|
+
/** What the four limit fields hold, as text */
|
|
1531
|
+
const limitFields = () => Object.fromEntries(LIMIT_KEYS.map((k) => [k, $(`agent-limit-${k}`).value]));
|
|
1532
|
+
|
|
1533
|
+
/** Fills the four limit fields (blank where `limits` has none) and remembers what was filled */
|
|
1534
|
+
function fillLimits(limits) {
|
|
1535
|
+
for (const k of LIMIT_KEYS) {
|
|
1536
|
+
const field = $(`agent-limit-${k}`);
|
|
1537
|
+
field.value = limits && limits[k] != null ? String(limits[k]) : '';
|
|
1538
|
+
field.removeAttribute('aria-invalid');
|
|
1539
|
+
field.removeAttribute('aria-describedby');
|
|
1540
|
+
}
|
|
1541
|
+
if (ui.agent) ui.agent.filled = JSON.stringify(limitFields());
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
/** Another profile: its limits fill the fields, unless the person has typed in them */
|
|
1545
|
+
function onAgentProfile() {
|
|
1546
|
+
if (ui.agent && ui.agent.filled === JSON.stringify(limitFields())) fillLimits(limitDefaultsNow());
|
|
1495
1547
|
}
|
|
1496
1548
|
|
|
1497
1549
|
/** Closes the dialog; the focus goes back to the button that opened it unless told not to */
|
|
@@ -1517,8 +1569,30 @@ async function submitAgent(e) {
|
|
|
1517
1569
|
go.setAttribute('aria-busy', 'true');
|
|
1518
1570
|
go.textContent = 'Asking …';
|
|
1519
1571
|
$('agent-start-msg').hidden = true;
|
|
1572
|
+
const again = ui.agent.retryOf;
|
|
1573
|
+
const fields = limitFields();
|
|
1574
|
+
const limits = limitsFromFields(fields);
|
|
1575
|
+
// Each field that is not a number above zero is marked, and the first has the focus; the message says why
|
|
1576
|
+
const wrong = LIMIT_KEYS.filter((k) => limitsFromFields({ [k]: fields[k] }) === null);
|
|
1577
|
+
for (const k of LIMIT_KEYS) {
|
|
1578
|
+
const field = $(`agent-limit-${k}`);
|
|
1579
|
+
if (wrong.includes(k)) { field.setAttribute('aria-invalid', 'true'); field.setAttribute('aria-describedby', 'agent-start-msg'); } else { field.removeAttribute('aria-invalid'); field.removeAttribute('aria-describedby'); }
|
|
1580
|
+
}
|
|
1581
|
+
if (limits === null) {
|
|
1582
|
+
ui.agent.posting = false;
|
|
1583
|
+
go.disabled = false;
|
|
1584
|
+
go.removeAttribute('aria-busy');
|
|
1585
|
+
go.textContent = 'Ask the runner';
|
|
1586
|
+
const bad = $('agent-start-msg');
|
|
1587
|
+
bad.textContent = `A limit is a number above zero, or blank for the config's (${wrong.join(', ')}).`;
|
|
1588
|
+
bad.hidden = false;
|
|
1589
|
+
$(`agent-limit-${wrong[0]}`).focus();
|
|
1590
|
+
announce(bad.textContent);
|
|
1591
|
+
return;
|
|
1592
|
+
}
|
|
1520
1593
|
const res = await post(RUNS_URL, startBody({
|
|
1521
1594
|
kind: $('agent-kind').value, profile: $('agent-profile-field').hidden ? '' : $('agent-profile').value, brief: $('agent-brief').value, refs: ui.agent.refs, force: $('agent-force').checked,
|
|
1595
|
+
limits, ...(again ? { retryOf: again } : {}),
|
|
1522
1596
|
}));
|
|
1523
1597
|
if (!ui.agent) return;
|
|
1524
1598
|
ui.agent.posting = false;
|
|
@@ -1823,6 +1897,10 @@ function onClick(e) {
|
|
|
1823
1897
|
if (agent) { openAgent(agent.dataset.forgeAgent, `[data-forge-agent="${agent.dataset.forgeAgent}"]`); return; }
|
|
1824
1898
|
const stop = t.closest('[data-forge-stop]');
|
|
1825
1899
|
if (stop) { stopRun(stop.dataset.forgeStop); return; }
|
|
1900
|
+
const retry = t.closest('[data-forge-retry]');
|
|
1901
|
+
if (retry) { startAgain(retry.dataset.forgeRetry); return; }
|
|
1902
|
+
const goto = t.closest('[data-run-goto]');
|
|
1903
|
+
if (goto) { goToRun(goto.dataset.runGoto); return; }
|
|
1826
1904
|
const answer = t.closest('[data-run-answer]');
|
|
1827
1905
|
if (answer) { answerRun(answer.dataset.runId, answer.dataset.runAnswer); return; }
|
|
1828
1906
|
const pick = t.closest('[data-run-select]');
|
|
@@ -1956,7 +2034,7 @@ export function initForgePanel(config, opts = {}) {
|
|
|
1956
2034
|
agent.addEventListener('click', onAgentClick);
|
|
1957
2035
|
agent.addEventListener('keydown', onAgentKey);
|
|
1958
2036
|
agent.querySelector('form').addEventListener('submit', submitAgent);
|
|
1959
|
-
$('agent-profile').addEventListener('change',
|
|
2037
|
+
$('agent-profile').addEventListener('change', onAgentProfile);
|
|
1960
2038
|
}
|
|
1961
2039
|
const confirm = confirmEl();
|
|
1962
2040
|
if (confirm) {
|
|
@@ -1998,5 +2076,5 @@ export function resetForgePanelForTests(clock = () => Date.now()) {
|
|
|
1998
2076
|
runsTimer = 0;
|
|
1999
2077
|
pageAway = false;
|
|
2000
2078
|
clearRunsOnMap();
|
|
2001
|
-
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 });
|
|
2079
|
+
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, retrying: false });
|
|
2002
2080
|
}
|
package/explorer/index.html
CHANGED
|
@@ -365,10 +365,16 @@
|
|
|
365
365
|
<h2 id="agent-start-title" class="hx-confirm-title">Start an agent</h2>
|
|
366
366
|
<p id="agent-start-about" class="hx-forge-meta"></p>
|
|
367
367
|
<p id="agent-start-runner" class="hx-forge-meta" hidden></p>
|
|
368
|
+
<p id="agent-retry-note" class="hx-forge-meta" hidden></p>
|
|
368
369
|
<form id="agent-start-form" class="hx-forge-confirm" novalidate>
|
|
369
370
|
<label class="hx-forge-field">Kind of run<select id="agent-kind" class="hx-forge-select"></select></label>
|
|
370
371
|
<label id="agent-profile-field" class="hx-forge-field" hidden>Profile<select id="agent-profile" class="hx-forge-select"></select></label>
|
|
371
|
-
<
|
|
372
|
+
<fieldset id="agent-limits-edit" class="hx-forge-field hx-forge-limits"><legend>Limits, hints for the runner (one left blank takes the config's, if any)</legend>
|
|
373
|
+
<label class="hx-forge-field">Minutes<input type="number" id="agent-limit-minutes" class="hx-forge-input" min="0" step="any" inputmode="decimal" /></label>
|
|
374
|
+
<label class="hx-forge-field">Turns<input type="number" id="agent-limit-turns" class="hx-forge-input" min="0" step="1" inputmode="numeric" /></label>
|
|
375
|
+
<label class="hx-forge-field">Cost<input type="number" id="agent-limit-cost" class="hx-forge-input" min="0" step="any" inputmode="decimal" /></label>
|
|
376
|
+
<label class="hx-forge-field">Tokens<input type="number" id="agent-limit-tokens" class="hx-forge-input" min="0" step="1" inputmode="numeric" /></label>
|
|
377
|
+
</fieldset>
|
|
372
378
|
<label class="hx-forge-field">Brief for the runner<textarea id="agent-brief" class="hx-forge-preview" rows="6" maxlength="20000" spellcheck="true"></textarea></label>
|
|
373
379
|
<label id="agent-force-field" class="hx-forge-toggle" hidden><input type="checkbox" id="agent-force" /> Ask for another run on purpose</label>
|
|
374
380
|
<p id="agent-start-words" class="hx-confirm-note"></p>
|
package/explorer/runs-model.js
CHANGED
|
@@ -12,6 +12,8 @@ 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
14
|
export const answerUrl = (runId) => `${RUNS_URL}/${encodeURIComponent(runId)}/answer`;
|
|
15
|
+
/** A run's whole brief, for Start again: the list carries its first 2000 characters */
|
|
16
|
+
export const briefUrl = (runId) => `${RUNS_URL}/${encodeURIComponent(runId)}/brief`;
|
|
15
17
|
|
|
16
18
|
/** The kinds of run (the contract's), and what each asks the runner for */
|
|
17
19
|
export const KINDS = Object.freeze([
|
|
@@ -202,29 +204,61 @@ export function runnerWords(presence, nowMs) {
|
|
|
202
204
|
|
|
203
205
|
/**
|
|
204
206
|
* 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.
|
|
205
|
-
* @param {{ kind: string, profile?: string, brief?: string, refs: object, force?: boolean }} input
|
|
207
|
+
* @param {{ kind: string, profile?: string, brief?: string, refs: object, force?: boolean, limits?: object, retryOf?: string }} input `limits`: the
|
|
208
|
+
* dialog's fields, blanks left out (the server fills those from the config); `retryOf` only with Start again
|
|
206
209
|
*/
|
|
207
|
-
export function startBody({ kind, profile, brief, refs, force }) {
|
|
210
|
+
export function startBody({ kind, profile, brief, refs, force, limits, retryOf }) {
|
|
208
211
|
const out = { kind, refs, brief: (brief || '').trim() };
|
|
209
212
|
if (profile) out.profile = profile;
|
|
213
|
+
if (limits && Object.keys(limits).length) out.limits = limits;
|
|
214
|
+
if (retryOf) out.retryOf = retryOf;
|
|
210
215
|
if (force) out.force = true;
|
|
211
216
|
return out;
|
|
212
217
|
}
|
|
213
218
|
|
|
214
|
-
|
|
219
|
+
/** The four limits a request may carry, in the order the Start dialog's fields show them */
|
|
220
|
+
export const LIMIT_KEYS = Object.freeze(['minutes', 'turns', 'cost', 'tokens']);
|
|
215
221
|
|
|
216
222
|
/**
|
|
217
|
-
* The limits a request for `profile`
|
|
218
|
-
* over them key by key (as core/config.js `limitDefaults
|
|
223
|
+
* The limits a request for `profile` starts from, to fill the Start dialog's fields: the config's flat `agents.limits`, then the profile's own
|
|
224
|
+
* over them key by key (as core/config.js `limitDefaults`, which the server applies to a field left blank). `{}` when the config sets none.
|
|
219
225
|
* @param {Record<string, any> | undefined} limits the `limits` of `GET /api/agent-runs`
|
|
220
226
|
* @param {string} profile '' for none
|
|
221
227
|
*/
|
|
222
|
-
export function
|
|
223
|
-
if (!limits || typeof limits !== 'object'
|
|
224
|
-
const
|
|
225
|
-
const
|
|
226
|
-
const
|
|
227
|
-
return
|
|
228
|
+
export function defaultLimits(limits, profile) {
|
|
229
|
+
if (!limits || typeof limits !== 'object') return {};
|
|
230
|
+
const own = profile && !LIMIT_KEYS.includes(profile) && limits[profile] && typeof limits[profile] === 'object' ? limits[profile] : {};
|
|
231
|
+
const out = {};
|
|
232
|
+
for (const k of LIMIT_KEYS) { const n = own[k] ?? limits[k]; if (typeof n === 'number') out[k] = n; }
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Start again is offered on a run that failed (a runner's refusal is a `failed` report too) or was stopped, and on nothing else */
|
|
237
|
+
export const canRetry = (run) => run.status === 'failed' || run.status === 'stopped';
|
|
238
|
+
|
|
239
|
+
/** The refs a run is started again on: the subject it had (the spec pull request of a proposal is found again by the server) */
|
|
240
|
+
export function retryRefs(run) {
|
|
241
|
+
const refs = {};
|
|
242
|
+
for (const k of ['issue', 'thread', 'proposal']) if (run.refs && run.refs[k] != null) refs[k] = run.refs[k];
|
|
243
|
+
return refs;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** The four limits as the dialog's fields hold them (text), to the object a request carries: blanks are left out, and `null` when a field is not a number above zero */
|
|
247
|
+
export function limitsFromFields(fields) {
|
|
248
|
+
const out = {};
|
|
249
|
+
for (const k of LIMIT_KEYS) {
|
|
250
|
+
const text = String(fields[k] ?? '').trim();
|
|
251
|
+
if (text === '') continue;
|
|
252
|
+
const n = Number(text);
|
|
253
|
+
if (!Number.isFinite(n) || n <= 0) return null;
|
|
254
|
+
out[k] = n;
|
|
255
|
+
}
|
|
256
|
+
return out;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** The line under the dialog's title when it starts a run again */
|
|
260
|
+
export function retryWords(run) {
|
|
261
|
+
return `Starts again on ${run.runId}.`;
|
|
228
262
|
}
|
|
229
263
|
|
|
230
264
|
/** What a start came to, in words */
|
|
@@ -324,6 +358,8 @@ export function timelineWords(entry) {
|
|
|
324
358
|
const by = who ? ` by ${who}` : '';
|
|
325
359
|
switch (entry.kind) {
|
|
326
360
|
case 'requested': return { what: `Requested${by}${entry.ref ? ` under the profile ${entry.ref}` : ''}`, note: '' };
|
|
361
|
+
case 'retry-of': return { what: `Starts again on ${entry.ref || 'an earlier run'}`, note: '' };
|
|
362
|
+
case 'retried-by': return { what: `Started again as ${entry.ref || 'a new run'}`, note: '' };
|
|
327
363
|
case 'claimed': return { what: `Claimed${by}`, note: entry.note || '' };
|
|
328
364
|
case 'report': return { what: `Reported ${entry.ref || 'in'}${by}`, note: entry.note || '' };
|
|
329
365
|
// When cornfield saw it, not when it was pushed: the forge does not say
|
package/explorer/runs-view.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import { relativeTime } from './review-model.js';
|
|
12
|
-
import { runTone, aboutWords, statusWords, statusWhy, runMeta, canStop, canAnswer, groupRuns, compareTitle, limitRows, checksWords, timelineWords, nodeLabels, collisionWords, answerWords } from './runs-model.js';
|
|
12
|
+
import { runTone, canRetry, aboutWords, statusWords, statusWhy, runMeta, canStop, canAnswer, groupRuns, compareTitle, limitRows, checksWords, timelineWords, nodeLabels, collisionWords, answerWords } from './runs-model.js';
|
|
13
13
|
|
|
14
14
|
|
|
15
15
|
/**
|
|
@@ -49,10 +49,24 @@ function linksHtml(ctx, run) {
|
|
|
49
49
|
].filter(Boolean).join(' · ');
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
-
|
|
52
|
+
/** A run id that is another run of the list is a button that takes you to it; otherwise it is plain text */
|
|
53
|
+
function runLink(ctx, runId, all) {
|
|
54
|
+
const there = (all || []).some((r) => r.runId === runId);
|
|
55
|
+
return there ? `<button type="button" class="hx-btn hx-forge-act" data-run-goto="${ctx.esc(runId)}" aria-label="Go to run ${ctx.esc(runId)}">${ctx.esc(runId)}</button>` : ctx.esc(runId);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Which run this one starts again, and which start it again */
|
|
59
|
+
function retryHtml(ctx, run, all) {
|
|
60
|
+
const again = Array.isArray(run.retriedBy) ? run.retriedBy : [];
|
|
61
|
+
if (!run.retryOf && !again.length) return '';
|
|
62
|
+
return `<p class="hx-forge-meta">${run.retryOf ? `Starts again on ${runLink(ctx, run.retryOf, all)}` : ''}${run.retryOf && again.length ? ' · ' : ''}${again.length ? `Started again as ${again.map((id) => runLink(ctx, id, all)).join(', ')}` : ''}</p>`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function timelineHtml(ctx, run, all) {
|
|
53
66
|
const items = (run.timeline || []).map((e) => {
|
|
54
67
|
const w = timelineWords(e);
|
|
55
|
-
|
|
68
|
+
const goto = (e.kind === 'retry-of' || e.kind === 'retried-by') && e.ref && (all || []).some((r) => r.runId === e.ref) ? ` <button type="button" class="hx-btn hx-forge-act" data-run-goto="${ctx.esc(e.ref)}" aria-label="Go to run ${ctx.esc(e.ref)}">Go to it</button>` : '';
|
|
69
|
+
return `<li><time datetime="${ctx.esc(e.at)}" title="${ctx.esc(e.at)}">${ctx.esc(relativeTime(e.at, ctx.now) || e.at)}</time>${ctx.esc(w.what)}${goto}${w.note ? `<span class="hx-run-note">${ctx.esc(w.note)}</span>` : ''}</li>`;
|
|
56
70
|
});
|
|
57
71
|
return `<ol class="hx-run-timeline" id="run-tl-${ctx.esc(run.runId)}" aria-label="Timeline of ${ctx.esc(run.runId)}, oldest first">${items.join('')}</ol>`;
|
|
58
72
|
}
|
|
@@ -88,25 +102,27 @@ export function runHtml(ctx, run, all) {
|
|
|
88
102
|
const why = statusWhy(run);
|
|
89
103
|
const note = run.report && run.report.note ? `<p class="hx-forge-meta">Runner: ${ctx.esc(run.report.note)}</p>` : '';
|
|
90
104
|
const answering = canAnswer(run);
|
|
105
|
+
const retry = canRetry(run) ? `<button type="button" class="hx-btn hx-forge-act" data-forge-retry="${ctx.esc(run.runId)}" aria-label="Start again on run ${ctx.esc(run.runId)}"${ctx.busy ? ' disabled' : ''}>Start again</button>` : '';
|
|
91
106
|
const stop = canStop(run) && !answering ? `<button type="button" class="hx-btn hx-forge-act" data-forge-stop="${ctx.esc(run.runId)}" aria-label="Stop run ${ctx.esc(run.runId)}"${ctx.busy ? ' disabled' : ''}>Stop</button>` : '';
|
|
92
107
|
const names = nodeLabels(run.nodes, ctx.nodes);
|
|
93
108
|
const collision = collisionWords(run, all, ctx.nodes);
|
|
94
109
|
const limits = limitRows(run);
|
|
95
110
|
const count = (run.timeline || []).length;
|
|
96
111
|
const links = linksHtml(ctx, run);
|
|
97
|
-
return `<li class="hx-run hx-forge-file" data-run="${ctx.esc(run.runId)}">
|
|
112
|
+
return `<li class="hx-run hx-forge-file" data-run="${ctx.esc(run.runId)}" tabindex="-1">
|
|
98
113
|
<div class="hx-run-head"><span class="hx-forge-state hx-forge-state--${tone}">${ctx.esc(statusWords(run))}</span> <span class="hx-name">${ctx.esc(run.kind)} on ${ctx.esc(aboutWords(run.refs))}</span>${run.profile ? ` <span class="hx-faint">profile ${ctx.esc(run.profile)}</span>` : ''}</div>
|
|
99
114
|
${collision ? `<p class="hx-run-collide"><span aria-hidden="true">⚠</span> ${ctx.esc(collision)}</p>` : ''}
|
|
100
115
|
<p class="hx-forge-meta">${ctx.esc(runMeta(run, ctx.now))}</p>${why ? `<p class="hx-forge-why hx-faint">${ctx.esc(why)}</p>` : ''}${note}
|
|
101
116
|
<dl class="hx-run-limits" aria-label="Limits and what the runner reported">${limits.length ? limits.map((r) => `<dt>${ctx.esc(r.name)}</dt><dd>limit: ${ctx.esc(r.limit)}; reported: ${ctx.esc(r.reported)}</dd>`).join('') : '<dt>Limits</dt><dd>none asked, nothing reported</dd>'}</dl>
|
|
102
117
|
<p class="hx-forge-meta">${ctx.esc(checksWords(run))}</p>
|
|
103
118
|
<p class="hx-forge-meta">${names.length ? `Changing ${run.nodesFrom === 'files' ? '' : 'or expected to change '}${ctx.esc(names.join(', '))}` : 'No node on the map yet.'}</p>
|
|
119
|
+
${retryHtml(ctx, run, all)}
|
|
104
120
|
${links ? `<p class="hx-forge-meta">${links}</p>` : ''}
|
|
105
121
|
${answering ? answerHtml(ctx, run) : ''}${run.answer && !answering ? answeredHtml(ctx, run) : ''}
|
|
106
|
-
<div class="hx-run-actions">${stop}
|
|
122
|
+
<div class="hx-run-actions">${stop}${retry}
|
|
107
123
|
<button type="button" class="hx-btn hx-forge-act" data-run-select="${ctx.esc(run.runId)}" aria-pressed="${lit}" aria-label="Light the nodes of ${ctx.esc(run.runId)} on the map"${(run.nodes || []).length ? '' : ' disabled'}>${lit ? 'Lit on the map' : 'Light on the map'}</button>
|
|
108
124
|
<button type="button" class="hx-btn hx-forge-act" data-run-timeline="${ctx.esc(run.runId)}" aria-expanded="${open}" aria-controls="run-tl-${ctx.esc(run.runId)}">Timeline (${count})</button></div>
|
|
109
|
-
${open ? timelineHtml(ctx, run) : ''}</li>`;
|
|
125
|
+
${open ? timelineHtml(ctx, run, all) : ''}</li>`;
|
|
110
126
|
}
|
|
111
127
|
|
|
112
128
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cornfield",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.21.0",
|
|
4
4
|
"description": "A self-hostable dev dashboard with the topology map at its centre: proposals on the map, scenarios, outages and what-if edits, for any repo.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "popcorn245 (https://github.com/popcorn245)",
|
package/server/agent-api.js
CHANGED
|
@@ -3,11 +3,12 @@
|
|
|
3
3
|
*
|
|
4
4
|
* The routes that ask for agent runs and show them (issue #80, spec 0005 D10; the engine is server/agent-runs.js).
|
|
5
5
|
*
|
|
6
|
-
* POST /api/agent-requests { kind, refs, profile?, brief?, branch?, limits?, nodes?, force? }, with `Authorization: Bearer cf_at_…`
|
|
6
|
+
* POST /api/agent-requests { kind, refs, profile?, brief?, branch?, limits?, nodes?, retryOf?, force? }, with `Authorization: Bearer cf_at_…`
|
|
7
7
|
* GET /api/agent-requests the queue, for a runner token: server/runner-api.js (and the pull transport's claim and report routes)
|
|
8
8
|
* GET /api/agent-tokens the signed-in maintainer's agent tokens (and POST, and /<id>/revoke: server/review-api.js)
|
|
9
9
|
* GET /api/agent-runs[?follow=1] the runs, newest first, with the cap and how many are open; `follow=1` looks at the forge first
|
|
10
10
|
* GET /api/agent-runs/<runId> one run
|
|
11
|
+
* GET /api/agent-runs/<runId>/brief its whole brief, for Start again (the run shows the first 2000 characters): the signed-in maintainer's only
|
|
11
12
|
* POST /api/agent-runs the dashboard's Start an agent: the same body as the API
|
|
12
13
|
* POST /api/agent-runs/<runId>/stop { note? } asks the runner to stop
|
|
13
14
|
* POST /api/agent-runs/<runId>/answer { action: 'continue' | 'stop' | 'reply', text? } answers a run that reported `waiting`
|
|
@@ -157,11 +158,12 @@ export async function serveAgentCall(req, res, ctx) {
|
|
|
157
158
|
* @returns {Promise<boolean>} whether the path was one of these
|
|
158
159
|
*/
|
|
159
160
|
export async function serveRunRoutes(req, res, reqPath, ctx) {
|
|
160
|
-
const m = /^\/api\/agent-runs(?:\/(run-[0-9A-Za-z]{26}))?(\/stop|\/answer)?$/.exec(reqPath);
|
|
161
|
+
const m = /^\/api\/agent-runs(?:\/(run-[0-9A-Za-z]{26}))?(\/stop|\/answer|\/brief)?$/.exec(reqPath);
|
|
161
162
|
if (!m || (m[2] && !m[1])) return false;
|
|
162
163
|
const { auth, runs, session } = ctx;
|
|
163
164
|
const runId = m[1] ?? null;
|
|
164
|
-
const
|
|
165
|
+
const reading = m[2] === '/brief';
|
|
166
|
+
const allow = reading ? 'GET, HEAD' : m[2] ? 'POST' : runId ? 'GET, HEAD' : 'GET, HEAD, POST';
|
|
165
167
|
if (!allow.split(', ').includes(req.method || '')) {
|
|
166
168
|
req.resume();
|
|
167
169
|
send(res, 405, { ok: false, error: 'Method not allowed.', code: 'invalid' }, { Allow: allow });
|
|
@@ -175,6 +177,12 @@ export async function serveRunRoutes(req, res, reqPath, ctx) {
|
|
|
175
177
|
|
|
176
178
|
if (req.method === 'GET' || req.method === 'HEAD') {
|
|
177
179
|
req.resume();
|
|
180
|
+
if (reading) {
|
|
181
|
+
// A session's only (the guard reads cookies, never a token), and a run of this repo's only
|
|
182
|
+
const brief = await runs.brief(/** @type {string} */ (runId));
|
|
183
|
+
send(res, brief !== null ? 200 : 404, brief !== null ? { ok: true, runId, brief } : { ok: false, error: 'cornfield has no such run.', code: 'not-found' });
|
|
184
|
+
return true;
|
|
185
|
+
}
|
|
178
186
|
if (runId) {
|
|
179
187
|
const run = isRunId(runId) ? await runs.get(runId) : null;
|
|
180
188
|
send(res, run ? 200 : 404, run ? { ok: true, run } : { ok: false, error: 'cornfield has no such run.', code: 'not-found' });
|
package/server/agent-runs.js
CHANGED
|
@@ -58,9 +58,10 @@
|
|
|
58
58
|
* (refused as a duplicate). A fence without an id gets one from cornfield, the same on every look (`handRunId`), confirmed by a reply block in the
|
|
59
59
|
* thread that the poll's signed-in maintainer posts (the block's `requestedBy` is the author; the audit row names who posted it). A reply the forge
|
|
60
60
|
* refuses is posted on a later look; the run is kept meanwhile (on pull it may be claimed at once)
|
|
61
|
+
* - a `retryOf` is checked as an API request's is (`retryProblem`: a run of this repo that failed or was stopped), before the cap
|
|
61
62
|
* - the cap and the one-run-per-subject rule are `reserve`'s, in the same transaction as the insert, so a hand-written request counts toward later
|
|
62
63
|
* cap checks and is refused when they say so; the rate limit guards people at the dashboard and does not apply
|
|
63
|
-
* - what started nothing (not a maintainer, edited, malformed with the contract's reason, duplicate, old, cap, subject) is kept in `actions` and shown by `list` as `handWritten.refused`
|
|
64
|
+
* - what started nothing (not a maintainer, edited, malformed with the contract's reason, duplicate, old, retryOf, cap, subject) is kept in `actions` and shown by `list` as `handWritten.refused`
|
|
64
65
|
*
|
|
65
66
|
* ## Waiting, and the answer (issue #101)
|
|
66
67
|
*
|
|
@@ -179,7 +180,7 @@ export const NUDGE_FRESH_MS = 10 * 60_000;
|
|
|
179
180
|
export const MAX_HAND_JUDGED = 50;
|
|
180
181
|
/** The runs that are over once the runner has said so */
|
|
181
182
|
/** The keys of a request as the API and the button send it: the contract's fields, less what cornfield writes, plus `force` */
|
|
182
|
-
export const REQUEST_BODY_KEYS = Object.freeze(['kind', 'profile', 'refs', 'branch', 'brief', 'limits', 'nodes', 'requestedBy', 'force']);
|
|
183
|
+
export const REQUEST_BODY_KEYS = Object.freeze(['kind', 'profile', 'refs', 'branch', 'brief', 'limits', 'nodes', 'requestedBy', 'retryOf', 'force']);
|
|
183
184
|
|
|
184
185
|
/** The states in which a run is over for good unless the runner says more */
|
|
185
186
|
export const FINISHED = Object.freeze(['done', 'failed', 'stopped', 'merged', 'closed']);
|
|
@@ -260,14 +261,15 @@ function answerOf(row) {
|
|
|
260
261
|
export function publicRun(row, nowMs, quietMs, extra = {}) {
|
|
261
262
|
const { status, open } = statusOf(row, nowMs, quietMs);
|
|
262
263
|
let limits = null;
|
|
263
|
-
|
|
264
|
+
let retryOf = null;
|
|
265
|
+
try { const asked = JSON.parse(row.request); limits = asked.limits ?? null; retryOf = typeof asked.retryOf === 'string' ? asked.retryOf : null; } catch { limits = null; }
|
|
264
266
|
return {
|
|
265
267
|
runId: row.run_id, kind: row.kind, profile: row.profile,
|
|
266
268
|
refs: { ...(row.issue != null ? { issue: row.issue } : {}), ...(row.proposal != null ? { proposal: row.proposal } : {}), ...(row.thread != null ? { thread: row.thread } : {}) },
|
|
267
269
|
status, open, requestedBy: row.requested_by, requestedAt: row.requested_at, via: row.via, byHand: row.via === 'hand', transport: row.transport, target: row.target,
|
|
268
270
|
claimedAt: row.claimed_at,
|
|
269
271
|
comment: row.comment_id ? { id: row.comment_id, url: row.comment_url } : null,
|
|
270
|
-
limits,
|
|
272
|
+
limits, retryOf,
|
|
271
273
|
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,
|
|
272
274
|
stopRequested: row.stop_requested_at ? { at: row.stop_requested_at, by: row.stop_requested_by } : null,
|
|
273
275
|
answer: answerOf(row),
|
|
@@ -283,10 +285,13 @@ export function publicRun(row, nowMs, quietMs, extra = {}) {
|
|
|
283
285
|
* @param {{ at: string, kind: string, actor: string | null, ref: string | null, note: string | null, url: string | null }[]} events
|
|
284
286
|
* @param {{ status: string }} now `statusOf`'s answer
|
|
285
287
|
* @param {number} quietMs
|
|
288
|
+
* @param {{ retryOf?: string | null, retriedBy?: { runId: string, at: string }[] }} [links] the run this one starts again, and the runs that start it again
|
|
286
289
|
*/
|
|
287
|
-
export function timelineOf(row, events, now, quietMs) {
|
|
290
|
+
export function timelineOf(row, events, now, quietMs, links = {}) {
|
|
288
291
|
const out = [{ at: row.requested_at, kind: 'requested', actor: row.requested_by, ref: row.profile, note: null, url: row.comment_url }];
|
|
289
|
-
|
|
292
|
+
if (links.retryOf) out.push({ at: row.requested_at, kind: 'retry-of', actor: null, ref: links.retryOf, note: null, url: null });
|
|
293
|
+
const later = (links.retriedBy ?? []).map((r) => ({ at: r.at, kind: 'retried-by', actor: null, ref: r.runId, note: null, url: null }));
|
|
294
|
+
out.push(...[...events.map((e) => ({ ...e, actor: byFromText(e.actor) })), ...later].sort((a, b) => Date.parse(a.at) - Date.parse(b.at)));
|
|
290
295
|
if (now.status === 'quiet') out.push({ at: iso(Date.parse(row.last_activity) + quietMs), kind: 'quiet', actor: null, ref: null, note: null, url: null });
|
|
291
296
|
return out;
|
|
292
297
|
}
|
|
@@ -427,6 +432,12 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
427
432
|
const ask = db.prepare('SELECT at, kind, actor, ref, note, url FROM run_events WHERE run_id = ? ORDER BY at, rowid LIMIT ?');
|
|
428
433
|
for (const r of rows) events.set(r.run_id, ask.all(r.run_id, TIMELINE_LIMIT));
|
|
429
434
|
}
|
|
435
|
+
// The runs that start these again: found by the id their request names
|
|
436
|
+
const retried = new Map();
|
|
437
|
+
if (rows.length) {
|
|
438
|
+
const again = /** @type {{ run_id: string, requested_at: string, again: string }[]} */ (db.prepare(`SELECT run_id, requested_at, json_extract(request, '$.retryOf') AS again FROM runs WHERE repo = ? AND ${POSTED} AND json_extract(request, '$.retryOf') IN (${rows.map(() => '?').join(',')}) ORDER BY requested_at, run_id`).all(repo, ...rows.map((r) => r.run_id)));
|
|
439
|
+
for (const a of again) retried.set(a.again, [...(retried.get(a.again) ?? []), { runId: a.run_id, at: a.requested_at }]);
|
|
440
|
+
}
|
|
430
441
|
const mirrors = new Map(rows.length ? /** @type {{ run_id: string, comment_url: string | null, gone: number }[]} */ (db.prepare(`SELECT run_id, comment_url, gone FROM run_mirrors WHERE run_id IN (${rows.map(() => '?').join(',')})`).all(...rows.map((r) => r.run_id))).map((m) => [m.run_id, m]) : []);
|
|
431
442
|
return new Map(rows.map((r) => {
|
|
432
443
|
const mine = nodesOf.get(r.run_id);
|
|
@@ -435,8 +446,11 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
435
446
|
? open.filter((o) => o.run_id !== r.run_id && nodesOf.get(o.run_id).nodes.some((id) => mine.nodes.includes(id))).map((o) => o.run_id)
|
|
436
447
|
: [];
|
|
437
448
|
let brief = '';
|
|
438
|
-
|
|
439
|
-
|
|
449
|
+
let briefCut = false;
|
|
450
|
+
let retryOf = null;
|
|
451
|
+
try { const asked = JSON.parse(r.request); const whole = String(asked.brief ?? ''); brief = whole.slice(0, BRIEF_SHOWN); briefCut = whole.length > BRIEF_SHOWN; retryOf = typeof asked.retryOf === 'string' ? asked.retryOf : null; } catch { brief = ''; }
|
|
452
|
+
const retriedBy = retried.get(r.run_id) ?? [];
|
|
453
|
+
return [r.run_id, { brief, briefCut, retriedBy: retriedBy.map((x) => x.runId), nodes: mine.nodes, nodesFrom: mine.from, collidesWith, timeline: timelineOf(r, events.get(r.run_id) ?? [], statusOf(r, at, quietMs), quietMs, { retryOf, retriedBy }),
|
|
440
454
|
thread: { number: r.target, mirror: kept && kept.comment_url && kept.gone === 0 ? { url: kept.comment_url } : null } }];
|
|
441
455
|
}));
|
|
442
456
|
}
|
|
@@ -562,6 +576,16 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
562
576
|
}
|
|
563
577
|
}
|
|
564
578
|
|
|
579
|
+
/** A request that starts again names a run of this repo that is over without having done its work: `failed` or `stopped`. Throws a `Refused` otherwise */
|
|
580
|
+
function retryProblem(db, runId) {
|
|
581
|
+
const row = /** @type {RunRow | undefined} */ (db.prepare(`SELECT * FROM runs WHERE run_id = ? AND repo = ? AND ${POSTED}`).get(runId, repo));
|
|
582
|
+
if (!row) throw new Refused(404, `"retryOf" names ${runId}, which is not a run of ${repo}.`, 'not-found');
|
|
583
|
+
const { status, open } = statusOf(row, now(), quietMs);
|
|
584
|
+
if (open) throw new Refused(409, `"retryOf" names ${runId}, which is still open (${status}). Only a run that failed or was stopped is started again; stop it first, or wait.`, 'retry-open');
|
|
585
|
+
if (status !== 'failed' && status !== 'stopped') throw new Refused(409, `"retryOf" names ${runId}, which ${status === 'quiet' ? 'went quiet' : `ended as ${status}`}. Only a run that failed or was stopped is started again.`, 'retry-not-over');
|
|
586
|
+
return row;
|
|
587
|
+
}
|
|
588
|
+
|
|
565
589
|
/** What a request's audit row says: the shape of what was asked and never its words (a brief may be long, and may be anything) */
|
|
566
590
|
function askedOf(body, via) {
|
|
567
591
|
const out = /** @type {Record<string, unknown>} */ ({});
|
|
@@ -579,6 +603,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
579
603
|
out.refs = refs;
|
|
580
604
|
}
|
|
581
605
|
if (typeof body.brief === 'string') out.briefChars = body.brief.length;
|
|
606
|
+
if (typeof body.retryOf === 'string' && isRunId(body.retryOf)) out.retryOf = body.retryOf;
|
|
582
607
|
if (body.force === true) out.force = true;
|
|
583
608
|
if (transport !== 'forge') out.transport = transport;
|
|
584
609
|
if (via) Object.assign(out, { via: 'api', token: via.token });
|
|
@@ -604,7 +629,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
604
629
|
let runId = null;
|
|
605
630
|
try {
|
|
606
631
|
if (problem) throw new Refused(problem.status, problem.message, 'invalid');
|
|
607
|
-
if (!isObject(body)) throw new Refused(400, `A request is a JSON object: { kind, refs, profile?, brief?, branch?, limits?, nodes?, force? }.`, 'invalid');
|
|
632
|
+
if (!isObject(body)) throw new Refused(400, `A request is a JSON object: { kind, refs, profile?, brief?, branch?, limits?, nodes?, retryOf?, force? }.`, 'invalid');
|
|
608
633
|
const { force, requestedBy, trigger: forged, ...fields } = body;
|
|
609
634
|
// What caused a request is cornfield's to write, from a trigger's own call; a caller cannot say it was a trigger
|
|
610
635
|
if (forged !== undefined) throw new Refused(400, '"trigger" is written by cornfield for an automatic request; leave it out.', 'invalid');
|
|
@@ -691,6 +716,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
691
716
|
}
|
|
692
717
|
}
|
|
693
718
|
const db = await auth.store();
|
|
719
|
+
if (made.retryOf !== undefined) retryProblem(db, made.retryOf);
|
|
694
720
|
reserve(db, made, { target: number, who, via, force: force === true, trigger: Boolean(made.trigger), derived });
|
|
695
721
|
// What was read is what the map marks for this run until it pushes: kept, so the overlay has it now and the poll need not read it again
|
|
696
722
|
if (derived) db.prepare('INSERT OR REPLACE INTO run_reads (run_id, source, sha, data, at) VALUES (?, ?, ?, ?, ?)').run(made.runId, 'mentions', '', JSON.stringify(derived), iso(now()));
|
|
@@ -985,6 +1011,18 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
985
1011
|
return row ? publicRun(row, now(), quietMs, extrasFor(db, [row], now()).get(row.run_id)) : null;
|
|
986
1012
|
}
|
|
987
1013
|
|
|
1014
|
+
/**
|
|
1015
|
+
* The whole brief of one run of this repo, for **Start again** (the list and `get` show the first `BRIEF_SHOWN` characters): '' for a request
|
|
1016
|
+
* without one, null when this repo has no such run. The route that answers it is the signed-in maintainer's only (server/agent-api.js)
|
|
1017
|
+
*/
|
|
1018
|
+
async function briefOf(runId) {
|
|
1019
|
+
if (!isRunId(runId)) return null;
|
|
1020
|
+
const db = await auth.store();
|
|
1021
|
+
const row = /** @type {{ request: string } | undefined} */ (db.prepare(`SELECT request FROM runs WHERE run_id = ? AND repo = ? AND ${POSTED}`).get(runId, repo));
|
|
1022
|
+
if (!row) return null;
|
|
1023
|
+
try { return String(JSON.parse(row.request).brief ?? ''); } catch { return ''; }
|
|
1024
|
+
}
|
|
1025
|
+
|
|
988
1026
|
/** The runs a follow looks at: posted, not over for good (a trusted pull request merged or closed), and active within the follow window or waiting on a maintainer */
|
|
989
1027
|
function followable(db, at) {
|
|
990
1028
|
const window = Math.max(2 * quietMs, FOLLOW_FLOOR_MS);
|
|
@@ -1199,6 +1237,8 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1199
1237
|
}
|
|
1200
1238
|
if (at - Date.parse(request.requestedAt) >= quietMs) return { accepted: false, why: 'old', reason: 'posted more than agents.quietAfter ago, so the run would be quiet at once and count for nothing; write it again to ask now' };
|
|
1201
1239
|
try {
|
|
1240
|
+
// `retryOf` is checked as it is for a request from the API: first, then the cap and the one-run-per-subject rule
|
|
1241
|
+
if (request.retryOf !== undefined) retryProblem(db, request.retryOf);
|
|
1202
1242
|
reserve(db, request, { target: t.number, who: { userId: '' }, via: null, force: false, hand: { comment } });
|
|
1203
1243
|
} catch (err) {
|
|
1204
1244
|
if (err instanceof Refused) return { accepted: false, why: err.code ?? 'refused', reason: err.message };
|
|
@@ -1875,7 +1915,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1875
1915
|
return hit ? hit.run_id : null;
|
|
1876
1916
|
}
|
|
1877
1917
|
|
|
1878
|
-
return { request, stop, answer, list, get, follow, discover, discovers, hasWork, resume, queued, claim, runnerGet, report, openOn, maxOpen: cap, profiles, transport };
|
|
1918
|
+
return { request, stop, answer, list, get, brief: briefOf, follow, discover, discovers, hasWork, resume, queued, claim, runnerGet, report, openOn, maxOpen: cap, profiles, transport };
|
|
1879
1919
|
}
|
|
1880
1920
|
|
|
1881
1921
|
/** @typedef {ReturnType<typeof createRuns>} Runs */
|