Skip to content

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

6.5 KB
Raw Blame
/** Console API: App lifecycle, agent handoff, environments and runtime operations. */
import type { Hono } from 'hono'
import { z } from 'zod'
import { summaryView } from '../../console-views'
import { handoffPrompt } from '../../console-prompt'
import { fail } from '../../errors'
import { deleteApp, purgeApp, restoreApp } from '../../lifecycle'
import { capturePreview, previewImage } from '../../preview'
import { createOpenTicket } from '../../proxy/gate'
import { createApp } from '../../services/apps'
import { canSee, orgIdFor } from '../../orgs'
import { actorOf, type ConsoleKit } from './kit'
import { principalStorage } from '../../platform-principal'

export function consoleAppRoutes(api: Hono, k: ConsoleKit): void {
  const { ctx, cp, appOf, viewer, envOf, v1, detail, json } = k
  const { store } = ctx

  // ---- apps ----------------------------------------------------------------

  api.get('/apps', async (c) => {
    const v = viewer(c)
    return c.json(
      await Promise.all((await store.apps()).filter((a) => canSee(v, a)).map(async (a) => await summaryView(ctx, a))),
    )
  })

  api.post('/apps', async (c) => {
    const b = await json(c, z.object({ name: z.string().trim().min(1).max(64) }))
    const v = viewer(c)
    const app = await createApp(ctx, b.name, actorOf(v), orgIdFor(v))
    const env = (await store.envByName(app.id, 'main'))!
    return c.json({ app: await detail(app, env), prompt: handoffPrompt(ctx, app.name) }, 201)
  })

  /** Soft-deleted apps (PRD 3.13): kept until purge_after, restorable until then. */
  api.get('/apps/deleted', async (c) => {
    const v = viewer(c)
    return c.json(
      await Promise.all(
        (await store.deletedApps())
          .filter((a) => canSee(v, a))
          .map(async (a) => ({
            name: a.name,
            deletedAt: a.deleted_at,
            purgeAfter: a.purge_after,
            environments: (await store.envs(a.id)).length,
          })),
      ),
    )
  })

  api.post('/apps/deleted/:name/restore', async (c) => {
    const app = await store.appByNameAnyState(c.req.param('name'))
    if (!app?.deleted_at || !canSee(viewer(c), app))
      throw fail('not_found_app', `no deleted app named "${c.req.param('name')}"`, 'it may have been purged already')
    await restoreApp(ctx, app, actorOf(viewer(c)))
    return c.json(await summaryView(ctx, (await store.appById(app.id))!))
  })

  api.delete('/apps/deleted/:name', async (c) => {
    if (!principalStorage.getStore()?.permissions.includes('delete:apps'))
      throw fail('forbidden', 'permanent App deletion requires delete:apps')
    const app = await store.appByNameAnyState(c.req.param('name'))
    if (!app?.deleted_at || !canSee(viewer(c), app))
      throw fail('not_found_app', `no deleted app named "${c.req.param('name')}"`)
    await purgeApp(ctx, app, { deletedOnly: true })
    return c.body(null, 204)
  })

  api.get('/apps/:id/view', async (c) => {
    const app = await appOf(c)
    return c.json(await detail(app, await envOf(c, app)))
  })

  /** The last screenshot of the env's live URL (preview.ts), for the Overview. */
  api.get('/apps/:id/preview', async (c) => {
    const app = await appOf(c)
    const env = await envOf(c, app)
    const image = await previewImage(ctx, env.id)
    if (!image)
      throw fail(
        'not_found',
        `no screenshot of ${app.name} · ${env.name} yet`,
        'one is taken when a deployment goes live',
      )
    return c.body(new Uint8Array(image), 200, {
      'content-type': 'image/jpeg',
      'cache-control': 'private, max-age=86400',
    })
  })

  /** A new screenshot now (it wakes a sleeping app, as a visitor would); taken in the background. */
  api.post('/apps/:id/preview', async (c) => {
    const app = await appOf(c)
    const env = await envOf(c, app)
    if (!env.live_deployment) throw fail('conflict', `${app.name} · ${env.name} has nothing live to take a picture of`)
    capturePreview(ctx, app.id, env.id, env.live_deployment)
    return c.json({ capturing: true }, 202)
  })

  /** Delete is the soft delete of PRD 3.13; the purger removes the resources later. */
  api.delete('/apps/:id', async (c) => {
    await deleteApp(ctx, await appOf(c), actorOf(viewer(c)))
    return c.body(null, 204)
  })

  api.get('/apps/:id/handoff', async (c) => {
    const app = await appOf(c)
    const env = await envOf(c, app)
    return c.json({ prompt: handoffPrompt(ctx, app.name, env.name) })
  })

  /**
   * "Open app": a one-time link into the env's own origin that signs this browser in to it
   * Body or query `next` is the path in the app.
   */
  api.post('/apps/:id/open-ticket', async (c) => {
    const app = await appOf(c)
    const env = await envOf(c, app)
    const b = c.req.header('content-type')?.includes('json')
      ? await json(c, z.object({ next: z.string().max(2000).optional() }))
      : {}
    const { url } = await createOpenTicket(ctx, app, env, b.next ?? c.req.query('next'), actorOf(viewer(c)))
    return c.json({ url })
  })

  // ---- env operations ------------------------------------------------------

  api.post('/apps/:id/publish', async (c) => {
    const app = await appOf(c)
    const env = await envOf(c, app)
    const b = await json(c, z.object({ visibility: z.enum(['private', 'org', 'public']) }))
    await cp('PUT', `${v1(app, env)}/access`, { access: b.visibility })
    return c.json(await detail(app, env))
  })

  api.post('/apps/:id/restart', async (c) => {
    const app = await appOf(c)
    const env = await envOf(c, app)
    const b = await json(c, z.object({ service: z.string().optional() })).catch(() => ({ service: undefined }))
    await cp('POST', `${v1(app, env)}/services/${encodeURIComponent(b.service ?? 'all')}/restart`)
    return c.json(await detail(app, env))
  })

  api.post('/apps/:id/sleep', async (c) => {
    const app = await appOf(c)
    const env = await envOf(c, app)
    const boxes = await ctx.boxes.list(app, env, 'sleep')
    if (!boxes.length && !env.active_box_id) throw fail('conflict', 'nothing is running yet', 'deploy first')
    for (const boxId of boxes) await ctx.resources.sleep(boxId)
    await store.recordActivity(app.id, env.name, actorOf(viewer(c)), 'box.sleep')
    return c.json(await detail(app, env))
  })

  api.post('/apps/:id/schedules/:name/run', async (c) => {
    const app = await appOf(c)
    const env = await envOf(c, app)
    const out = await cp<{ name: string; status: number; ms: number; starting: boolean }>(
      'POST',
      `${v1(app, env)}/schedules/${encodeURIComponent(c.req.param('name'))}/run`,
    )
    return c.json({ ...out, app: await detail(app, env) })
  })
}