cornfield 0.19.1 → 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/deep-link.js +87 -0
- package/explorer/explorer.css +3 -0
- package/explorer/forge-panel-model.js +2 -0
- package/explorer/forge-panel.js +184 -23
- package/explorer/index.html +7 -1
- package/explorer/main.js +6 -2
- 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/server/auth.js +65 -18
- package/server/forge-routes.js +6 -0
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",
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module explorer/deep-link
|
|
3
|
+
*
|
|
4
|
+
* Links from chat that land in the right place (issue #103, docs/agents.md "Deep links"):
|
|
5
|
+
*
|
|
6
|
+
* ?run=<runId> the Agents tab, that run lit and in view
|
|
7
|
+
* ?issue=<n> the Issues tab, that issue's Start an agent button focused
|
|
8
|
+
* ?proposal=<slug>&start=1 the proposal opened (proposal.js) and the Start dialog on it
|
|
9
|
+
*
|
|
10
|
+
* On a phone the sheet it opens is expanded. A name that is not there is a line in the panel and said through the live
|
|
11
|
+
* region, never a blank. A link that is followed is taken out of the address (`run`, `issue`, `start`) at once, so a
|
|
12
|
+
* reload does not open it again; `?proposal=` stays, as it always has (it follows the open proposal).
|
|
13
|
+
* Without a live sign-in the server asks for it first and returns here with the same query (server/auth.js).
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { announce } from './keyboard.js';
|
|
17
|
+
import { isPhone, expandSheet } from './sheets.js';
|
|
18
|
+
import { parseProposalQuery } from './proposal-model.js';
|
|
19
|
+
import { openRunLink, openIssueLink, openProposalStart } from './forge-panel.js';
|
|
20
|
+
|
|
21
|
+
const RUN_ID = /^run-[0-9A-Za-z]{26}$/;
|
|
22
|
+
const ISSUE = /^[1-9][0-9]{0,8}$/;
|
|
23
|
+
/** The parameters a followed link gives up */
|
|
24
|
+
const SPENT = ['run', 'issue', 'start'];
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* What a query asks for, or null. One link asks for one thing: a run before an issue before a proposal. A value that
|
|
28
|
+
* cannot be a name is `{ kind, bad: words }`.
|
|
29
|
+
* @param {string} search
|
|
30
|
+
* @returns {{ kind: 'run', id: string } | { kind: 'issue', n: number } | { kind: 'proposal', slug: string } | { kind: string, bad: string } | null}
|
|
31
|
+
*/
|
|
32
|
+
export function parseDeepLink(search) {
|
|
33
|
+
const params = new URLSearchParams(search || '');
|
|
34
|
+
if (params.has('run')) {
|
|
35
|
+
const id = params.get('run');
|
|
36
|
+
return RUN_ID.test(id) ? { kind: 'run', id } : { kind: 'run', bad: `${id ? `"${id.slice(0, 40)}"` : 'That'} is not a run id.` };
|
|
37
|
+
}
|
|
38
|
+
if (params.has('issue')) {
|
|
39
|
+
const n = params.get('issue');
|
|
40
|
+
return ISSUE.test(n) ? { kind: 'issue', n: Number(n) } : { kind: 'issue', bad: `${n ? `"${n.slice(0, 40)}"` : 'That'} is not an issue number.` };
|
|
41
|
+
}
|
|
42
|
+
if (params.get('start') === '1' && params.has('proposal')) {
|
|
43
|
+
const asked = parseProposalQuery(search);
|
|
44
|
+
return asked ? { kind: 'proposal', slug: asked.slug } : { kind: 'proposal', bad: 'That is not a proposal name.' };
|
|
45
|
+
}
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Takes the spent parameters out of the address, without a new history entry; the rest stays */
|
|
50
|
+
export function cleanAddress() {
|
|
51
|
+
if (typeof history === 'undefined' || typeof location === 'undefined') return;
|
|
52
|
+
try {
|
|
53
|
+
const params = new URLSearchParams(location.search);
|
|
54
|
+
if (!SPENT.some((k) => params.has(k))) return;
|
|
55
|
+
SPENT.forEach((k) => params.delete(k));
|
|
56
|
+
const query = params.toString();
|
|
57
|
+
history.replaceState(null, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`);
|
|
58
|
+
} catch { /* the address is a convenience */ }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** A thing the link names that cannot be shown here at all (no forge in the config): said, so the page is not silent */
|
|
62
|
+
const unavailable = (words) => { announce(words); return false; };
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Follows the link in the address, once. Call it after the forge panel and the proposals are set up.
|
|
66
|
+
* @param {{ search?: string, proposalOpened?: boolean, forgeOn?: boolean }} [opts]
|
|
67
|
+
* `proposalOpened`: what `initProposals()` answered; `forgeOn`: whether `initForgePanel()` found a forge in the config
|
|
68
|
+
* @returns {Promise<boolean>} whether the link was followed to what it names
|
|
69
|
+
*/
|
|
70
|
+
export async function followDeepLink({ search = typeof location === 'undefined' ? '' : location.search, proposalOpened = false, forgeOn = true } = {}) {
|
|
71
|
+
const link = parseDeepLink(search);
|
|
72
|
+
if (!link) return false;
|
|
73
|
+
cleanAddress();
|
|
74
|
+
if ('bad' in link) return unavailable(link.bad);
|
|
75
|
+
if (link.kind === 'proposal') {
|
|
76
|
+
if (!proposalOpened) {
|
|
77
|
+
// proposal.js has put the reason in the bar (a status region); it is said here too
|
|
78
|
+
const bar = typeof document !== 'undefined' ? document.getElementById('proposal-message') : null;
|
|
79
|
+
return unavailable((bar && bar.textContent) || `There is no proposal called ${link.slug}.`);
|
|
80
|
+
}
|
|
81
|
+
if (!forgeOn) return unavailable('Start an agent needs a forge in the config.');
|
|
82
|
+
if (isPhone()) expandSheet('proposal');
|
|
83
|
+
return openProposalStart(link.slug);
|
|
84
|
+
}
|
|
85
|
+
if (!forgeOn) return unavailable('Runs and issues need a forge in the config.');
|
|
86
|
+
return link.kind === 'run' ? openRunLink(link.id) : openIssueLink(link.n);
|
|
87
|
+
}
|
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; }
|
|
@@ -61,6 +61,8 @@ export const listKeyOf = (kind, state) => (kind === 'deploys' ? 'deploys' : `${k
|
|
|
61
61
|
export const threadsUrl = (state) => `/api/forge/threads?state=${state}&limit=${LIST_LIMIT}`;
|
|
62
62
|
export const threadUrl = (n) => `/api/forge/threads/${n}`;
|
|
63
63
|
export const IDEAS_URL = '/api/forge/threads';
|
|
64
|
+
/** The address of one issue, whatever its state */
|
|
65
|
+
export const issueUrl = (n) => `/api/forge/issues/${n}`;
|
|
64
66
|
/** The address of one pull request with its files and checks */
|
|
65
67
|
export const pullUrl = (n) => `/api/forge/pulls/${n}`;
|
|
66
68
|
|
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';
|
|
@@ -79,7 +79,7 @@ import {
|
|
|
79
79
|
specBlock, buildOffers, planUrl, confirmSpec, confirmBuild, specBody, buildBody, existingWords,
|
|
80
80
|
listKeyOf, litForDeploy, nodesForRestarts, deployWords, deployMeta,
|
|
81
81
|
DRAFTS_URL, notesUrl, sinceChoices, notesSummary, validTag, confirmWords, postedWords, draftRequest,
|
|
82
|
-
threadsUrl, threadUrl, IDEAS_URL, threadKindWords, threadMeta, litForThread, mentionsIndex, ideaRequest, ideaWords,
|
|
82
|
+
threadsUrl, threadUrl, issueUrl, IDEAS_URL, threadKindWords, threadMeta, litForThread, mentionsIndex, ideaRequest, ideaWords,
|
|
83
83
|
} from './forge-panel-model.js';
|
|
84
84
|
|
|
85
85
|
const $ = (id) => document.getElementById(id);
|
|
@@ -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;
|
|
@@ -1616,7 +1690,7 @@ async function answerRun(runId, action) {
|
|
|
1616
1690
|
export const isForgeOpen = () => ui.open;
|
|
1617
1691
|
|
|
1618
1692
|
/** Opens the panel with the focus on its title; the first time, loads the pull requests */
|
|
1619
|
-
export function openForge() {
|
|
1693
|
+
export function openForge({ load = true } = {}) {
|
|
1620
1694
|
const panel = $('forge-panel');
|
|
1621
1695
|
if (!panel || panel.hidden) return;
|
|
1622
1696
|
ui.open = true;
|
|
@@ -1627,10 +1701,93 @@ export function openForge() {
|
|
|
1627
1701
|
const title = $('forge-title');
|
|
1628
1702
|
title.focus();
|
|
1629
1703
|
announce('Issues and pull requests');
|
|
1704
|
+
if (!load) return; // a deep link loads the list it wants itself (openTab)
|
|
1630
1705
|
if (ui.kind === 'notes') { if (!ui.notes.data && !ui.notes.loading) loadNotes(); else paint(); return; }
|
|
1631
1706
|
if (!current()) { paintFilters(); loadList(); } else paint();
|
|
1632
1707
|
}
|
|
1633
1708
|
|
|
1709
|
+
// ---------------------------------------------------------------------------
|
|
1710
|
+
// Deep links (explorer/deep-link.js): a run, an issue, a proposal's Start dialog
|
|
1711
|
+
// ---------------------------------------------------------------------------
|
|
1712
|
+
|
|
1713
|
+
/** Shows `tab` in the panel, opened (and, on a phone, expanded), with its list read; resolves when the list is in */
|
|
1714
|
+
async function openTab(tab) {
|
|
1715
|
+
ui.kind = tab;
|
|
1716
|
+
ui.filters = defaultFilters(tab); // a filter left from before must not hide what the link names
|
|
1717
|
+
ui.actNote = null;
|
|
1718
|
+
paintFilters();
|
|
1719
|
+
if (!ui.open) openForge({ load: false });
|
|
1720
|
+
if (isPhone()) expandSheet('forge');
|
|
1721
|
+
if (current()) paint(); else await loadList();
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
/** What a link names is not there: a line in the panel, said through the live region */
|
|
1725
|
+
function linkMissing(words) {
|
|
1726
|
+
ui.actNote = { ok: false, text: words };
|
|
1727
|
+
paint();
|
|
1728
|
+
announce(words);
|
|
1729
|
+
return false;
|
|
1730
|
+
}
|
|
1731
|
+
|
|
1732
|
+
/** Moves the focus to `el` (made focusable if it is a row) and brings it into view */
|
|
1733
|
+
function bringIntoView(el) {
|
|
1734
|
+
if (!el) return;
|
|
1735
|
+
if (!el.matches('button, a, input, select, textarea')) el.setAttribute('tabindex', '-1');
|
|
1736
|
+
el.focus();
|
|
1737
|
+
if (typeof el.scrollIntoView === 'function') el.scrollIntoView({ block: 'nearest' });
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
/** `?run=<runId>`: the Agents tab with that run lit and in view. A run that is not there is said, never a blank panel. */
|
|
1741
|
+
export async function openRunLink(id) {
|
|
1742
|
+
if (!ui.config) return false;
|
|
1743
|
+
await openTab('work');
|
|
1744
|
+
if (!(ui.runs && ui.runs.data)) await loadRuns(false, { say: false });
|
|
1745
|
+
let run = runById(id);
|
|
1746
|
+
// A run asked for a moment ago may not be in what was read before: ask once more, past the cache
|
|
1747
|
+
if (!run && ui.runs && ui.runs.data) { await loadRuns(true, { say: false }); run = runById(id); }
|
|
1748
|
+
if (!run) return linkMissing(ui.runs && ui.runs.data ? `There is no run ${id}.` : (ui.runs && ui.runs.error) || 'The runs could not be read.');
|
|
1749
|
+
if (ui.runSel !== id) selectRun(id);
|
|
1750
|
+
paint();
|
|
1751
|
+
bringIntoView($('forge-runs-list').querySelector(`[data-run="${id}"]`));
|
|
1752
|
+
announce(`Run ${id}, in the Runs view`);
|
|
1753
|
+
return true;
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
/** `?issue=<n>`: the Issues tab with that issue's Start an agent button in view and focused, ready to press */
|
|
1757
|
+
export async function openIssueLink(n) {
|
|
1758
|
+
if (!ui.config) return false;
|
|
1759
|
+
await openTab('issues');
|
|
1760
|
+
const list = current();
|
|
1761
|
+
if (!list) return linkMissing(ui.error || 'The issues could not be read.');
|
|
1762
|
+
const item = list.items.find((i) => i.number === n);
|
|
1763
|
+
if (!item) return issueNotListed(n);
|
|
1764
|
+
paint();
|
|
1765
|
+
const start = $('forge-list').querySelector(`[data-forge-agent="issue:${n}"]`);
|
|
1766
|
+
bringIntoView(start);
|
|
1767
|
+
announce(`Issue ${n}: ${item.title}. Start an agent is ready`);
|
|
1768
|
+
return true;
|
|
1769
|
+
}
|
|
1770
|
+
|
|
1771
|
+
/** An issue the open list does not hold: asked for once, directly, so a closed one is called closed and a missing one missing */
|
|
1772
|
+
async function issueNotListed(n) {
|
|
1773
|
+
const res = await request(issueUrl(n));
|
|
1774
|
+
if (res.ok && res.body.issue) {
|
|
1775
|
+
const { issue } = res.body;
|
|
1776
|
+
ui.actNote = { ok: false, text: issue.state === 'closed' ? `Issue ${n} is closed: ${issue.title}` : `Issue ${n} is open, but not in the list shown here: ${issue.title}`, url: issue.url };
|
|
1777
|
+
paint();
|
|
1778
|
+
announce(ui.actNote.text);
|
|
1779
|
+
return false;
|
|
1780
|
+
}
|
|
1781
|
+
return linkMissing(res.status === 404 ? `There is no issue ${n}.` : errorWords(res.status, res.body));
|
|
1782
|
+
}
|
|
1783
|
+
|
|
1784
|
+
/** `?proposal=<slug>&start=1`: the Start dialog on that proposal (the proposal itself is opened by proposal.js) */
|
|
1785
|
+
export async function openProposalStart(slug) {
|
|
1786
|
+
if (!ui.config || !agentEl()) return false;
|
|
1787
|
+
await openAgent(`proposal:${slug}`, '#forge-title');
|
|
1788
|
+
return !!ui.agent;
|
|
1789
|
+
}
|
|
1790
|
+
|
|
1634
1791
|
/** Closes the panel. What a selected pull request lit stays lit (the button says which); Clear lets go of it. */
|
|
1635
1792
|
export function closeForge({ restoreFocus = true } = {}) {
|
|
1636
1793
|
const panel = $('forge-panel');
|
|
@@ -1740,6 +1897,10 @@ function onClick(e) {
|
|
|
1740
1897
|
if (agent) { openAgent(agent.dataset.forgeAgent, `[data-forge-agent="${agent.dataset.forgeAgent}"]`); return; }
|
|
1741
1898
|
const stop = t.closest('[data-forge-stop]');
|
|
1742
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; }
|
|
1743
1904
|
const answer = t.closest('[data-run-answer]');
|
|
1744
1905
|
if (answer) { answerRun(answer.dataset.runId, answer.dataset.runAnswer); return; }
|
|
1745
1906
|
const pick = t.closest('[data-run-select]');
|
|
@@ -1873,7 +2034,7 @@ export function initForgePanel(config, opts = {}) {
|
|
|
1873
2034
|
agent.addEventListener('click', onAgentClick);
|
|
1874
2035
|
agent.addEventListener('keydown', onAgentKey);
|
|
1875
2036
|
agent.querySelector('form').addEventListener('submit', submitAgent);
|
|
1876
|
-
$('agent-profile').addEventListener('change',
|
|
2037
|
+
$('agent-profile').addEventListener('change', onAgentProfile);
|
|
1877
2038
|
}
|
|
1878
2039
|
const confirm = confirmEl();
|
|
1879
2040
|
if (confirm) {
|
|
@@ -1915,5 +2076,5 @@ export function resetForgePanelForTests(clock = () => Date.now()) {
|
|
|
1915
2076
|
runsTimer = 0;
|
|
1916
2077
|
pageAway = false;
|
|
1917
2078
|
clearRunsOnMap();
|
|
1918
|
-
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 });
|
|
1919
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/main.js
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
* proposal.js the proposal overlay (picker, Before / Diff / After); proposal-model.js its pure half
|
|
14
14
|
* whatif.js what-if edits on an open proposal (add, remove, draw, steps, undo); whatif-model.js its pure half
|
|
15
15
|
* review.js approve a proposal or send it back with a note and the edits; review-model.js its pure half
|
|
16
|
+
* deep-link.js ?run=, ?issue= and ?proposal=…&start=1 land on a run, an issue and a Start dialog
|
|
16
17
|
* scenario.js the player's pure core scenario-ui.js its bar, keys and camera
|
|
17
18
|
* bench.js /?bench=1 stopwatch and /?fixture=5k (the generated topology, from the server)
|
|
18
19
|
* keyboard.js the map by keyboard and the screen reader's announcer; keyboard-model.js its pure half
|
|
@@ -33,6 +34,7 @@ import { initSheets } from './sheets.js';
|
|
|
33
34
|
import { loadTopology, setView, syncViewUi } from './view.js';
|
|
34
35
|
import { bindCanvasInput } from './input.js';
|
|
35
36
|
import { initProposals } from './proposal.js';
|
|
37
|
+
import { followDeepLink } from './deep-link.js';
|
|
36
38
|
import { initWhatIf } from './whatif.js';
|
|
37
39
|
import { initReview } from './review.js';
|
|
38
40
|
import { initMockups } from './mockups.js';
|
|
@@ -208,18 +210,20 @@ loadTopology().then(async (ok) => {
|
|
|
208
210
|
// The sources the repo's cornfield.config.js names (plugins.js): a live layer, a house, devices, a checker; each optional
|
|
209
211
|
const config = await configReady;
|
|
210
212
|
const { liveSource, floorRenderer, checker } = await loadSources(config);
|
|
211
|
-
initForgePanel(config); // issues and PRs: only when the config names a forge (forge-panel.js)
|
|
213
|
+
const forgeOn = initForgePanel(config); // issues and PRs: only when the config names a forge (forge-panel.js)
|
|
212
214
|
initReviewTokens(config); // review tokens for the review API: only for somebody signed in (review-tokens.js)
|
|
213
215
|
initWhatIf(); // before a proposal can open, so its edits come with it
|
|
214
216
|
initReview(); // after it: the review controls sit under the edit controls on the bar
|
|
215
217
|
initMockups(); // a proposal's screens open from the node they name
|
|
216
|
-
await initProposals();
|
|
218
|
+
const proposalOpened = await initProposals();
|
|
217
219
|
// The live layer (live.js): loads only once a live layer goes on in the Layers menu; with no source it stays off
|
|
218
220
|
initLive({ source: liveSource, onSelectionGone: closeDrawer });
|
|
219
221
|
// The House view (house.js): a source's floor renderer draws the plan under the map (plain room boxes without one); /?view=house opens it
|
|
220
222
|
initHouse({ floor: floorRenderer });
|
|
221
223
|
initChecks({ checker }); // scenarios ask the source's checker, when there is one (check.js)
|
|
222
224
|
if (new URLSearchParams(window.location.search).get("view") === "dataflow") setView("dataflow");
|
|
225
|
+
// /?run=, /?issue= and /?proposal=…&start=1 land on a run, an issue's Start button and a proposal's Start dialog (deep-link.js)
|
|
226
|
+
followDeepLink({ proposalOpened, forgeOn }).catch((err) => console.error('Following the link failed', err));
|
|
223
227
|
// /?scenario-demo=1 plays a small scenario over real nodes, to look at the player
|
|
224
228
|
maybeStartDemo();
|
|
225
229
|
// /?bench=1 runs the stopwatch (bench.js) once the map is up
|
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 */
|
package/server/auth.js
CHANGED
|
@@ -274,10 +274,44 @@ ${body}
|
|
|
274
274
|
|
|
275
275
|
const signOutForm = '<form method="post" action="/auth/sign-out"><button class="button quiet" type="submit">Sign out</button></form>';
|
|
276
276
|
|
|
277
|
-
/** The sign-in
|
|
278
|
-
|
|
277
|
+
/** The longest way back a sign-in keeps (as it comes out, percent-encoded): it rides in the state cookie, which stays small */
|
|
278
|
+
const RETURN_MAX = 1024;
|
|
279
|
+
/** What a way back may not hold: a control character or a backslash (browsers read `\\` as `/`) */
|
|
280
|
+
const RETURN_BAD = /[\u0000-\u001f\u007f\\]/;
|
|
281
|
+
/** A path the browser takes as this origin's: one `/`, then not a second `/` or a `\\` (`//x` is another host) */
|
|
282
|
+
const isOwnPath = (p) => p[0] === '/' && p[1] !== '/' && p[1] !== '\\' && !RETURN_BAD.test(p);
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Where a sign-in may send the person back to: a same-origin relative path (with its query), or null. An absolute URL
|
|
286
|
+
* (`https://elsewhere`), a protocol-relative one (`//elsewhere`), a backslash trick (`/\\elsewhere`), a control character
|
|
287
|
+
* and the sign-in routes themselves are refused, so the return is never an open redirect. The path is checked again as
|
|
288
|
+
* the URL parser leaves it: it resolves dot segments, so `/.//elsewhere` and `/%2e//elsewhere` come out as `//elsewhere`.
|
|
289
|
+
* @param {unknown} raw
|
|
290
|
+
* @returns {string | null}
|
|
291
|
+
*/
|
|
292
|
+
export function safeReturn(raw) {
|
|
293
|
+
if (typeof raw !== 'string' || raw.length === 0 || raw.length > RETURN_MAX || !isOwnPath(raw)) return null;
|
|
294
|
+
let parsed;
|
|
295
|
+
try { parsed = new URL(raw, 'http://cornfield.invalid'); } catch { return null; }
|
|
296
|
+
if (parsed.origin !== 'http://cornfield.invalid') return null;
|
|
297
|
+
const back = `${parsed.pathname}${parsed.search}`;
|
|
298
|
+
if (back.length > RETURN_MAX || !isOwnPath(back)) return null;
|
|
299
|
+
let path;
|
|
300
|
+
try { path = decodeURIComponent(parsed.pathname); } catch { return null; }
|
|
301
|
+
if (/^\/auth(\/|$)/i.test(path)) return null;
|
|
302
|
+
return back;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** The sign-in start, with the way back (checked by safeReturn) when there is one */
|
|
306
|
+
const startHref = (returnTo) => {
|
|
307
|
+
const back = safeReturn(returnTo);
|
|
308
|
+
return `/auth/start${back && back !== '/' ? `?return=${encodeURIComponent(back)}` : ''}`;
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
/** The sign-in page; `returnTo` (checked by safeReturn) is where the sign-in ends, so a link followed signed out is followed after */
|
|
312
|
+
export const signInPage = (title, forgeName, returnTo = null) => pageHtml(title, `Sign in to ${title}`, `
|
|
279
313
|
<p>This is the dev dashboard. Sign in with ${escapeHtml(forgeName)} to see it; it is open to the repo's maintainers.</p>
|
|
280
|
-
<a class="button" href="
|
|
314
|
+
<a class="button" href="${escapeHtml(startHref(returnTo))}">Sign in with ${escapeHtml(forgeName)}</a>`);
|
|
281
315
|
|
|
282
316
|
/** The one page a signed-in non-maintainer sees */
|
|
283
317
|
export const askMaintainerPage = (title, login, repo) => pageHtml(title, 'This is the dev dashboard', `
|
|
@@ -285,10 +319,10 @@ export const askMaintainerPage = (title, login, repo) => pageHtml(title, 'This i
|
|
|
285
319
|
<p>Made a maintainer since? Sign out and sign in again.</p>
|
|
286
320
|
${signOutForm}`);
|
|
287
321
|
|
|
288
|
-
/** A sign-in that did not work, and the way to try again */
|
|
289
|
-
const failedPage = (title, words) => pageHtml(title, 'Sign-in did not work', `
|
|
322
|
+
/** A sign-in that did not work, and the way to try again (to the same place) */
|
|
323
|
+
const failedPage = (title, words, returnTo = null) => pageHtml(title, 'Sign-in did not work', `
|
|
290
324
|
<p>${escapeHtml(words)}</p>
|
|
291
|
-
<a class="button" href="
|
|
325
|
+
<a class="button" href="${escapeHtml(startHref(returnTo))}">Try again</a>`);
|
|
292
326
|
|
|
293
327
|
/** The forge could not be asked about a session's permission */
|
|
294
328
|
const uncheckedPage = (title, words) => pageHtml(title, 'Your access could not be checked', `
|
|
@@ -386,6 +420,13 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
|
|
|
386
420
|
res.writeHead(303, { Location: location, 'Cache-Control': 'no-store', ...(cookies.length ? { 'Set-Cookie': cookies } : {}) });
|
|
387
421
|
res.end();
|
|
388
422
|
};
|
|
423
|
+
/** Where a sign-in ends: the checked way back as an absolute URL on the public origin, or `/` */
|
|
424
|
+
const landAt = (back) => {
|
|
425
|
+
const path = safeReturn(back);
|
|
426
|
+
if (!path) return '/';
|
|
427
|
+
const to = new URL(path, publicUrl);
|
|
428
|
+
return to.origin === publicUrl.origin ? to.href : '/';
|
|
429
|
+
};
|
|
389
430
|
const clearSession = cookie(SESSION_COOKIE, '', { maxAge: 0, secure });
|
|
390
431
|
const clearState = cookie(STATE_COOKIE, '', { maxAge: 0, secure });
|
|
391
432
|
|
|
@@ -481,11 +522,13 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
|
|
|
481
522
|
|
|
482
523
|
// --- the routes under /auth/ ---
|
|
483
524
|
|
|
484
|
-
function start(res) {
|
|
525
|
+
function start(res, url) {
|
|
485
526
|
const state = random();
|
|
486
527
|
const verifier = random();
|
|
487
528
|
const expires = now() + STATE_MS;
|
|
488
|
-
|
|
529
|
+
// The way back is signed with the state: a 5th part, base64url (no dots), empty for none
|
|
530
|
+
const back = safeReturn(url.searchParams.get('return'));
|
|
531
|
+
const payload = `${state}.${verifier}.${expires}.${back ? b64url(Buffer.from(back)) : ''}`;
|
|
489
532
|
const q = new URLSearchParams({ client_id: clientId, redirect_uri: redirectUri, response_type: 'code', state, code_challenge: b64url(createHash('sha256').update(verifier).digest()), code_challenge_method: 'S256' });
|
|
490
533
|
if (endpoints.scope) q.set('scope', endpoints.scope);
|
|
491
534
|
redirect(res, `${endpoints.authorize}?${q}`, [cookie(STATE_COOKIE, `${payload}.${macOf(keys.mac, `state:${payload}`)}`, { maxAge: STATE_MS / 1000, secure })]);
|
|
@@ -495,12 +538,14 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
|
|
|
495
538
|
function checkState(req, url) {
|
|
496
539
|
const raw = parseCookies(req.headers.cookie)[STATE_COOKIE];
|
|
497
540
|
const parts = raw ? raw.split('.') : [];
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
if (
|
|
541
|
+
// A sign-in started before the way back was signed with it (4 parts) is not followed: it is started again
|
|
542
|
+
if (parts.length === 4) return { error: 'The sign-in was started before cornfield was updated. Start it again.' };
|
|
543
|
+
if (parts.length !== 5) return { error: 'The sign-in was started in another browser, or too long ago.' };
|
|
544
|
+
const [state, verifier, expires, back, mac] = parts;
|
|
545
|
+
if (!sameText(mac, macOf(keys.mac, `state:${state}.${verifier}.${expires}.${back}`))) return { error: 'The sign-in was started in another browser, or too long ago.' };
|
|
501
546
|
if (!(Number(expires) > now())) return { error: 'The sign-in took too long.' };
|
|
502
547
|
if (!sameText(state, url.searchParams.get('state') || '')) return { error: 'The sign-in came back with an answer to another request.' };
|
|
503
|
-
return { verifier };
|
|
548
|
+
return { verifier, returnTo: safeReturn(back ? Buffer.from(back, 'base64url').toString('utf8') : '') };
|
|
504
549
|
}
|
|
505
550
|
|
|
506
551
|
/**
|
|
@@ -678,8 +723,9 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
|
|
|
678
723
|
async function callback(req, res, url) {
|
|
679
724
|
// The state cookie is cleared only by an answer to the sign-in it belongs to: a link from anywhere else
|
|
680
725
|
// (`/auth/callback?error=x`) cannot cancel one in progress
|
|
681
|
-
const fail = (words, clear = true) => send(res, 400, failedPage(title, words), clear ? { 'Set-Cookie': clearState } : {});
|
|
682
726
|
const checked = checkState(req, url);
|
|
727
|
+
// Try again goes back to the same place: the way back is known only from a state cookie that checked out
|
|
728
|
+
const fail = (words, clear = true) => send(res, 400, failedPage(title, words, checked.returnTo), clear ? { 'Set-Cookie': clearState } : {});
|
|
683
729
|
if (checked.error) return fail(checked.error, false);
|
|
684
730
|
if (url.searchParams.get('error')) return fail(url.searchParams.get('error') === 'access_denied' ? `The sign-in was cancelled on ${forgeName}.` : `${forgeName} did not sign you in.`);
|
|
685
731
|
const code = url.searchParams.get('code');
|
|
@@ -711,7 +757,7 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
|
|
|
711
757
|
// Signed in, and not a maintainer: whatever API tokens they made while they were one stop working now
|
|
712
758
|
await demoted(String(user.id), user.login, permission);
|
|
713
759
|
}
|
|
714
|
-
redirect(res,
|
|
760
|
+
redirect(res, landAt(checked.returnTo), [cookie(SESSION_COOKIE, value, { maxAge: sessionMs / 1000, secure }), clearState]);
|
|
715
761
|
}
|
|
716
762
|
|
|
717
763
|
async function authRoute(req, res, reqPath, url) {
|
|
@@ -724,10 +770,11 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
|
|
|
724
770
|
}
|
|
725
771
|
if (reqPath === '/auth/sign-in') {
|
|
726
772
|
const { session } = await currentSession(req);
|
|
727
|
-
|
|
728
|
-
return
|
|
773
|
+
const back = safeReturn(url.searchParams.get('return'));
|
|
774
|
+
if (session?.admin) return redirect(res, landAt(back));
|
|
775
|
+
return send(res, 200, req.method === 'HEAD' ? '' : signInPage(title, forgeName, back));
|
|
729
776
|
}
|
|
730
|
-
if (reqPath === '/auth/start') return start(res);
|
|
777
|
+
if (reqPath === '/auth/start') return start(res, url);
|
|
731
778
|
if (reqPath === '/auth/callback') return callback(req, res, url);
|
|
732
779
|
if (reqPath === '/auth/me') {
|
|
733
780
|
const { session } = await currentSession(req);
|
|
@@ -762,7 +809,7 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
|
|
|
762
809
|
const { session, unchecked } = await currentSession(req);
|
|
763
810
|
if (!session) {
|
|
764
811
|
req.resume();
|
|
765
|
-
answer(req, res, reqPath, 401, signInPage(title, forgeName), 'Sign in first.');
|
|
812
|
+
answer(req, res, reqPath, 401, signInPage(title, forgeName, `${url.pathname}${url.search}`), 'Sign in first.');
|
|
766
813
|
return { done: true };
|
|
767
814
|
}
|
|
768
815
|
if (unchecked) {
|
package/server/forge-routes.js
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
* shared by every visitor and no cache-less repeats.
|
|
11
11
|
*
|
|
12
12
|
* GET /api/forge/issues?state=open|closed|all&labels=a,b&limit=100 issues, newest first
|
|
13
|
+
* GET /api/forge/issues/<n> one issue, whatever its state (a deep link to a closed one, explorer/deep-link.js)
|
|
13
14
|
* GET /api/forge/pulls?state=open|closed|all&limit=100 pull requests, newest first
|
|
14
15
|
* GET /api/forge/pulls/<n> one pull request with its files and the checks on its head
|
|
15
16
|
* (each check says whether cornfield can re-run it: `canRerun`)
|
|
@@ -180,6 +181,11 @@ function routeOf(reqPath, url, config, where, hooks = null) {
|
|
|
180
181
|
},
|
|
181
182
|
};
|
|
182
183
|
}
|
|
184
|
+
const issue = /^\/api\/forge\/issues\/([1-9]\d{0,8})$/.exec(reqPath);
|
|
185
|
+
if (issue) {
|
|
186
|
+
const n = Number(issue[1]);
|
|
187
|
+
return { key: `issues/${n}`, load: async (forge) => ({ issue: await forge.issue(n) }) };
|
|
188
|
+
}
|
|
183
189
|
const one = /^\/api\/forge\/pulls\/([1-9]\d{0,8})$/.exec(reqPath);
|
|
184
190
|
if (one) {
|
|
185
191
|
const n = Number(one[1]);
|