The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
import Ajv2020 from 'ajv/dist/2020'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { parse } from 'yaml'
import { appRoutePermissions } from './cloud-app-route-permissions'
import { CloudAppWebsocket } from './cloud-app-websocket'
import type { Ctx } from './engine/ctx'
import { createServer } from './engine/server'
const spec = parse(readFileSync(resolve(__dirname, '../../../../openapi/apps.openapi.yaml'), 'utf8'))
const operations = Object.entries(spec.paths as Record<string, Record<string, any>>).flatMap(([path, item]) =>
Object.entries(item)
.filter(([_, op]) => op.operationId)
.map(([method, op]) => ({ path, method: method.toUpperCase(), op })),
)
const shape = (path: string) => path.replace(/:(\w+)(?:\{[^}]+\})?|\{\w+\}/g, '{}').replace(/\/$/, '')
const ctx = {
config: {},
store: {
appByName: async () => ({ id: 'app-1', name: 'example', org_id: 'org' }),
envByName: async () => ({ id: 'env-1', name: 'test', public_url: null, db_url: null }),
spec: async () => undefined,
effectiveSpecVersion: async () => 3,
deploymentByIdempotencyKey: async () => ({ kind: 'deploy', number: 4, status: 'queued' }),
recordActivity: async () => undefined,
},
resources: { currentSpec: async () => undefined, runtimeEnv: async () => ({ LOG_LEVEL: 'debug' }) },
} as unknown as Ctx
const server = createServer(ctx)
const mounted = new Set(server.routes.filter((r) => r.method !== 'ALL').map((r) => `${r.method} ${shape(r.path)}`))
const principal = {
organizationId: 'org',
userId: 'user',
actor: 'user:user',
permissions: ['read:apps', 'write:apps'],
}
const ajv = new Ajv2020({ strict: false, validateFormats: false })
ajv.addSchema({ components: spec.components, paths: spec.paths }, 'apps')
describe('Apps public contract', () => {
it.each(operations)('$method $path is mounted with its declared permissions', ({ path, method, op }) => {
const sample = path.replace(/{\w+}/g, 'example')
if (op.responses['101']) {
expect(CloudAppWebsocket.prototype.matches('/api/v1/org' + sample)).toBe(true)
expect(op['x-permissions']).toEqual(['read:apps', 'write:apps'])
return
}
expect(mounted).toContain(`${method} /v1${shape(path)}`)
expect([...appRoutePermissions(method, sample)].sort()).toEqual([...op['x-permissions']].sort())
})
it.each([
['GET', '/apps/example/environments'],
['POST', '/apps/example/environments'],
['DELETE', '/apps/example/environments/qa'],
['GET', '/apps/example/database'],
['GET', '/apps/example/database/export'],
['POST', '/apps/example/database/restore'],
['POST', '/apps/example/users/test/sign-out'],
])('withdraws the redundant %s %s route', (method, path) => {
expect(appRoutePermissions(method, path)).toEqual([])
})
it.each([
['listVariables', '/apps/example/envs/test/vars'],
['getDevEnvironment', '/apps/example/envs/test/dev-env'],
['getDatabase', '/apps/example/envs/test/db'],
])('%s returns data matching its documented schema', async (id, path) => {
const endpoint = operations.find(({ op }) => op.operationId === id)!
const response = await server.request('/v1' + path, {}, { platformPrincipal: principal })
expect(response.status).toBe(200)
const schema = endpoint.op.responses['200'].content['application/json'].schema
const validate = ajv.compile({ ...schema, components: spec.components })
const data = await response.json()
expect(validate(data) ? [] : validate.errors).toEqual([])
})
it('validates actual plan and idempotent deployment responses against their public models', async () => {
const post = (tail: string, body: unknown) =>
server.request(
'/v1/apps/example/envs/test/' + tail,
{
method: 'POST',
headers: { 'content-type': 'application/json', 'idempotency-key': 'retry' },
body: JSON.stringify(body),
},
{ platformPrincipal: principal },
)
const plan = await post('plan', { manifest: { app: 'example', environment: 'other' }, base_version: 2 })
expect(plan.status).toBe(200)
const result = await plan.json()
expect(result).toMatchObject({ stale: true, errors: [{ rule: 'env_mismatch' }] })
expect(ajv.validate({ $ref: 'apps#/components/schemas/Plan' }, result)).toBe(true)
const deployment = await post('deployments', { kind: 'deploy', snapshot_id: 'snapshot', manifest: {} })
expect(deployment.status).toBe(200)
const task = await deployment.json()
expect(task).toMatchObject({ number: 4, kind: 'deploy', status: 'queued' })
expect(ajv.validate({ $ref: 'apps#/components/schemas/Deployment' }, task)).toBe(true)
})
it('uses the environment in the Dashboard database path to build its view', async () => {
const lookup = jest.spyOn(ctx.store, 'envByName')
try {
const response = await server.request(
'/v1/apps/example/envs/test/db/view?env=main',
{},
{ platformPrincipal: principal },
)
expect(response.status).toBe(200)
expect(await response.json()).toEqual({ status: 'none' })
expect(lookup).toHaveBeenCalledWith('app-1', 'test')
} finally {
lookup.mockRestore()
}
})
it('rejects an unauthenticated call with the documented error body', async () => {
const response = await server.request('/v1/apps/example/envs/test/vars')
expect(response.status).toBe(401)
const schema = spec.components.responses.Error.content['application/json'].schema
expect(ajv.validate(schema, await response.json())).toBe(true)
})
})