Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(console): local control API for programmatic agent management (CHOO-2570) (#362)

Abel Dantasfc197a89ea6e
diff --git a/console/apps/switch-console-desktop/src/main/core/control-api/control-server.test.ts b/console/apps/switch-console-desktop/src/main/core/control-api/control-server.test.ts
new file mode 100644
index 000000000..e8933f580
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/control-api/control-server.test.ts
@@ -0,0 +1,163 @@
+import http from 'node:http';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { ControlServer, sendJson } from './control-server';
+
+const silentLogger = {
+ info: () => {},
+ warn: () => {},
+ error: () => {},
+};
+
+function request(
+ port: number,
+ method: string,
+ path: string,
+ headers: Record<string, string> = {},
+ body?: string
+): Promise<{ status: number; body: string }> {
+ return new Promise((resolve, reject) => {
+ const req = http.request({ hostname: '127.0.0.1', port, method, path, headers }, (res) => {
+ let data = '';
+ res.on('data', (chunk: Buffer) => {
+ data += chunk.toString();
+ });
+ res.on('end', () => resolve({ status: res.statusCode!, body: data }));
+ });
+ req.on('error', reject);
+ if (body) req.write(body);
+ req.end();
+ });
+}
+
+describe('ControlServer', () => {
+ let server: ControlServer;
+
+ beforeEach(async () => {
+ server = new ControlServer(silentLogger);
+ });
+
+ afterEach(() => {
+ server.stop();
+ });
+
+ it('rejects requests without a token', async () => {
+ server.route('GET', '/test', (_req, res) => {
+ sendJson(res, 200, { ok: true });
+ });
+ await server.start();
+ const result = await request(server.getPort(), 'GET', '/test');
+ expect(result.status).toBe(403);
+ });
+
+ it('rejects requests with a wrong token', async () => {
+ server.route('GET', '/test', (_req, res) => {
+ sendJson(res, 200, { ok: true });
+ });
+ await server.start();
+ const result = await request(server.getPort(), 'GET', '/test', {
+ 'x-switch-control-token': 'wrong-token',
+ });
+ expect(result.status).toBe(403);
+ });
+
+ it('accepts requests with the correct token', async () => {
+ server.route('GET', '/test', (_req, res) => {
+ sendJson(res, 200, { ok: true });
+ });
+ await server.start();
+ const result = await request(server.getPort(), 'GET', '/test', {
+ 'x-switch-control-token': server.getToken(),
+ });
+ expect(result.status).toBe(200);
+ expect(JSON.parse(result.body)).toEqual({ ok: true });
+ });
+
+ it('returns 404 for unregistered routes', async () => {
+ await server.start();
+ const result = await request(server.getPort(), 'GET', '/nonexistent', {
+ 'x-switch-control-token': server.getToken(),
+ });
+ expect(result.status).toBe(404);
+ });
+
+ it('matches routes with path parameters', async () => {
+ let captured: Record<string, string> = {};
+ server.route('GET', '/items/:id', (_req, res, params) => {
+ captured = params;
+ sendJson(res, 200, { id: params['id'] });
+ });
+ await server.start();
+ const result = await request(server.getPort(), 'GET', '/items/abc-123', {
+ 'x-switch-control-token': server.getToken(),
+ });
+ expect(result.status).toBe(200);
+ expect(captured['id']).toBe('abc-123');
+ expect(JSON.parse(result.body)).toEqual({ id: 'abc-123' });
+ });
+
+ it('matches routes with multiple path parameters', async () => {
+ let captured: Record<string, string> = {};
+ server.route('DELETE', '/agents/:agentId/sessions/:sessionId', (_req, res, params) => {
+ captured = params;
+ sendJson(res, 200, { ok: true });
+ });
+ await server.start();
+ const result = await request(server.getPort(), 'DELETE', '/agents/agent-1/sessions/session-2', {
+ 'x-switch-control-token': server.getToken(),
+ });
+ expect(result.status).toBe(200);
+ expect(captured['agentId']).toBe('agent-1');
+ expect(captured['sessionId']).toBe('session-2');
+ });
+
+ it('distinguishes methods on the same path', async () => {
+ server.route('GET', '/items', (_req, res) => {
+ sendJson(res, 200, { action: 'list' });
+ });
+ server.route('POST', '/items', (_req, res) => {
+ sendJson(res, 201, { action: 'create' });
+ });
+ await server.start();
+ const token = server.getToken();
+
+ const getResult = await request(server.getPort(), 'GET', '/items', {
+ 'x-switch-control-token': token,
+ });
+ expect(JSON.parse(getResult.body)).toEqual({ action: 'list' });
+
+ const postResult = await request(server.getPort(), 'POST', '/items', {
+ 'x-switch-control-token': token,
+ });
+ expect(postResult.status).toBe(201);
+ expect(JSON.parse(postResult.body)).toEqual({ action: 'create' });
+ });
+
+ it('is reachable on 127.0.0.1', async () => {
+ server.route('GET', '/ping', (_req, res) => {
+ sendJson(res, 200, { pong: true });
+ });
+ await server.start();
+ const result = await request(server.getPort(), 'GET', '/ping', {
+ 'x-switch-control-token': server.getToken(),
+ });
+ expect(result.status).toBe(200);
+ });
+
+ it('generates a valid UUID token', async () => {
+ await server.start();
+ const token = server.getToken();
+ expect(token).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);
+ });
+
+ it('returns a non-zero port after start', async () => {
+ await server.start();
+ expect(server.getPort()).toBeGreaterThan(0);
+ });
+
+ it('resets port after stop', async () => {
+ await server.start();
+ expect(server.getPort()).toBeGreaterThan(0);
+ server.stop();
+ expect(server.getPort()).toBe(0);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/control-api/control-server.ts b/console/apps/switch-console-desktop/src/main/core/control-api/control-server.ts
new file mode 100644
index 000000000..fe3fe863a
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/control-api/control-server.ts
@@ -0,0 +1,179 @@
+import crypto from 'node:crypto';
+import http from 'node:http';
+
+export interface ControlServerLogger {
+ info(...input: unknown[]): void;
+ warn(...input: unknown[]): void;
+ error(...input: unknown[]): void;
+}
+
+export type ControlRouteHandler = (
+ req: http.IncomingMessage,
+ res: http.ServerResponse,
+ params: Record<string, string>
+) => void | Promise<void>;
+
+interface Route {
+ method: string;
+ pattern: RegExp;
+ paramNames: string[];
+ handler: ControlRouteHandler;
+}
+
+/**
+ * Localhost-only HTTP server for the Console local control API. Modeled on
+ * hook-server.ts: binds 127.0.0.1, OS-assigned port, token-gated via the
+ * `x-switch-control-token` header.
+ */
+export class ControlServer {
+ private server: http.Server | null = null;
+ private port = 0;
+ private token = '';
+ private routes: Route[] = [];
+
+ constructor(private readonly log: ControlServerLogger) {}
+
+ /** Register a route. Call before start(). */
+ route(method: string, path: string, handler: ControlRouteHandler): void {
+ const paramNames: string[] = [];
+ const regexStr = path.replace(/:([a-zA-Z]+)/g, (_match, name: string) => {
+ paramNames.push(name);
+ return '([^/]+)';
+ });
+ this.routes.push({
+ method: method.toUpperCase(),
+ pattern: new RegExp(`^${regexStr}$`),
+ paramNames,
+ handler,
+ });
+ }
+
+ async start(): Promise<void> {
+ if (this.server) return;
+ this.token = crypto.randomUUID();
+
+ this.server = http.createServer((req, res) => {
+ if (!this.tokenMatches(req.headers['x-switch-control-token'])) {
+ this.log.warn('ControlServer: rejected request with invalid token');
+ res.writeHead(403);
+ res.end();
+ return;
+ }
+
+ const url = (req.url ?? '').split('?')[0]!;
+ const method = (req.method ?? 'GET').toUpperCase();
+
+ for (const route of this.routes) {
+ if (route.method !== method) continue;
+ const match = route.pattern.exec(url);
+ if (!match) continue;
+
+ let params: Record<string, string>;
+ try {
+ params = {};
+ for (let i = 0; i < route.paramNames.length; i++) {
+ params[route.paramNames[i]!] = decodeURIComponent(match[i + 1]!);
+ }
+ } catch {
+ res.writeHead(400);
+ res.end();
+ return;
+ }
+
+ try {
+ const result = route.handler(req, res, params);
+ if (result instanceof Promise) {
+ result.catch((err) => {
+ this.log.error('ControlServer: handler error', { error: String(err) });
+ if (!res.headersSent) {
+ res.writeHead(500);
+ res.end();
+ }
+ });
+ }
+ } catch (err) {
+ this.log.error('ControlServer: handler error', { error: String(err) });
+ if (!res.headersSent) {
+ res.writeHead(500);
+ res.end();
+ }
+ }
+ return;
+ }
+
+ res.writeHead(404);
+ res.end();
+ });
+
+ return new Promise<void>((resolve, reject) => {
+ this.server!.listen(0, '127.0.0.1', () => {
+ const addr = this.server!.address();
+ if (addr && typeof addr === 'object') {
+ this.port = addr.port;
+ }
+ this.log.info('ControlServer: started', { port: this.port });
+ resolve();
+ });
+ this.server!.on('error', (err) => {
+ this.log.error('ControlServer: failed to start', { error: String(err) });
+ reject(err);
+ });
+ });
+ }
+
+ /** Constant-time token check (hash both sides to a fixed length first). */
+ private tokenMatches(provided: unknown): boolean {
+ if (typeof provided !== 'string' || this.token === '') return false;
+ const a = crypto.createHash('sha256').update(provided).digest();
+ const b = crypto.createHash('sha256').update(this.token).digest();
+ return crypto.timingSafeEqual(a, b);
+ }
+
+ stop(): void {
+ if (this.server) {
+ this.server.close();
+ this.server = null;
+ this.port = 0;
+ }
+ }
+
+ getPort(): number {
+ return this.port;
+ }
+
+ getToken(): string {
+ return this.token;
+ }
+}
+
+/** Send a JSON response with explicit Content-Length (not chunked). */
+export function sendJson(res: http.ServerResponse, status: number, body: unknown): void {
+ const payload = Buffer.from(JSON.stringify(body), 'utf8');
+ res.writeHead(status, {
+ 'content-type': 'application/json',
+ 'content-length': payload.byteLength,
+ });
+ res.end(payload);
+}
+
+/** Read the full request body as a parsed JSON object. */
+export function readJsonBody(req: http.IncomingMessage): Promise<unknown> {
+ return new Promise((resolve, reject) => {
+ let body = '';
+ req.on('data', (chunk: Buffer) => {
+ body += chunk.toString();
+ if (body.length > 1_000_000) {
+ req.destroy();
+ reject(new Error('request body too large'));
+ }
+ });
+ req.on('end', () => {
+ try {
+ resolve(body.length > 0 ? JSON.parse(body) : {});
+ } catch {
+ reject(new Error('invalid JSON'));
+ }
+ });
+ req.on('error', reject);
+ });
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/control-api/control-service.test.ts b/console/apps/switch-console-desktop/src/main/core/control-api/control-service.test.ts
new file mode 100644
index 000000000..7123ac18d
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/control-api/control-service.test.ts
@@ -0,0 +1,299 @@
+import fs from 'node:fs';
+import http from 'node:http';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('electron', () => ({
+ app: { getPath: (name: string) => (name === 'userData' ? os.tmpdir() : '/tmp') },
+}));
+
+const mockGetAgents = vi.fn();
+const mockGetAgentById = vi.fn();
+const mockGetSession = vi.fn();
+const mockCreateSession = vi.fn();
+const mockTeardown = vi.fn();
+const mockGetSessions = vi.fn();
+const mockSidecarRestart = vi.fn();
+const mockSidecarStop = vi.fn();
+const mockSidecarGetStatus = vi.fn();
+
+vi.mock('@main/core/agents/getAgents', () => ({ getAgents: mockGetAgents }));
+vi.mock('@main/core/agents/getAgentById', () => ({ getAgentById: mockGetAgentById }));
+vi.mock('@main/core/sessions/operations/getSession', () => ({ getSession: mockGetSession }));
+vi.mock('@main/core/sessions/session-service', () => ({
+ sessionService: {
+ getSessions: mockGetSessions,
+ createSession: mockCreateSession,
+ teardown: mockTeardown,
+ },
+}));
+vi.mock('@main/core/sidecar/controller', () => ({
+ sidecarController: {
+ restart: mockSidecarRestart,
+ stop: mockSidecarStop,
+ getStatus: mockSidecarGetStatus,
+ },
+}));
+vi.mock('@main/lib/logger', () => ({
+ log: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },
+}));
+
+// Import after mocks are set up
+const { controlService } = await import('./control-service');
+
+function request(
+ port: number,
+ method: string,
+ urlPath: string,
+ token: string,
+ body?: string
+): Promise<{ status: number; body: string }> {
+ return new Promise((resolve, reject) => {
+ const req = http.request(
+ {
+ hostname: '127.0.0.1',
+ port,
+ method,
+ path: urlPath,
+ headers: {
+ 'x-switch-control-token': token,
+ ...(body ? { 'content-type': 'application/json' } : {}),
+ },
+ },
+ (res) => {
+ let data = '';
+ res.on('data', (chunk: Buffer) => {
+ data += chunk.toString();
+ });
+ res.on('end', () => resolve({ status: res.statusCode!, body: data }));
+ }
+ );
+ req.on('error', reject);
+ if (body) req.write(body);
+ req.end();
+ });
+}
+
+const AGENT_A = {
+ id: 'agent-aaa',
+ name: 'test-agent',
+ locationId: 'loc-1',
+ providerId: 'claude-code',
+ switchAgentId: null,
+ apiEndpoint: null,
+ serverId: null,
+ status: null,
+ autoApprove: false,
+ providerConfig: null,
+ createdAt: '2025-01-01T00:00:00Z',
+ updatedAt: '2025-01-01T00:00:00Z',
+};
+
+const SESSION_1 = {
+ id: 'session-111',
+ agentId: 'agent-aaa',
+ providerId: 'claude-code',
+ title: 'Test session',
+ shellId: 'xterm',
+ status: 'in_progress',
+ statusChangedAt: '2025-01-01T00:00:00Z',
+ agentSessionId: null,
+ isInitialSession: false,
+ isPinned: false,
+ createdAt: '2025-01-01T00:00:00Z',
+ updatedAt: '2025-01-01T00:00:00Z',
+};
+
+describe('ControlService routes', () => {
+ let port: number;
+ let token: string;
+
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ await controlService.initialize();
+ port = controlService.getPort();
+ token = controlService.getToken();
+ });
+
+ afterEach(() => {
+ controlService.dispose();
+ });
+
+ describe('GET /agents', () => {
+ it('returns the agent list', async () => {
+ mockGetAgents.mockResolvedValue([AGENT_A]);
+ const res = await request(port, 'GET', '/agents', token);
+ expect(res.status).toBe(200);
+ expect(JSON.parse(res.body)).toEqual({ agents: [AGENT_A] });
+ });
+ });
+
+ describe('GET /agents/:agentId', () => {
+ it('returns a single agent', async () => {
+ mockGetAgentById.mockResolvedValue(AGENT_A);
+ const res = await request(port, 'GET', '/agents/agent-aaa', token);
+ expect(res.status).toBe(200);
+ expect(JSON.parse(res.body)).toEqual({ agent: AGENT_A });
+ });
+
+ it('returns 404 for unknown agent', async () => {
+ mockGetAgentById.mockResolvedValue(undefined);
+ const res = await request(port, 'GET', '/agents/nonexistent', token);
+ expect(res.status).toBe(404);
+ });
+ });
+
+ describe('GET /agents/:agentId/sessions', () => {
+ it('returns sessions for the agent', async () => {
+ mockGetAgentById.mockResolvedValue(AGENT_A);
+ mockGetSessions.mockResolvedValue([
+ SESSION_1,
+ { ...SESSION_1, id: 'other', agentId: 'other' },
+ ]);
+ const res = await request(port, 'GET', '/agents/agent-aaa/sessions', token);
+ expect(res.status).toBe(200);
+ const parsed = JSON.parse(res.body);
+ expect(parsed.sessions).toHaveLength(1);
+ expect(parsed.sessions[0].id).toBe('session-111');
+ });
+
+ it('returns 404 for unknown agent', async () => {
+ mockGetAgentById.mockResolvedValue(undefined);
+ const res = await request(port, 'GET', '/agents/nonexistent/sessions', token);
+ expect(res.status).toBe(404);
+ });
+ });
+
+ describe('POST /agents/:agentId/sessions', () => {
+ it('creates a session', async () => {
+ mockGetAgentById.mockResolvedValue(AGENT_A);
+ mockCreateSession.mockResolvedValue({ success: true, data: SESSION_1 });
+ const res = await request(
+ port,
+ 'POST',
+ '/agents/agent-aaa/sessions',
+ token,
+ JSON.stringify({ title: 'New session' })
+ );
+ expect(res.status).toBe(201);
+ expect(JSON.parse(res.body)).toEqual({ session: SESSION_1 });
+ expect(mockCreateSession).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agent-aaa', title: 'New session' })
+ );
+ });
+
+ it('returns 422 on creation failure', async () => {
+ mockGetAgentById.mockResolvedValue(AGENT_A);
+ mockCreateSession.mockResolvedValue({
+ success: false,
+ error: { type: 'agent-not-found' },
+ });
+ const res = await request(
+ port,
+ 'POST',
+ '/agents/agent-aaa/sessions',
+ token,
+ JSON.stringify({})
+ );
+ expect(res.status).toBe(422);
+ });
+
+ it('returns 404 for unknown agent', async () => {
+ mockGetAgentById.mockResolvedValue(undefined);
+ const res = await request(
+ port,
+ 'POST',
+ '/agents/nonexistent/sessions',
+ token,
+ JSON.stringify({})
+ );
+ expect(res.status).toBe(404);
+ });
+ });
+
+ describe('DELETE /agents/:agentId/sessions/:sessionId', () => {
+ it('tears down a session', async () => {
+ mockGetAgentById.mockResolvedValue(AGENT_A);
+ mockGetSession.mockResolvedValue(SESSION_1);
+ mockTeardown.mockResolvedValue({ success: true, data: undefined });
+ const res = await request(port, 'DELETE', '/agents/agent-aaa/sessions/session-111', token);
+ expect(res.status).toBe(200);
+ expect(mockTeardown).toHaveBeenCalledWith('session-111', 'terminate');
+ });
+
+ it('returns 404 for unknown session', async () => {
+ mockGetAgentById.mockResolvedValue(AGENT_A);
+ mockGetSession.mockResolvedValue(null);
+ const res = await request(port, 'DELETE', '/agents/agent-aaa/sessions/nonexistent', token);
+ expect(res.status).toBe(404);
+ });
+
+ it('returns 404 when session belongs to different agent', async () => {
+ mockGetAgentById.mockResolvedValue(AGENT_A);
+ mockGetSession.mockResolvedValue({ ...SESSION_1, agentId: 'other-agent' });
+ const res = await request(port, 'DELETE', '/agents/agent-aaa/sessions/session-111', token);
+ expect(res.status).toBe(404);
+ });
+
+ it('returns 500 when teardown fails', async () => {
+ mockGetAgentById.mockResolvedValue(AGENT_A);
+ mockGetSession.mockResolvedValue(SESSION_1);
+ mockTeardown.mockResolvedValue({
+ success: false,
+ error: { type: 'timeout', message: 'timed out', timeout: 5000 },
+ });
+ const res = await request(port, 'DELETE', '/agents/agent-aaa/sessions/session-111', token);
+ expect(res.status).toBe(500);
+ expect(JSON.parse(res.body)).toEqual({ error: 'timeout' });
+ });
+ });
+
+ describe('POST /agents/:agentId/sidecar/restart', () => {
+ it('restarts the sidecar', async () => {
+ mockGetAgentById.mockResolvedValue(AGENT_A);
+ const mockStatus = { agentId: 'agent-aaa', running: true };
+ mockSidecarRestart.mockResolvedValue(mockStatus);
+ const res = await request(port, 'POST', '/agents/agent-aaa/sidecar/restart', token);
+ expect(res.status).toBe(200);
+ expect(JSON.parse(res.body)).toEqual({ status: mockStatus });
+ });
+
+ it('returns 404 for unknown agent', async () => {
+ mockGetAgentById.mockResolvedValue(undefined);
+ const res = await request(port, 'POST', '/agents/nonexistent/sidecar/restart', token);
+ expect(res.status).toBe(404);
+ });
+
+ it('returns 500 on sidecar error', async () => {
+ mockGetAgentById.mockResolvedValue(AGENT_A);
+ mockSidecarRestart.mockRejectedValue(new Error('ssh connection failed'));
+ const res = await request(port, 'POST', '/agents/agent-aaa/sidecar/restart', token);
+ expect(res.status).toBe(500);
+ });
+ });
+
+ describe('GET /agents/:agentId/sidecar/status', () => {
+ it('returns sidecar status', async () => {
+ mockGetAgentById.mockResolvedValue(AGENT_A);
+ const mockStatus = { agentId: 'agent-aaa', running: false };
+ mockSidecarGetStatus.mockResolvedValue(mockStatus);
+ const res = await request(port, 'GET', '/agents/agent-aaa/sidecar/status', token);
+ expect(res.status).toBe(200);
+ expect(JSON.parse(res.body)).toEqual({ status: mockStatus });
+ });
+ });
+
+ describe('token file', () => {
+ it('writes a token file on initialize and removes it on dispose', () => {
+ const tokenPath = path.join(os.tmpdir(), 'control-api.json');
+ expect(fs.existsSync(tokenPath)).toBe(true);
+ const content = JSON.parse(fs.readFileSync(tokenPath, 'utf8'));
+ expect(content.port).toBe(port);
+ expect(content.token).toBe(token);
+
+ controlService.dispose();
+ expect(fs.existsSync(tokenPath)).toBe(false);
+ });
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/control-api/control-service.ts b/console/apps/switch-console-desktop/src/main/core/control-api/control-service.ts
new file mode 100644
index 000000000..bd791ca3e
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/control-api/control-service.ts
@@ -0,0 +1,197 @@
+import crypto from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import type { IDisposable, IInitializable } from '@switch-console/shared';
+import { app } from 'electron';
+import { getAgentById } from '@main/core/agents/getAgentById';
+import { getAgents } from '@main/core/agents/getAgents';
+import { getSession } from '@main/core/sessions/operations/getSession';
+import { sessionService } from '@main/core/sessions/session-service';
+import { log } from '@main/lib/logger';
+import { ControlServer, readJsonBody, sendJson } from './control-server';
+
+const TOKEN_FILENAME = 'control-api.json';
+
+class ControlService implements IInitializable, IDisposable {
+ private server = new ControlServer(log);
+
+ async initialize(): Promise<void> {
+ this.registerRoutes();
+ await this.server.start();
+ try {
+ this.writeTokenFile();
+ } catch (err) {
+ this.server.stop();
+ throw err;
+ }
+ log.info('ControlService: initialized', { port: this.server.getPort() });
+ }
+
+ dispose(): void {
+ this.server.stop();
+ this.removeTokenFile();
+ }
+
+ getPort(): number {
+ return this.server.getPort();
+ }
+
+ getToken(): string {
+ return this.server.getToken();
+ }
+
+ private registerRoutes(): void {
+ this.server.route('GET', '/agents', async (_req, res) => {
+ const agents = await getAgents();
+ sendJson(res, 200, { agents });
+ });
+
+ this.server.route('GET', '/agents/:agentId', async (_req, res, params) => {
+ const agent = await getAgentById(params['agentId']!);
+ if (!agent) {
+ sendJson(res, 404, { error: 'agent not found' });
+ return;
+ }
+ sendJson(res, 200, { agent });
+ });
+
+ this.server.route('GET', '/agents/:agentId/sessions', async (_req, res, params) => {
+ const agent = await getAgentById(params['agentId']!);
+ if (!agent) {
+ sendJson(res, 404, { error: 'agent not found' });
+ return;
+ }
+ const allSessions = await sessionService.getSessions();
+ const agentSessions = allSessions.filter((s) => s.agentId === agent.id);
+ sendJson(res, 200, { sessions: agentSessions });
+ });
+
+ this.server.route('POST', '/agents/:agentId/sessions', async (req, res, params) => {
+ const agent = await getAgentById(params['agentId']!);
+ if (!agent) {
+ sendJson(res, 404, { error: 'agent not found' });
+ return;
+ }
+ let body: Record<string, unknown> = {};
+ try {
+ body = (await readJsonBody(req)) as Record<string, unknown>;
+ } catch {
+ sendJson(res, 400, { error: 'invalid request body' });
+ return;
+ }
+ const title = typeof body['title'] === 'string' ? body['title'] : 'API session';
+ const result = await sessionService.createSession({
+ id: crypto.randomUUID(),
+ agentId: agent.id,
+ title,
+ startSource: 'auto',
+ });
+ if (!result.success) {
+ const message =
+ 'message' in result.error && typeof result.error.message === 'string'
+ ? result.error.message
+ : undefined;
+ sendJson(res, 422, { error: result.error.type, ...(message ? { message } : {}) });
+ return;
+ }
+ sendJson(res, 201, { session: result.data });
+ });
+
+ this.server.route(
+ 'DELETE',
+ '/agents/:agentId/sessions/:sessionId',
+ async (_req, res, params) => {
+ const agent = await getAgentById(params['agentId']!);
+ if (!agent) {
+ sendJson(res, 404, { error: 'agent not found' });
+ return;
+ }
+ const session = await getSession(params['sessionId']!);
+ if (!session || session.agentId !== agent.id) {
+ sendJson(res, 404, { error: 'session not found' });
+ return;
+ }
+ const teardownResult = await sessionService.teardown(session.id, 'terminate');
+ if (!teardownResult.success) {
+ sendJson(res, 500, { error: teardownResult.error.type });
+ return;
+ }
+ sendJson(res, 200, { ok: true });
+ }
+ );
+
+ this.server.route('POST', '/agents/:agentId/sidecar/restart', async (_req, res, params) => {
+ const agent = await getAgentById(params['agentId']!);
+ if (!agent) {
+ sendJson(res, 404, { error: 'agent not found' });
+ return;
+ }
+ try {
+ const { sidecarController } = await import('@main/core/sidecar/controller');
+ const status = await sidecarController.restart(agent.id);
+ sendJson(res, 200, { status });
+ } catch (err) {
+ log.warn('ControlService: sidecar restart failed', {
+ agentId: agent.id,
+ error: String(err),
+ });
+ sendJson(res, 500, { error: 'sidecar-restart-failed' });
+ }
+ });
+
+ this.server.route('POST', '/agents/:agentId/sidecar/stop', async (_req, res, params) => {
+ const agent = await getAgentById(params['agentId']!);
+ if (!agent) {
+ sendJson(res, 404, { error: 'agent not found' });
+ return;
+ }
+ try {
+ const { sidecarController } = await import('@main/core/sidecar/controller');
+ const status = await sidecarController.stop(agent.id);
+ sendJson(res, 200, { status });
+ } catch (err) {
+ log.warn('ControlService: sidecar stop failed', { agentId: agent.id, error: String(err) });
+ sendJson(res, 500, { error: 'sidecar-stop-failed' });
+ }
+ });
+
+ this.server.route('GET', '/agents/:agentId/sidecar/status', async (_req, res, params) => {
+ const agent = await getAgentById(params['agentId']!);
+ if (!agent) {
+ sendJson(res, 404, { error: 'agent not found' });
+ return;
+ }
+ try {
+ const { sidecarController } = await import('@main/core/sidecar/controller');
+ const status = await sidecarController.getStatus(agent.id);
+ sendJson(res, 200, { status });
+ } catch (err) {
+ log.warn('ControlService: sidecar status failed', {
+ agentId: agent.id,
+ error: String(err),
+ });
+ sendJson(res, 500, { error: 'sidecar-status-failed' });
+ }
+ });
+ }
+
+ private tokenFilePath(): string {
+ return path.join(app.getPath('userData'), TOKEN_FILENAME);
+ }
+
+ private writeTokenFile(): void {
+ const filePath = this.tokenFilePath();
+ const data = JSON.stringify({ port: this.server.getPort(), token: this.server.getToken() });
+ fs.writeFileSync(filePath, data, { mode: 0o600 });
+ }
+
+ private removeTokenFile(): void {
+ try {
+ fs.unlinkSync(this.tokenFilePath());
+ } catch {
+ // already gone
+ }
+ }
+}
+
+export const controlService = new ControlService();
diff --git a/console/apps/switch-console-desktop/src/main/index.ts b/console/apps/switch-console-desktop/src/main/index.ts
index 5046d1b3e..59a96b772 100644
--- a/console/apps/switch-console-desktop/src/main/index.ts
+++ b/console/apps/switch-console-desktop/src/main/index.ts
@@ -15,6 +15,7 @@ import { migrateAgentStorage } from './core/agents/migrate-agent-storage';
import { initializeRemoteDiscovery, initializeRemoteWatchers } from './core/agents/remote-watcher';
import { resolveAgentServers } from './core/agents/resolve-servers';
import { appService } from './core/app/service';
+import { controlService } from './core/control-api/control-service';
import { localDependencyManager } from './core/dependencies/dependency-managers';
import { locationManager } from './core/locations/location-manager';
import { locationSettingsService } from './core/locations/settings/location-settings-service';
@@ -163,6 +164,10 @@ void app.whenReady().then(async () => {
log.error('Failed to start agent event service:', e);
});
+ controlService.initialize().catch((e) => {
+ log.error('Failed to start control API service:', e);
+ });
+
registerRPCRouter(rpcRouter, ipcMain, withRPCLogContext);
void reconcileResourceSampler();
@@ -264,6 +269,7 @@ app.on('before-quit', (event) => {
event.preventDefault();
logAppExit('before-quit');
agentHookService.dispose();
+ controlService.dispose();
stopResourceSampler();
localServerService.dispose();
remoteServerService.dispose();