Drei Sachen, die nie gelaufen sind, weil die CI fuer die api noch nicht existierte. canDropPrivileges faellt unter Linux zu, solange der Prozess nicht root ist und kein `coach`-User im Image steht. Ein CI-Runner ist Linux, laeuft als normaler User und hat keinen `coach` — also hat dort jedes enqueue() refused, und acht Tests waeren mit dem neuen api-Job rot geworden. Die Suite pinnt das Urteil jetzt selbst, statt es vom Host zu erben; der Test, dem die Verweigerung selbst gehoert, pinnt die Gegenrichtung und laeuft damit erstmals wirklich (vorher sprang er auf jedem Host raus, auf dem der Drop zufaellig klappte — und rief require() in einem ESM-Modul auf). testRun() griff auf ein `job`, das in seinem Scope nicht existiert: ReferenceError bei jedem Klick auf "Test the Coach", und weil der Wurf vor dem try lag, blieb jedes Mal ein Temp-Verzeichnis liegen. Ohne Nutzer gibt es kein Profil, das zahlt — im Instance-Modus ist das der gebundene Credential, im Profile-Modus niemand. Danach antwortete die Fixture auf den Test-Prompt mit einem ganzen Trainingsplan, weil ohne Payload-Fence auf 'create' geraten wird. Genau dieser fehlende Fence unterscheidet den Rundlauf von einem echten Job. Dazu zwei Kleinigkeiten: /api/coach/disclosure verriet den Provider an Nicht-Angemeldete, und der Poll, der ein Proposal verfallen laesst, lieferte als einziger kein cap-Feld zurueck.
175 lines
7.8 KiB
JavaScript
175 lines
7.8 KiB
JavaScript
/* HTTP surface for the Coach — user routes and admin routes.
|
|
*
|
|
* Written as a factory taking server.js's own helpers rather than importing them: the helpers
|
|
* are closures over the db and the session secret, and passing them in keeps this module free
|
|
* of a cycle (and trivially testable against fakes).
|
|
*/
|
|
import * as cfgStore from './config.js';
|
|
import * as jobs from './jobs.js';
|
|
import { adapterFor } from './adapters/index.js';
|
|
import { canDropPrivileges } from './adapters/spawn.js';
|
|
import { DATA_CATEGORIES } from './payload.js';
|
|
|
|
// Job failures the user sees, in the app's own voice. The raw provider detail never reaches
|
|
// them — it goes to the admin card, which is where someone can act on it (FR-47).
|
|
const USER_ERROR = {
|
|
off: 'the Coach is not set up on this instance',
|
|
busy: 'the Coach is already thinking about your training',
|
|
cap: 'the Coach is resting — try again tomorrow',
|
|
consent: 'the Coach needs your go-ahead first',
|
|
// Verbatim, because it tells the user the one thing that resolves it and names who resolves
|
|
// it. A vaguer message here turns into a support question for the person running the box.
|
|
shared: cfgStore.SHARED_ACCOUNT_REFUSAL,
|
|
unprivileged: 'the Coach is switched off on this instance for safety reasons'
|
|
};
|
|
const HTTP_FOR = { off: 503, busy: 409, cap: 429, consent: 403, shared: 409, unprivileged: 503 };
|
|
|
|
export function coachRoutes({ json, readBody, readSession, requireAdmin }) {
|
|
/** Every user route starts the same way: signed in, feature on, feature reachable. */
|
|
const guard = (req, res) => {
|
|
const user = readSession(req);
|
|
if (!user) { json(res, 401, { error: 'not signed in' }); return null; }
|
|
if (!cfgStore.isEnabled() || !cfgStore.isConnected()) { json(res, 503, { error: USER_ERROR.off }); return null; }
|
|
return user;
|
|
};
|
|
const failEnqueue = (res, e) => {
|
|
if (e instanceof jobs.CoachError) return json(res, HTTP_FOR[e.code] || 400, { error: USER_ERROR[e.code] || e.message, code: e.code });
|
|
throw e;
|
|
};
|
|
|
|
return {
|
|
/* ------------------------------ user ------------------------------ */
|
|
|
|
// What the consent screen has to disclose, straight from the module that builds payloads,
|
|
// so the screen cannot drift from what actually leaves (FR-09). Signed in only: the screen
|
|
// that reads it sits behind a session anyway, and on an invite-only instance which provider
|
|
// this box is wired to is nobody's business who has not been let in.
|
|
'GET /api/coach/disclosure': async (req, res) => {
|
|
if (!readSession(req)) return json(res, 401, { error: 'not signed in' });
|
|
const cfg = cfgStore.load();
|
|
json(res, 200, {
|
|
provider: cfg.provider,
|
|
providerLabel: cfgStore.providerMeta(cfg).label,
|
|
categories: DATA_CATEGORIES,
|
|
version: 1
|
|
});
|
|
},
|
|
|
|
'GET /api/coach/status': async (req, res) => {
|
|
const user = guard(req, res); if (!user) return;
|
|
json(res, 200, jobs.status(user.id));
|
|
},
|
|
|
|
'POST /api/coach/plan': async (req, res) => {
|
|
const user = guard(req, res); if (!user) return;
|
|
const body = await readBody(req);
|
|
try {
|
|
const job = jobs.enqueue(user.id, {
|
|
kind: 'create',
|
|
intake: body.intake || null,
|
|
refine: body.refine ? String(body.refine).slice(0, 1000) : null
|
|
});
|
|
json(res, 202, { job });
|
|
} catch (e) { failEnqueue(res, e); }
|
|
},
|
|
|
|
'POST /api/coach/review': async (req, res) => {
|
|
const user = guard(req, res); if (!user) return;
|
|
const body = await readBody(req);
|
|
try {
|
|
const job = jobs.enqueue(user.id, { kind: 'review', note: body.note ? String(body.note).slice(0, 1000) : null });
|
|
json(res, 202, { job });
|
|
} catch (e) { failEnqueue(res, e); }
|
|
},
|
|
|
|
'POST /api/coach/pending/resolve': async (req, res) => {
|
|
const user = guard(req, res); if (!user) return;
|
|
const body = await readBody(req);
|
|
json(res, 200, jobs.resolvePending(user.id, {
|
|
accepted: Array.isArray(body.accepted) ? body.accepted : [],
|
|
rejected: Array.isArray(body.rejected) ? body.rejected : [],
|
|
dismissed: !!body.dismissed
|
|
}));
|
|
},
|
|
|
|
// Consent withdrawn, or the profile turned the Coach off: drop everything held server-side
|
|
// for them at once, without waiting for a sync to carry the news (D5).
|
|
'POST /api/coach/forget': async (req, res) => {
|
|
const user = readSession(req);
|
|
if (!user) return json(res, 401, { error: 'not signed in' });
|
|
jobs.clearUser(user.id);
|
|
json(res, 200, { ok: true });
|
|
},
|
|
|
|
/* ------------------------------ admin ------------------------------ */
|
|
|
|
'GET /api/admin/coach': async (req, res) => {
|
|
if (!requireAdmin(req, res)) return;
|
|
const cfg = cfgStore.load();
|
|
const adapter = adapterFor(cfg.provider);
|
|
const check = adapter ? await adapter.check(cfg, cfgStore.jobEnv(process.env.TMPDIR || '/tmp')) : { ok: false, error: 'unknown provider' };
|
|
const log = cfg.log || [];
|
|
const today = new Date().toISOString().slice(0, 10);
|
|
json(res, 200, {
|
|
disabledByEnv: cfgStore.COACH_DISABLED,
|
|
enabled: !!cfg.enabled,
|
|
provider: cfg.provider,
|
|
providers: Object.entries(cfgStore.PROVIDERS).map(([id, p]) => ({ id, label: p.label, runtime: p.runtime, setupToken: !!p.setupToken, deviceLogin: !!p.deviceLogin, apiKey: !!p.apiKeyEnv })),
|
|
model: cfg.model,
|
|
caps: cfg.caps,
|
|
runtime: { ok: !!check.ok, version: check.version || null, error: check.error || null },
|
|
authMode: cfg.authMode,
|
|
boundUid: cfg.boundUid || null,
|
|
// Whether the privilege drop can actually be performed. Surfaced because the control
|
|
// now fails closed: if this reads false, no job runs, and the admin needs to know that
|
|
// from the card rather than from a user reporting that nothing happens.
|
|
unprivileged: canDropPrivileges(),
|
|
// Counts and outcomes only — never intake answers, payloads or proposals (FR-12/A4).
|
|
jobsToday: log.filter(e => (e.at || '').slice(0, 10) === today).length,
|
|
lastSuccess: cfgStore.lastSuccess(),
|
|
lastError: cfgStore.lastError(),
|
|
recent: log.slice(-20).reverse().map(e => ({ at: e.at, kind: e.kind, trigger: e.trigger, outcome: e.outcome, errorClass: e.errorClass, ms: e.ms }))
|
|
});
|
|
},
|
|
|
|
'POST /api/admin/coach/config': async (req, res) => {
|
|
if (!requireAdmin(req, res)) return;
|
|
const body = await readBody(req);
|
|
const patch = {};
|
|
if (body.enabled !== undefined) patch.enabled = !!body.enabled;
|
|
if (body.provider !== undefined) {
|
|
if (!cfgStore.PROVIDERS[body.provider]) return json(res, 400, { error: 'unknown provider' });
|
|
// Credentials belong to the provider that issued them.
|
|
if (body.provider !== cfgStore.load().provider) patch.auth = null;
|
|
patch.provider = body.provider;
|
|
}
|
|
if (body.model !== undefined) patch.model = body.model ? String(body.model).slice(0, 80) : null;
|
|
if (body.caps) {
|
|
patch.caps = {
|
|
perProfileDaily: Math.max(0, Math.min(200, +body.caps.perProfileDaily || 0)),
|
|
instanceDaily: Math.max(0, Math.min(5000, +body.caps.instanceDaily || 0))
|
|
};
|
|
}
|
|
cfgStore.save(patch);
|
|
json(res, 200, { ok: true });
|
|
},
|
|
|
|
'POST /api/admin/coach/test': async (req, res) => {
|
|
if (!requireAdmin(req, res)) return;
|
|
const r = await jobs.testRun();
|
|
json(res, 200, r);
|
|
},
|
|
|
|
|
|
|
|
|
|
/* Whose account this profile is about to spend. Its own route because both the Coach screen
|
|
and the admin card must state it, and neither should be inferring it from settings. */
|
|
'GET /api/coach/account': async (req, res) => {
|
|
const user = readSession(req);
|
|
if (!user) return json(res, 401, { error: 'not signed in' });
|
|
json(res, 200, cfgStore.accountFor(user.id));
|
|
}
|
|
};
|
|
}
|