The WebUI packs receipt passes routeFrom through on each hire line; the WebUI README and TOOLS.md name it. The starter packs design doc gets a dated note for the 2026-11-14 route ruling. New bus tests: a member pack hire on the assistant route marks hired and awaiting-owner lines routeFrom assistant, and a project pack with no chief route hires into the project on the assistant's harness and model.
178 lines
13 KiB
JavaScript
178 lines
13 KiB
JavaScript
// Starter packs SP4 (#1873, design section 8): the owner's pack, board and workflow routes on a
|
|
// selected organization. Owner Console transports only; no caller-supplied business, actor, subject
|
|
// or origin reaches the bus.
|
|
//
|
|
// GET /api/orgs/<id>/packs {packs, applied, writable}: packs.console, the shipped and installed
|
|
// packs (never a saved template), and each applied entry with the
|
|
// agents its hires created and its open proposals. /api/packs on a root Console.
|
|
// POST /api/orgs/<id>/packs/preview {pack, project?, as?}: pack.preview.console. Writes nothing.
|
|
// POST /api/orgs/<id>/packs/apply {pack, digest, project?, as?}: pack.apply.console. Ruling 2026-11-14:
|
|
// the owner's apply is the hire decision; the receipt carries `hires`
|
|
// POST /api/orgs/<id>/packs/hire {pack, project?}: pack.hire.console, the proposals of a pack already
|
|
// applied, hired through the same loop. {pack, hires}
|
|
// POST /api/orgs/<id>/board {revision, board, project?}: board.set.console (board null removes it)
|
|
// POST /api/orgs/<id>/workflows/<name> {revision, workflow, project?}: workflow.set.console
|
|
// DELETE /api/orgs/<id>/workflows/<name> {revision, project?}: workflow.set.console with workflow null
|
|
// GET /api/orgs/<id>/workflows {workflows, projects, roles, revision, writable} (SP6): the org's and
|
|
// each code project's workflows, the role names a step may resolve to
|
|
// now (org definitions and V2 templates; `human` always does), and the
|
|
// file revision a workflow write sends back
|
|
//
|
|
// `read` is the owner's Console call (consoleCall), used for the two verbs that write nothing. `write`
|
|
// is the owner's Console call fenced to the four write verbs (packsCaller), present only for the
|
|
// owner's own session under --send. The broker answers every .console verb to the business human's
|
|
// console cap alone, and runs the merge, the digest and the held-credential check itself. `workflows`
|
|
// (SP6) is the owner's read of the organization file as the writer reads it ({document, revision,
|
|
// templates}), the same read `mosaic org workflow set` takes its revision from; no bus verb answers it.
|
|
export const PACKS_ROUTE = /^\/api\/(?:packs(?:\/(preview|apply|hire))?|board|workflows(?:\/([^/]+))?)$/;
|
|
// Which requests the pack route answers. GET and HEAD /api/board stay the Board read (the Console's own task
|
|
// board through its upstream); every other method on /api/board is this route's (POST writes, the rest 405).
|
|
// serve.mjs dispatches on this, so the HEAD pin in packs-http.test.mjs tests the predicate it uses.
|
|
export const packsServes = (path, method) => PACKS_ROUTE.test(path) && !(path === '/api/board' && (method === 'GET' || method === 'HEAD'));
|
|
export const PACK_WRITE_VERBS = Object.freeze(['pack.apply.console', 'pack.hire.console', 'board.set.console', 'workflow.set.console']);
|
|
export const packsCaller = call => async (verb, args, options) => {
|
|
if (!PACK_WRITE_VERBS.includes(verb)) throw new Error(`the pack writer does not call ${verb}`);
|
|
return call(verb, args, options);
|
|
};
|
|
// A pack id, project id or workflow name: the bus's own name rule (vocabulary KIND_NAME, PACK_AS).
|
|
const NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
const SAVED = /^saved:[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
const REVISION = /^[a-f0-9]{64}$/;
|
|
// A board or workflow body stays small; the organization config caps both (WORKFLOWS_MAX, board columns).
|
|
const LIMIT = 65536;
|
|
const codes = {
|
|
'invalid-request': 400, 'credential-leak': 400, 'starter-pack-invalid': 400, 'definition-invalid': 400,
|
|
'starter-pack-not-found': 404, 'project-not-found': 404, 'pack-not-applied': 404,
|
|
'pack-plan-stale': 409, 'revision-conflict': 409, 'organization-busy': 409,
|
|
'human-required': 403, 'read-only': 403, 'right-required': 403,
|
|
'not-configured': 503, 'no-bus-host': 503,
|
|
};
|
|
const one = (req, key) => req.headersDistinct[key]?.length === 1 ? req.headersDistinct[key][0] : null;
|
|
function json(res, status, value) {
|
|
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
res.end(JSON.stringify(value));
|
|
}
|
|
const plain = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
|
|
// The body names exactly the required keys and any of the optional ones; nothing else reaches the bus.
|
|
async function body(req, required, optional) {
|
|
if (one(req, 'content-type')?.split(';')[0].trim().toLowerCase() !== 'application/json') return null;
|
|
const chunks = []; let size = 0;
|
|
for await (const chunk of req) { size += chunk.length; if (size > LIMIT) return 'too-large'; chunks.push(chunk); }
|
|
let value;
|
|
try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return null; }
|
|
if (!plain(value) || !required.every(k => Object.hasOwn(value, k)) || Object.keys(value).some(k => !required.includes(k) && !optional.includes(k))) return null;
|
|
return value;
|
|
}
|
|
|
|
export async function packsHTTP(req, res, { path, owner, read, write, workflows = null, session, live, origin }) {
|
|
const refuse = (status, error) => json(res, status, { error });
|
|
const fail = error => { const code = codes[error?.code] ? error.code : 'outcome-unknown'; return refuse(codes[code] ?? 503, code); };
|
|
const match = PACKS_ROUTE.exec(path);
|
|
const step = match?.[1] ?? null;
|
|
let name = null;
|
|
if (match?.[2] !== undefined) {
|
|
try { name = decodeURIComponent(match[2]); } catch { return refuse(400, 'invalid-request'); }
|
|
if (!NAME.test(name)) return refuse(400, 'invalid-request');
|
|
}
|
|
const list = path === '/api/packs', flows = path === '/api/workflows';
|
|
const allowed = list || flows ? ['GET'] : name !== null ? ['POST', 'DELETE'] : ['POST'];
|
|
if (!allowed.includes(req.method)) return refuse(405, 'method-not-allowed');
|
|
// A method the route never serves answers 405 first; every served method is the root owner's.
|
|
if (!owner) return refuse(403, 'owner-only');
|
|
if (!session) return refuse(401, 'sign-in-required');
|
|
if (flows ? !workflows : !read) return refuse(503, 'not-configured');
|
|
const writes = !list && !flows && step !== 'preview';
|
|
if (writes && !write) return refuse(403, 'read-only');
|
|
const site = one(req, 'sec-fetch-site'), from = one(req, 'origin');
|
|
if (req.method !== 'GET' ? from !== origin || site !== 'same-origin'
|
|
: (req.headersDistinct.origin && from !== origin) || (req.headersDistinct['sec-fetch-site'] && !['same-origin', 'none'].includes(site)))
|
|
return refuse(403, 'cross-origin');
|
|
|
|
if (flows) return workflowsRead(res, { workflows, live, session, writable: Boolean(write) });
|
|
let verb, args = {};
|
|
if (list) verb = 'packs.console';
|
|
else if (step !== null) {
|
|
const value = await body(req, step === 'apply' ? ['pack', 'digest'] : ['pack'], step === 'hire' ? ['project'] : ['project', 'as']);
|
|
if (value === 'too-large') return refuse(413, 'invalid-request');
|
|
if (!value || typeof value.pack !== 'string' || !(NAME.test(value.pack) || SAVED.test(value.pack))
|
|
|| (step === 'apply' && (typeof value.digest !== 'string' || !REVISION.test(value.digest)))
|
|
|| (value.project !== undefined && (typeof value.project !== 'string' || !NAME.test(value.project)))
|
|
|| (value.as !== undefined && (!Array.isArray(value.as) || value.as.length > 32 || value.as.some(a => typeof a !== 'string' || a.length > 200))))
|
|
return refuse(400, 'invalid-request');
|
|
verb = `pack.${step}.console`;
|
|
args = value;
|
|
} else {
|
|
const value = await body(req, name === null ? ['revision', 'board'] : req.method === 'DELETE' ? ['revision'] : ['revision', 'workflow'], ['project']);
|
|
if (value === 'too-large') return refuse(413, 'invalid-request');
|
|
if (!value || typeof value.revision !== 'string' || !REVISION.test(value.revision)
|
|
|| (value.project !== undefined && (typeof value.project !== 'string' || !NAME.test(value.project))))
|
|
return refuse(400, 'invalid-request');
|
|
if (name === null) {
|
|
if (value.board !== null && !plain(value.board)) return refuse(400, 'invalid-request');
|
|
verb = 'board.set.console';
|
|
args = value;
|
|
} else {
|
|
if (req.method === 'POST' && !plain(value.workflow)) return refuse(400, 'invalid-request');
|
|
verb = 'workflow.set.console';
|
|
args = { revision: value.revision, name, workflow: req.method === 'DELETE' ? null : value.workflow, ...(value.project === undefined ? {} : { project: value.project }) };
|
|
}
|
|
}
|
|
|
|
// The session is checked again after the body is read: a sign-out meanwhile dispatches nothing.
|
|
if (live() !== session) return refuse(401, 'sign-in-required');
|
|
const subject = { provider: session.provider, iss: session.iss, sub: session.sub };
|
|
let result;
|
|
try { result = writes ? await write(verb, args, { subject }) : await read(verb, args, { subject }); }
|
|
catch (error) { return fail(error); }
|
|
if (!plain(result)) return refuse(503, 'outcome-unknown');
|
|
if (list) {
|
|
if (!Array.isArray(result.packs)) return refuse(503, 'outcome-unknown');
|
|
const applied = Array.isArray(result.applied) ? result.applied.filter(plain).map(a => ({ id: a.id, origin: a.origin ?? null, project: a.project ?? null,
|
|
hired: Array.isArray(a.hired) ? a.hired.filter(n => typeof n === 'string') : [],
|
|
open: Array.isArray(a.open) ? a.open.filter(plain).map(o => ({ name: o.name, reason: typeof o.reason === 'string' ? o.reason : '', state: o.state, ...(typeof o.code === 'string' ? { code: o.code } : {}), ...(typeof o.decision === 'string' ? { decision: o.decision } : {}), ...(o.fromPack === true ? { fromPack: true } : {}) })) : [] })) : [];
|
|
return json(res, 200, { packs: result.packs, applied, writable: Boolean(write) });
|
|
}
|
|
if (step === 'preview') {
|
|
if (!REVISION.test(result.digest ?? '')) return refuse(503, 'outcome-unknown');
|
|
return json(res, 200, result);
|
|
}
|
|
// A write admitted may already have committed: its receipt is returned even if the session ended
|
|
// meanwhile, never reported as not done. Each hire line is its name, state and decision or code,
|
|
// and for a raised hire routeFrom, whose harness and model it got (lane pr2).
|
|
const hires = Array.isArray(result.hires) ? result.hires.filter(plain).map(h => ({ name: h.name, state: h.state,
|
|
...(typeof h.decision === 'string' ? { decision: h.decision } : {}), ...(typeof h.code === 'string' ? { code: h.code } : {}),
|
|
...(['chief', 'assistant'].includes(h.routeFrom) ? { routeFrom: h.routeFrom } : {}) })) : null;
|
|
if (step === 'hire') {
|
|
if (!hires) return refuse(503, 'outcome-unknown');
|
|
return json(res, 200, { pack: result.pack, hires });
|
|
}
|
|
if (!REVISION.test(result.revision ?? '')) return refuse(503, 'outcome-unknown');
|
|
// hireError: the apply committed but its hire loop did not run (organization-busy, outcome-unknown).
|
|
const hireError = step === 'apply' && typeof result.hireError === 'string' && /^[a-z0-9-]{1,64}$/.test(result.hireError) ? { hireError: result.hireError } : {};
|
|
return json(res, 200, { revision: result.revision, added: Array.isArray(result.added) ? result.added : [], ...(step === 'apply' ? { pack: result.pack, hires: hires ?? [], ...hireError } : {}) });
|
|
}
|
|
|
|
// SP6: the workflow list and editor's read. Only workflows, the names a step role may resolve to and the
|
|
// revision leave; nothing else of the organization file does. A workflow stays as the file holds it, so a
|
|
// step naming a role that no longer resolves is shown as written and the page marks it.
|
|
async function workflowsRead(res, { workflows, live, session, writable }) {
|
|
const refuse = (status, error) => json(res, status, { error });
|
|
let current;
|
|
try { current = await workflows(); } catch { return refuse(503, 'org-unavailable'); }
|
|
const doc = current?.document;
|
|
if (!plain(doc) || !REVISION.test(current.revision ?? '') || !Array.isArray(current.templates)) return refuse(503, 'outcome-unknown');
|
|
// A sign-out while the file was read shows nothing.
|
|
if (live() !== session) return refuse(401, 'sign-in-required');
|
|
const flowsOf = scope => (plain(scope?.workflows) ? scope.workflows : {});
|
|
const projects = {};
|
|
for (const [id, entry] of Object.entries(plain(doc.projects) ? doc.projects : {})) {
|
|
if (plain(entry) && entry.kind !== 'library') projects[id] = flowsOf(entry);
|
|
}
|
|
const roles = {
|
|
definitions: Object.keys(plain(doc.definitions) ? doc.definitions : {}).sort(),
|
|
templates: current.templates.filter(n => typeof n === 'string').sort(),
|
|
};
|
|
return json(res, 200, { workflows: flowsOf(doc), projects, roles, revision: current.revision, writable });
|
|
}
|