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
fix([issue-1084]): normalize aiToolkit route errors to the PortOS envelope
Adam Eivy25026b69f9b0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2c5e654b89..c27b95468f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -12,6 +12,7 @@- **Docs:** Split the AI Toolkit and Dashboard Widgets sections out of the root `CLAUDE.md` into directory-scoped `server/lib/aiToolkit/CLAUDE.md` and `client/src/components/dashboard/CLAUDE.md` files (load on demand when working in those subtrees), leaving discovery pointers at root. Trims root context with no loss of guidance.- **[issue-1082] Maintenance:** Decomposed the Chief-of-Staff task-evaluation engine's monolithic spawn loop into one named function per priority tier — no behavior change, making each tier independently testable.- **[issue-1083] Maintenance:** Split the 2,600-line task-prompt module into a pure data leaf (the default-prompt catalog) and a thin getter layer, removing a circular import between the prompt and schedule services — no behavior change.+- **[issue-1084] Maintenance:** AI provider/run/prompt API errors now report the same structured shape (with an error code and timestamp) as the rest of PortOS, so error-handling UI behaves consistently across every API.## Fixeddiff --git a/server/index.js b/server/index.jsindex 4deaa234cc..44b165708b 100644--- a/server/index.js+++ b/server/index.js@@ -127,7 +127,7 @@ import { initSyncLog } from './services/brainSyncLog.js';import { backfillOriginInstanceId } from './services/brainStorage.js';import { initSyncOrchestrator } from './services/syncOrchestrator.js';import { initSocket } from './services/socket.js';-import { errorMiddleware, setupProcessErrorHandlers, asyncHandler } from './lib/errorHandler.js';+import { errorMiddleware, setupProcessErrorHandlers, asyncHandler, ServerError } from './lib/errorHandler.js';import { initAutoFixer } from './services/autoFixer.js';import { initCertRenewer } from './services/certRenewer.js';import { setHttpsEnabledAtBoot } from './lib/httpsState.js';@@ -287,6 +287,9 @@ const aiToolkit = createAIToolkit({sampleProvidersFile: join(DATA_REFERENCE_DIR, 'providers.json'),io,asyncHandler,+ // Inject PortOS's ServerError so toolkit route errors normalize into the+ // canonical `{ error, code, timestamp, context? }` envelope (issue #1084).+ ServerError,hooks: aiToolkitHooks});diff --git a/server/lib/aiToolkit/index.js b/server/lib/aiToolkit/index.jsindex 56bc55f214..fa1eb491d9 100644--- a/server/lib/aiToolkit/index.js+++ b/server/lib/aiToolkit/index.js@@ -37,6 +37,11 @@ export function createAIToolkit(config = {}) {sampleProvidersFile = null,io = null,asyncHandler = (fn) => fn,+ // Host-injected HTTP error class (PortOS passes its `ServerError` so route+ // errors normalize into `{ error, code, timestamp, context? }`). Threaded+ // to every router; routes default to the toolkit's own ToolkitHttpError+ // when this is unset (standalone use).+ ServerError,hooks = {},maxConcurrentRuns = 5,enableProviderStatus = true,@@ -90,12 +95,15 @@ export function createAIToolkit(config = {}) {console.error(`❌ Failed to initialize prompts: ${err.message}`);});- const providersRouter = createProvidersRoutes(providerService, { asyncHandler });- const runsRouter = createRunsRoutes(runnerService, { asyncHandler, io });- const promptsRouter = createPromptsRoutes(promptsService, { asyncHandler });+ // `ServerError: undefined` lets the router's own default (ToolkitHttpError)+ // apply — destructuring defaults fire for undefined values.+ const providersRouter = createProvidersRoutes(providerService, { asyncHandler, ServerError });+ const runsRouter = createRunsRoutes(runnerService, { asyncHandler, io, ServerError });+ const promptsRouter = createPromptsRoutes(promptsService, { asyncHandler, ServerError });let providerStatusRouter = null;if (providerStatusService) {+ // providerStatus has no 4xx error paths today, so it takes no ServerError.providerStatusRouter = createProviderStatusRoutes(providerStatusService, { asyncHandler });}diff --git a/server/lib/aiToolkit/internal/httpError.js b/server/lib/aiToolkit/internal/httpError.jsnew file mode 100644index 0000000000..3c43f86956--- /dev/null+++ b/server/lib/aiToolkit/internal/httpError.js@@ -0,0 +1,48 @@+/**+ * HTTP error class for the aiToolkit route handlers.+ *+ * Shaped to mirror PortOS's `ServerError` (server/lib/errorHandler.js) so a+ * thrown toolkit error normalizes into the canonical PortOS error envelope+ * `{ error, code, timestamp, context? }` when the host injects its own+ * `ServerError` + `asyncHandler`. Kept in-tree so the toolkit stays+ * self-contained (no imports out to sibling PortOS modules).+ *+ * Routes accept the error class via options (`ServerError`), defaulting to+ * this `ToolkitHttpError`. PortOS injects its real `ServerError` in+ * `server/index.js` so the host's `normalizeError` passes the instance+ * through untouched — preserving the `code`/`timestamp`/`context` clients+ * read on `/api/{providers,runs,prompts}` errors.+ */++/**+ * Map an HTTP status to a machine-readable error code. Mirrors PortOS's+ * `getErrorCode` so standalone toolkit responses carry the same codes the+ * host would derive.+ */+export function getErrorCode(status) {+ const codeMap = {+ 400: 'BAD_REQUEST',+ 401: 'UNAUTHORIZED',+ 403: 'FORBIDDEN',+ 404: 'NOT_FOUND',+ 409: 'CONFLICT',+ 422: 'VALIDATION_ERROR',+ 500: 'INTERNAL_ERROR',+ 502: 'BAD_GATEWAY',+ 503: 'SERVICE_UNAVAILABLE'+ };+ return codeMap[status] || 'INTERNAL_ERROR';+}++export class ToolkitHttpError extends Error {+ constructor(message, options = {}) {+ super(message);+ this.name = 'ToolkitHttpError';+ this.status = options.status || 500;+ // An explicit code always wins; otherwise derive from the status so a+ // `{ status: 404 }` error reports `NOT_FOUND`, matching ServerError.+ this.code = options.code || getErrorCode(this.status);+ this.timestamp = Date.now();+ this.context = options.context || {};+ }+}diff --git a/server/lib/aiToolkit/routes/errorEnvelope.test.js b/server/lib/aiToolkit/routes/errorEnvelope.test.jsnew file mode 100644index 0000000000..57c4681af7--- /dev/null+++ b/server/lib/aiToolkit/routes/errorEnvelope.test.js@@ -0,0 +1,112 @@+import { describe, it, expect, vi } from 'vitest';+import express from 'express';+import { request } from '../../testHelper.js';+import { asyncHandler, errorMiddleware, ServerError } from '../../errorHandler.js';+import { createRunsRoutes } from './runs.js';+import { createProvidersRoutes } from './providers.js';+import { createPromptsRoutes } from './prompts.js';+import { ToolkitHttpError, getErrorCode } from '../internal/httpError.js';++// Issue #1084 — toolkit route errors must normalize into PortOS's canonical+// error envelope `{ error, code, timestamp, context? }` (not the old+// `{ error, details }`) when the host injects its ServerError + asyncHandler.+// This suite pins that contract end-to-end through PortOS's real asyncHandler+// and errorMiddleware, and also pins the standalone default (ToolkitHttpError).++/** Mount a router under PortOS's asyncHandler + ServerError + errorMiddleware. */+function portosApp(mountPath, makeRouter) {+ const app = express();+ app.use(express.json());+ app.use(mountPath, makeRouter({ asyncHandler, ServerError }));+ app.use(errorMiddleware);+ return app;+}++describe('issue-1084: toolkit routes emit the PortOS error envelope', () => {+ it('runs 404 (GET /:id missing) → { error, code, timestamp }', async () => {+ const runner = { getRun: vi.fn().mockResolvedValue(null), isRunActive: vi.fn() };+ const app = portosApp('/api/runs', (opts) => createRunsRoutes(runner, opts));++ const res = await request(app).get('/api/runs/nope');+ expect(res.status).toBe(404);+ expect(res.body.error).toBe('Run not found');+ expect(res.body.code).toBe('NOT_FOUND');+ expect(typeof res.body.timestamp).toBe('number');+ // The retired shape used `details`; the envelope must not carry it here.+ expect(res.body.details).toBeUndefined();+ });++ it('runs 400 (invalid payload) → VALIDATION_ERROR with details in context', async () => {+ const runner = { createRun: vi.fn() };+ const app = portosApp('/api/runs', (opts) => createRunsRoutes(runner, opts));++ // `timeout: 'abc'` fails runSchema → the validation-reject branch.+ const res = await request(app).post('/api/runs').send({ providerId: 'p1', prompt: 'hi', timeout: 'abc' });+ expect(res.status).toBe(400);+ expect(res.body.error).toBe('Invalid run data');+ expect(res.body.code).toBe('VALIDATION_ERROR');+ expect(typeof res.body.timestamp).toBe('number');+ // The zod issues moved from top-level `details` into `context.details`.+ expect(res.body.context?.details).toBeDefined();+ expect(runner.createRun).not.toHaveBeenCalled();+ });++ it('providers 404 (GET /:id missing) → NOT_FOUND envelope', async () => {+ const providers = { getProviderById: vi.fn().mockResolvedValue(null) };+ const app = portosApp('/api/providers', (opts) => createProvidersRoutes(providers, opts));++ const res = await request(app).get('/api/providers/ghost');+ expect(res.status).toBe(404);+ expect(res.body).toMatchObject({ error: 'Provider not found', code: 'NOT_FOUND' });+ expect(typeof res.body.timestamp).toBe('number');+ });++ it('providers 400 (POST missing name) → BAD_REQUEST envelope', async () => {+ const providers = { createProvider: vi.fn() };+ const app = portosApp('/api/providers', (opts) => createProvidersRoutes(providers, opts));++ const res = await request(app).post('/api/providers').send({ type: 'cli' });+ expect(res.status).toBe(400);+ expect(res.body).toMatchObject({ error: 'Name is required', code: 'BAD_REQUEST' });+ expect(providers.createProvider).not.toHaveBeenCalled();+ });++ it('prompts 404 (GET /stages/:name missing) → NOT_FOUND envelope', async () => {+ const prompts = { getStage: vi.fn().mockReturnValue(null) };+ const app = portosApp('/api/prompts', (opts) => createPromptsRoutes(prompts, opts));++ const res = await request(app).get('/api/prompts/stages/missing');+ expect(res.status).toBe(404);+ expect(res.body).toMatchObject({ error: 'Stage not found', code: 'NOT_FOUND' });+ });+});++describe('issue-1084: standalone default (no injected ServerError)', () => {+ it('falls back to ToolkitHttpError and Express 5 honors its status', async () => {+ // No ServerError injected → routes throw ToolkitHttpError. With Express 5's+ // built-in async error handling, the thrown error's `status` is honored.+ const identityHandler = (fn) => fn;+ const providers = { getProviderById: vi.fn().mockResolvedValue(null) };+ const app = express();+ app.use(express.json());+ app.use('/api/providers', createProvidersRoutes(providers, { asyncHandler: identityHandler }));++ const res = await request(app).get('/api/providers/ghost');+ expect(res.status).toBe(404);+ });++ it('ToolkitHttpError derives code from status and stamps a timestamp', () => {+ const err = new ToolkitHttpError('boom', { status: 404 });+ expect(err.code).toBe('NOT_FOUND');+ expect(err.status).toBe(404);+ expect(typeof err.timestamp).toBe('number');+ expect(err.context).toEqual({});+ });++ it('getErrorCode mirrors the PortOS status→code map', () => {+ expect(getErrorCode(400)).toBe('BAD_REQUEST');+ expect(getErrorCode(404)).toBe('NOT_FOUND');+ expect(getErrorCode(422)).toBe('VALIDATION_ERROR');+ expect(getErrorCode(599)).toBe('INTERNAL_ERROR');+ });+});diff --git a/server/lib/aiToolkit/routes/prompts.js b/server/lib/aiToolkit/routes/prompts.jsindex ebe431ad5a..1077c6f11d 100644--- a/server/lib/aiToolkit/routes/prompts.js+++ b/server/lib/aiToolkit/routes/prompts.js@@ -1,8 +1,12 @@import { Router } from 'express';+import { ToolkitHttpError } from '../internal/httpError.js';export function createPromptsRoutes(promptsService, options = {}) {const router = Router();- const { asyncHandler = (fn) => fn } = options;+ // `ServerError` is injected by the host (PortOS passes its real ServerError+ // so thrown errors normalize into `{ error, code, timestamp, context? }`).+ // Defaults to the toolkit's own error class for standalone use.+ const { asyncHandler = (fn) => fn, ServerError = ToolkitHttpError } = options;router.get('/stages', asyncHandler(async (req, res) => {const stages = promptsService.getStages();@@ -13,7 +17,7 @@ export function createPromptsRoutes(promptsService, options = {}) {const stage = promptsService.getStage(req.params.name);if (!stage) {- return res.status(404).json({ error: 'Stage not found' });+ throw new ServerError('Stage not found', { status: 404 });}const template = await promptsService.getStageTemplate(req.params.name);@@ -51,7 +55,7 @@ export function createPromptsRoutes(promptsService, options = {}) {const variable = promptsService.getVariable(req.params.key);if (!variable) {- return res.status(404).json({ error: 'Variable not found' });+ throw new ServerError('Variable not found', { status: 404 });}res.json(variable);@@ -61,7 +65,7 @@ export function createPromptsRoutes(promptsService, options = {}) {const { key, ...data } = req.body;if (!key) {- return res.status(400).json({ error: 'Variable key is required' });+ throw new ServerError('Variable key is required', { status: 400 });}await promptsService.createVariable(key, data);diff --git a/server/lib/aiToolkit/routes/providers.js b/server/lib/aiToolkit/routes/providers.jsindex 17cb0c198b..2ccdb259bd 100644--- a/server/lib/aiToolkit/routes/providers.js+++ b/server/lib/aiToolkit/routes/providers.js@@ -1,8 +1,12 @@import { Router } from 'express';+import { ToolkitHttpError } from '../internal/httpError.js';export function createProvidersRoutes(providerService, options = {}) {const router = Router();- const { asyncHandler = (fn) => fn } = options;+ // `ServerError` is injected by the host (PortOS passes its real ServerError+ // so thrown errors normalize into `{ error, code, timestamp, context? }`).+ // Defaults to the toolkit's own error class for standalone use.+ const { asyncHandler = (fn) => fn, ServerError = ToolkitHttpError } = options;router.get('/', asyncHandler(async (req, res) => {const data = await providerService.getAllProviders();@@ -17,13 +21,13 @@ export function createProvidersRoutes(providerService, options = {}) {router.put('/active', asyncHandler(async (req, res) => {const { id } = req.body;if (!id) {- return res.status(400).json({ error: 'Provider ID required' });+ throw new ServerError('Provider ID required', { status: 400 });}const provider = await providerService.setActiveProvider(id);if (!provider) {- return res.status(404).json({ error: 'Provider not found' });+ throw new ServerError('Provider not found', { status: 404 });}res.json(provider);@@ -38,7 +42,7 @@ export function createProvidersRoutes(providerService, options = {}) {const provider = await providerService.getProviderById(req.params.id);if (!provider) {- return res.status(404).json({ error: 'Provider not found' });+ throw new ServerError('Provider not found', { status: 404 });}res.json(provider);@@ -48,11 +52,11 @@ export function createProvidersRoutes(providerService, options = {}) {const { name, type } = req.body;if (!name) {- return res.status(400).json({ error: 'Name is required' });+ throw new ServerError('Name is required', { status: 400 });}if (!type || !['cli', 'api', 'tui'].includes(type)) {- return res.status(400).json({ error: 'Type must be "cli", "api", or "tui"' });+ throw new ServerError('Type must be "cli", "api", or "tui"', { status: 400 });}const provider = await providerService.createProvider(req.body);@@ -63,7 +67,7 @@ export function createProvidersRoutes(providerService, options = {}) {const provider = await providerService.updateProvider(req.params.id, req.body);if (!provider) {- return res.status(404).json({ error: 'Provider not found' });+ throw new ServerError('Provider not found', { status: 404 });}res.json(provider);@@ -73,7 +77,7 @@ export function createProvidersRoutes(providerService, options = {}) {const deleted = await providerService.deleteProvider(req.params.id);if (!deleted) {- return res.status(404).json({ error: 'Provider not found' });+ throw new ServerError('Provider not found', { status: 404 });}res.status(204).send();@@ -88,7 +92,7 @@ export function createProvidersRoutes(providerService, options = {}) {const provider = await providerService.refreshProviderModels(req.params.id);if (!provider) {- return res.status(404).json({ error: 'Provider not found or not an API type' });+ throw new ServerError('Provider not found or not an API type', { status: 404 });}res.json(provider);diff --git a/server/lib/aiToolkit/routes/runs.js b/server/lib/aiToolkit/routes/runs.jsindex 0967645f35..4b09e1d4e1 100644--- a/server/lib/aiToolkit/routes/runs.js+++ b/server/lib/aiToolkit/routes/runs.js@@ -1,9 +1,13 @@import { Router } from 'express';import { runSchema, validate } from '../validation.js';+import { ToolkitHttpError } from '../internal/httpError.js';export function createRunsRoutes(runnerService, options = {}) {const router = Router();- const { asyncHandler = (fn) => fn, io = null } = options;+ // `ServerError` is injected by the host (PortOS passes its real ServerError+ // so thrown errors normalize into `{ error, code, timestamp, context? }`).+ // Defaults to the toolkit's own error class for standalone use.+ const { asyncHandler = (fn) => fn, io = null, ServerError = ToolkitHttpError } = options;router.get('/', asyncHandler(async (req, res) => {const limit = parseInt(req.query.limit) || 50;@@ -21,16 +25,16 @@ export function createRunsRoutes(runnerService, options = {}) {// characters as individual paths.const result = validate(runSchema, req.body);if (!result.success) {- return res.status(400).json({ error: 'Invalid run data', details: result.errors });+ throw new ServerError('Invalid run data', { status: 400, code: 'VALIDATION_ERROR', context: { details: result.errors } });}const { providerId, model, prompt, workspacePath, workspaceName, timeout, screenshots } = result.data;console.log(`🚀 POST /runs - provider: ${providerId}, model: ${model}, workspace: ${workspaceName}`);if (!providerId) {- return res.status(400).json({ error: 'providerId is required' });+ throw new ServerError('providerId is required', { status: 400 });}if (!prompt) {- return res.status(400).json({ error: 'prompt is required' });+ throw new ServerError('prompt is required', { status: 400 });}const runData = await runnerService.createRun({@@ -119,11 +123,13 @@ export function createRunsRoutes(runnerService, options = {}) {effectiveTimeout);} else {- return res.status(400).json({- error: `Unsupported provider type: ${provider.type}`,- details: provider.type === 'tui'- ? 'TUI executor not attached to runner — check that executeTuiRun is patched in index.js'- : `Known types: cli, api, tui (received: ${provider.type})`,+ throw new ServerError(`Unsupported provider type: ${provider.type}`, {+ status: 400,+ context: {+ details: provider.type === 'tui'+ ? 'TUI executor not attached to runner — check that executeTuiRun is patched in index.js'+ : `Known types: cli, api, tui (received: ${provider.type})`,+ },});}@@ -138,7 +144,7 @@ export function createRunsRoutes(runnerService, options = {}) {const metadata = await runnerService.getRun(req.params.id);if (!metadata) {- return res.status(404).json({ error: 'Run not found' });+ throw new ServerError('Run not found', { status: 404 });}const isActive = await runnerService.isRunActive(req.params.id);@@ -152,7 +158,7 @@ export function createRunsRoutes(runnerService, options = {}) {const output = await runnerService.getRunOutput(req.params.id);if (output === null) {- return res.status(404).json({ error: 'Run not found' });+ throw new ServerError('Run not found', { status: 404 });}res.type('text/plain').send(output);@@ -162,7 +168,7 @@ export function createRunsRoutes(runnerService, options = {}) {const prompt = await runnerService.getRunPrompt(req.params.id);if (prompt === null) {- return res.status(404).json({ error: 'Run not found' });+ throw new ServerError('Run not found', { status: 404 });}res.type('text/plain').send(prompt);@@ -172,7 +178,7 @@ export function createRunsRoutes(runnerService, options = {}) {const stopped = await runnerService.stopRun(req.params.id);if (!stopped) {- return res.status(404).json({ error: 'Run not found or not active' });+ throw new ServerError('Run not found or not active', { status: 404 });}res.json({ success: true });@@ -182,7 +188,7 @@ export function createRunsRoutes(runnerService, options = {}) {const deleted = await runnerService.deleteRun(req.params.id);if (!deleted) {- return res.status(404).json({ error: 'Run not found' });+ throw new ServerError('Run not found', { status: 404 });}res.status(204).send();@@ -190,7 +196,7 @@ export function createRunsRoutes(runnerService, options = {}) {router.delete('/', asyncHandler(async (req, res) => {if (req.query.filter !== 'failed') {- return res.status(400).json({ error: 'Only filter=failed is supported for bulk delete' });+ throw new ServerError('Only filter=failed is supported for bulk delete', { status: 400 });}const deletedCount = await runnerService.deleteFailedRuns();