fwdloop 0.26.2 → 0.28.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/bin/fwdloop +46 -7
- package/package.json +2 -2
- package/src/authoring.js +21 -1
- package/src/canrun.js +23 -0
- package/src/config.js +18 -0
- package/src/declaration.js +129 -3
- package/src/drafter.js +38 -10
- package/src/flow.js +2 -1
- package/src/launcher.js +4 -2
- package/src/learnstore.js +3 -2
- package/src/mcp-checks.js +50 -0
- package/src/mcp-pick.js +33 -0
- package/src/mcp-sources.js +84 -0
- package/src/mcp-use.js +54 -0
- package/src/natural.js +23 -0
- package/src/panel/author.js +17 -1
- package/src/panel/authorcard.js +35 -0
- package/src/panel/authorflows.js +15 -6
- package/src/panel/authorstart.js +10 -6
- package/src/panel/authortrigger.js +263 -82
- package/src/panel/data.js +127 -9
- package/src/panel/index.html +945 -94
- package/src/panel/jobgrid.js +127 -0
- package/src/panel/scheduler.js +48 -6
- package/src/panel/server.js +33 -8
- package/src/panel/settings.js +119 -4
- package/src/panel/tickets.js +118 -0
- package/src/primitives.js +34 -5
- package/src/runner.js +129 -15
- package/src/schedule.js +5 -0
- package/src/summary-words.js +27 -7
- package/src/ticket-draft.js +85 -0
- package/src/ticket-labels.js +75 -0
- package/src/ticket-mcp.js +89 -0
- package/src/ticket-next.js +33 -0
- package/src/ticket-shape.js +33 -0
- package/src/trigger-clock.js +4 -4
- package/src/trigger-files.js +4 -4
- package/src/trigger-line.js +2 -1
- package/src/trigger-tickets.js +238 -0
- package/types/authoring.d.ts +5 -1
- package/types/canrun.d.ts +7 -0
- package/types/config.d.ts +6 -0
- package/types/declaration.d.ts +8 -0
- package/types/drafter.d.ts +552 -21
- package/types/mcp-checks.d.ts +8 -0
- package/types/mcp-pick.d.ts +23 -0
- package/types/mcp-sources.d.ts +51 -0
- package/types/mcp-use.d.ts +12 -0
- package/types/natural.d.ts +2 -0
- package/types/panel/author.d.ts +44 -0
- package/types/panel/authorcard.d.ts +11 -0
- package/types/panel/authorflows.d.ts +11 -1
- package/types/panel/authorstart.d.ts +3 -1
- package/types/panel/authortrigger.d.ts +83 -7
- package/types/panel/data.d.ts +78 -5
- package/types/panel/jobgrid.d.ts +109 -0
- package/types/panel/scheduler.d.ts +7 -2
- package/types/panel/server.d.ts +13 -2
- package/types/panel/settings.d.ts +3 -2
- package/types/panel/tickets.d.ts +103 -0
- package/types/primitives.d.ts +15 -2
- package/types/runner.d.ts +133 -75
- package/types/summary-words.d.ts +24 -4
- package/types/ticket-draft.d.ts +104 -0
- package/types/ticket-labels.d.ts +42 -0
- package/types/ticket-mcp.d.ts +57 -0
- package/types/ticket-next.d.ts +23 -0
- package/types/ticket-shape.d.ts +30 -0
- package/types/trigger-clock.d.ts +4 -3
- package/types/trigger-files.d.ts +3 -1
- package/types/trigger-line.d.ts +7 -0
- package/types/trigger-tickets.d.ts +105 -0
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// M13 piece 6 (docs/wiki/the-module-ladder.md, M13 item 8; mock docs/product/m13-setup-mock.html Part 3, variant B): the Result tab's ONE grid for a job.
|
|
2
|
+
// Rows are the job's runs; the four buckets (Needs you / Stopped / Passed / Skipped) are fold rows; columns are `every step: exists, done`, `output judged`,
|
|
3
|
+
// cost and time. Pure of the panel: the run lookups are injected (data.js `getJobGrid`). Nothing is written.
|
|
4
|
+
//
|
|
5
|
+
// ONE decider of a run's bucket: `bucketOf` below reads the run's glyph (`computeGlyph`) through the M12 map in tickets.js (`GROUP_OF`); this module has no second
|
|
6
|
+
// outcome reader. What it throws away: any diary field but a check's `n`, `text`, `ok`, `result` and `source`; a run's money is only the history row's total, or the
|
|
7
|
+
// priced spend rows when the run has no history row yet.
|
|
8
|
+
import { GROUP_OF, TICKET_GROUPS } from './tickets.js';
|
|
9
|
+
import { EVERY_STEP } from '../try-checks.js';
|
|
10
|
+
import { compareNatural } from '../natural.js';
|
|
11
|
+
|
|
12
|
+
/** the buckets, in the mock's order (the same four as the M12 ticket list: one list of words) */
|
|
13
|
+
export const GRID_BUCKETS = TICKET_GROUPS;
|
|
14
|
+
|
|
15
|
+
/** @param {string} glyph @returns {'wait'|'stop'|'done'|'skip'} */
|
|
16
|
+
export const bucketOf = (glyph) => /** @type {any} */ (GROUP_OF[glyph] ?? 'stop');
|
|
17
|
+
|
|
18
|
+
const isNum = (x) => typeof x === 'number' && Number.isFinite(x);
|
|
19
|
+
|
|
20
|
+
/** a figure in dollars: `$0` for an exact zero, `$0.0412`, or `at least $0.0412` when the figure is only a floor (never `$0` for unknown) @param {number} usd @param {boolean} complete */
|
|
21
|
+
export function moneyWords(usd, complete) {
|
|
22
|
+
const body = complete && usd === 0 ? '$0' : `$${usd.toFixed(4)}`;
|
|
23
|
+
return complete ? body : `at least ${body}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* One run's money: its history row's total when it has one (complete unless the row says the figure is a floor), else the priced spend rows (always a floor), else unknown.
|
|
28
|
+
* @param {{spentUsd?: unknown, spendComplete?: unknown}|null} history @param {any[]} spendRows
|
|
29
|
+
* @returns {{usd: number|null, complete: boolean}}
|
|
30
|
+
*/
|
|
31
|
+
export function runMoney(history, spendRows) {
|
|
32
|
+
if (history && isNum(history.spentUsd)) return { usd: /** @type {number} */ (history.spentUsd), complete: history.spendComplete !== false };
|
|
33
|
+
const priced = (spendRows ?? []).filter((r) => isNum(r?.costUsd));
|
|
34
|
+
return priced.length === 0 ? { usd: null, complete: false } : { usd: priced.reduce((a, r) => a + r.costUsd, 0), complete: false };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** the stats line's money: the sum of the runs' money, a floor when any run's is a floor or unknown; `null` usd = nothing is known @param {Array<{usd: number|null, complete: boolean}>} moneys */
|
|
38
|
+
export function sumMoney(moneys) {
|
|
39
|
+
const known = moneys.filter((m) => m.usd !== null);
|
|
40
|
+
return { usd: known.length === 0 ? null : known.reduce((a, m) => a + (m.usd ?? 0), 0), complete: moneys.every((m) => m.usd !== null && m.complete) };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The newest try of each step in the run's check record (`diary.jsonl` kind checks), in step order.
|
|
45
|
+
* @param {any[]} diary @returns {Array<{step: string, checks: Array<{n: number, text: string, ok: boolean, result: string|null, source: string|null}>}>}
|
|
46
|
+
*/
|
|
47
|
+
function newestTries(diary) {
|
|
48
|
+
const by = new Map();
|
|
49
|
+
for (const r of diary ?? []) {
|
|
50
|
+
if (!r || typeof r.step !== 'string' || !Number.isInteger(r.try) || !Array.isArray(r.checks)) continue;
|
|
51
|
+
const prev = by.get(r.step);
|
|
52
|
+
if (!prev || r.try >= prev.try) by.set(r.step, r);
|
|
53
|
+
}
|
|
54
|
+
return [...by.values()].map((r) => ({
|
|
55
|
+
step: r.step,
|
|
56
|
+
checks: r.checks.filter((c) => c && typeof c.text === 'string' && typeof c.ok === 'boolean')
|
|
57
|
+
.map((c) => ({ n: c.n, text: c.text, ok: c.ok, result: typeof c.result === 'string' ? c.result : null, source: typeof c.source === 'string' ? c.source : null })),
|
|
58
|
+
}));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The two check columns of one run, from the run's own check record (the Audit grid's rows, by the same identities: #1 and #2 are `every step`, #3 and up are the
|
|
63
|
+
* close's checks, `try-checks.js`). `g` passed, `r` failed, `n` nothing ran or only a human's yes judged it (a human's yes is not a check), `none` steps ran but the job has no output check at all (only #1 and #2), `q` no verdict (the run ended
|
|
64
|
+
* red and its record holds no check at all). Also the detail lines the row opens to.
|
|
65
|
+
* @param {{diary: any[], steps: any[], ended: boolean, red: boolean, skipped: boolean}} a
|
|
66
|
+
* @returns {{ex: 'g'|'r'|'n'|'q', oj: 'g'|'r'|'n'|'none'|'q', lines: string[]}}
|
|
67
|
+
*/
|
|
68
|
+
export function checkCells({ diary, steps, ended, red, skipped }) {
|
|
69
|
+
if (skipped) return { ex: 'n', oj: 'n', lines: [] };
|
|
70
|
+
const tries = newestTries(diary);
|
|
71
|
+
if (tries.length === 0) { const v = ended && red ? 'q' : 'n'; return { ex: v, oj: v, lines: [] }; }
|
|
72
|
+
const lines = [];
|
|
73
|
+
let exBad = false;
|
|
74
|
+
let ojBad = false;
|
|
75
|
+
let ojAny = false;
|
|
76
|
+
for (const t of tries) {
|
|
77
|
+
const at = (steps ?? []).findIndex((s) => s?.emits === t.step);
|
|
78
|
+
const goal = at >= 0 && typeof steps[at].goal === 'string' ? steps[at].goal.replace(/[\s,.;:]+$/, '') : t.step;
|
|
79
|
+
const name = `step ${at >= 0 ? at + 1 : '?'} ${goal}`;
|
|
80
|
+
const every = t.checks.filter((c) => c.source === EVERY_STEP || c.n === 1 || c.n === 2);
|
|
81
|
+
const closes = t.checks.filter((c) => !every.includes(c));
|
|
82
|
+
const badEvery = every.find((c) => !c.ok);
|
|
83
|
+
if (badEvery) { exBad = true; lines.push(`${name}: ${badEvery.text}${badEvery.result ? ` (${badEvery.result})` : ''}`); } else lines.push(`${name}: exists, done`);
|
|
84
|
+
for (const c of closes) {
|
|
85
|
+
ojAny = true;
|
|
86
|
+
if (!c.ok) ojBad = true;
|
|
87
|
+
lines.push(`output judged: ${c.text}${c.result ? ` (${c.result})` : ''}${c.ok ? '' : ' - failed'}`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return { ex: exBad ? 'r' : 'g', oj: ojBad ? 'r' : (ojAny ? 'g' : 'none'), lines };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The grid of one job: every run a row in its bucket, newest first inside each bucket, and the stats line's numbers.
|
|
95
|
+
* @param {{runs: Array<{runId: string, glyph: string, ticket: number|null, title?: string|null, unsure?: boolean, at: number|null, history: any, spendRows: any[], diary: any[], steps: any[], reason: string|null}>, anyway?: {runId: string, numbers: Set<number>}|null, now?: number}} a
|
|
96
|
+
*/
|
|
97
|
+
export function buildJobGrid({ runs, anyway = null, now = Date.now() }) {
|
|
98
|
+
const rows = runs.map((r) => {
|
|
99
|
+
const bucket = bucketOf(r.glyph);
|
|
100
|
+
const money = runMoney(r.history, r.spendRows);
|
|
101
|
+
const cells = checkCells({ diary: r.diary, steps: r.steps, ended: r.history !== null, red: bucket === 'stop', skipped: bucket === 'skip' });
|
|
102
|
+
const wall = r.history && isNum(r.history.wallMs) ? r.history.wallMs : null;
|
|
103
|
+
const lines = [...cells.lines];
|
|
104
|
+
if (money.usd === null) lines.push('cost unknown, not shown as $0');
|
|
105
|
+
return {
|
|
106
|
+
unsure: r.unsure === true, runId: r.runId, name: r.ticket !== null ? `#${r.ticket}` : r.runId, title: r.ticket !== null && typeof r.title === 'string' ? r.title : null, number: r.ticket, bucket, glyph: r.glyph, at: r.at ?? now,
|
|
107
|
+
ex: cells.ex, oj: cells.oj,
|
|
108
|
+
cost: { mark: money.usd !== null && money.complete ? 'g' : 'q', value: money.usd === null ? '—' : moneyWords(money.usd, money.complete) },
|
|
109
|
+
time: { mark: bucket === 'skip' ? 'n' : (wall !== null ? 'g' : 'q'), value: wall }, // value: ms, or null = unknown
|
|
110
|
+
reason: bucket === 'skip' ? r.reason : null,
|
|
111
|
+
anyway: bucket === 'skip' && r.ticket !== null && anyway !== null && anyway.numbers.has(r.ticket),
|
|
112
|
+
lines, money,
|
|
113
|
+
};
|
|
114
|
+
});
|
|
115
|
+
const order = (a, b) => b.at - a.at || compareNatural(b.runId, a.runId);
|
|
116
|
+
const groups = GRID_BUCKETS.map((g) => ({ ...g, rows: rows.filter((r) => r.bucket === g.key).sort(order).map(({ money, ...row }) => row) }));
|
|
117
|
+
const total = sumMoney(rows.map((r) => r.money));
|
|
118
|
+
return {
|
|
119
|
+
groups,
|
|
120
|
+
anywayRunId: anyway ? anyway.runId : null,
|
|
121
|
+
stats: {
|
|
122
|
+
counts: Object.fromEntries(groups.map((g) => [g.key, g.rows.length])),
|
|
123
|
+
spent: total.usd === null ? null : moneyWords(total.usd, total.complete),
|
|
124
|
+
spentUsd: total.usd, spentComplete: total.complete,
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
package/src/panel/scheduler.js
CHANGED
|
@@ -19,14 +19,21 @@ import {
|
|
|
19
19
|
createFileTrigger, queueOf, readSeen, recheck, recordArrived, recordDropped, recordRan,
|
|
20
20
|
} from '../trigger-files.js';
|
|
21
21
|
import { ledgerOf } from '../schedule.js';
|
|
22
|
+
import {
|
|
23
|
+
TICKET_LOOK_MS, hasBaseline, lastSeen, lookTickets, recordLook, seenNumbers,
|
|
24
|
+
} from '../trigger-tickets.js';
|
|
22
25
|
import { readOutcomes } from './authortrigger.js';
|
|
23
26
|
|
|
24
27
|
/**
|
|
25
|
-
* @param {{ door: ReturnType<typeof import('./authortrigger.js').createTriggerDoor>, now?: () => number, intervalMs?: number }} opts
|
|
26
|
-
* `intervalMs` 0 = no timer (a test drives `tick`).
|
|
28
|
+
* @param {{ door: ReturnType<typeof import('./authortrigger.js').createTriggerDoor>, now?: () => number, intervalMs?: number, look?: typeof lookTickets, mcpConfig?: string }} opts
|
|
29
|
+
* `intervalMs` 0 = no timer (a test drives `tick`). `look`/`mcpConfig`: M12 piece 2, the ticket look and the MCP config it reads (default: the person's own ~/.mcp.json).
|
|
27
30
|
*/
|
|
28
31
|
export function createScheduler(opts) {
|
|
29
|
-
const {
|
|
32
|
+
const {
|
|
33
|
+
door, now = Date.now, intervalMs = 500, look = lookTickets, mcpConfig,
|
|
34
|
+
} = opts;
|
|
35
|
+
/** M12 piece 2: per ticket schedule, when it last looked and whether a look is out (a look is async; `tick` never waits for one). @type {Map<string, {at: number|null, out: Promise<void>|null}>} */
|
|
36
|
+
const lookers = new Map();
|
|
30
37
|
/** @type {Map<string, ReturnType<typeof createFileTrigger>>} */
|
|
31
38
|
const watchers = new Map();
|
|
32
39
|
/** @type {Set<string>} refusals already written, so a folder that stays gone is told once, not every tick */
|
|
@@ -46,7 +53,8 @@ export function createScheduler(opts) {
|
|
|
46
53
|
if (queue.length === 0) return;
|
|
47
54
|
const key = (/** @type {string} */ sha, /** @type {Record<string, any>} */ r) => `${sha}|${r.outcome}|${r.why ?? ''}`; // a refusal is told once PER REASON; busy / monthly carry no `why`
|
|
48
55
|
const spoken = new Set(readOutcomes(job.flowDir).filter((r) => typeof r.sha === 'string' && r.sig === sig).map((r) => key(r.sha, r)));
|
|
49
|
-
const
|
|
56
|
+
const ticketJob = job.trigger.kind === 'new-ticket'; // M12 piece 2: a ticket has no file to look at again; it is its number
|
|
57
|
+
const cause = (/** @type {any} */ q) => (ticketJob ? { kind: /** @type {'ticket'} */ ('ticket'), number: q.number, sha: q.sha, role: job.trigger.role, list: job.trigger.list, ...(q.reason ? { why: q.reason } : {}), ...(q.anyway === true ? { anyway: true } : {}) } : { kind: /** @type {'file'} */ ('file'), path: q.path, sha: q.sha });
|
|
50
58
|
const told = (/** @type {any} */ q) => (/** @type {Record<string, any>} */ row) => { const k = key(q.sha, row); const had = spoken.has(k); spoken.add(k); return had; };
|
|
51
59
|
if (door.busy(job)) {
|
|
52
60
|
for (const q of queue) door.fire(job, cause(q), { told: told(q) });
|
|
@@ -54,7 +62,7 @@ export function createScheduler(opts) {
|
|
|
54
62
|
}
|
|
55
63
|
while (queue.length > 0) {
|
|
56
64
|
const q = queue[0];
|
|
57
|
-
const seen = recheck(q);
|
|
65
|
+
const seen = ticketJob ? { state: /** @type {'ok'} */ ('ok'), path: q.path, sha: q.sha, size: 0 } : recheck(q);
|
|
58
66
|
if (seen.state !== 'ok') {
|
|
59
67
|
const why = seen.state === 'deleted' ? 'deleted' : 'changed';
|
|
60
68
|
recordDropped(ledger, q, why, nowMs, sig);
|
|
@@ -69,10 +77,38 @@ export function createScheduler(opts) {
|
|
|
69
77
|
}
|
|
70
78
|
}
|
|
71
79
|
|
|
80
|
+
/**
|
|
81
|
+
* M12 piece 2 (items 5, 6, 7): when a ticket schedule's look is due (never looked, or 15 minutes since the last START of one) and none is out, start it. THE writer of the
|
|
82
|
+
* ticket rows is `recordLook`, called once the look settles: first look = baseline rows (nothing runs); later = one `arrived` row per new ticket or watched change;
|
|
83
|
+
* an unreadable list = one `unreadable` row with its cause, and the next look is a first look again while there is no baseline.
|
|
84
|
+
* @param {any} job @param {string} key @param {string} ledger @param {number} nowMs
|
|
85
|
+
*/
|
|
86
|
+
function startLook(job, key, ledger, nowMs) {
|
|
87
|
+
let st = lookers.get(key);
|
|
88
|
+
if (!st) { st = { at: null, out: null }; lookers.set(key, st); }
|
|
89
|
+
if (st.out !== null || (st.at !== null && nowMs - st.at < TICKET_LOOK_MS)) return;
|
|
90
|
+
st.at = nowMs;
|
|
91
|
+
const { sig, trigger } = job;
|
|
92
|
+
const first = !hasBaseline(ledger, sig);
|
|
93
|
+
const watch = Array.isArray(trigger.watch) ? trigger.watch : [];
|
|
94
|
+
// M13 piece 5 (F114f): the turn-on wrote the ticket number the first green run read; the first look baselines only tickets up to it
|
|
95
|
+
const armedRow = first ? readRows(ledger, sig).find((r) => r.kind === 'armed') : undefined;
|
|
96
|
+
const cut = Number.isInteger(armedRow?.ticketN) ? armedRow?.ticketN : undefined;
|
|
97
|
+
const out = Promise.resolve(look({
|
|
98
|
+
listUrl: trigger.list, mcp: { server: trigger.server, tool: trigger.tool }, ...(mcpConfig ? { configPath: mcpConfig } : {}),
|
|
99
|
+
seen: first ? null : seenNumbers(ledger, sig), last: first ? new Map() : lastSeen(ledger, sig), watch, ...(cut === undefined ? {} : { cut }),
|
|
100
|
+
})).catch((e) => ({ ok: /** @type {const} */ (false), error: String(e?.message ?? e) }))
|
|
101
|
+
// M13 item 9.3: a save that throws (ledger path unwritable, disk full) is told once as a refusal and never leaves the look's promise rejected, so the panel stays up
|
|
102
|
+
.then((r) => { try { recordLook(ledger, sig, r, now()); } catch (e) { try { door.refuse(job, `ticket look: its result could not be saved: ${String(/** @type {any} */ (e)?.message ?? e).split('\n')[0]}`); } catch { /* telling is best effort */ } } })
|
|
103
|
+
.finally(() => { /** @type {any} */ (st).out = null; });
|
|
104
|
+
st.out = out;
|
|
105
|
+
}
|
|
106
|
+
|
|
72
107
|
function tick() {
|
|
73
108
|
const nowMs = now();
|
|
74
109
|
const live = new Set();
|
|
75
110
|
try { door.retireStale(); } catch { /* one job's files never stop the others; tried again next tick */ }
|
|
111
|
+
try { door.armWaiting?.(); } catch { /* M13 piece 5: a schedule signed with the job turns on after its first green run; tried again next tick */ }
|
|
76
112
|
for (const job of door.scan()) {
|
|
77
113
|
const { sig } = job;
|
|
78
114
|
const key = `${job.flow}|${sig}`;
|
|
@@ -80,7 +116,10 @@ export function createScheduler(opts) {
|
|
|
80
116
|
try {
|
|
81
117
|
const ledger = ledgerOf(job.flowDir);
|
|
82
118
|
const { trigger } = job;
|
|
83
|
-
if (trigger.kind === '
|
|
119
|
+
if (trigger.kind === 'new-ticket') {
|
|
120
|
+
startLook(job, key, ledger, nowMs);
|
|
121
|
+
runQueue(job, ledger, nowMs);
|
|
122
|
+
} else if (trigger.kind === 'file-updated' || trigger.kind === 'new-file') {
|
|
84
123
|
let w = watchers.get(key);
|
|
85
124
|
if (!w) {
|
|
86
125
|
w = createFileTrigger({
|
|
@@ -107,10 +146,13 @@ export function createScheduler(opts) {
|
|
|
107
146
|
}
|
|
108
147
|
}
|
|
109
148
|
for (const k of [...watchers.keys()]) if (!live.has(k)) watchers.delete(k);
|
|
149
|
+
for (const k of [...lookers.keys()]) if (!live.has(k)) lookers.delete(k);
|
|
110
150
|
}
|
|
111
151
|
|
|
112
152
|
return {
|
|
113
153
|
tick,
|
|
154
|
+
/** M12 piece 2: resolves when every ticket look now out has been written to its ledger (a test awaits it; the timer never does). */
|
|
155
|
+
async settled() { await Promise.all([...lookers.values()].map((l) => l.out)); },
|
|
114
156
|
/** Start the real timer (idempotent). */
|
|
115
157
|
start() {
|
|
116
158
|
if (intervalMs <= 0 || timer !== null) return;
|
package/src/panel/server.js
CHANGED
|
@@ -60,13 +60,15 @@ import { resolveRunDir } from '../flow.js';
|
|
|
60
60
|
import { readAsk, requestStop, stopParkedRun } from '../runner.js';
|
|
61
61
|
import { removeFromNeedsYou } from './needsyou.js';
|
|
62
62
|
import {
|
|
63
|
-
listRuns, listScheduled, summarizeJobs, RUNS_LIST_LIMITS, getRunDetail, getRunControls, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, getRunResult, getRunDownload, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
|
|
63
|
+
listRuns, listScheduled, summarizeJobs, RUNS_LIST_LIMITS, getRunDetail, getRunControls, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, getRunResult, getJobGrid, getTicketList, getRunDownload, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
|
|
64
64
|
} from './data.js';
|
|
65
|
+
import { ticketAnyway, arriveAnywayOf } from './tickets.js';
|
|
65
66
|
import { createResumer } from './resume.js';
|
|
66
67
|
import { createScheduler } from './scheduler.js';
|
|
67
68
|
import { createAuthor } from './author.js';
|
|
68
69
|
import { keysForDoor } from '../keysfile.js';
|
|
69
70
|
import { configDoorHome } from '../config.js';
|
|
71
|
+
import { newestMcpChecks } from '../mcp-checks.js';
|
|
70
72
|
import { createSettings } from './settings.js';
|
|
71
73
|
import { removeOldLock } from './lock.js';
|
|
72
74
|
|
|
@@ -370,13 +372,27 @@ function authorPost(res, url, body, author) {
|
|
|
370
372
|
refuse(res, 404, 'not-found', url);
|
|
371
373
|
}
|
|
372
374
|
|
|
375
|
+
/**
|
|
376
|
+
* M12 piece 3: `POST /api/author/ticket-anyway` — queue a skipped ticket as a new arrival after a short reason (src/panel/tickets.js decides every refusal).
|
|
377
|
+
* The queue is the schedule builder's seam: `createPanelServer({ticketQueue: {arriveAnyway}})`; production wires `arriveAnywayOf` (one `arrived` row in the schedule ledger).
|
|
378
|
+
* @param {any} res @param {any} body @param {any} opts
|
|
379
|
+
*/
|
|
380
|
+
function ticketAnywayRoute(res, body, opts) {
|
|
381
|
+
const loaded = loadCatalogue();
|
|
382
|
+
if (!loaded.ok) { refuse(res, 500, 'catalogue', 'the catalogue failed to load'); return; }
|
|
383
|
+
const r = ticketAnyway({
|
|
384
|
+
body, listOf: (flow, runId) => getTicketList({ root: opts.root, flow, runId, catalogue: loaded.primitives }), queue: opts.ticketQueue,
|
|
385
|
+
});
|
|
386
|
+
sendJson(res, r.status, r.body);
|
|
387
|
+
}
|
|
388
|
+
|
|
373
389
|
/**
|
|
374
390
|
* Handle one request against the API + the page. Exported
|
|
375
391
|
* separately from {@link createPanelServer} so tests can drive it without a
|
|
376
392
|
* real listening socket where that is simpler.
|
|
377
393
|
* @param {import('node:http').IncomingMessage} req
|
|
378
394
|
* @param {import('node:http').ServerResponse} res
|
|
379
|
-
* @param {{ root: string, port: number, version?: string|null, startedAt?: string, packagePath?: string, resumer: ReturnType<typeof createResumer>, settings: ReturnType<typeof createSettings>, author: ReturnType<typeof createAuthor>, now?: () => number }} opts
|
|
395
|
+
* @param {{ root: string, port: number, checksHome: { skip: boolean, home: string|undefined }, version?: string|null, startedAt?: string, packagePath?: string, resumer: ReturnType<typeof createResumer>, settings: ReturnType<typeof createSettings>, author: ReturnType<typeof createAuthor>, now?: () => number, ticketQueue: {arriveAnyway: Function} }} opts
|
|
380
396
|
*/
|
|
381
397
|
export function handleRequest(req, res, opts) {
|
|
382
398
|
const method = req.method ?? 'GET';
|
|
@@ -433,6 +449,7 @@ export function handleRequest(req, res, opts) {
|
|
|
433
449
|
if (tooBig) return;
|
|
434
450
|
let body;
|
|
435
451
|
try { body = JSON.parse(Buffer.concat(parts).toString('utf8')); } catch { refuse(res, 400, 'body-not-json'); return; }
|
|
452
|
+
if (isAuthorPost && req.url === '/api/author/ticket-anyway') { ticketAnywayRoute(res, body, opts); return; }
|
|
436
453
|
if (isAuthorPost) { authorPost(res, String(req.url), body, opts.author); return; }
|
|
437
454
|
if (isSettingsPost) { settingsReply(res, opts.settings.handle({ method, pathname: String(req.url), query: new URLSearchParams(), body })); return; }
|
|
438
455
|
if (isResume) resumeRoute(res, body, opts.root, opts.resumer);
|
|
@@ -558,8 +575,8 @@ export function handleRequest(req, res, opts) {
|
|
|
558
575
|
return;
|
|
559
576
|
}
|
|
560
577
|
|
|
561
|
-
// /api/runs/:flow/:runId(/audit|/job|/asks|/result|/download)?
|
|
562
|
-
const runMatch = /^\/api\/runs\/([^/]+)\/([^/]+)(\/(audit|job|asks|result|download))?$/.exec(pathname);
|
|
578
|
+
// /api/runs/:flow/:runId(/audit|/job|/asks|/result|/grid|/download)?
|
|
579
|
+
const runMatch = /^\/api\/runs\/([^/]+)\/([^/]+)(\/(audit|job|asks|result|grid|download))?$/.exec(pathname);
|
|
563
580
|
if (runMatch) {
|
|
564
581
|
let flow;
|
|
565
582
|
let runId;
|
|
@@ -588,6 +605,7 @@ export function handleRequest(req, res, opts) {
|
|
|
588
605
|
if (sub === 'job') {
|
|
589
606
|
const result = getRunJob({
|
|
590
607
|
root: opts.root, flow, runId, catalogue, scheduleRead: (f) => opts.author?.trigger?.facts(f) ?? null,
|
|
608
|
+
mcpChecks: () => (opts.checksHome.skip ? new Map() : newestMcpChecks(opts.checksHome.home)),
|
|
591
609
|
});
|
|
592
610
|
if (!result) { sendText(res, 404, 'no such run'); return; }
|
|
593
611
|
send(200, result);
|
|
@@ -609,6 +627,13 @@ export function handleRequest(req, res, opts) {
|
|
|
609
627
|
send(200, result);
|
|
610
628
|
return;
|
|
611
629
|
}
|
|
630
|
+
if (sub === 'grid') {
|
|
631
|
+
// M13 piece 6 (item 8): the job's one Result grid (every run of the flow); the run in the URL only names the flow's run the person is looking at
|
|
632
|
+
const result = getJobGrid({ root: opts.root, flow, catalogue, now: opts.now });
|
|
633
|
+
if (!result) { sendText(res, 404, 'no such job'); return; }
|
|
634
|
+
send(200, result);
|
|
635
|
+
return;
|
|
636
|
+
}
|
|
612
637
|
if (sub === 'download') {
|
|
613
638
|
const got = getRunDownload({
|
|
614
639
|
root: opts.root, flow, runId, catalogue, index: url.searchParams.get('i'),
|
|
@@ -679,7 +704,7 @@ export function panelUrl(boundPort) {
|
|
|
679
704
|
* header). Resolves once actually listening; rejects on a bind error
|
|
680
705
|
* (including `EADDRINUSE`) with a `.port` field on the error for the
|
|
681
706
|
* caller's message.
|
|
682
|
-
* @param {{ port?: number, root: string, packagePath?: string, settings?: { home?: string, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number, openFolderSpawn?: (cmd: string, args: string[], o: object) => any, platform?: string }, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number }, author?: { env?: Record<string,string|undefined>, loadEnv?: () => any, bin?: string, now?: () => number }, scheduler?: { intervalMs?: number } }} opts
|
|
707
|
+
* @param {{ port?: number, root: string, packagePath?: string, settings?: { home?: string, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number, openFolderSpawn?: (cmd: string, args: string[], o: object) => any, platform?: string }, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number }, author?: { env?: Record<string,string|undefined>, loadEnv?: () => any, bin?: string, now?: () => number }, scheduler?: { intervalMs?: number, mcpConfig?: string }, ticketQueue?: {arriveAnyway?: Function} }} opts
|
|
683
708
|
* `resume` and `author` are for tests only (a fake env/bin, a short retry window); the CLI passes none.
|
|
684
709
|
* @returns {Promise<{ server: import('node:http').Server, port: number, tick: () => void, close: () => Promise<void> }>}
|
|
685
710
|
*/
|
|
@@ -704,11 +729,11 @@ export function createPanelServer(opts) {
|
|
|
704
729
|
});
|
|
705
730
|
// M9: the scheduler runs the clock and the file watch while this server is up (item 3). The clock is the author's `now` (tests inject one);
|
|
706
731
|
// `scheduler.intervalMs` 0 = no timer, a test calls `tick`. Stopped on close.
|
|
707
|
-
const scheduler = createScheduler({ door: author.trigger, now: opts.author?.now, intervalMs: opts.scheduler?.intervalMs });
|
|
732
|
+
const scheduler = createScheduler({ door: author.trigger, now: opts.author?.now, intervalMs: opts.scheduler?.intervalMs, mcpConfig: opts.scheduler?.mcpConfig });
|
|
708
733
|
// Settings reads and writes only under the one config home: an injected one (tests), else the door's — under a test
|
|
709
734
|
// process with no FWDLOOP_CONFIG_HOME, Settings is switched off rather than touch the real ~/.config/fwdloop.
|
|
710
735
|
const settings = createSettings({
|
|
711
|
-
home: opts.settings?.home ?? door.home, skip: opts.settings?.home === undefined && door.skip, env: opts.settings?.env, fetch: opts.settings?.fetch, now: opts.settings?.now, openFolderSpawn: opts.settings?.openFolderSpawn, platform: opts.settings?.platform,
|
|
736
|
+
root, home: opts.settings?.home ?? door.home, skip: opts.settings?.home === undefined && door.skip, env: opts.settings?.env, fetch: opts.settings?.fetch, now: opts.settings?.now, openFolderSpawn: opts.settings?.openFolderSpawn, platform: opts.settings?.platform,
|
|
712
737
|
});
|
|
713
738
|
return new Promise((resolve, reject) => {
|
|
714
739
|
// Bound port is resolved from the live socket (`server.address().port`)
|
|
@@ -720,7 +745,7 @@ export function createPanelServer(opts) {
|
|
|
720
745
|
const server = createServer((req, res) => {
|
|
721
746
|
try {
|
|
722
747
|
handleRequest(req, res, {
|
|
723
|
-
root, port: boundPort, resumer, settings, author, version, startedAt, packagePath: opts.packagePath, now: opts.author?.now,
|
|
748
|
+
root, port: boundPort, resumer, settings, checksHome: { skip: opts.settings?.home === undefined && door.skip, home: opts.settings?.home ?? door.home }, author, version, startedAt, packagePath: opts.packagePath, now: opts.author?.now, ticketQueue: /** @type {any} */ (opts.ticketQueue) ?? arriveAnywayOf({ scan: () => author.trigger.scan(), startAnyway: (a) => author.trigger.startAnyway(a), now: opts.author?.now ?? Date.now }),
|
|
724
749
|
});
|
|
725
750
|
} catch (e) {
|
|
726
751
|
sendText(res, 500, 'internal error');
|
package/src/panel/settings.js
CHANGED
|
@@ -24,16 +24,23 @@ import { spendSummary } from '../monthly.js';
|
|
|
24
24
|
import { openInOs } from '../opener.js';
|
|
25
25
|
import { dirname } from 'node:path';
|
|
26
26
|
import { homedir } from 'node:os';
|
|
27
|
+
import { listServerTools } from 'bare-agent/mcp';
|
|
28
|
+
import { mcpPathProblem } from '../config.js';
|
|
29
|
+
import { appendMcpCheck, newestMcpChecks } from '../mcp-checks.js';
|
|
30
|
+
import { mcpSources, expandMcpPath, DEFAULT_MCP_PLACES } from '../mcp-sources.js';
|
|
31
|
+
import { countMcpUse } from '../mcp-use.js';
|
|
32
|
+
import { mcpStartOpts } from '../ticket-mcp.js';
|
|
27
33
|
|
|
28
34
|
const TIMEOUT_MS = 4000;
|
|
35
|
+
const MCP_CHECK_MS = 15000;
|
|
29
36
|
|
|
30
37
|
const BROKEN_CONFIG = 'Your settings file (config.json) cannot be read. Fix or remove it, then look again.';
|
|
31
38
|
|
|
32
39
|
const isNumberAbove0 = (v) => typeof v === 'number' && Number.isFinite(v) && v > 0;
|
|
33
40
|
|
|
34
41
|
/**
|
|
35
|
-
* @param {{ home?: string, skip?: boolean, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number, openFolderSpawn?: (cmd: string, args: string[], o: object) => any, platform?: string }} cfg
|
|
36
|
-
* `home` the config home (undefined = the real `~/.config/fwdloop`); `skip` true under a test process
|
|
42
|
+
* @param {{ root?: string, home?: string, skip?: boolean, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number, openFolderSpawn?: (cmd: string, args: string[], o: object) => any, platform?: string }} cfg
|
|
43
|
+
* `root` the jobs folder (the MCP use counts read its runs); `home` the config home (undefined = the real `~/.config/fwdloop`); `skip` true under a test process
|
|
37
44
|
* with no `FWDLOOP_CONFIG_HOME` (Settings then touches nothing); `env` the shell side (tests only);
|
|
38
45
|
* `fetch` and `now` are test seams.
|
|
39
46
|
*/
|
|
@@ -56,7 +63,7 @@ export function createSettings(cfg) {
|
|
|
56
63
|
/** The row named by a request, or null: only a key that is in the keys file (or the shell) is a row. @param {any} slot */
|
|
57
64
|
const slotOf = (slot) => (rowNames(keys()).includes(slot) ? slot : null);
|
|
58
65
|
|
|
59
|
-
/** config.json, or `{problem}` in plain words when it is broken (never read as "nothing set"). */
|
|
66
|
+
/** config.json, or `{problem}` in plain words when it is broken (never read as "nothing set"). @returns {{ config: Record<string, any>, problem: string|null }} */
|
|
60
67
|
function config() {
|
|
61
68
|
try { return { config: readConfig({ home: cfg.home }), problem: null }; } catch (e) {
|
|
62
69
|
if (!(e instanceof ConfigError)) throw e;
|
|
@@ -290,18 +297,126 @@ export function createSettings(cfg) {
|
|
|
290
297
|
return reply(200, { ok: true, monthlyLimitUsd: clear ? null : raw });
|
|
291
298
|
}
|
|
292
299
|
|
|
300
|
+
// ---- M13 piece 3: Settings > MCP. Reads the MCP config files (never writes them) and shows names, flags and counts only: no command, args, env or key.
|
|
301
|
+
/** @type {Set<string>} */
|
|
302
|
+
const checking = new Set();
|
|
303
|
+
/** a tool hint as the page shows it: only `readOnlyHint: true` is a hint; anything else is "no hint" (null) @param {any} a */
|
|
304
|
+
const hintOf = (a) => (a?.readOnlyHint === true ? 'read-only' : null);
|
|
305
|
+
|
|
306
|
+
function mcpGet() {
|
|
307
|
+
const src = mcpSources({ home: cfg.home });
|
|
308
|
+
const names = [...new Set(src.places.flatMap((p) => p.servers.map((x) => x.name)))];
|
|
309
|
+
const use = cfg.root ? countMcpUse(cfg.root, names) : new Map();
|
|
310
|
+
const checks = newestMcpChecks(cfg.home);
|
|
311
|
+
const places = src.places.map((p) => ({
|
|
312
|
+
path: p.path,
|
|
313
|
+
added: p.added,
|
|
314
|
+
status: p.status,
|
|
315
|
+
servers: p.servers.map((x) => {
|
|
316
|
+
const u = use.get(x.name);
|
|
317
|
+
const c = x.remote || x.shadowedBy !== null ? null : checks.get(`${p.path}\t${x.name}`) ?? null;
|
|
318
|
+
return {
|
|
319
|
+
name: x.name,
|
|
320
|
+
remote: x.remote,
|
|
321
|
+
shadowedBy: x.shadowedBy,
|
|
322
|
+
check: c === null ? null : (c.ok === true && Array.isArray(c.tools)
|
|
323
|
+
? { at: c.at, ok: true, tools: c.tools.map((/** @type {any} */ t) => ({ name: String(t?.name), hint: t?.hint === 'read-only' ? 'read-only' : null })) }
|
|
324
|
+
: { at: c.at, ok: false, error: typeof c.error === 'string' ? c.error : 'The check failed.' }),
|
|
325
|
+
use: x.remote || x.shadowedBy !== null || !u ? null : { calls: u.calls, runs: u.runs, last: u.last, denied: u.denied, tools: Object.fromEntries(u.tools) },
|
|
326
|
+
};
|
|
327
|
+
}),
|
|
328
|
+
}));
|
|
329
|
+
return reply(200, { ok: true, problem: src.problem, places });
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** the plain sentence for a failed `check tools`; the library's own message can hold the start command, so it is never passed on @param {any} e */
|
|
333
|
+
function checkFailure(e) {
|
|
334
|
+
if (e?.context?.timeout === true) return 'The server did not answer in time.';
|
|
335
|
+
if (e?.context?.spawnError === true) return 'The server did not start.';
|
|
336
|
+
if (e?.context?.notFound === true) return 'The server is not in the list any more.';
|
|
337
|
+
return 'The check failed.';
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** The one place a press starts a server: ONLY from this POST (never a page load or a GET), that one server, once, with the same start options as a run. */
|
|
341
|
+
async function mcpCheck(body) {
|
|
342
|
+
const server = body?.server;
|
|
343
|
+
if (typeof server !== 'string' || server === '') return refuse('bad-server', 'Pick an MCP to check. Nothing was started.');
|
|
344
|
+
const place = mcpSources({ home: cfg.home }).places.find((p) => p.servers.some((x) => x.name === server));
|
|
345
|
+
const row = place?.servers.find((x) => x.name === server);
|
|
346
|
+
if (!place || !row) return refuse('unknown-mcp', 'That MCP is not in the list. Nothing was started.');
|
|
347
|
+
if (row.remote) return refuse('remote-mcp', 'A remote server is not supported yet. Nothing was started.');
|
|
348
|
+
if (row.shadowedBy !== null) return refuse('shadowed-mcp', 'An earlier path has an MCP with this name, so this one is not used. Nothing was started.');
|
|
349
|
+
if (checking.has(server)) return refuse('already-checking', 'That MCP is being checked right now.', 409);
|
|
350
|
+
checking.add(server);
|
|
351
|
+
const line = { server, path: place.path, at: new Date(cfg.now ? cfg.now() : Date.now()).toISOString() };
|
|
352
|
+
try {
|
|
353
|
+
let entry;
|
|
354
|
+
try {
|
|
355
|
+
const tools = await listServerTools({ server, configPaths: [place.file], ...mcpStartOpts(), confirmServer: () => true, timeout: MCP_CHECK_MS });
|
|
356
|
+
entry = { ...line, ok: true, tools: tools.map((t) => ({ name: t.name, hint: hintOf(t.annotations) })) };
|
|
357
|
+
} catch (e) {
|
|
358
|
+
entry = { ...line, ok: false, error: checkFailure(e) };
|
|
359
|
+
}
|
|
360
|
+
try {
|
|
361
|
+
appendMcpCheck(cfg.home, entry);
|
|
362
|
+
} catch {
|
|
363
|
+
return refuse('log-failed', 'The check ran but its result could not be saved.', 500);
|
|
364
|
+
}
|
|
365
|
+
return reply(200, { ok: true, checked: entry.ok });
|
|
366
|
+
} finally {
|
|
367
|
+
checking.delete(server);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function mcpPathAdd(body) {
|
|
372
|
+
const typed = typeof body?.path === 'string' ? body.path.trim() : body?.path;
|
|
373
|
+
const why = mcpPathProblem(typed);
|
|
374
|
+
if (why) return refuse('bad-path', `The path ${why}. Nothing was saved.`);
|
|
375
|
+
const c = config();
|
|
376
|
+
if (c.problem) return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
|
|
377
|
+
const list = Array.isArray(c.config.mcpPaths) ? c.config.mcpPaths : [];
|
|
378
|
+
const same = (/** @type {string} */ a) => expandMcpPath(a) === expandMcpPath(typed);
|
|
379
|
+
if (DEFAULT_MCP_PLACES().some(same) || list.some(same)) return refuse('path-listed', 'That path is already in the list. Nothing was saved.');
|
|
380
|
+
try {
|
|
381
|
+
updateConfig({ mcpPaths: [...list, typed] }, { home: cfg.home });
|
|
382
|
+
} catch (e) {
|
|
383
|
+
if (!(e instanceof ConfigError)) throw e;
|
|
384
|
+
return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
|
|
385
|
+
}
|
|
386
|
+
return reply(200, { ok: true, path: typed });
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function mcpPathRemove(body) {
|
|
390
|
+
const c = config();
|
|
391
|
+
if (c.problem) return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
|
|
392
|
+
const list = Array.isArray(c.config.mcpPaths) ? c.config.mcpPaths : [];
|
|
393
|
+
if (typeof body?.path !== 'string' || !list.includes(body.path)) return refuse('path-unknown', 'That path is not one you added. Nothing was changed.');
|
|
394
|
+
const next = list.filter((/** @type {string} */ p) => p !== body.path);
|
|
395
|
+
try {
|
|
396
|
+
updateConfig({ mcpPaths: next.length ? next : null }, { home: cfg.home });
|
|
397
|
+
} catch (e) {
|
|
398
|
+
if (!(e instanceof ConfigError)) throw e;
|
|
399
|
+
return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
|
|
400
|
+
}
|
|
401
|
+
return reply(200, { ok: true });
|
|
402
|
+
}
|
|
403
|
+
|
|
293
404
|
/**
|
|
294
405
|
* @param {{ method: string, pathname: string, query: URLSearchParams, body: any }} r
|
|
295
406
|
* @returns {Promise<{ status: number, body: any }>}
|
|
296
407
|
*/
|
|
297
408
|
async function handle({ method, pathname, query, body }) {
|
|
298
409
|
if (cfg.skip) return refuse('settings-unavailable', 'Settings is not available here.', 404);
|
|
299
|
-
const known = { GET: ['/api/settings/providers', '/api/settings/money'], POST: ['/api/settings/open-keys-folder', '/api/settings/test', '/api/settings/models', '/api/settings/model', '/api/settings/provider', '/api/settings/money'] };
|
|
410
|
+
const known = { GET: ['/api/settings/providers', '/api/settings/money', '/api/settings/mcp'], POST: ['/api/settings/mcp-check', '/api/settings/mcp-path', '/api/settings/mcp-path-remove', '/api/settings/open-keys-folder', '/api/settings/test', '/api/settings/models', '/api/settings/model', '/api/settings/provider', '/api/settings/money'] };
|
|
300
411
|
if (!(known[method] ?? []).includes(pathname)) return refuse('no-such-settings-route', 'Settings cannot do that. Keys are typed into your keys file by hand.', 404);
|
|
301
412
|
if (method === 'GET') {
|
|
302
413
|
if (pathname === '/api/settings/providers') return providers();
|
|
414
|
+
if (pathname === '/api/settings/mcp') return mcpGet();
|
|
303
415
|
return moneyGet();
|
|
304
416
|
}
|
|
417
|
+
if (pathname === '/api/settings/mcp-check') return mcpCheck(body);
|
|
418
|
+
if (pathname === '/api/settings/mcp-path') return mcpPathAdd(body);
|
|
419
|
+
if (pathname === '/api/settings/mcp-path-remove') return mcpPathRemove(body);
|
|
305
420
|
if (pathname === '/api/settings/open-keys-folder') return openKeysFolder(body);
|
|
306
421
|
if (pathname === '/api/settings/test') return test(body);
|
|
307
422
|
if (pathname === '/api/settings/models') return models(body);
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// M12 piece 3 (docs/wiki/the-module-ladder.md, "M12 scope (restart)" item 9; mockup docs/product/m12-ticket-results-mock.html, variant E): the ticket list in the
|
|
2
|
+
// Result tab of the run the ticket schedule was set from. One row per ticket NUMBER, for all time: the ticket's newest run decides its group. The rows are read
|
|
3
|
+
// from the runs themselves (`run.json` keeps `ticket: {number, title}` for every ticket run, M12 p3) and the schedule ledger's `arrived` rows (arrival time, and
|
|
4
|
+
// the reason a watched change made a ticket arrive again). No file of its own; nothing written. Pure of the panel: the run lookups are injected.
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
|
|
7
|
+
import { readSchedule, ledgerOf } from '../schedule.js';
|
|
8
|
+
import { readSeen } from '../trigger-files.js';
|
|
9
|
+
import { compareNatural } from '../natural.js';
|
|
10
|
+
import { readRunInputs } from '../runfile.js';
|
|
11
|
+
import { recordAnyway } from '../trigger-tickets.js';
|
|
12
|
+
import { isTicketNumber, TICKET_NUMBER_WORDS } from '../ticket-shape.js';
|
|
13
|
+
|
|
14
|
+
/** the four groups, in the mockup's order: key, label, open at first. The page draws them; it types none of these words. */
|
|
15
|
+
export const TICKET_GROUPS = Object.freeze([
|
|
16
|
+
{ key: 'wait', label: 'Needs you', open: true },
|
|
17
|
+
{ key: 'stop', label: 'Stopped', open: true },
|
|
18
|
+
{ key: 'done', label: 'Passed', open: false },
|
|
19
|
+
{ key: 'skip', label: 'Skipped', open: false },
|
|
20
|
+
]);
|
|
21
|
+
|
|
22
|
+
/** a run's sign -> its group. Running / stuck / expired / waiting all need a person or are still going: Needs you. */
|
|
23
|
+
export const GROUP_OF = Object.freeze({
|
|
24
|
+
'[·]': 'wait', '[▶]': 'wait', '[II]': 'wait', '[!]': 'wait', '[✓]': 'done', '[–]': 'skip', '[✗]': 'stop', '[■]': 'stop', '[?]': 'stop',
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The ticket schedule this run was set from, or null (no schedule, not a ticket schedule, or set from another run).
|
|
29
|
+
* @param {string} flowDir @param {string} runId @param {(dir: string) => any} [readSched]
|
|
30
|
+
*/
|
|
31
|
+
export function ticketScheduleOf(flowDir, runId, readSched = readSchedule) {
|
|
32
|
+
const s = readSched(flowDir);
|
|
33
|
+
return s && s.trigger?.kind === 'new-ticket' && s.from === runId ? s : null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @param {{flowDir: string, runId: string, runIdsOf: (flowDir: string) => string[], glyphOf: (runId: string) => {glyph: string, label: string}|null, atOf?: (runId: string) => number|null, readSched?: (dir: string) => any}} a
|
|
38
|
+
* @returns {null | {line: string, list: string, groups: Array<{key: string, label: string, open: boolean, rows: any[]}>}}
|
|
39
|
+
*/
|
|
40
|
+
export function ticketListOf({ flowDir, runId, runIdsOf, glyphOf, atOf = () => null, readSched }) {
|
|
41
|
+
const sched = ticketScheduleOf(flowDir, runId, readSched);
|
|
42
|
+
if (!sched) return null;
|
|
43
|
+
const arrivals = new Map();
|
|
44
|
+
for (const r of /** @type {any[]} */ (readSeen(ledgerOf(flowDir), sched.sig))) {
|
|
45
|
+
if (r.kind !== 'arrived' || !Number.isInteger(r.number)) continue;
|
|
46
|
+
const a = arrivals.get(r.number) ?? { first: r.at, last: r.at, count: 0, reason: null };
|
|
47
|
+
arrivals.set(r.number, { first: Math.min(a.first, r.at), last: Math.max(a.last, r.at), count: a.count + 1, reason: typeof r.reason === 'string' ? r.reason : a.reason });
|
|
48
|
+
}
|
|
49
|
+
/** @type {Map<number, any>} */
|
|
50
|
+
const byNumber = new Map();
|
|
51
|
+
for (const id of runIdsOf(flowDir)) {
|
|
52
|
+
const runDir = join(flowDir, 'runs', id);
|
|
53
|
+
const inputs = readRunInputs(runDir);
|
|
54
|
+
const entry = inputs.ok ? inputs.entries.find((e) => e && e.ticket && Number.isInteger(e.ticket.number)) : null;
|
|
55
|
+
if (!entry) continue;
|
|
56
|
+
const g = glyphOf(id);
|
|
57
|
+
if (!g) continue;
|
|
58
|
+
const at = atOf(id) ?? Date.now();
|
|
59
|
+
const n = entry.ticket.number;
|
|
60
|
+
const arr = arrivals.get(n);
|
|
61
|
+
const row = {
|
|
62
|
+
number: n, title: typeof entry.ticket.title === 'string' ? entry.ticket.title : null, group: GROUP_OF[g.glyph] ?? 'stop', glyph: g.glyph,
|
|
63
|
+
runId: id, at: arr ? arr.last : at,
|
|
64
|
+
reason: g.glyph === '[–]' ? g.label.replace(/^skipped — ?/, '') || null : null,
|
|
65
|
+
changed: arr && arr.count > 1 ? arr.reason : null,
|
|
66
|
+
};
|
|
67
|
+
const prior = byNumber.get(n);
|
|
68
|
+
if (!prior || compareNatural(id, prior.runId) > 0) byNumber.set(n, row);
|
|
69
|
+
}
|
|
70
|
+
const rows = [...byNumber.values()].sort((a, b) => b.at - a.at || b.number - a.number);
|
|
71
|
+
return {
|
|
72
|
+
line: `When a new ticket arrives in ${sched.trigger.role} · looks every 15 min`,
|
|
73
|
+
list: sched.trigger.list,
|
|
74
|
+
groups: TICKET_GROUPS.map((g) => ({ ...g, rows: rows.filter((r) => r.group === g.key) })),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** a "Run it anyway" reason: short, never blank. The same bar as a rerun's. */
|
|
79
|
+
export const ANYWAY_REASON_MAX = 500;
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* `POST /api/author/ticket-anyway`: queue a SKIPPED ticket as a new arrival, after a short reason. Without a reason nothing starts. The queue is the schedule builder's:
|
|
83
|
+
* `queue.arriveAnyway({flow, number, reason})` is the ONE seam (production: `arriveAnywayOf`).
|
|
84
|
+
* @param {{body: any, listOf: (flow: string, runId: string) => ReturnType<typeof ticketListOf>, queue: {arriveAnyway: (a: {flow: string, runId: string, number: number, reason: string}) => {ok: boolean, say?: string, started?: boolean}}}} a
|
|
85
|
+
* @returns {{status: number, body: Record<string, any>}}
|
|
86
|
+
*/
|
|
87
|
+
export function ticketAnyway({ body, listOf, queue }) {
|
|
88
|
+
const b = body !== null && typeof body === 'object' ? body : {};
|
|
89
|
+
const reason = typeof b.reason === 'string' ? b.reason.trim() : '';
|
|
90
|
+
if (reason === '') return { status: 400, body: { ok: false, refused: 'reason-required', say: 'Please write a reason to run it anyway.' } };
|
|
91
|
+
if (reason.length > ANYWAY_REASON_MAX) return { status: 400, body: { ok: false, refused: 'reason-too-long', say: `Keep the reason under ${ANYWAY_REASON_MAX} characters. Nothing started.` } };
|
|
92
|
+
if (typeof b.flow !== 'string' || typeof b.runId !== 'string' || !isTicketNumber(b.number)) return { status: 400, body: { ok: false, refused: 'bad-request', say: `Name the job, the run and the ticket number (${TICKET_NUMBER_WORDS}). Nothing started.` } };
|
|
93
|
+
const list = listOf(b.flow, b.runId);
|
|
94
|
+
const row = list?.groups.find((g) => g.key === 'skip')?.rows.find((r) => r.number === b.number);
|
|
95
|
+
if (!row) return { status: 409, body: { ok: false, refused: 'not-skipped', say: `Ticket #${b.number} is not a skipped ticket of this list. Nothing started.` } };
|
|
96
|
+
const r = queue.arriveAnyway({ flow: b.flow, runId: b.runId, number: b.number, reason });
|
|
97
|
+
if (!r.ok) return { status: 409, body: { ok: false, refused: 'queue', say: r.say ?? 'The ticket was not queued. Nothing started.' } };
|
|
98
|
+
if (r.started === true) return { status: 202, body: { ok: true, started: true, number: b.number, say: r.say } }; // M13 am3: the schedule is off, so the run started at once
|
|
99
|
+
return { status: 202, body: { ok: true, queued: true, number: b.number, say: `Ticket #${b.number} is queued; it runs when its turn comes.` } };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The production queue seam: ONE `arrived` row (`recordAnyway`, the ledger's writer) in the job's schedule ledger, so the scheduler's queue starts the ticket as a new
|
|
104
|
+
* arrival under the job's normal cap. A job with no live ticket schedule is refused by name, at $0, with nothing written.
|
|
105
|
+
* M13 am3: a ticket schedule that is signed but OFF (`startAnyway`, the trigger door's one by-hand start) starts the ticket at once instead; it writes no row.
|
|
106
|
+
* @param {{scan: () => any[], now: () => number, startAnyway?: (a: {flow: string, number: number}) => {ok: boolean, say: string} | null}} a
|
|
107
|
+
* @returns {{arriveAnyway: (a: {flow: string, runId: string, number: number, reason: string}) => {ok: boolean, say?: string, started?: boolean}}}
|
|
108
|
+
*/
|
|
109
|
+
export function arriveAnywayOf({ scan, now, startAnyway }) {
|
|
110
|
+
return {
|
|
111
|
+
arriveAnyway({ flow, number, reason }) {
|
|
112
|
+
const job = scan().find((j) => j.flow === flow && j.trigger?.kind === 'new-ticket');
|
|
113
|
+
if (!job && startAnyway) { const r = startAnyway({ flow, number }); if (r !== null) return { ok: r.ok, say: r.say, started: r.ok }; }
|
|
114
|
+
if (!job) return { ok: false, say: `Job "${flow}" has no live ticket schedule, so Run it anyway has no queue to join. Nothing started.` };
|
|
115
|
+
return recordAnyway(ledgerOf(job.flowDir), job.sig, { number, reason }, now());
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
}
|