summaryrefslogtreecommitdiff
path: root/makima/cloudflare-agent/src/index.ts
blob: 0b64af4a16f7e53418f36a569d0248bd0082c87d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
 * Makima Cloudflare Agent — Worker Entry Point
 *
 * Routes incoming requests to the MakimaAgent Durable Object which manages
 * the upstream WebSocket connection to the Makima server and relays tasks
 * to downstream native daemon instances.
 *
 * Routes:
 *   GET  /                → Agent status (JSON)
 *   GET  /status          → Agent status (JSON)
 *   GET  /health          → Health check
 *   GET  /tasks           → Task history (paginated)
 *   GET  /logs            → Connection logs
 *   POST /reconnect       → Force upstream reconnection
 *   *    /ws              → WebSocket upgrade for downstream daemons
 *   *    /agent/*         → Forwarded to Agent's onRequest handler
 */

import { MakimaAgent } from "./agent";
import type { Env } from "./types";

export { MakimaAgent };

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    const url = new URL(request.url);

    // Use a singleton Durable Object — all traffic routes to one agent
    // instance identified by a fixed name. This ensures a single persistent
    // upstream WebSocket to the Makima server.
    const agentId = env.MAKIMA_AGENT.idFromName("makima-relay-primary");
    const agent = env.MAKIMA_AGENT.get(agentId);

    // WebSocket upgrade path — downstream daemons connect here
    if (url.pathname === "/ws" || url.pathname === "/ws/daemon") {
      const upgradeHeader = request.headers.get("Upgrade");
      if (upgradeHeader !== "websocket") {
        return new Response("Expected WebSocket upgrade", { status: 426 });
      }
      // Forward the WebSocket upgrade to the Durable Object
      return agent.fetch(request);
    }

    // All other routes are forwarded to the Durable Object's onRequest handler
    return agent.fetch(request);
  },
};