feat(api): establish stable HTTP contract — uniform {success,data} envelope, status codes, /api/v1

Point 1 of the v1.0 lock-in: commit to a stable HTTP API (the cleanest, fullest form).

Core (centralized):
- Every JSON /api response now uses ONE envelope via a Fastify preSerialization hook (src/web/server.ts): success -> { success:true, data:<payload> }; error -> { success:false, error, errorCode } with a conventional HTTP status. Non-JSON routes (file-raw, tail-file SSE, download, screenshots, /q redirect, WS) are skipped.
- Error-code -> HTTP status is a single source of truth (httpStatusForErrorCode in src/types/api.ts): 400/401/404/409/422/429/500. Expanded ApiErrorCode (added UNAUTHORIZED, CONFLICT, RATE_LIMITED). Errors are no longer HTTP 200.
- Versioned alias: /api/v1/* rewrites to /api/* (rewriteApiV1Url), so external clients pin to a stable surface while the bundled UI keeps using /api/*.
- Handlers stripped of manual 'success:true' (50 across 14 route files) so they return bare payloads the hook wraps uniformly; fixed the mux DELETE {success:<bool>} envelope collision (-> {killed}).

Frontend (48 call sites across 10 files):
- _apiJson() auto-unwraps { success:true, data } -> data (null on error), so most bare-shape readers are transparent. Raw-fetch sites relocate payload reads under .data; success/res.ok/error checks unchanged.

Docs: new docs/api-reference.md (envelope, status table, error codes, /api/v1, SSE); versioning-policy.md flipped — the HTTP/SSE API is now part of the stable, SemVer-covered surface.

Verification: full unit/route suite green (2680 passed) incl. ~166 updated assertions across 24 test files; typecheck/lint/format/frontend-syntax clean; a headless-chromium smoke loaded the migrated UI and drove the panels with 0 console/page errors; /api/status and /api/v1/status confirmed returning the uniform envelope live.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
arkon
2026-06-10 01:30:43 +02:00
co-authored by Claude Opus 4.8
parent 5b3024b327
commit 458fb81cbe
49 changed files with 929 additions and 554 deletions
+1 -2
View File
@@ -262,7 +262,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
const fixPlanPath = join(casePath, '@fix_plan.md');
if (!existsSync(fixPlanPath)) {
return { success: true, exists: false, content: null, todos: [] };
return { exists: false, content: null, todos: [] };
}
try {
@@ -339,7 +339,6 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
const stats = { total: todos.length, pending, inProgress, completed };
return {
success: true,
exists: true,
content,
todos,
+1 -1
View File
@@ -19,6 +19,6 @@ export function registerClipboardRoutes(app: FastifyInstance, ctx: EventPort): v
sessionId: body.sessionId ?? null,
timestamp: Date.now(),
});
return { success: true };
return {};
});
}
+1 -1
View File
@@ -66,6 +66,6 @@ export function registerHookEventRoutes(
summaryTracker.recordHookEvent(event, safeData);
}
return { success: true };
return {};
});
}
+3 -3
View File
@@ -19,7 +19,7 @@ export function registerMuxRoutes(app: FastifyInstance, ctx: InfraPort): void {
app.delete('/api/mux-sessions/:sessionId', async (req) => {
const { sessionId } = req.params as { sessionId: string };
const success = await ctx.mux.killSession(sessionId);
return { success };
return { killed: success };
});
app.post('/api/mux-sessions/reconcile', async () => {
@@ -29,11 +29,11 @@ export function registerMuxRoutes(app: FastifyInstance, ctx: InfraPort): void {
app.post('/api/mux-sessions/stats/start', async () => {
ctx.mux.startStatsCollection(STATS_COLLECTION_INTERVAL_MS);
return { success: true };
return {};
});
app.post('/api/mux-sessions/stats/stop', async () => {
ctx.mux.stopStatsCollection();
return { success: true };
return {};
});
}
+2 -2
View File
@@ -35,7 +35,7 @@ export function registerPushRoutes(app: FastifyInstance, ctx: InfraPort): void {
if (!updated) {
return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Subscription not found');
}
return { success: true };
return {};
});
app.delete('/api/push/subscribe/:id', async (req) => {
@@ -44,6 +44,6 @@ export function registerPushRoutes(app: FastifyInstance, ctx: InfraPort): void {
if (!removed) {
return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Subscription not found');
}
return { success: true };
return {};
});
}
+2 -2
View File
@@ -101,7 +101,7 @@ export function registerRalphRoutes(
state: session.ralphLoopState,
});
return { success: true };
return {};
});
// Reset circuit breaker for Ralph tracker
@@ -110,7 +110,7 @@ export function registerRalphRoutes(
const session = findSessionOrFail(ctx, id);
session.ralphTracker.resetCircuitBreaker();
return { success: true };
return {};
});
// Get Ralph status block and circuit breaker state
+7 -8
View File
@@ -62,16 +62,16 @@ export function registerRespawnRoutes(
const controller = ctx.respawnControllers.get(id);
if (controller) {
return { success: true, config: controller.getConfig(), active: true };
return { config: controller.getConfig(), active: true };
}
// Return pre-saved config from mux-sessions.json
const preConfig = ctx.mux.getSession(id)?.respawnConfig;
if (preConfig) {
return { success: true, config: preConfig, active: false };
return { config: preConfig, active: false };
}
return { success: true, config: null, active: false };
return { config: null, active: false };
});
// ═══════════════════════════════════════════════════════════════
@@ -114,7 +114,7 @@ export function registerRespawnRoutes(
ctx.broadcast(SseEvent.RespawnStarted, { sessionId: id, status: controller.getStatus() });
return { success: true, status: controller.getStatus() };
return { status: controller.getStatus() };
});
// ========== Stop Respawn ==========
@@ -150,7 +150,7 @@ export function registerRespawnRoutes(
ctx.broadcast(SseEvent.RespawnStopped, { sessionId: id });
return { success: true };
return {};
});
// ========== Update Respawn Config ==========
@@ -169,7 +169,7 @@ export function registerRespawnRoutes(
ctx.saveRespawnConfig(id, controller.getConfig());
ctx.persistSessionState(session);
ctx.broadcast(SseEvent.RespawnConfigUpdated, { sessionId: id, config: controller.getConfig() });
return { success: true, config: controller.getConfig() };
return { config: controller.getConfig() };
}
// No controller running - save as pre-config for when respawn starts
@@ -206,7 +206,7 @@ export function registerRespawnRoutes(
ctx.mux.updateRespawnConfig(id, merged);
ctx.persistSessionState(session);
ctx.broadcast(SseEvent.RespawnConfigUpdated, { sessionId: id, config: merged });
return { success: true, config: merged };
return { config: merged };
});
// ═══════════════════════════════════════════════════════════════
@@ -332,7 +332,6 @@ export function registerRespawnRoutes(
ctx.broadcast(SseEvent.RespawnStarted, { sessionId: id, status: controller.getStatus() });
return {
success: true,
message: 'Respawn enabled on existing session',
respawnStatus: controller.getStatus(),
};
+3 -3
View File
@@ -15,7 +15,7 @@ export function registerScheduledRoutes(app: FastifyInstance, ctx: SessionPort &
return Array.from(ctx.scheduledRuns.values());
});
app.post('/api/scheduled', async (req): Promise<{ success: boolean; run: ScheduledRun } | ApiResponse<never>> => {
app.post('/api/scheduled', async (req): Promise<{ run: ScheduledRun } | ApiResponse<never>> => {
const { prompt, workingDir, durationMinutes } = parseBody(ScheduledRunSchema, req.body, 'Invalid request body');
// Validate workingDir exists and is a directory
@@ -31,7 +31,7 @@ export function registerScheduledRoutes(app: FastifyInstance, ctx: SessionPort &
}
const run = await ctx.startScheduledRun(prompt, workingDir || process.cwd(), durationMinutes ?? 60);
return { success: true, run };
return { run };
});
app.delete('/api/scheduled/:id', async (req) => {
@@ -43,7 +43,7 @@ export function registerScheduledRoutes(app: FastifyInstance, ctx: SessionPort &
}
await ctx.stopScheduledRun(id);
return { success: true };
return {};
});
app.get('/api/scheduled/:id', async (req) => {
+23 -25
View File
@@ -16,7 +16,6 @@ import {
createErrorResponse,
getErrorMessage,
type ApiResponse,
type QuickStartResponse,
type SessionColor,
} from '../../types.js';
import { Session } from '../../session.js';
@@ -211,7 +210,7 @@ export function registerSessionRoutes(
ctx.authSessions?.delete(sessionToken);
}
reply.clearCookie(AUTH_COOKIE_NAME, { path: '/' });
return { success: true };
return {};
});
// ═══════════════════════════════════════════════════════════════
@@ -349,7 +348,7 @@ export function registerSessionRoutes(
// Avoids serializing 2-3MB of terminal+text buffers per session creation.
const lightState = ctx.getSessionStateWithRespawn(session);
ctx.broadcast(SseEvent.SessionCreated, lightState);
return { success: true, session: lightState };
return { session: lightState };
});
// ========== Rename Session ==========
@@ -364,7 +363,7 @@ export function registerSessionRoutes(
// Also update the mux session name if applicable
ctx.mux.updateSessionName(id, session.name);
persistAndBroadcastSession(ctx, session);
return { success: true, name: session.name };
return { name: session.name };
});
// ========== Set Session Color ==========
@@ -381,12 +380,12 @@ export function registerSessionRoutes(
session.setColor(body.color as SessionColor);
persistAndBroadcastSession(ctx, session);
return { success: true, color: session.color };
return { color: session.color };
});
// ========== Delete Session ==========
app.delete('/api/sessions/:id', async (req): Promise<ApiResponse> => {
app.delete('/api/sessions/:id', async (req) => {
const { id } = req.params as { id: string };
const query = req.query as { killMux?: string };
const killMux = query.killMux !== 'false'; // Default to true
@@ -396,7 +395,7 @@ export function registerSessionRoutes(
}
await ctx.cleanupSession(id, killMux, 'user_delete');
return { success: true };
return {};
});
// ========== Delete All Sessions ==========
@@ -473,13 +472,13 @@ export function registerSessionRoutes(
// Create a fresh tracker if one doesn't exist (shouldn't happen normally)
const newTracker = new RunSummaryTracker(id, session.name);
ctx.runSummaryTrackers.set(id, newTracker);
return { success: true, summary: newTracker.getSummary() };
return { summary: newTracker.getSummary() };
}
// Update session name in case it changed
tracker.setSessionName(session.name);
return { success: true, summary: tracker.getSummary() };
return { summary: tracker.getSummary() };
});
// ========== Get Active Tools ==========
@@ -502,7 +501,7 @@ export function registerSessionRoutes(
// ========== Run Prompt ==========
app.post('/api/sessions/:id/run', async (req): Promise<ApiResponse> => {
app.post('/api/sessions/:id/run', async (req) => {
const { id } = req.params as { id: string };
const { prompt } = parseBody(RunPromptSchema, req.body);
const session = findSessionOrFail(ctx, id);
@@ -517,12 +516,12 @@ export function registerSessionRoutes(
});
ctx.broadcast(SseEvent.SessionRunning, { id, prompt });
return { success: true };
return {};
});
// ========== Start Interactive Mode ==========
app.post('/api/sessions/:id/interactive', async (req): Promise<ApiResponse> => {
app.post('/api/sessions/:id/interactive', async (req) => {
const { id } = req.params as { id: string };
const session = findSessionOrFail(ctx, id);
@@ -554,7 +553,7 @@ export function registerSessionRoutes(
ctx.broadcast(SseEvent.SessionInteractive, { id });
ctx.broadcast(SseEvent.SessionUpdated, { session: ctx.getSessionStateWithRespawn(session) });
return { success: true };
return {};
} catch (err) {
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err));
}
@@ -562,7 +561,7 @@ export function registerSessionRoutes(
// ========== Start Shell Mode ==========
app.post('/api/sessions/:id/shell', async (req): Promise<ApiResponse> => {
app.post('/api/sessions/:id/shell', async (req) => {
const { id } = req.params as { id: string };
const session = findSessionOrFail(ctx, id);
@@ -580,7 +579,7 @@ export function registerSessionRoutes(
});
ctx.broadcast(SseEvent.SessionInteractive, { id, mode: 'shell' });
ctx.broadcast(SseEvent.SessionUpdated, { session: ctx.getSessionStateWithRespawn(session) });
return { success: true };
return {};
} catch (err) {
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err));
}
@@ -592,7 +591,7 @@ export function registerSessionRoutes(
// ========== Send Input ==========
app.post('/api/sessions/:id/input', async (req): Promise<ApiResponse> => {
app.post('/api/sessions/:id/input', async (req) => {
const { id } = req.params as { id: string };
const { input, useMux } = parseBody(SessionInputWithLimitSchema, req.body);
const session = findSessionOrFail(ctx, id);
@@ -624,7 +623,7 @@ export function registerSessionRoutes(
} else {
session.write(inputStr);
}
return { success: true };
return {};
});
// ========== Send Named Key (tmux send-keys -H) ==========
@@ -632,7 +631,7 @@ export function registerSessionRoutes(
// Uses send-keys -H (hex) to inject 0x0a (line feed) which Claude Code's
// Ink input recognizes as "insert newline" vs 0x0d (carriage return = submit).
app.post('/api/sessions/:id/send-key', async (req): Promise<ApiResponse> => {
app.post('/api/sessions/:id/send-key', async (req) => {
const { id } = req.params as { id: string };
const body = req.body as Record<string, unknown>;
const key = typeof body?.key === 'string' ? body.key : '';
@@ -671,18 +670,18 @@ export function registerSessionRoutes(
console.error('[Server] send-key failed:', err);
return createErrorResponse(ApiErrorCode.INTERNAL_ERROR, 'tmux send-keys failed');
}
return { success: true };
return {};
});
// ========== Resize Terminal ==========
app.post('/api/sessions/:id/resize', async (req): Promise<ApiResponse> => {
app.post('/api/sessions/:id/resize', async (req) => {
const { id } = req.params as { id: string };
const { cols, rows } = parseBody(ResizeSchema, req.body);
const session = findSessionOrFail(ctx, id);
session.resize(cols, rows);
return { success: true };
return {};
});
// ========== Get Last Response (from transcript JSONL) ==========
@@ -1084,7 +1083,7 @@ export function registerSessionRoutes(
const result = await session.runPrompt(prompt);
// Clean up session after completion to prevent memory leak
await ctx.cleanupSession(session.id, true, 'run_prompt_complete');
return { success: true, sessionId: session.id, ...result };
return { sessionId: session.id, ...result };
} catch (err) {
// Clean up session on error too
await ctx.cleanupSession(session.id, true, 'run_prompt_error');
@@ -1094,7 +1093,7 @@ export function registerSessionRoutes(
// ========== Quick Start ==========
app.post('/api/quick-start', async (req): Promise<QuickStartResponse> => {
app.post('/api/quick-start', async (req) => {
// Prevent unbounded session creation
if (ctx.sessions.size >= MAX_CONCURRENT_SESSIONS) {
return createErrorResponse(
@@ -1263,7 +1262,6 @@ export function registerSessionRoutes(
}
return {
success: true,
sessionId: session.id,
casePath,
caseName,
@@ -1725,6 +1723,6 @@ export function registerSessionRoutes(
await fh.close();
}
return { success: true, path: filepath, filename };
return { path: filepath, filename };
});
}
+13 -17
View File
@@ -238,7 +238,7 @@ export function registerSystemRoutes(
app.post('/api/tunnel/qr/regenerate', async () => {
ctx.tunnelManager.regenerateQrToken();
return { success: true };
return {};
});
// ========== Auth Session Revocation ==========
@@ -251,7 +251,7 @@ export function registerSystemRoutes(
// Revoke all sessions (nuclear option)
ctx.authSessions?.clear();
}
return { success: true };
return {};
});
// ═══════════════════════════════════════════════════════════════
@@ -288,7 +288,7 @@ export function registerSystemRoutes(
const child = spawn('bash', [scriptPath, url], { detached: true, stdio: 'ignore' });
child.on('error', (err) => app.log.error({ err }, 'span-displays launch failed'));
child.unref();
return { success: true, url };
return { url };
} catch (err) {
return reply.code(500).send(createErrorResponse(ApiErrorCode.INTERNAL_ERROR, getErrorMessage(err)));
}
@@ -313,7 +313,7 @@ export function registerSystemRoutes(
app.post('/api/system/update', async (_req, reply) => {
const result = await startUpdate();
if (result.ok) {
return { success: true, updateId: result.updateId, toTag: result.toTag, toVersion: result.toVersion };
return { updateId: result.updateId, toTag: result.toTag, toVersion: result.toVersion };
}
const map = {
'in-flight': { http: 409, api: ApiErrorCode.ALREADY_EXISTS },
@@ -354,7 +354,7 @@ export function registerSystemRoutes(
for (const s of result.cleaned) {
lifecycleLog.log({ event: 'stale_cleaned', sessionId: s.id, name: s.name });
}
return { success: true, cleanedSessions: result.count };
return { cleanedSessions: result.count };
});
app.get('/api/session-lifecycle', async (req) => {
@@ -371,7 +371,7 @@ export function registerSystemRoutes(
since: query.since ? Number(query.since) : undefined,
limit: query.limit ? Math.min(Number(query.limit), 1000) : 200,
});
return { success: true, entries };
return { entries };
});
// ========== Stats ==========
@@ -391,7 +391,6 @@ export function registerSystemRoutes(
app.get('/api/stats', async () => {
const activeSessionTokens = collectActiveTokens();
return {
success: true,
stats: ctx.store.getAggregateStats(activeSessionTokens),
raw: ctx.store.getGlobalStats(),
};
@@ -400,7 +399,6 @@ export function registerSystemRoutes(
app.get('/api/token-stats', async () => {
const activeSessionTokens = collectActiveTokens();
return {
success: true,
daily: ctx.store.getDailyStats(30),
totals: ctx.store.getAggregateStats(activeSessionTokens),
};
@@ -413,13 +411,13 @@ export function registerSystemRoutes(
// ========== Config ==========
app.get('/api/config', async () => {
return { success: true, config: ctx.store.getConfig() };
return { config: ctx.store.getConfig() };
});
app.put('/api/config', async (req) => {
const configData = parseBody(ConfigUpdateSchema, req.body, 'Invalid config');
ctx.store.setConfig(configData as Partial<ReturnType<typeof ctx.store.getConfig>>);
return { success: true, config: ctx.store.getConfig() };
return { config: ctx.store.getConfig() };
});
// ========== Debug/Memory ==========
@@ -535,7 +533,7 @@ export function registerSystemRoutes(
}
}
return { success: true };
return {};
} catch (err) {
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err));
}
@@ -568,7 +566,7 @@ export function registerSystemRoutes(
}
await fs.writeFile(SETTINGS_PATH, JSON.stringify(existingSettings, null, 2));
return { success: true };
return {};
} catch (err) {
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err));
}
@@ -580,7 +578,6 @@ export function registerSystemRoutes(
const { id } = req.params as { id: string };
const session = findSessionOrFail(ctx, id);
return {
success: true,
nice: session.niceConfig,
};
});
@@ -596,7 +593,6 @@ export function registerSystemRoutes(
ctx.broadcast(SseEvent.SessionUpdated, { session: ctx.getSessionStateWithRespawn(session) });
return {
success: true,
nice: session.niceConfig,
note: 'Nice priority only affects newly created mux sessions, not currently running ones.',
};
@@ -620,7 +616,7 @@ export function registerSystemRoutes(
mkdirSync(dir, { recursive: true });
}
await fs.writeFile(windowStatesPath, JSON.stringify(states, null, 2));
return { success: true };
return {};
} catch (err) {
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err));
}
@@ -640,7 +636,7 @@ export function registerSystemRoutes(
mkdirSync(dir, { recursive: true });
}
await fs.writeFile(parentMapPath, JSON.stringify(parentMap, null, 2));
return { success: true };
return {};
} catch (err) {
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err));
}
@@ -799,7 +795,7 @@ export function registerSystemRoutes(
const filepath = join(SCREENSHOTS_DIR, filename);
await fs.writeFile(filepath, filePart.data);
return { success: true, path: filepath, filename };
return { path: filepath, filename };
});
app.get('/api/screenshots', async () => {