Skip to content

Your always-on AI coworkers that move between text, calls, and Slack.

TypeScript
2.1 KB
Raw Blame
import { Hono } from 'hono';
import { z } from 'zod';
import type { ComputerService } from './computer-service.js';
import type { ComputerAction } from '../shared/computer-types.js';
export function computerRoutes(computers: ComputerService) {
  const app = new Hono();
  app.onError((error, c) => {
    if (error instanceof SyntaxError)
      return c.json({ error: 'Invalid JSON request.' }, 400);
    if (error instanceof z.ZodError)
      return c.json({ error: 'Invalid computer request.' }, 400);
    const text = error.message;
    if (text === 'Dot not found.') return c.json({ error: text }, 404);
    if (
      text === 'Computer permission is disabled.' ||
      text === 'Human controls are owner-only.'
    )
      return c.json({ error: text }, 403);
    if (
      text === 'Start this Dot’s computer first.' ||
      text === 'There is no active control request.'
    )
      return c.json({ error: text }, 409);
    if (text === 'Unknown computer action.')
      return c.json({ error: text }, 400);
    return c.json({ error: text }, 503);
  });
  app.get('/dots/:id/computer', async (c) =>
    c.json(await computers.status(c.req.param('id'))),
  );
  app.patch('/dots/:id/computer/permissions', async (c) =>
    c.json(await computers.permissions(c.req.param('id'), await c.req.json())),
  );
  app.post('/dots/:id/computer/start', async (c) =>
    c.json(await computers.start(c.req.param('id'))),
  );
  app.post('/dots/:id/computer/stop', async (c) =>
    c.json(await computers.stop(c.req.param('id'))),
  );
  app.post('/dots/:id/computer/take', async (c) =>
    c.json(await computers.control(c.req.param('id'), 'take')),
  );
  app.post('/dots/:id/computer/release', async (c) =>
    c.json(await computers.control(c.req.param('id'), 'release')),
  );
  app.post('/dots/:id/computer/actions', async (c) => {
    const body = z
      .object({ action: z.string(), input: z.unknown() })
      .strict()
      .parse(await c.req.json());
    return c.json(
      await computers.action(
        c.req.param('id'),
        body.action as ComputerAction,
        body.input,
        'owner',
        c.req.raw.signal,
      ),
    );
  });
  return app;
}