Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(image-gen): add image generation settings, tools registry, and character avatars
Adam Eivyda0654aadad0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdnew file mode 100644index 0000000000..6ea96c4e26--- /dev/null+++ b/.changelog/NEXT.md@@ -0,0 +1,8 @@+# Unreleased++## Added++- **Image Generation Settings** — New Settings > Image Gen tab for configuring Stable Diffusion API (AUTOMATIC1111 / Forge WebUI). Auto-detects Flux models and adjusts parameters accordingly.+- **CoS Tools Registry** — New onboard tools system (`data/tools/`) that lets CoS agents discover and use instance-specific capabilities like image generation. Tools are exposed in agent prompts via `getToolsSummaryForPrompt()`.+- **Character Avatar Generation** — D&D Character Sheet now supports AI-generated avatars via the configured SD API. Hover over the avatar area to generate a new portrait.+- **Image serving** — Generated images stored in `data/images/` and served via `/data/images/` static route.diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex ec2d283f28..7e84585f63 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -66,7 +66,8 @@ import {Dog,FilePen,MessageCircle,- Swords+ Swords,+ Image as ImageIcon} from 'lucide-react';/* global __APP_VERSION__ */import Logo from './Logo';@@ -219,6 +220,7 @@ const navItems = [children: [{ to: '/settings/backup', label: 'Backup', icon: Download },{ to: '/settings/database', label: 'Database', icon: Database },+ { to: '/settings/image-gen', label: 'Image Gen', icon: ImageIcon },{ to: '/prompts', label: 'Prompts', icon: FileText },{ to: '/ai', label: 'Providers', icon: Bot },{ to: '/security', label: 'Security', icon: Camera },diff --git a/client/src/pages/CharacterSheet.jsx b/client/src/pages/CharacterSheet.jsxindex 197a2718c7..dfff5f74a3 100644--- a/client/src/pages/CharacterSheet.jsx+++ b/client/src/pages/CharacterSheet.jsx@@ -1,7 +1,7 @@import { useState, useEffect, useCallback } from 'react';import {Sword, Star, Moon, ScrollText, Shield, Heart,- Sparkles, RefreshCw, Dices, X, ChevronDown, Zap+ Sparkles, RefreshCw, Dices, X, ChevronDown, Zap, Image} from 'lucide-react';import toast from 'react-hot-toast';import { timeAgo } from '../utils/formatters';@@ -72,6 +72,7 @@ export default function CharacterSheet() {const [nameVal, setNameVal] = useState('');const [classVal, setClassVal] = useState('');const [syncing, setSyncing] = useState(null);+ const [generatingAvatar, setGeneratingAvatar] = useState(false);// Form statesconst [dmgDice, setDmgDice] = useState('1d6');@@ -188,6 +189,24 @@ export default function CharacterSheet() {setEditingClass(false);};+ const handleGenerateAvatar = () => {+ setGeneratingAvatar(true);+ fetch('/api/image-gen/avatar', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: char.name, characterClass: char.class })+ })+ .then(res => res.ok ? res.json() : res.json().then(e => Promise.reject(new Error(e.error))))+ .then(result => {+ const updated = { ...char, avatarPath: result.path };+ setChar(updated);+ return put({ avatarPath: result.path });+ })+ .then(() => toast.success('Avatar generated'))+ .catch(err => toast.error(err.message || 'Failed to generate avatar'))+ .finally(() => setGeneratingAvatar(false));+ };+if (loading) {return (<div className="h-full flex items-center justify-center text-gray-400">@@ -234,6 +253,27 @@ export default function CharacterSheet() {{/* Character Identity & Stats */}<div className="bg-port-card border border-port-border rounded-xl p-4 md:p-6"><div className="flex flex-col md:flex-row md:items-start gap-4">+ {/* Avatar */}+ <div className="flex-shrink-0">+ <div className="relative group w-20 h-20 rounded-lg overflow-hidden border border-port-border bg-port-bg">+ {char.avatarPath ? (+ <img src={char.avatarPath} alt={char.name} className="w-full h-full object-cover" />+ ) : (+ <div className="w-full h-full flex items-center justify-center text-gray-600">+ <Shield className="w-8 h-8" />+ </div>+ )}+ <button+ onClick={handleGenerateAvatar}+ disabled={generatingAvatar}+ className="absolute inset-0 flex items-center justify-center bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity"+ title="Generate avatar"+ >+ {generatingAvatar ? <RefreshCw className="w-5 h-5 text-white animate-spin" /> : <Image className="w-5 h-5 text-white" />}+ </button>+ </div>+ </div>+{/* Name, Class, Level */}<div className="flex-1 min-w-0"><div className="flex items-center gap-3 mb-1">diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsxindex a51bcfd0c7..1b5b22d6d2 100644--- a/client/src/pages/Settings.jsx+++ b/client/src/pages/Settings.jsx@@ -1,6 +1,6 @@import { useState, useEffect, useCallback, useRef, useMemo } from 'react';import { useParams, useNavigate } from 'react-router-dom';-import { Save, Plus, X, Eye, EyeOff, Trash2, Send, Container, HardDrive, Download, ArrowRightLeft, Wrench, RefreshCw, Square, RotateCw, Play } from 'lucide-react';+import { Save, Plus, X, Eye, EyeOff, Trash2, Send, Container, HardDrive, Download, ArrowRightLeft, Wrench, RefreshCw, Square, RotateCw, Play, Image, Zap } from 'lucide-react';import toast from 'react-hot-toast';import BrailleSpinner from '../components/BrailleSpinner';import { formatBytes } from '../utils/formatters';@@ -8,7 +8,8 @@ import {getSettings, updateSettings, getTelegramStatus, updateTelegramConfig,deleteTelegramConfig, testTelegram, updateTelegramForwardTypes, updateTelegramMethod,getDatabaseStatus, switchDatabase, setupNativeDatabase, exportDatabase, fixDatabase,- syncDatabase, startDatabase, stopDatabase, destroyDatabase+ syncDatabase, startDatabase, stopDatabase, destroyDatabase,+ getImageGenStatus, registerTool, updateTool, getToolsList} from '../services/api';import socket from '../services/socket';@@ -868,10 +869,136 @@ function GeneralTab() {);}+function ImageGenTab() {+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [sdapiUrl, setSdapiUrl] = useState('');+ const [status, setStatus] = useState(null);+ const [checking, setChecking] = useState(false);+ const [toolId, setToolId] = useState(null);++ useEffect(() => {+ Promise.all([getSettings(), getToolsList()])+ .then(([settings, tools]) => {+ setSdapiUrl(settings?.imageGen?.sdapiUrl || '');+ const sdTool = tools.find(t => t.category === 'image-generation' && t.name === 'Stable Diffusion');+ if (sdTool) setToolId(sdTool.id);+ })+ .catch(() => toast.error('Failed to load image gen settings'))+ .finally(() => setLoading(false));+ }, []);++ const checkStatus = useCallback(() => {+ setChecking(true);+ getImageGenStatus()+ .then(setStatus)+ .catch(() => setStatus({ connected: false, reason: 'Check failed' }))+ .finally(() => setChecking(false));+ }, []);++ const handleSave = async () => {+ setSaving(true);+ const url = sdapiUrl.trim().replace(/\/+$/, '') || undefined;++ await updateSettings({ imageGen: { sdapiUrl: url } })+ .then(() => toast.success('Image gen settings saved'))+ .catch(() => toast.error('Failed to save settings'));++ // Register or update the tool in the CoS tools registry+ if (url) {+ const toolData = {+ name: 'Stable Diffusion',+ category: 'image-generation',+ description: 'Generate images via Stable Diffusion API (AUTOMATIC1111 / Forge WebUI)',+ enabled: true,+ config: { sdapiUrl: url },+ promptHints: 'Use POST /api/image-gen/generate with { prompt, negativePrompt, width, height, steps, cfgScale }. Use POST /api/image-gen/avatar for character portraits.'+ };+ if (toolId) {+ await updateTool(toolId, toolData).catch(() => {});+ } else {+ const created = await registerTool({ id: 'sdapi', ...toolData }).catch(() => null);+ if (created) setToolId(created.id);+ }+ } else if (toolId) {+ await updateTool(toolId, { enabled: false }).catch(() => {});+ }++ setSaving(false);+ };++ if (loading) return <BrailleSpinner text="Loading image gen settings" />;++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-5">+ <div className="flex items-center gap-2 text-white">+ <Image size={18} />+ <h2 className="text-lg font-semibold">Stable Diffusion API</h2>+ </div>++ <div className="space-y-1">+ <label className="block text-sm text-gray-400">API URL</label>+ <p className="text-xs text-gray-500 mb-1">+ Base URL for AUTOMATIC1111 / Forge WebUI (e.g. http://localhost:7860)+ </p>+ <input+ type="text"+ value={sdapiUrl}+ onChange={e => setSdapiUrl(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"+ placeholder="http://localhost:7860"+ />+ </div>++ <div className="flex items-center gap-3">+ <button+ onClick={handleSave}+ disabled={saving}+ className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white text-sm rounded-lg transition-colors disabled:opacity-50"+ >+ {saving ? <BrailleSpinner /> : <Save size={14} />}+ Save+ </button>++ <button+ onClick={checkStatus}+ disabled={checking || !sdapiUrl.trim()}+ className="flex items-center gap-2 px-4 py-2 bg-port-border hover:bg-port-border/70 text-white text-sm rounded-lg transition-colors disabled:opacity-50"+ >+ {checking ? <BrailleSpinner /> : <Zap size={14} />}+ Test Connection+ </button>+ </div>++ {status && (+ <div className={`flex items-center gap-2 text-sm ${status.connected ? 'text-port-success' : 'text-port-error'}`}>+ <span className={`w-2 h-2 rounded-full ${status.connected ? 'bg-port-success' : 'bg-port-error'}`} />+ {status.connected ? `Connected — model: ${status.model}` : status.reason || 'Not connected'}+ </div>+ )}++ <div className="border-t border-port-border pt-4 space-y-2">+ <h3 className="text-sm font-medium text-gray-300">CoS Integration</h3>+ <p className="text-xs text-gray-500">+ When configured, this tool is registered with the CoS tools registry. Agents can use it to generate+ images for briefings, character avatars, and other visual content. Images are stored in <code className="text-gray-400">./data/images/</code>.+ </p>+ {toolId && (+ <div className="flex items-center gap-2 text-xs text-port-success">+ <Wrench size={12} />+ Registered as CoS tool (ID: {toolId})+ </div>+ )}+ </div>+ </div>+ );+}+const TABS = [{ id: 'general', label: 'General' },{ id: 'backup', label: 'Backup' },{ id: 'database', label: 'Database' },+ { id: 'image-gen', label: 'Image Gen' },{ id: 'telegram', label: 'Telegram' }];@@ -889,6 +1016,7 @@ export default function Settings() {case 'general': return <GeneralTab />;case 'backup': return <BackupTab />;case 'database': return <DatabaseTab />;+ case 'image-gen': return <ImageGenTab />;case 'telegram': return <TelegramTab />;default: return <GeneralTab />;}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 15563a5472..40135640a5 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1676,6 +1676,30 @@ export const updateTelegramMethod = (method) => request('/telegram/method', {});export const reloadTelegramBridge = () => request('/telegram/bridge/reload', { method: 'POST' });+// Image Generation+export const getImageGenStatus = () => request('/image-gen/status');+export const generateImage = (data) => request('/image-gen/generate', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const generateAvatar = (data) => request('/image-gen/avatar', {+ method: 'POST',+ body: JSON.stringify(data)+});++// Tools Registry+export const getToolsList = () => request('/tools');+export const getEnabledTools = () => request('/tools/enabled');+export const registerTool = (data) => request('/tools', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const updateTool = (id, data) => request(`/tools/${id}`, {+ method: 'PUT',+ body: JSON.stringify(data)+});+export const deleteTool = (id) => request(`/tools/${id}`, { method: 'DELETE' });+// Insightsexport const getGenomeHealthCorrelations = () => request('/insights/genome-health');export const getInsightThemes = () => request('/insights/themes');diff --git a/server/index.js b/server/index.jsindex df569a2c4e..e4db1aa1ad 100644--- a/server/index.js+++ b/server/index.js@@ -62,6 +62,8 @@ import telegramRoutes from './routes/telegram.js';import updateRoutes from './routes/update.js';import loopsRoutes from './routes/loops.js';import characterRoutes from './routes/character.js';+import toolsRoutes from './routes/tools.js';+import imageGenRoutes from './routes/imageGen.js';import { ensureSelf, startPolling } from './services/instances.js';import { initSyncLog } from './services/brainSyncLog.js';import { backfillOriginInstanceId } from './services/brainStorage.js';@@ -260,6 +262,8 @@ app.use('/api/telegram', telegramRoutes);app.use('/api/update', updateRoutes);app.use('/api/loops', loopsRoutes);app.use('/api/character', characterRoutes);+app.use('/api/tools', toolsRoutes);+app.use('/api/image-gen', imageGenRoutes);// Initialize agent automation scheduler and action executorautomationScheduler.init().catch(err => console.error(`❌ Agent scheduler init failed: ${err.message}`));@@ -333,6 +337,9 @@ startUpdateScheduler();// Restore any active loops from previous sessionrestoreLoops().catch(err => console.error(`❌ Loop restore failed: ${err.message}`));+// Serve generated images from data/images/+app.use('/data/images', express.static(join(PATHS.data, 'images')));+// Serve built client UI (production mode — no Vite dev server needed)const CLIENT_DIST = join(__dirname, '..', 'client', 'dist');if (existsSync(CLIENT_DIST)) {diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex f22b76c370..cc22fb2e30 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -47,7 +47,9 @@ export const PATHS = {telegram: join(__lib_dirname, '../../data/telegram'),templates: join(__lib_dirname, '../../data/prompts/templates'),settings: join(__lib_dirname, '../../data/settings'),- missions: join(__lib_dirname, '../../data/cos/missions')+ missions: join(__lib_dirname, '../../data/cos/missions'),+ tools: join(__lib_dirname, '../../data/tools'),+ images: join(__lib_dirname, '../../data/images')};/**diff --git a/server/routes/character.js b/server/routes/character.jsindex 369384f4c6..126b24aa7e 100644--- a/server/routes/character.js+++ b/server/routes/character.js@@ -14,7 +14,8 @@ const router = Router();// Zod schemas for request validationconst updateCharacterSchema = z.object({name: z.string().min(1).max(100).optional(),- class: z.string().min(1).max(100).optional()+ class: z.string().min(1).max(100).optional(),+ avatarPath: z.string().max(500).optional()});const addXPSchema = z.object({@@ -50,6 +51,7 @@ router.put('/', asyncHandler(async (req, res) => {const character = await characterService.getCharacter();if (data.name) character.name = data.name;if (data.class) character.class = data.class;+ if (data.avatarPath) character.avatarPath = data.avatarPath;const updated = await characterService.saveCharacter(character);res.json(updated);}));diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsnew file mode 100644index 0000000000..36da7841b7--- /dev/null+++ b/server/routes/imageGen.js@@ -0,0 +1,51 @@+/**+ * Image Generation Routes+ *+ * Endpoints for generating images via Stable Diffusion API.+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import * as imageGen from '../services/imageGen.js';++const router = Router();++const generateSchema = z.object({+ prompt: z.string().min(1).max(2000),+ negativePrompt: z.string().max(2000).optional(),+ width: z.number().int().min(64).max(2048).optional(),+ height: z.number().int().min(64).max(2048).optional(),+ steps: z.number().int().min(1).max(150).optional(),+ cfgScale: z.number().min(0).max(30).optional(),+ seed: z.number().int().optional()+});++const avatarSchema = z.object({+ name: z.string().max(100).optional(),+ characterClass: z.string().max(100).optional(),+ prompt: z.string().max(2000).optional()+});++// GET /api/image-gen/status - Check SD API connection+router.get('/status', asyncHandler(async (req, res) => {+ const status = await imageGen.checkConnection();+ res.json(status);+}));++// POST /api/image-gen/generate - Generate an image+router.post('/generate', asyncHandler(async (req, res) => {+ const data = validateRequest(generateSchema, req.body);+ const result = await imageGen.generateImage(data);+ res.json(result);+}));++// POST /api/image-gen/avatar - Generate a character avatar+router.post('/avatar', asyncHandler(async (req, res) => {+ const data = validateRequest(avatarSchema, req.body);+ const result = await imageGen.generateAvatar(data);+ res.json(result);+}));++export default router;diff --git a/server/routes/tools.js b/server/routes/tools.jsnew file mode 100644index 0000000000..8f72cd054a--- /dev/null+++ b/server/routes/tools.js@@ -0,0 +1,73 @@+/**+ * Tools Registry Routes+ *+ * CRUD endpoints for managing onboard tools available to CoS agents.+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import * as toolsService from '../services/tools.js';++const router = Router();++const registerToolSchema = z.object({+ id: z.string().max(100).optional(),+ name: z.string().min(1).max(100),+ category: z.string().min(1).max(50),+ description: z.string().max(500).optional(),+ enabled: z.boolean().optional(),+ config: z.record(z.unknown()).optional(),+ promptHints: z.string().max(1000).optional()+});++const updateToolSchema = registerToolSchema.partial();++// GET /api/tools - List all tools+router.get('/', asyncHandler(async (req, res) => {+ const tools = await toolsService.getTools();+ res.json(tools);+}));++// GET /api/tools/enabled - List enabled tools+router.get('/enabled', asyncHandler(async (req, res) => {+ const tools = await toolsService.getEnabledTools();+ res.json(tools);+}));++// GET /api/tools/summary - Get prompt-ready summary for agents+router.get('/summary', asyncHandler(async (req, res) => {+ const summary = await toolsService.getToolsSummaryForPrompt();+ res.json({ summary });+}));++// GET /api/tools/:id - Get single tool+router.get('/:id', asyncHandler(async (req, res) => {+ const tool = await toolsService.getTool(req.params.id);+ if (!tool) return res.status(404).json({ error: 'Tool not found' });+ res.json(tool);+}));++// POST /api/tools - Register a new tool+router.post('/', asyncHandler(async (req, res) => {+ const data = validateRequest(registerToolSchema, req.body);+ const tool = await toolsService.registerTool(data);+ res.status(201).json(tool);+}));++// PUT /api/tools/:id - Update a tool+router.put('/:id', asyncHandler(async (req, res) => {+ const data = validateRequest(updateToolSchema, req.body);+ const tool = await toolsService.updateTool(req.params.id, data);+ if (!tool) return res.status(404).json({ error: 'Tool not found' });+ res.json(tool);+}));++// DELETE /api/tools/:id - Delete a tool+router.delete('/:id', asyncHandler(async (req, res) => {+ await toolsService.deleteTool(req.params.id);+ res.status(204).end();+}));++export default router;diff --git a/server/services/imageGen.js b/server/services/imageGen.jsnew file mode 100644index 0000000000..4dcc83a96f--- /dev/null+++ b/server/services/imageGen.js@@ -0,0 +1,93 @@+/**+ * Image Generation Service+ *+ * Handles communication with Stable Diffusion API (AUTOMATIC1111 / Forge WebUI).+ * Generated images are stored in data/images/.+ */++import { writeFile } from 'fs/promises';+import { join } from 'path';+import { randomUUID } from 'crypto';+import { ensureDir, PATHS } from '../lib/fileUtils.js';+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';+import { getSettings } from './settings.js';++async function getSdApiUrl() {+ const settings = await getSettings();+ return settings.imageGen?.sdapiUrl || null;+}++export async function checkConnection() {+ const baseUrl = await getSdApiUrl();+ if (!baseUrl) return { connected: false, reason: 'No SD API URL configured' };++ const res = await fetchWithTimeout(`${baseUrl}/sdapi/v1/options`, {}, 10000).catch(() => null);+ if (!res?.ok) return { connected: false, reason: 'SD API unreachable' };++ const options = await res.json().catch(() => null);+ return {+ connected: true,+ model: options?.sd_model_checkpoint || 'unknown'+ };+}++export async function generateImage({ prompt, negativePrompt, width, height, steps, cfgScale, seed }) {+ const baseUrl = await getSdApiUrl();+ if (!baseUrl) throw new Error('No SD API URL configured — set it in Settings > Image Gen');++ // Auto-detect model for Flux-specific parameters+ const status = await checkConnection();+ const isFlux = status.model?.toLowerCase().includes('flux');++ const payload = {+ prompt,+ negative_prompt: negativePrompt || 'blurry, low quality, distorted, deformed, ugly, watermark, text, signature',+ steps: steps || (isFlux ? 15 : 25),+ width: width || (isFlux ? 832 : 512),+ height: height || (isFlux ? 1216 : 768),+ cfg_scale: cfgScale ?? (isFlux ? 1 : 7),+ sampler_name: isFlux ? 'Euler' : 'Euler a',+ ...(isFlux && { scheduler: 'simple' }),+ batch_size: 1,+ ...(seed != null && seed >= 0 && { seed })+ };++ console.log(`🎨 Generating image: ${prompt.slice(0, 80)}... (${payload.width}x${payload.height}, ${payload.steps} steps)`);++ const res = await fetchWithTimeout(+ `${baseUrl}/sdapi/v1/txt2img`,+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload)+ },+ 300000 // 5 min timeout for generation+ );++ if (!res.ok) {+ const errBody = await res.text().catch(() => '');+ throw new Error(`SD API error ${res.status}: ${errBody.slice(0, 200)}`);+ }++ const data = await res.json();+ if (!data.images?.length) throw new Error('SD API returned no images');++ // Save base64 image to disk+ await ensureDir(PATHS.images);+ const filename = `${randomUUID()}.png`;+ const filePath = join(PATHS.images, filename);+ await writeFile(filePath, Buffer.from(data.images[0], 'base64'));++ console.log(`🖼️ Image saved: ${filename}`);+ return { filename, path: `/data/images/${filename}` };+}++export async function generateAvatar({ name, characterClass, prompt }) {+ const defaultPrompt = `fantasy portrait of ${name || 'an adventurer'}, ${characterClass || 'warrior'} class, D&D character art, detailed, dramatic lighting, painterly style`;+ return generateImage({+ prompt: prompt || defaultPrompt,+ width: 512,+ height: 512,+ negativePrompt: 'blurry, low quality, distorted, deformed, ugly, watermark, text, signature, nude, nsfw'+ });+}diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex 418233a1e3..99365c8b0b 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -28,6 +28,7 @@ import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';import { getAppById } from './apps.js';import { createToolExecution, startExecution, updateExecution, completeExecution, errorExecution, getExecution, getStats as getToolStats } from './toolStateMachine.js';import { resolveThinkingLevel, getModelForLevel, isLocalPreferred } from './thinkingLevels.js';+import { getToolsSummaryForPrompt } from './tools.js';import { determineLane, acquire, release, hasCapacity, waitForLane } from './executionLanes.js';import { detectConflicts } from './taskConflict.js';import { createWorktree, removeWorktree, cleanupOrphanedWorktrees } from './worktreeManager.js';@@ -2794,6 +2795,12 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switch}): null;+ // Build onboard tools section for agent awareness+ const toolsSection = await getToolsSummaryForPrompt().catch(err => {+ console.log(`⚠️ Tools summary retrieval failed: ${err.message}`);+ return '';+ });+// Build .planning/ context section for GSD-enabled appslet planningContextSection = '';if (task.metadata?.app) {@@ -2827,6 +2834,7 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switchcompactionSection,skillSection,planningContextSection,+ toolsSection,soulSection: digitalTwinSection, // Backwards compatibility for prompt templatestimestamp: new Date().toISOString()}).catch(() => null);@@ -2857,7 +2865,7 @@ ${jiraSection}${simplifySection}${reviewLoopSection}${compactionSection}-${skillSection ? `## Task-Type Skill Guidelines\n\n${skillSection}\n` : ''}${planningContextSection}+${skillSection ? `## Task-Type Skill Guidelines\n\n${skillSection}\n` : ''}${toolsSection ? `\n${toolsSection}\n` : ''}${planningContextSection}## Instructions1. Analyze the task requirements carefully2. Make necessary changes to complete the taskdiff --git a/server/services/tools.js b/server/services/tools.jsnew file mode 100644index 0000000000..1eb3563ff6--- /dev/null+++ b/server/services/tools.js@@ -0,0 +1,89 @@+/**+ * Tools Registry Service+ *+ * Manages onboard tools (image generation, etc.) that CoS agents can discover and use.+ * Tools are stored as individual JSON files in data/tools/.+ */++import { readFile, writeFile, readdir, unlink } from 'fs/promises';+import { join } from 'path';+import { randomUUID } from 'crypto';+import { ensureDir, PATHS } from '../lib/fileUtils.js';++const toolPath = (id) => join(PATHS.tools, `${id}.json`);++export async function getTools() {+ await ensureDir(PATHS.tools);+ const files = await readdir(PATHS.tools);+ const tools = [];+ for (const f of files) {+ if (!f.endsWith('.json')) continue;+ const raw = await readFile(join(PATHS.tools, f), 'utf-8').catch(() => null);+ if (raw) tools.push(JSON.parse(raw));+ }+ return tools;+}++export async function getTool(id) {+ const raw = await readFile(toolPath(id), 'utf-8').catch(() => null);+ return raw ? JSON.parse(raw) : null;+}++export async function getEnabledTools() {+ const all = await getTools();+ return all.filter(t => t.enabled);+}++export async function getToolsByCategory(category) {+ const all = await getTools();+ return all.filter(t => t.category === category);+}++export async function registerTool(config) {+ await ensureDir(PATHS.tools);+ const now = new Date().toISOString();+ const tool = {+ id: config.id || randomUUID(),+ name: config.name,+ category: config.category,+ description: config.description || '',+ enabled: config.enabled ?? true,+ config: config.config || {},+ promptHints: config.promptHints || '',+ createdAt: now,+ updatedAt: now+ };+ await writeFile(toolPath(tool.id), JSON.stringify(tool, null, 2) + '\n');+ console.log(`🔧 Tool registered: ${tool.name} (${tool.id})`);+ return tool;+}++export async function updateTool(id, updates) {+ const existing = await getTool(id);+ if (!existing) return null;+ const merged = {+ ...existing,+ ...updates,+ id, // prevent id override+ updatedAt: new Date().toISOString()+ };+ await writeFile(toolPath(id), JSON.stringify(merged, null, 2) + '\n');+ console.log(`🔧 Tool updated: ${merged.name} (${id})`);+ return merged;+}++export async function deleteTool(id) {+ await unlink(toolPath(id)).catch(() => null);+ console.log(`🗑️ Tool deleted: ${id}`);+}++export function getToolsSummaryForPrompt() {+ return getEnabledTools().then(tools => {+ if (tools.length === 0) return '';+ const lines = tools.map(t => {+ const hint = t.promptHints ? ` — ${t.promptHints}` : '';+ return `- **${t.name}** (${t.category}): ${t.description}${hint}`;+ });+ return `## Available Tools\nThe following onboard tools are available for this instance:\n\n${lines.join('\n')}\n`;+ });+}