// #1873 Phase A slice A2: the owner's Settings > Agents writes for the root and project agent levels // (design docs/plans/2026-11-10_agent-levels-design.md sections 6, 7 and 9 item 1). // // GET /api/agents/root root entries, the file's revision, writable // POST /api/agents/root {revision, name, entry}: entry is a patch // {definition?, vars?, excludeOrgs?} (a var // set to null is removed) or null to remove // GET /api/orgs//agent-levels/projects/ the project's entries and the org revision // POST /api/orgs//agent-levels/projects/ {revision, name, entry}: entry is a define // {definition, vars?}, a narrow {vars}, an // exclude {exclude: true} or null to remove // // These are registered hooks, so serve.mjs's hook fence runs first, as it does for // /api/agents/levels: a signed-in session on the page's name, no granted user on a write, and on a // POST the exact Origin and Sec-Fetch-Site: same-origin. An org path is resolved for the session // before the hook runs. Here: the owner's own session only (owner-only otherwise), and a POST only // when the Console was started with writes on (read-only otherwise). The writers then check again: // the root writer takes the session's principal as the owner, and the project writer acts as the // organization's human, as the bus's human transport does. // // A response or trail entry names agents, keys and revisions, never a var value or a host path. import { organizationWriter } from '../../organization/src/organization.mjs'; import { changeRootAgent, patchRootEntry, projectAgentSummary, readRootAgentsFile, rootAgentSummary } from '../../organization/src/agent-levels-write.mjs'; import { ID_PATTERN } from '../../organization/src/vocabulary.mjs'; import { actor } from './action-trail.mjs'; export const ROOT_ROUTE = '/api/agents/root'; export const PROJECT_ROUTE = /^\/api\/orgs\/([^/]+)\/agent-levels\/projects\/([^/]+)$/; // routeTable takes GET and POST only; any other method never reaches these hooks (serve.mjs answers it). const METHODS = ['GET', 'POST']; const REVISION = /^[a-f0-9]{64}$/; // Agent and project names are the writers' ids (requireId): checked here so a bad one is a 400 // naming the field, not a writer error the Console can't classify. const NAME = ID_PATTERN; const NAME_RULE = 'lowercase letters, digits, dot, dash or underscore, at most 64'; const LIMIT = 4096; const ROOT_PATCH = ['definition', 'vars', 'excludeOrgs']; const PROJECT_ENTRY = ['definition', 'vars', 'exclude']; const STATUS = { 'invalid-request': 400, 'agents-invalid': 400, 'project-agents-invalid': 400, 'project-agents-library': 400, 'no-change': 400, 'human-required': 403, 'owner-only': 403, 'read-only': 403, 'project-not-found': 404, 'agent-not-found': 404, 'revision-conflict': 409, 'agents-locked': 409, 'organization-busy': 409, 'agents-unsafe': 503, 'organization-uncertain': 503, }; // The writers' own text for these codes names keys and ids only (A1's checks and the A2 scrubber). const SAYS = new Set(['agents-invalid', 'project-agents-invalid', 'project-agents-library', 'no-change', 'human-required', 'project-not-found', 'agent-not-found', 'revision-conflict', 'agents-locked', 'organization-busy', 'agents-unsafe']); const FIXED = { 'outcome-unknown': 'the change may have been made; nothing was retried. Read the agents again before trying', committed: 'the change was written; its receipt may be missing. Read the agents again before trying', }; 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; charset=utf-8', 'cache-control': 'no-store' }); res.end(JSON.stringify(value)); } const plain = value => value !== null && typeof value === 'object' && !Array.isArray(value); // Every string a var value carries, and each non-string value as JSON: a refusal that quotes any of // them gets a fixed line instead. function values(entry) { const out = []; const walk = v => { if (typeof v === 'string') { if (v.length >= 3) out.push(v); } else if (Array.isArray(v)) v.forEach(walk); else if (plain(v)) Object.entries(v).forEach(([k, x]) => { if (k.length >= 3) out.push(k); walk(x); }); else if (v !== null && v !== undefined) out.push(JSON.stringify(v)); }; if (plain(entry?.vars)) Object.values(entry.vars).forEach(walk); return out.filter(s => s.length >= 3); } // A coded refusal's own text when it names no value and no path; a fixed line otherwise. function refusal(error, entry) { const code = typeof error?.code === 'string' && Object.hasOwn(STATUS, error.code) ? error.code : 'outcome-unknown'; if (error?.committed) return { status: 503, body: { error: 'receipt-missing', committed: true, message: FIXED.committed } }; const text = typeof error?.message === 'string' ? error.message : ''; const quoted = values(entry).some(v => text.includes(v)); const message = SAYS.has(code) && text && text.length <= 400 && !text.includes('/') && !quoted ? text : (FIXED[code] ?? 'refused'); return { status: STATUS[code] ?? 503, body: { error: code, message } }; } async function body(req) { 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; } const keys = ['revision', 'name', 'entry']; if (!plain(value) || Object.keys(value).length !== keys.length || !keys.every(k => Object.hasOwn(value, k))) return null; if (typeof value.revision !== 'string' || !REVISION.test(value.revision) || typeof value.name !== 'string') return null; if (!NAME.test(value.name)) return 'bad-name'; return value; } const only = (entry, keys) => plain(entry) && Object.keys(entry).length > 0 && Object.keys(entry).every(k => keys.includes(k)); // `configDir` and `rolesDir` are the instance's; `trail` is the Console action trail. export function agentLevelsWriteRoutes({ configDir, rolesDir, trail = null, log = () => {} }) { const writer = organizationWriter({ dir: configDir, rolesDir }); const note = (session, entry) => { if (!trail) return; try { trail({ by: actor(session), ...entry }); } catch { log(`${new Date().toISOString()} trail write failed for ${entry.action}`); } }; // The fence every request takes after serve.mjs's: method, owner, writes on, then the body. async function gate(req, res, { session, owner, send }) { if (!['GET', 'POST'].includes(req.method)) { json(res, 405, { error: 'method-not-allowed' }); return null; } if (!owner || !session) { json(res, 403, { error: 'owner-only', message: 'agent levels are the owner\'s' }); return null; } if (req.method === 'GET') return {}; if (!send) { json(res, 403, { error: 'read-only', message: 'this Console was started without writes' }); return null; } const value = await body(req); if (value === 'too-large') { json(res, 413, { error: 'invalid-request', message: `a change is at most ${LIMIT} bytes` }); return null; } if (value === 'bad-name') { json(res, 400, { error: 'invalid-request', message: `name must be an id: ${NAME_RULE}` }); return null; } if (!value) { json(res, 400, { error: 'invalid-request', message: 'this takes revision, name and entry, nothing else' }); return null; } return value; } async function root(req, res, context) { const value = await gate(req, res, context); if (!value) return; const { session } = context; if (req.method === 'GET') { try { const read = await readRootAgentsFile(configDir); return json(res, 200, { revision: read.revision, state: read.exists ? 'present' : 'absent', agents: rootAgentSummary(read.document), writable: Boolean(context.send) }); } catch (error) { const r = refusal(error, null); return json(res, r.status, r.body); } } const { revision, name, entry } = value; if (entry !== null && !only(entry, ROOT_PATCH)) return json(res, 400, { error: 'invalid-request', message: 'entry is null or takes definition, vars and excludeOrgs' }); if (entry?.vars !== undefined && !plain(entry.vars)) return json(res, 400, { error: 'invalid-request', message: 'vars is an object of keys' }); const action = entry === null ? 'agents.root.remove' : 'agents.root.set'; const principal = { provider: session.provider, iss: session.iss, sub: session.sub }; let receipt; try { receipt = await changeRootAgent(configDir, { revision, name, entry: entry === null ? null : old => patchRootEntry(old, entry) }, { actor: principal, owner: principal, rolesDir }); } catch (error) { const r = refusal(error, entry); note(session, { action, agent: name, outcome: r.body.error }); return json(res, r.status, r.body); } note(session, { action, agent: name, changed: receipt.changed, outcome: 'done' }); return json(res, 200, { outcome: 'done', receipt }); } async function project(req, res, context) { const value = await gate(req, res, context); if (!value) return; const { session, orgId } = context; let projectId; try { projectId = decodeURIComponent(PROJECT_ROUTE.exec(context.path)?.[2] ?? ''); } catch { projectId = ''; } if (typeof orgId !== 'string' || !NAME.test(projectId)) return json(res, 404, { error: 'project-not-found', message: 'no such project' }); if (req.method === 'GET') { try { const { document, revision } = writer.read(orgId); const target = document.projects?.[projectId]; if (!plain(target)) return json(res, 404, { error: 'project-not-found', message: `projects.${projectId} does not exist` }); return json(res, 200, { organization: orgId, project: projectId, revision, library: target.kind === 'library', agents: projectAgentSummary(target.agents ?? {}), writable: Boolean(context.send) }); } catch (error) { const r = refusal(error, null); return json(res, r.status, r.body); } } const { revision, name, entry } = value; if (entry !== null && !only(entry, PROJECT_ENTRY)) return json(res, 400, { error: 'invalid-request', message: 'entry is null or takes definition, vars or exclude' }); const form = entry === null ? 'remove' : Object.hasOwn(entry, 'exclude') ? 'exclude' : Object.hasOwn(entry, 'definition') ? 'define' : 'narrow'; const base = { org: orgId, action: 'project.agents.set', project: projectId, agent: name, form }; let result; // The Console's owner is each organization's human, as the bus binds it (bindConsole with the // document's human; request-bootstrap's addProject passes document.human the same way). The // owner gate above is the identity check; the writer re-reads under its lock and refuses if the // human changed since this read. try { result = writer.setProjectAgent(orgId, { revision, project: projectId, name, entry }, writer.read(orgId).document.human); } catch (error) { const r = refusal(error, entry); note(session, { ...base, outcome: r.body.error }); return json(res, r.status, r.body); } note(session, { ...base, outcome: 'done' }); return json(res, 200, { outcome: 'done', receipt: { verb: 'project.agents.set', organization: orgId, project: projectId, agent: name, form, revisionBefore: revision, revisionAfter: result.revision, transaction: result.transaction } }); } return table => { for (const method of METHODS) { table.add(method, ROOT_ROUTE, root); table.add(method, PROJECT_ROUTE, project); } }; }