Skip to content

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

fix([issue-1084]): serialize standalone toolkit errors as JSON (address review: codex)

Adam Eivy45bbc8929150
diff --git a/server/lib/aiToolkit/index.js b/server/lib/aiToolkit/index.js
index fa1eb491d9..08df786b0e 100644
--- a/server/lib/aiToolkit/index.js
+++ b/server/lib/aiToolkit/index.js
@@ -14,6 +14,7 @@ import { createProvidersRoutes } from './routes/providers.js';
import { createRunsRoutes } from './routes/runs.js';
import { createPromptsRoutes } from './routes/prompts.js';
import { createProviderStatusRoutes } from './routes/providerStatus.js';
+import { defaultAsyncHandler } from './internal/httpError.js';
import * as errorDetection from './errorDetection.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -36,7 +37,10 @@ export function createAIToolkit(config = {}) {
screenshotsDir = './data/screenshots',
sampleProvidersFile = null,
io = null,
- asyncHandler = (fn) => fn,
+ // Standalone, fall back to the toolkit's own JSON-serializing handler so
+ // thrown errors still produce the canonical envelope (not Express 5's HTML
+ // error page). PortOS injects its own asyncHandler (→ errorMiddleware).
+ asyncHandler = defaultAsyncHandler,
// 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
diff --git a/server/lib/aiToolkit/internal/httpError.js b/server/lib/aiToolkit/internal/httpError.js
index 3c43f86956..3a23faf5f3 100644
--- a/server/lib/aiToolkit/internal/httpError.js
+++ b/server/lib/aiToolkit/internal/httpError.js
@@ -12,6 +12,10 @@
* `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.
+ *
+ * Standalone (no host `asyncHandler`), `defaultAsyncHandler` below serializes
+ * the same envelope, so the toolkit's error shape is consistent even outside
+ * PortOS (rather than falling to Express 5's HTML error page).
*/
/**
@@ -46,3 +50,26 @@ export class ToolkitHttpError extends Error {
this.context = options.context || {};
}
}
+
+/**
+ * Default async route wrapper for standalone toolkit use (no host
+ * `asyncHandler` injected). Catches a thrown error and serializes it into the
+ * same `{ error, code, timestamp, context? }` envelope PortOS emits.
+ *
+ * Without this, a thrown error would fall to Express 5's built-in handler,
+ * which honors `err.status` but renders an HTML error page — dropping
+ * `code`/`timestamp`/`context` for any standalone consumer. PortOS injects its
+ * own `asyncHandler` (→ `errorMiddleware`), so this default never runs there.
+ */
+export function defaultAsyncHandler(fn) {
+ return (req, res, next) => Promise.resolve(fn(req, res, next)).catch((err) => {
+ if (res.headersSent) return next(err);
+ const status = err?.status || 500;
+ res.status(status).json({
+ error: err?.message || 'Internal error',
+ code: err?.code || getErrorCode(status),
+ timestamp: err?.timestamp || Date.now(),
+ ...(err?.context && Object.keys(err.context).length > 0 && { context: err.context })
+ });
+ });
+}
diff --git a/server/lib/aiToolkit/routes/errorEnvelope.test.js b/server/lib/aiToolkit/routes/errorEnvelope.test.js
index 57c4681af7..71aef78571 100644
--- a/server/lib/aiToolkit/routes/errorEnvelope.test.js
+++ b/server/lib/aiToolkit/routes/errorEnvelope.test.js
@@ -81,18 +81,37 @@ describe('issue-1084: toolkit routes emit the PortOS error envelope', () => {
});
});
-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;
+describe('issue-1084: standalone default (no injected asyncHandler/ServerError)', () => {
+ it('serializes the canonical JSON envelope via the toolkit defaults', async () => {
+ // No asyncHandler/ServerError injected → routes throw ToolkitHttpError and
+ // the toolkit's defaultAsyncHandler serializes the same envelope. Without
+ // it, Express 5's built-in handler would honor the status but render an
+ // HTML error page, dropping code/timestamp/context — assert the body, not
+ // just the status, so that regression can't slip back in.
const providers = { getProviderById: vi.fn().mockResolvedValue(null) };
const app = express();
app.use(express.json());
- app.use('/api/providers', createProvidersRoutes(providers, { asyncHandler: identityHandler }));
+ app.use('/api/providers', createProvidersRoutes(providers));
const res = await request(app).get('/api/providers/ghost');
expect(res.status).toBe(404);
+ expect(res.headers['content-type']).toContain('application/json');
+ expect(res.body).toMatchObject({ error: 'Provider not found', code: 'NOT_FOUND' });
+ expect(typeof res.body.timestamp).toBe('number');
+ });
+
+ it('standalone validation error carries context.details as JSON', async () => {
+ const runner = { createRun: vi.fn() };
+ const app = express();
+ app.use(express.json());
+ app.use('/api/runs', createRunsRoutes(runner));
+
+ const res = await request(app).post('/api/runs').send({ providerId: 'p1', prompt: 'hi', timeout: 'abc' });
+ expect(res.status).toBe(400);
+ expect(res.headers['content-type']).toContain('application/json');
+ expect(res.body).toMatchObject({ error: 'Invalid run data', code: 'VALIDATION_ERROR' });
+ expect(res.body.context?.details).toBeDefined();
+ expect(runner.createRun).not.toHaveBeenCalled();
});
it('ToolkitHttpError derives code from status and stamps a timestamp', () => {
diff --git a/server/lib/aiToolkit/routes/prompts.js b/server/lib/aiToolkit/routes/prompts.js
index 1077c6f11d..53a27fd417 100644
--- a/server/lib/aiToolkit/routes/prompts.js
+++ b/server/lib/aiToolkit/routes/prompts.js
@@ -1,12 +1,13 @@
import { Router } from 'express';
-import { ToolkitHttpError } from '../internal/httpError.js';
+import { ToolkitHttpError, defaultAsyncHandler } from '../internal/httpError.js';
export function createPromptsRoutes(promptsService, options = {}) {
const router = Router();
- // `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;
+ // `asyncHandler`/`ServerError` are injected by the host (PortOS passes its
+ // real ServerError + asyncHandler so thrown errors normalize into
+ // `{ error, code, timestamp, context? }` and route to errorMiddleware).
+ // Standalone, the toolkit's own defaults serialize the same envelope.
+ const { asyncHandler = defaultAsyncHandler, ServerError = ToolkitHttpError } = options;
router.get('/stages', asyncHandler(async (req, res) => {
const stages = promptsService.getStages();
diff --git a/server/lib/aiToolkit/routes/providerStatus.js b/server/lib/aiToolkit/routes/providerStatus.js
index e722d02625..ff0cb6fb99 100644
--- a/server/lib/aiToolkit/routes/providerStatus.js
+++ b/server/lib/aiToolkit/routes/providerStatus.js
@@ -1,8 +1,12 @@
import { Router } from 'express';
+import { defaultAsyncHandler } from '../internal/httpError.js';
export function createProviderStatusRoutes(providerStatusService, options = {}) {
const router = Router();
- const { asyncHandler = (fn) => fn } = options;
+ // Standalone default serializes thrown errors into the canonical envelope;
+ // PortOS injects its own asyncHandler. This router has no 4xx throws of its
+ // own, but a rejected service call still lands in the same JSON shape.
+ const { asyncHandler = defaultAsyncHandler } = options;
router.get('/', asyncHandler(async (req, res) => {
const statuses = providerStatusService.getAllStatuses();
diff --git a/server/lib/aiToolkit/routes/providers.js b/server/lib/aiToolkit/routes/providers.js
index 2ccdb259bd..88ec1dcb01 100644
--- a/server/lib/aiToolkit/routes/providers.js
+++ b/server/lib/aiToolkit/routes/providers.js
@@ -1,12 +1,13 @@
import { Router } from 'express';
-import { ToolkitHttpError } from '../internal/httpError.js';
+import { ToolkitHttpError, defaultAsyncHandler } from '../internal/httpError.js';
export function createProvidersRoutes(providerService, options = {}) {
const router = Router();
- // `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;
+ // `asyncHandler`/`ServerError` are injected by the host (PortOS passes its
+ // real ServerError + asyncHandler so thrown errors normalize into
+ // `{ error, code, timestamp, context? }` and route to errorMiddleware).
+ // Standalone, the toolkit's own defaults serialize the same envelope.
+ const { asyncHandler = defaultAsyncHandler, ServerError = ToolkitHttpError } = options;
router.get('/', asyncHandler(async (req, res) => {
const data = await providerService.getAllProviders();
diff --git a/server/lib/aiToolkit/routes/runs.js b/server/lib/aiToolkit/routes/runs.js
index 4b09e1d4e1..b93c0e67df 100644
--- a/server/lib/aiToolkit/routes/runs.js
+++ b/server/lib/aiToolkit/routes/runs.js
@@ -1,13 +1,14 @@
import { Router } from 'express';
import { runSchema, validate } from '../validation.js';
-import { ToolkitHttpError } from '../internal/httpError.js';
+import { ToolkitHttpError, defaultAsyncHandler } from '../internal/httpError.js';
export function createRunsRoutes(runnerService, options = {}) {
const router = Router();
- // `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;
+ // `asyncHandler`/`ServerError` are injected by the host (PortOS passes its
+ // real ServerError + asyncHandler so thrown errors normalize into
+ // `{ error, code, timestamp, context? }` and route to errorMiddleware).
+ // Standalone, the toolkit's own defaults serialize the same envelope.
+ const { asyncHandler = defaultAsyncHandler, io = null, ServerError = ToolkitHttpError } = options;
router.get('/', asyncHandler(async (req, res) => {
const limit = parseInt(req.query.limit) || 50;