Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

3.6 KB
Raw Blame
import { Hono } from 'hono'
import { requireAppScope } from '../platform-principal'
import { dbCoordinates } from '../services/db'
import type { Vars } from '../auth'
import type { Ctx } from '../ctx'
import { fail } from '../errors'
import { body, envOf } from './util'
import { z } from 'zod'

export function serviceRoutes(ctx: Ctx) {
  const r = new Hono<{ Variables: Vars }>()

  /** Live state from the supervisor; falls back to its last status report when the Box is asleep. */
  r.get('/envs/:env/services', async (c) => {
    const env = await envOf(ctx, c)
    if (!env.box_url) return c.json([])
    const { box, services, fresh } = await ctx.resources.liveServices(env, 10_000)
    if (fresh)
      return c.json(
        services.map((s) => ({
          name: s.name,
          state: s.state,
          restarts: s.restarts ?? 0,
          last_exit_code: s.last_exit_code ?? null,
          health: s.health ?? null,
          pid: s.pid ?? null,
          memory_bytes: s.memory_bytes ?? null,
        })),
      )
    return c.json(
      services.map((s) => ({
        ...s,
        state: box === 'stopped' ? 'stopped (Box asleep)' : s.state,
        memory_bytes: null,
        reported_at: env.services_at,
      })),
    )
  })

  r.post('/envs/:env/services/:name/restart', async (c) => {
    const env = await envOf(ctx, c)
    if (!env.box_url) throw fail('not_found', 'this environment has no Box yet', 'run `boxlite app deploy` first')
    const name = c.req.param('name')
    const spec = await ctx.resources.currentSpec(env)
    if (name !== 'all' && !spec?.services.some((s) => s.name === name)) throw fail('not_found', `no service "${name}"`)
    await ctx.resources.ensureRunning(env.id, () => undefined)
    await ctx.supervisor.restart(env.box_url, env.control_secret, name === 'all' ? null : name)
    return c.json({ restarted: name }, 202)
  })

  r.post('/envs/:env/schedules/:name/run', async (c) => {
    const env = await envOf(ctx, c)
    const out = await ctx.scheduler.run(c.get('app'), env, c.req.param('name'))
    return c.json(out)
  })

  r.get('/envs/:env/access', async (c) => {
    const env = await envOf(ctx, c)
    return c.json({
      access: await ctx.resources.effectiveAccess(env),
      source: env.access_override ? 'online' : 'manifest',
    })
  })

  /** An online override; it wins over boxlite.toml (plan shows it as `online_only`). null clears it. */
  r.put('/envs/:env/access', async (c) => {
    const env = await envOf(ctx, c)
    const b = await body(c, z.object({ access: z.enum(['private', 'org', 'public']).nullable() }))
    await ctx.store.updateEnv(env.id, { access_override: b.access })
    const fresh = (await ctx.store.envById(env.id))!
    return c.json({
      access: await ctx.resources.effectiveAccess(fresh),
      source: fresh.access_override ? 'online' : 'manifest',
    })
  })

  r.get('/envs/:env/dev-env', async (c) => {
    requireAppScope('write:apps')
    const app = c.get('app')
    let env = await envOf(ctx, c)
    const spec = await ctx.store.spec(env.id)
    if (spec?.database && !env.db_url) {
      await ctx.resources.ensureDatabase(app.id, env.id)
      env = (await ctx.store.envById(env.id))!
    }
    // No database password leaves the CP: `boxlite app dev` points DATABASE_URL at its local
    // `db proxy` (owner login, through an organization API key) only needs the database name here.
    const { DATABASE_URL: _password, ...vars } = await ctx.resources.runtimeEnv(app, env, spec)
    if (!env.public_url) delete vars.BOXLITE_APP_URL
    return c.json({ env: vars, database: env.db_url ? { name: dbCoordinates(env.db_url).database } : null })
  })

  return r
}