feat: 支持自托管的 remote-control-server (#214)

* feat: 支持自托管的 remote-control-server (#214)

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
This commit is contained in:
claude-code-best
2026-04-09 17:40:50 +08:00
committed by GitHub
parent f17b7c7163
commit 2da6514095
81 changed files with 9875 additions and 40 deletions

View File

@@ -0,0 +1,31 @@
import { Hono } from "hono";
import { registerEnvironment, deregisterEnvironment, reconnectEnvironment } from "../../services/environment";
import { apiKeyAuth, acceptCliHeaders } from "../../auth/middleware";
const app = new Hono();
/** POST /v1/environments/bridge — Register an environment */
app.post("/bridge", acceptCliHeaders, apiKeyAuth, async (c) => {
const body = await c.req.json();
const username = c.get("username");
const result = registerEnvironment({ ...body, username });
return c.json(result, 200);
});
/** DELETE /v1/environments/bridge/:id — Deregister */
app.delete("/bridge/:id", acceptCliHeaders, apiKeyAuth, async (c) => {
const envId = c.req.param("id");
deregisterEnvironment(envId);
return c.json({ status: "ok" }, 200);
});
/** POST /v1/environments/:id/bridge/reconnect — Reconnect */
app.post("/:id/bridge/reconnect", acceptCliHeaders, apiKeyAuth, async (c) => {
const envId = c.req.param("id");
reconnectEnvironment(envId);
const { reconnectWorkForEnvironment } = await import("../../services/work-dispatch");
await reconnectWorkForEnvironment(envId);
return c.json({ status: "ok" }, 200);
});
export default app;

View File

@@ -0,0 +1,41 @@
import { Hono } from "hono";
import { pollWork, ackWork, stopWork, heartbeatWork } from "../../services/work-dispatch";
import { apiKeyAuth, acceptCliHeaders } from "../../auth/middleware";
import { updatePollTime } from "../../services/environment";
const app = new Hono();
/** GET /v1/environments/:id/work/poll — Long-poll for work */
app.get("/:id/work/poll", acceptCliHeaders, apiKeyAuth, async (c) => {
const envId = c.req.param("id");
updatePollTime(envId);
const result = await pollWork(envId);
if (!result) {
// Return 204 No Content so the client's axios parses it as null
return c.body(null, 204);
}
return c.json(result, 200);
});
/** POST /v1/environments/:id/work/:workId/ack — Acknowledge work */
app.post("/:id/work/:workId/ack", acceptCliHeaders, apiKeyAuth, async (c) => {
const workId = c.req.param("workId");
ackWork(workId);
return c.json({ status: "ok" }, 200);
});
/** POST /v1/environments/:id/work/:workId/stop — Stop work */
app.post("/:id/work/:workId/stop", acceptCliHeaders, apiKeyAuth, async (c) => {
const workId = c.req.param("workId");
stopWork(workId);
return c.json({ status: "ok" }, 200);
});
/** POST /v1/environments/:id/work/:workId/heartbeat — Heartbeat */
app.post("/:id/work/:workId/heartbeat", acceptCliHeaders, apiKeyAuth, async (c) => {
const workId = c.req.param("workId");
const result = heartbeatWork(workId);
return c.json(result, 200);
});
export default app;

View File

@@ -0,0 +1,119 @@
import { Hono } from "hono";
import { createBunWebSocket } from "hono/bun";
import { validateApiKey } from "../../auth/api-key";
import { verifyWorkerJwt } from "../../auth/jwt";
import {
handleWebSocketOpen,
handleWebSocketMessage,
handleWebSocketClose,
ingestBridgeMessage,
} from "../../transport/ws-handler";
import { getSession } from "../../services/session";
const { upgradeWebSocket, websocket } = createBunWebSocket();
const app = new Hono();
/** Authenticate via API key or worker JWT in Authorization header or ?token= query param */
function authenticateRequest(c: any, label: string, expectedSessionId?: string): boolean {
const authHeader = c.req.header("Authorization");
const queryToken = c.req.query("token");
const token = authHeader?.replace("Bearer ", "") || queryToken;
// Try API key first
if (validateApiKey(token)) {
return true;
}
// Try JWT verification — validate session_id matches if provided
if (token) {
const payload = verifyWorkerJwt(token);
if (payload) {
if (expectedSessionId && payload.session_id !== expectedSessionId) {
console.log(`[Auth] ${label}: FAILED — JWT session_id mismatch`);
return false;
}
return true;
}
}
console.log(`[Auth] ${label}: FAILED — no valid API key or JWT`);
return false;
}
/** POST /v2/session_ingress/session/:sessionId/events — HTTP POST (HybridTransport writes) */
app.post("/session/:sessionId/events", async (c) => {
const sessionId = c.req.param("sessionId")!;
if (!authenticateRequest(c, `POST session/${sessionId}`, sessionId)) {
return c.json({ error: { type: "unauthorized", message: "Invalid auth" } }, 401);
}
const session = getSession(sessionId);
if (!session) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
const body = await c.req.json();
const events = Array.isArray(body.events) ? body.events : [body];
let count = 0;
for (const msg of events) {
if (!msg || typeof msg !== "object") continue;
ingestBridgeMessage(sessionId, msg as Record<string, unknown>);
count++;
}
return c.json({ status: "ok" }, 200);
});
/** WS /v2/session_ingress/ws/:sessionId — WebSocket transport */
app.get(
"/ws/:sessionId",
upgradeWebSocket(async (c) => {
const sessionId = c.req.param("sessionId")!;
if (!authenticateRequest(c, `WS ${sessionId}`, sessionId)) {
return {
onOpen(_evt, ws) {
ws.close(4003, "unauthorized");
},
};
}
const session = getSession(sessionId);
if (!session) {
console.log(`[WS] Upgrade rejected: session ${sessionId} not found`);
return {
onOpen(_evt, ws) {
ws.close(4001, "session not found");
},
};
}
console.log(`[WS] Upgrade accepted: session=${sessionId}`);
return {
onOpen(_evt, ws) {
handleWebSocketOpen(ws as any, sessionId);
},
onMessage(evt, ws) {
const data =
typeof evt.data === "string"
? evt.data
: new TextDecoder().decode(evt.data as ArrayBuffer);
handleWebSocketMessage(ws as any, sessionId, data);
},
onClose(evt, ws) {
const closeEvt = evt as unknown as CloseEvent;
handleWebSocketClose(ws as any, sessionId, closeEvt?.code, closeEvt?.reason);
},
onError(evt, ws) {
console.error(`[WS] Error on session=${sessionId}:`, evt);
handleWebSocketClose(ws as any, sessionId, 1006, "websocket error");
},
};
}),
);
export { websocket };
export default app;

View File

@@ -0,0 +1,85 @@
import { Hono } from "hono";
import {
createSession,
getSession,
updateSessionTitle,
archiveSession,
} from "../../services/session";
import { createWorkItem } from "../../services/work-dispatch";
import { apiKeyAuth, acceptCliHeaders } from "../../auth/middleware";
import { publishSessionEvent } from "../../services/transport";
const app = new Hono();
/** POST /v1/sessions — Create session */
app.post("/", acceptCliHeaders, apiKeyAuth, async (c) => {
const body = await c.req.json();
const username = c.get("username");
const session = createSession({ ...body, username });
// Create work item if environment is specified
if (body.environment_id) {
try {
await createWorkItem(body.environment_id, session.id);
} catch (err) {
console.error(`[RCS] Failed to create work item: ${(err as Error).message}`);
}
}
// Publish initial events if provided
if (body.events && Array.isArray(body.events)) {
for (const evt of body.events) {
publishSessionEvent(session.id, evt.type || "init", evt, "outbound");
}
}
return c.json(session, 200);
});
/** GET /v1/sessions/:id — Get session */
app.get("/:id", acceptCliHeaders, apiKeyAuth, async (c) => {
const session = getSession(c.req.param("id"));
if (!session) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
return c.json(session, 200);
});
/** PATCH /v1/sessions/:id — Update session title */
app.patch("/:id", acceptCliHeaders, apiKeyAuth, async (c) => {
const body = await c.req.json();
if (body.title) {
updateSessionTitle(c.req.param("id"), body.title);
}
const session = getSession(c.req.param("id"));
return c.json(session, 200);
});
/** POST /v1/sessions/:id/archive — Archive session */
app.post("/:id/archive", acceptCliHeaders, apiKeyAuth, async (c) => {
try {
archiveSession(c.req.param("id"));
} catch {
return c.json({ status: "ok" }, 409);
}
return c.json({ status: "ok" }, 200);
});
/** POST /v1/sessions/:id/events — Send event to session */
app.post("/:id/events", acceptCliHeaders, apiKeyAuth, async (c) => {
const sessionId = c.req.param("id");
const body = await c.req.json();
const events = body.events
? Array.isArray(body.events) ? body.events : [body.events]
: Array.isArray(body) ? body : [body];
const published = [];
for (const evt of events) {
const result = publishSessionEvent(sessionId, evt.type || "message", evt, "inbound");
published.push(result);
}
return c.json({ status: "ok", events: published.length }, 200);
});
export default app;

View File

@@ -0,0 +1,36 @@
import { Hono } from "hono";
import { createCodeSession, getSession, incrementEpoch } from "../../services/session";
import { apiKeyAuth, acceptCliHeaders } from "../../auth/middleware";
import { generateWorkerJwt } from "../../auth/jwt";
import { getBaseUrl, config } from "../../config";
const app = new Hono();
/** POST /v1/code/sessions — Create code session (wrapped response for TUI compat) */
app.post("/", acceptCliHeaders, apiKeyAuth, async (c) => {
const body = await c.req.json();
const session = createCodeSession(body);
return c.json({ session }, 200);
});
/** POST /v1/code/sessions/:id/bridge — Get connection info + worker JWT */
app.post("/:id/bridge", acceptCliHeaders, apiKeyAuth, async (c) => {
const sessionId = c.req.param("id");
const session = getSession(sessionId);
if (!session) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
const epoch = incrementEpoch(sessionId);
const expiresInSeconds = config.jwtExpiresIn;
const workerJwt = generateWorkerJwt(sessionId, expiresInSeconds);
return c.json({
api_base_url: getBaseUrl(),
worker_epoch: epoch,
worker_jwt: workerJwt,
expires_in: expiresInSeconds,
}, 200);
});
export default app;

View File

@@ -0,0 +1,24 @@
import { Hono } from "hono";
import { sessionIngressAuth, acceptCliHeaders } from "../../auth/middleware";
import { createSSEStream } from "../../transport/sse-writer";
import { getSession } from "../../services/session";
const app = new Hono();
/** SSE /v1/code/sessions/:id/worker/events/stream — SSE event stream */
app.get("/:id/worker/events/stream", acceptCliHeaders, sessionIngressAuth, async (c) => {
const sessionId = c.req.param("id");
const session = getSession(sessionId);
if (!session) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
// Support Last-Event-ID / from_sequence_num for reconnection
const lastEventId = c.req.header("Last-Event-ID");
const fromSeq = c.req.query("from_sequence_num");
const fromSeqNum = fromSeq ? parseInt(fromSeq) : lastEventId ? parseInt(lastEventId) : 0;
return createSSEStream(c, sessionId, fromSeqNum);
});
export default app;

View File

@@ -0,0 +1,48 @@
import { Hono } from "hono";
import { sessionIngressAuth, acceptCliHeaders } from "../../auth/middleware";
import { publishSessionEvent } from "../../services/transport";
import { getSession, updateSessionStatus } from "../../services/session";
const app = new Hono();
/** POST /v1/code/sessions/:id/worker/events — Write events */
app.post("/:id/worker/events", acceptCliHeaders, sessionIngressAuth, async (c) => {
const sessionId = c.req.param("id");
const body = await c.req.json();
const events = Array.isArray(body) ? body : [body];
const published = [];
for (const evt of events) {
const result = publishSessionEvent(sessionId, evt.type || "message", evt, "inbound");
published.push(result);
}
return c.json({ status: "ok", count: published.length }, 200);
});
/** PUT /v1/code/sessions/:id/worker/state — Report worker state */
app.put("/:id/worker/state", acceptCliHeaders, sessionIngressAuth, async (c) => {
const sessionId = c.req.param("id");
const body = await c.req.json();
if (body.status) {
updateSessionStatus(sessionId, body.status);
}
return c.json({ status: "ok" }, 200);
});
/** PUT /v1/code/sessions/:id/worker/external_metadata — Report worker metadata (no-op) */
app.put("/:id/worker/external_metadata", acceptCliHeaders, sessionIngressAuth, async (c) => {
// TUI's CCRClient calls this for metadata reporting. Accept and discard.
return c.json({ status: "ok" }, 200);
});
/** POST /v1/code/sessions/:id/worker/events/:eventId/delivery — Delivery tracking (no-op) */
app.post("/:id/worker/events/:eventId/delivery", acceptCliHeaders, sessionIngressAuth, async (c) => {
// TUI's CCRClient reports event delivery status (received/processing/processed).
// Accept and discard — event bus doesn't track per-event delivery.
return c.json({ status: "ok" }, 200);
});
export default app;

View File

@@ -0,0 +1,19 @@
import { Hono } from "hono";
import { getSession, incrementEpoch } from "../../services/session";
import { apiKeyAuth, acceptCliHeaders } from "../../auth/middleware";
const app = new Hono();
/** POST /v1/code/sessions/:id/worker/register — Register worker */
app.post("/:id/worker/register", acceptCliHeaders, apiKeyAuth, async (c) => {
const sessionId = c.req.param("id");
const session = getSession(sessionId);
if (!session) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
const epoch = incrementEpoch(sessionId);
return c.json({ worker_epoch: epoch }, 200);
});
export default app;

View File

@@ -0,0 +1,26 @@
import { Hono } from "hono";
import { storeGetSession, storeBindSession } from "../../store";
const app = new Hono();
/** POST /web/bind — Bind a session to a UUID (no-login auth) */
app.post("/bind", async (c) => {
const body = await c.req.json();
const sessionId = body.sessionId;
// UUID can come from query param (api.js sends it in URL) or body
const uuid = c.req.query("uuid") || body.uuid;
if (!sessionId || !uuid) {
return c.json({ error: "sessionId and uuid are required" }, 400);
}
const session = storeGetSession(sessionId);
if (!session) {
return c.json({ error: "Session not found" }, 404);
}
storeBindSession(sessionId, uuid);
return c.json({ ok: true, sessionId });
});
export default app;

View File

@@ -0,0 +1,64 @@
import { Hono } from "hono";
import { uuidAuth } from "../../auth/middleware";
import { getSession, updateSessionStatus } from "../../services/session";
import { publishSessionEvent } from "../../services/transport";
import { getEventBus } from "../../transport/event-bus";
import { storeIsSessionOwner } from "../../store";
const app = new Hono();
function checkOwnership(c: { get: (key: string) => string | undefined }, sessionId: string) {
const uuid = c.get("uuid");
if (!storeIsSessionOwner(sessionId, uuid)) {
return { error: true, session: null };
}
const session = getSession(sessionId);
if (!session) {
return { error: true, session: null };
}
return { error: false, session };
}
/** POST /web/sessions/:id/events — Send user message to session */
app.post("/sessions/:id/events", uuidAuth, async (c) => {
const sessionId = c.req.param("id")!;
const { error } = checkOwnership(c, sessionId);
if (error) {
return c.json({ error: { type: "forbidden", message: "Not your session" } }, 403);
}
const body = await c.req.json();
const eventType = body.type || "user";
console.log(`[RC-DEBUG] web -> server: POST /web/sessions/${sessionId}/events type=${eventType} content=${JSON.stringify(body).slice(0, 200)}`);
const event = publishSessionEvent(sessionId, eventType, body, "outbound");
console.log(`[RC-DEBUG] web -> server: published outbound event id=${event.id} type=${event.type} direction=${event.direction} subscribers=${getEventBus(sessionId).subscriberCount()}`);
return c.json({ status: "ok", event }, 200);
});
/** POST /web/sessions/:id/control — Send control request (permission approval etc) */
app.post("/sessions/:id/control", uuidAuth, async (c) => {
const sessionId = c.req.param("id")!;
const { error } = checkOwnership(c, sessionId);
if (error) {
return c.json({ error: { type: "forbidden", message: "Not your session" } }, 403);
}
const body = await c.req.json();
const event = publishSessionEvent(sessionId, body.type || "control_request", body, "outbound");
return c.json({ status: "ok", event }, 200);
});
/** POST /web/sessions/:id/interrupt — Interrupt session */
app.post("/sessions/:id/interrupt", uuidAuth, async (c) => {
const sessionId = c.req.param("id")!;
const { error } = checkOwnership(c, sessionId);
if (error) {
return c.json({ error: { type: "forbidden", message: "Not your session" } }, 403);
}
publishSessionEvent(sessionId, "interrupt", { action: "interrupt" }, "outbound");
updateSessionStatus(sessionId, "idle");
return c.json({ status: "ok" }, 200);
});
export default app;

View File

@@ -0,0 +1,14 @@
import { Hono } from "hono";
import { uuidAuth } from "../../auth/middleware";
import { listActiveEnvironmentsResponse } from "../../services/environment";
const app = new Hono();
/** GET /web/environments — List active environments (UUID-based, no user filtering) */
app.get("/environments", uuidAuth, async (c) => {
// Environments are shared across all UUIDs for now
const envs = listActiveEnvironmentsResponse();
return c.json(envs, 200);
});
export default app;

View File

@@ -0,0 +1,100 @@
import { Hono } from "hono";
import { uuidAuth } from "../../auth/middleware";
import { getSession, createSession } from "../../services/session";
import { storeListSessionsByOwnerUuid, storeIsSessionOwner, storeBindSession } from "../../store";
import { createWorkItem } from "../../services/work-dispatch";
import { listSessionSummariesByOwnerUuid } from "../../services/session";
import { createSSEStream } from "../../transport/sse-writer";
import { getEventBus } from "../../transport/event-bus";
const app = new Hono();
/** POST /web/sessions — Create a session from web UI */
app.post("/sessions", uuidAuth, async (c) => {
const uuid = c.get("uuid");
const body = await c.req.json();
const session = createSession({
environment_id: body.environment_id || null,
title: body.title || "New Session",
source: "web",
permission_mode: body.permission_mode || "default",
});
// Auto-bind to creator's UUID
storeBindSession(session.id, uuid);
// Dispatch work to environment if specified
if (body.environment_id) {
try {
await createWorkItem(body.environment_id, session.id);
} catch (err) {
console.error(`[RCS] Failed to create work item: ${(err as Error).message}`);
}
}
return c.json(session, 200);
});
/** GET /web/sessions — List sessions owned by the requesting UUID */
app.get("/sessions", uuidAuth, async (c) => {
const uuid = c.get("uuid");
const sessions = storeListSessionsByOwnerUuid(uuid);
return c.json(sessions, 200);
});
/** GET /web/sessions/all — List sessions owned by the requesting UUID (unowned sessions excluded) */
app.get("/sessions/all", uuidAuth, async (c) => {
const uuid = c.get("uuid");
const sessions = listSessionSummariesByOwnerUuid(uuid);
return c.json(sessions, 200);
});
/** GET /web/sessions/:id — Session detail */
app.get("/sessions/:id", uuidAuth, async (c) => {
const uuid = c.get("uuid");
const sessionId = c.req.param("id")!;
if (!storeIsSessionOwner(sessionId, uuid)) {
return c.json({ error: { type: "forbidden", message: "Not your session" } }, 403);
}
const session = getSession(sessionId);
if (!session) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
return c.json(session, 200);
});
/** GET /web/sessions/:id/history — Historical events for session */
app.get("/sessions/:id/history", uuidAuth, async (c) => {
const uuid = c.get("uuid");
const sessionId = c.req.param("id")!;
if (!storeIsSessionOwner(sessionId, uuid)) {
return c.json({ error: { type: "forbidden", message: "Not your session" } }, 403);
}
const session = getSession(sessionId);
if (!session) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
const bus = getEventBus(sessionId);
const events = bus.getEventsSince(0);
return c.json({ events }, 200);
});
/** SSE /web/sessions/:id/events — Real-time event stream */
app.get("/sessions/:id/events", uuidAuth, async (c) => {
const uuid = c.get("uuid");
const sessionId = c.req.param("id")!;
if (!storeIsSessionOwner(sessionId, uuid)) {
return c.json({ error: { type: "forbidden", message: "Not your session" } }, 403);
}
const session = getSession(sessionId);
if (!session) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
const lastEventId = c.req.header("Last-Event-ID");
const fromSeqNum = lastEventId ? parseInt(lastEventId) : 0;
return createSSEStream(c, sessionId, fromSeqNum);
});
export default app;