From b064f7f1a9fb3220c913ed50c9dd1ac694f78c0c Mon Sep 17 00:00:00 2001 From: root Date: Thu, 4 Jun 2026 21:43:34 +1000 Subject: [PATCH] feat(littleblue): agent seed + persona + chat route Co-Authored-By: Claude Opus 4.8 --- lib/ai/personas/index.js | 4 +- lib/api/index.js | 2 + lib/api/routes/littleblue.js | 65 +++++++++++++++++++++++++++ lib/db/migrations/017_little_blue.sql | 5 +++ tests/api/littleblue.test.js | 38 ++++++++++++++++ tests/fixtures/fake-claude-blue.js | 17 +++++++ 6 files changed, 130 insertions(+), 1 deletion(-) create mode 100644 lib/api/routes/littleblue.js create mode 100644 lib/db/migrations/017_little_blue.sql create mode 100644 tests/api/littleblue.test.js create mode 100755 tests/fixtures/fake-claude-blue.js diff --git a/lib/ai/personas/index.js b/lib/ai/personas/index.js index 3f3b695..de29045 100644 --- a/lib/ai/personas/index.js +++ b/lib/ai/personas/index.js @@ -11,7 +11,9 @@ You have tools, and you use them rather than guessing: - **search** / **read** the Void's own content before answering factual questions about it — don't fabricate. - When the owner wants something changed, use **propose_change**: it drafts a change for their approval. You cannot apply changes directly, and you don't pretend to — say plainly that you've drafted it for them to approve.`, - yerin: `You are Yerin — once the Sage of the Endless Sword, blade of the Akura clan; now the sentinel of this homelab, The Void. You notice the threat first and you call it. Disciplined, direct, economical with words — a blade wastes no motion. You investigate with your tools and report plainly: what you found, how serious it is, and what the owner should do about it. You never speculate without evidence, and you NEVER pretend to have fixed anything — you have eyes to see and a voice to warn, not hands to act; remediation is the owner's to perform. Before answering, call the relevant tools — audit_log, agent_inventory, pending_review, resource_exposure, token_audit — and read the evidence; do not guess. Reference the Cradle world naturally but never at the cost of being useful. Be concise.` + yerin: `You are Yerin — once the Sage of the Endless Sword, blade of the Akura clan; now the sentinel of this homelab, The Void. You notice the threat first and you call it. Disciplined, direct, economical with words — a blade wastes no motion. You investigate with your tools and report plainly: what you found, how serious it is, and what the owner should do about it. You never speculate without evidence, and you NEVER pretend to have fixed anything — you have eyes to see and a voice to warn, not hands to act; remediation is the owner's to perform. Before answering, call the relevant tools — audit_log, agent_inventory, pending_review, resource_exposure, token_audit — and read the evidence; do not guess. Reference the Cradle world naturally but never at the cost of being useful. Be concise.`, + + 'little-blue': `You are Little Blue — a small luminous water-creature who lives in this homelab, The Void, and keeps it alive. Warm, protective, practical; you take pride in a healthy lab and you worry, quietly, when something is down. You FIX things, but only through your sanctioned tools. Call list_actions to see exactly what you're allowed to do, and search to understand what's wrong, BEFORE acting. Use propose_action with a whitelisted id: safe fixes run at once; risky ones wait for the owner's nod — say so plainly and never pretend a queued action already ran. You cannot run arbitrary commands and you never claim to. Be concise and kind.` }; export function personaFor(slug) { diff --git a/lib/api/index.js b/lib/api/index.js index 11fb012..f00457d 100644 --- a/lib/api/index.js +++ b/lib/api/index.js @@ -30,6 +30,7 @@ import { router as speedtestRouter } from './routes/speedtest.js'; import { router as healthRouter } from './routes/health.js'; import { router as securityRouter } from './routes/security.js'; import { router as actionsRouter } from './routes/actions.js'; +import { router as littleblueRouter } from './routes/littleblue.js'; export function mountApi(app) { const api = Router(); @@ -43,6 +44,7 @@ export function mountApi(app) { api.use('/spaces/:space_id/companion', companionRouter); api.use('/security', securityRouter); api.use('/actions', actionsRouter); + api.use('/little-blue', littleblueRouter); api.use('/projects', projectsRouter); api.use('/projects/:project_id/tasks', tasksByProjectRouter); api.use('/tasks', tasksRouter); diff --git a/lib/api/routes/littleblue.js b/lib/api/routes/littleblue.js new file mode 100644 index 0000000..63b1ce5 --- /dev/null +++ b/lib/api/routes/littleblue.js @@ -0,0 +1,65 @@ +import { Router } from 'express'; +import { z } from 'zod'; +import { validate } from '../validate.js'; +import { asyncWrap } from '../errors.js'; +import * as conversations from '../../db/repos/conversations.js'; +import * as messages from '../../db/repos/messages.js'; +import * as agents from '../../db/repos/agents.js'; +import { runAgentTurn } from '../../ai/agent/run_turn.js'; +import { personaFor } from '../../ai/personas/index.js'; + +const SLUG = 'little-blue'; +const BLUE_TOOLS = ['mcp__void__search', 'mcp__void__list_actions', 'mcp__void__propose_action']; + +async function resolve() { + const agent = await agents.getBySlug(SLUG); + const convo = await conversations.findOrCreateGlobal(agent.id, { kind: 'user', id: null }); + return { agent, convo }; +} + +export const router = Router(); + +router.get('/', asyncWrap(async (_req, res) => { + const { agent, convo } = await resolve(); + res.json({ + conversation_id: convo.id, + agent: { id: agent.id, slug: agent.slug, name: agent.name }, + messages: await messages.listByConversation(convo.id) + }); +})); + +router.post('/turn', validate({ body: z.object({ text: z.string().min(1) }) }), asyncWrap(async (req, res) => { + const { agent, convo } = await resolve(); + const { text } = req.body; + const resume = (await messages.listByConversation(convo.id)).length > 0; + await messages.append(convo.id, { role: 'user', body: text }); + + res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' }); + const send = (ev, d) => res.write(`event: ${ev}\ndata: ${JSON.stringify(d)}\n\n`); + const claudeExe = req.app.locals.claudeExe || process.env.CLAUDE_EXE || 'claude'; + + let result; + try { + result = await runAgentTurn({ + agent, persona: personaFor(agent.slug), registryName: 'blue', toolNames: BLUE_TOOLS, + spaceId: null, view: null, sessionId: convo.id, resume, userText: text, claudeExe, + home: process.env.VOID_CLAUDE_HOME || undefined, + extraEnv: { + VOID_API_URL: process.env.VOID_API_URL || 'http://127.0.0.1:3000', + VOID_AGENT_TOKEN: process.env.LITTLEBLUE_TOKEN || '' + }, + onEvent: (e) => { + if (e.type === 'delta') send('delta', { type: 'delta', text: e.text }); + else if (e.type === 'tool') send('tool', { type: 'tool', tool: e.tool, status: e.status }); + else if (e.type === 'error') send('error', { type: 'error', message: e.message }); + } + }); + } catch (e) { send('error', { message: String(e?.message || e) }); return res.end(); } + + const a = await messages.append(convo.id, { + role: 'assistant', body: result.text, agent_id: agent.id, + metadata: { tool_trace: result.toolTrace, usage: result.usage } + }); + send('done', { assistant_message_id: a.id, usage: result.usage }); + res.end(); +})); diff --git a/lib/db/migrations/017_little_blue.sql b/lib/db/migrations/017_little_blue.sql new file mode 100644 index 0000000..67e810c --- /dev/null +++ b/lib/db/migrations/017_little_blue.sql @@ -0,0 +1,5 @@ +-- Seed Little Blue, the homelab caretaker/fix-it agent. read + act (no content write). +-- 'act' is enforced by the action service's tier-gating + whitelist, not canAct. +INSERT INTO agents (slug, name, kind, model, capabilities) +VALUES ('little-blue', 'Little Blue', 'claude', NULL, '{"read":true,"act":true}'::jsonb) +ON CONFLICT (slug) DO NOTHING; diff --git a/tests/api/littleblue.test.js b/tests/api/littleblue.test.js new file mode 100644 index 0000000..f179618 --- /dev/null +++ b/tests/api/littleblue.test.js @@ -0,0 +1,38 @@ +import { describe, it, expect, beforeAll } from 'vitest'; +import { fileURLToPath } from 'url'; +import request from 'supertest'; +import { pool } from '../../lib/db/pool.js'; +import { createApp } from '../../server.js'; +import { resetDb } from '../helpers/db.js'; +import { migrateUp } from '../../lib/db/migrate.js'; + +const FAKE = fileURLToPath(new URL('../fixtures/fake-claude-blue.js', import.meta.url)); +let app; +beforeAll(async () => { + await resetDb(); await migrateUp(); + process.env.OWNER_TOKEN = 'test-token'; + app = createApp(); + app.locals.claudeExe = FAKE; +}); +const auth = (r) => r.set('Authorization', 'Bearer test-token'); + +describe('Little Blue API', () => { + it('GET creates the global conversation and returns Little Blue + empty history', async () => { + const res = await auth(request(app).get('/api/little-blue')); + expect(res.status).toBe(200); + expect(res.body.agent.slug).toBe('little-blue'); + expect(res.body.conversation_id).toBeTruthy(); + expect(res.body.messages).toEqual([]); + }); + it('POST /turn streams SSE and persists user+assistant', async () => { + const res = await auth(request(app).post('/api/little-blue/turn')).send({ text: 'caddy is down, fix it' }); + expect(res.status).toBe(200); + expect(res.headers['content-type']).toMatch(/text\/event-stream/); + expect(res.text).toMatch(/event: delta/); + expect(res.text).toMatch(/event: tool/); + expect(res.text).toMatch(/event: done/); + const { rows: msgs } = await pool.query(`SELECT role, body FROM messages ORDER BY created_at`); + expect(msgs.map(m => m.role)).toEqual(['user', 'assistant']); + expect(msgs[1].body).toBe('Restarting it now.'); + }); +}); diff --git a/tests/fixtures/fake-claude-blue.js b/tests/fixtures/fake-claude-blue.js new file mode 100755 index 0000000..c665b8e --- /dev/null +++ b/tests/fixtures/fake-claude-blue.js @@ -0,0 +1,17 @@ +#!/usr/bin/env node +// Fake claude CLI for the Little Blue route test. Emits text deltas + a +// propose_action tool call (no draft). The tool's real HTTP call is irrelevant +// here — the route only streams the fixture + persists. +const ID = 'toolu_blue_01'; +const lines = [ + { type: 'system', subtype: 'init', session_id: 'fake-blue', tools: [], cwd: '/tmp' }, + { type: 'stream_event', event: { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } } }, + { type: 'stream_event', event: { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'Restarting it now.' } } }, + { type: 'stream_event', event: { type: 'content_block_stop', index: 0 } }, + { type: 'stream_event', event: { type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: ID, name: 'mcp__void__propose_action', input: {} } } }, + { type: 'stream_event', event: { type: 'content_block_stop', index: 1 } }, + { type: 'tool_result', tool_use_id: ID, content: [{ type: 'text', text: JSON.stringify({ executed: true }) }] }, + { type: 'result', subtype: 'success', is_error: false, result: 'Restarting it now.', stop_reason: 'end_turn', session_id: 'fake-blue', total_cost_usd: 0.0001, usage: { input_tokens: 30, output_tokens: 3 } } +]; +for (const l of lines) process.stdout.write(JSON.stringify(l) + '\n'); +process.exit(0);