diff --git a/lib/api/index.js b/lib/api/index.js index f72b3ad..c807af7 100644 --- a/lib/api/index.js +++ b/lib/api/index.js @@ -12,6 +12,7 @@ import { router as pagesRouter, spacesScopedRouter as pagesBySpaceRouter } from import { router as refsRouter } from './routes/refs.js'; import { router as resourcesRouter, spacesScopedRouter as resourcesBySpaceRouter } from './routes/resources.js'; import { router as sourceDocsRouter, resourcesScopedRouter as sourceDocsByResourceRouter } from './routes/source_docs.js'; +import { router as agentsRouter, tokensRouter as agentTokensRouter } from './routes/agents.js'; export function mountApi(app) { const api = Router(); @@ -30,6 +31,8 @@ export function mountApi(app) { api.use('/resources', resourcesRouter); api.use('/resources/:resource_id/source-docs', sourceDocsByResourceRouter); api.use('/source-docs', sourceDocsRouter); + api.use('/agents', agentsRouter); + api.use('/agent-tokens', agentTokensRouter); api.use((_req, _res, next) => next(new NotFoundError('route not found'))); diff --git a/lib/api/routes/agents.js b/lib/api/routes/agents.js new file mode 100644 index 0000000..5b4563f --- /dev/null +++ b/lib/api/routes/agents.js @@ -0,0 +1,87 @@ +import { Router } from 'express'; +import { z } from 'zod'; +import * as repo from '../../db/repos/agents.js'; +import { validate } from '../validate.js'; +import { requireOwner } from '../cap.js'; +import { NotFoundError, ValidationError, asyncWrap } from '../errors.js'; + +const KINDS = ['claude', 'ollama', 'mastra', 'mcp-client', 'external']; + +const createSchema = z.object({ + slug: z.string().min(1).max(64).regex(/^[a-z0-9-]+$/), + name: z.string().min(1).max(200), + kind: z.enum(KINDS), + model: z.string().nullable().optional(), + persona_path: z.string().nullable().optional(), + capabilities: z.record(z.string(), z.any()).optional(), + scopes: z.record(z.string(), z.any()).optional() +}); + +const capsSchema = z.object({ + capabilities: z.record(z.string(), z.any()), + scopes: z.record(z.string(), z.any()).optional() +}); + +const tokenSchema = z.object({ label: z.string().min(1).max(200).optional() }); + +const idParams = z.object({ id: z.string().uuid() }); +const tokenParams = z.object({ token_id: z.string().uuid() }); + +export const router = Router(); +export const tokensRouter = Router(); + +router.use(requireOwner); +tokensRouter.use(requireOwner); + +router.get('/', asyncWrap(async (_req, res) => { res.json(await repo.list()); })); + +router.post('/', + validate({ body: createSchema }), + asyncWrap(async (req, res) => { + try { + const row = await repo.create(req.body, req.actor); + res.status(201).json(row); + } catch (e) { + if (e.code === '23505') throw new ValidationError('agent slug already used', { slug: req.body.slug }); + throw e; + } + }) +); + +router.get('/:id', + validate({ params: idParams }), + asyncWrap(async (req, res) => { + const row = await repo.getById(req.params.id); + if (!row) throw new NotFoundError('agent not found'); + res.json(row); + }) +); + +router.patch('/:id/capabilities', + validate({ params: idParams, body: capsSchema }), + asyncWrap(async (req, res) => { + const existing = await repo.getById(req.params.id); + if (!existing) throw new NotFoundError('agent not found'); + res.json(await repo.setCapabilities(req.params.id, req.body.capabilities, req.body.scopes)); + }) +); + +// Mint a token. Plaintext is returned EXACTLY ONCE; future reads only +// see the bcrypt hash. +router.post('/:id/tokens', + validate({ params: idParams, body: tokenSchema }), + asyncWrap(async (req, res) => { + const existing = await repo.getById(req.params.id); + if (!existing) throw new NotFoundError('agent not found'); + const { token, id } = await repo.createToken(req.params.id, req.body.label); + res.status(201).json({ id, token }); + }) +); + +tokensRouter.delete('/:token_id', + validate({ params: tokenParams }), + asyncWrap(async (req, res) => { + await repo.revokeToken(req.params.token_id); + res.status(204).end(); + }) +); diff --git a/tests/api/agents.test.js b/tests/api/agents.test.js new file mode 100644 index 0000000..129997a --- /dev/null +++ b/tests/api/agents.test.js @@ -0,0 +1,70 @@ +import { describe, it, expect, beforeAll } from 'vitest'; +import request from 'supertest'; +import { setup } from './helpers.js'; +import * as agentsRepo from '../../lib/db/repos/agents.js'; + +let app, ownerHeaders; +const owner = { kind: 'user', id: null }; + +async function mintAgentToken(slug, caps = { read: true }) { + const a = await agentsRepo.create({ + slug, name: slug, kind: 'claude', model: 'sonnet', + capabilities: caps, scopes: {} + }, owner); + const { token } = await agentsRepo.createToken(a.id, 'h'); + return { Authorization: `Bearer ${token}` }; +} + +beforeAll(async () => { ({ app, ownerHeaders } = await setup()); }); + +describe('agents routes (owner-only)', () => { + it('GET /api/agents requires owner', async () => { + const headers = await mintAgentToken(`x-${Date.now()}`); + const res = await request(app).get('/api/agents').set(headers); + expect(res.status).toBe(403); + }); + + it('owner can POST agent and mint token', async () => { + const slug = `m-${Date.now()}`; + const create = await request(app).post('/api/agents').set(ownerHeaders).send({ + slug, name: 'Mercy', kind: 'claude', model: 'sonnet', + capabilities: { read: true, write: true }, scopes: { page: true } + }); + expect(create.status).toBe(201); + const mint = await request(app).post(`/api/agents/${create.body.id}/tokens`).set(ownerHeaders) + .send({ label: 'laptop' }); + expect(mint.status).toBe(201); + expect(mint.body.token).toBeDefined(); + expect(mint.body.token).toMatch(/^vk_/); + expect(mint.body.id).toBeDefined(); + + const auth = { Authorization: `Bearer ${mint.body.token}` }; + const spacesList = await request(app).get('/api/spaces').set(auth); + expect(spacesList.status).toBe(200); + + const revoke = await request(app).delete(`/api/agent-tokens/${mint.body.id}`).set(ownerHeaders); + expect(revoke.status).toBe(204); + const after = await request(app).get('/api/spaces').set(auth); + expect(after.status).toBe(401); + }); + + it('PATCH /:id/capabilities updates caps', async () => { + const slug = `c-${Date.now()}`; + const create = await request(app).post('/api/agents').set(ownerHeaders).send({ + slug, name: slug, kind: 'claude' + }); + const res = await request(app).patch(`/api/agents/${create.body.id}/capabilities`).set(ownerHeaders) + .send({ capabilities: { read: true, suggest: true }, scopes: { page: true } }); + expect(res.status).toBe(200); + expect(res.body.capabilities.suggest).toBe(true); + expect(res.body.scopes.page).toBe(true); + }); + + it('agent token cannot POST a new agent', async () => { + const headers = await mintAgentToken(`e-${Date.now()}`, { read: true, write: true }); + const res = await request(app).post('/api/agents').set(headers).send({ + slug: `bad-${Date.now()}`, name: 'Bad', kind: 'claude' + }); + expect(res.status).toBe(403); + }); +});